diff --git a/12_09_practice.py b/12_09_practice.py index 7914563..bc3ea5a 100644 --- a/12_09_practice.py +++ b/12_09_practice.py @@ -1,29 +1,131 @@ #Biggie Size - Given a list, write a function that changes all positive numbers in the list to "big". Example: make_it_big([-1, 3, 5, -5]) returns that same list, #changed to [-1, "big", "big", -5]. +def biggie(list): + for i in range(len(list)): + if list[i]>0: + list[i]='big' + return list +print(biggie([-1,3,5,-5])) #Count Positives - Given a list of numbers, create a function to replace last value with number of positive values. Example, count_positives([-1,1,1,1]) changes list #to [-1,1,1,3] and returns it. (Note that zero is not considered to be a positive number). +def positives(list): + count = 0 + for i in list: + if i > 0: + count += 1 + list[len(list) - 1] = count + return list + +print(positives([-1,1,1,1])) + + #SumTotal - Create a function that takes a list as an argument and returns the sum of all the values in the list. For example sum_total([1,2,3,4]) should return 10 +def sumtotal(list): + sum = 0 + for i in list: + sum += i + return sum + +print(sumtotal([1,2,3,4])) #Average - Create a function that takes a list as an argument and returns the average of all the values in the list. For example multiples([1,2,3,4]) should return #2.5 +def average(list): + sum = 0 + for i in list: + sum += i + return sum/len(list) + +print(average([1,2,3,4])) + #Length - Create a function that takes a list as an argument and returns the length of the list. For example length([1,2,3,4]) should return 4 +def length(list): + return len(list) + +print(length([1,2,3,4])) + #Minimum - Create a function that takes a list as an argument and returns the minimum value in the list. If the passed list is empty, have the function return false. #For example minimum([1,2,3,4]) should return 1; minimum([-1,-2,-3]) should return -3. -# + +def minimum(list): + return min(list) + +print(minimum([1,2,3,4])) + #Maximum - Create a function that takes a list as an argument and returns the maximum value in the list. If the passed list is empty, have the function return false. #For example maximum([1,2,3,4]) should return 4; maximum([-1,-2,-3]) should return -1. +def maximum(list): + return max(list) + +print(maximum([1,2,3,4])) + #Ultimateaalyze - Create a function that takes a list as an argument and returns a dictionary that has the sumTotal, average, minimum, maximum ad length of the list. +def ultimateanalyze(list): + dict = {'sumtotal':0, 'average':0, 'minimum': list[0], 'maximum': list[0], 'length': len(list)} + for i in list: + dict['sumtotal'] += i + dict['average'] = dict['sumtotal']/len(list) + if dict['minimum'] > i: + dict['minimum'] = i + if dict['maximum'] < i: + dict['maximum'] = i + return(dict) + +print(ultimateanalyze([-2,4,-5,6,10,1,0])) + #ReverseList - Create a function that takes a list as a argument and return a list in a reversed order. Do this without creating a empty temporary list. For example #reverse([1,2,3,4]) should return [4,3,2,1]. This challenge is known to appear during basic technical interviews. +def reverse_list(list): + for i in range(len(list) // 2): + list[i], list[-1-i] = list[-1-i], list[i] + return list +print(reverse_list([11,12,13])) +print(reverse_list([11,12,13,14,15,16])) + #Ispalindrome- Given a string, write a python function to check if it is palindrome or not. A string is said to be palindrome if the reverse of the string is the same as string. For example, “radar” is a palindrome, but “radix” is not a palindrome. +def isPalindrome(str): + + for i in range(0, (len(str)/2) ): + if str[i] != str[len(str)-i-1]: + return False + return True + +print(isPalindrome('radar')) +print(isPalindrome('radix')) + #Fizzbuzz- Create a function that will print numbers from 1 to 100, with certain exceptions: #If the number is a multiple of 3, print “Fizz” instead of the number. #If the number is a multiple of 5, print “Buzz” instead of the number. #If the number is a multiple of 3 and 5, print “FizzBuzz” instead of the number. +def fizzbuzz(): + for i in range(1,101): + if i % 3 == 0 and i % 5 == 0: + print("FizzBuzz") + elif i % 3 == 0: + print("Fizz") + elif i % 5 ==0: + print("buzz") + else: + print(i) + +fizzbuzz() + #Fibonacci- The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, #starting from 0 and 1. That is, #F(0) = 0, F(1) = 1 #F(n) = F(n - 1) + F(n - 2), for n > 1. - #Create a function that accepts any number and will create a sequence based on the fibonacci sequence. \ No newline at end of file + #Create a function that accepts any number and will create a sequence based on the fibonacci sequence. +def fibonacci(n): + if n == 0: + return 0 + elif n == 1: + return 1 + else: + return ((n-1) + (n-2)) + +print(fibonacci(5)) + + + diff --git a/data_file.json b/data_file.json new file mode 100644 index 0000000..5211774 --- /dev/null +++ b/data_file.json @@ -0,0 +1,6 @@ +{ + "user": { + "name": "William Williams", + "age": 93 + } +} \ No newline at end of file diff --git a/json_practice.py b/json_practice.py new file mode 100644 index 0000000..4baf187 --- /dev/null +++ b/json_practice.py @@ -0,0 +1,91 @@ +import json +import requests +from pprint import pp + +#serialize a json, encoding data into json format +#deserialize a json, decoding into another format + +### !!!! They are NOT perfect inverses !!!!! ##### +# +# +#Serialize +#dump() write data to a file like object in json format +#open() in a try and except block +#with open() as + +#dumps() write the data to string in json format + +data= { + "user": { + "name": "William Williams", + "age": 93 + } +} + +# print(data["user"]["age"]) + +with open("data_file.json", "w") as write_file: + json.dump(data, write_file, indent= 4) + + +json_str=json.dumps(data, indent=4) +print(json_str) + +#lets check and se + +blkjk_hand= (8, "Q") +encoded = json.dumps(blkjk_hand) +decoded= json.loads(encoded) + +print(type(blkjk_hand)) +print(type(decoded)) +print(blkjk_hand ==tuple(decoded)) + +##deserializatation example +response = requests.get("http://jsonplaceholder.typicode.com/todos") +todos= json.loads(response.text) + +#print(type(todos)) +pp(todos[:10]) + + +#see who has the most completed items +#we are going to need to loop through list to check all the todos +#we need to count all the items +#have a place to track and store the number of completed todos, by thu user +todos_by_user={} +for item in todos: + if item["completed"] == True and item["userId"] not in todos_by_user: + if item["userID"] not in todos_by_user.keys(): + todos_by_user[item["userId"]] = 1 + else: + todos_by_user[item["userId"]] += 1 + +print(todos_by_user) + +#with the code above, we have created a new dictionary that has all of the users with completed +#and the total number of tasks they created + +top_users = sorted(todos_by_user.items(), key=lambda x: x[1], reverse=True) +print(top_users) +max_complete= top_users[0][1] + +#with the code above we are sorting by the values due to the lambda function sorting at x[1] from high to low + +### Final Goal is to tell s in a string who are the users that have the highest number of todos completed with thei user ids 4 +stars = [x for x, y in top_users if y == max_complete] + +stars2 = [] +for users, value in top_users: + if value == max_complete: + stars2.append(users) +print(stars) +print(stars2) + + +#"Users {} completed {this many} TODOS" + +print("User(s) {} completed TODOs".format(user)) + + + diff --git a/movies.xml b/movies.xml new file mode 100644 index 0000000..cdce407 --- /dev/null +++ b/movies.xml @@ -0,0 +1,120 @@ + + + + + DVD + 1981 + PG + + 'Archaeologist and adventurer Indiana Jones + is hired by the U.S. government to find the Ark of the + Covenant before the Nazis.' + + + + DVD,Online + 1984 + PG + None provided. + + + Blu-ray + 1985 + PG + Marty McFly + + + + + dvd, digital + 2000 + PG-13 + Two mutants come to a private academy for their kind whose resident superhero team must + oppose a terrorist organization with similar powers. + + + VHS + 1992 + PG13 + NA. + + + Online + 1992 + R + WhAtEvER I Want!!!?! + + + + + + + + DVD + 1979 + R + """"""""" + + + + + DVD + 1986 + PG13 + Funny movie about a funny guy + + + blue-ray + 2000 + Unrated + psychopathic Bateman + + + + + + + + DVD,VHS + 1966 + PG + What a joke! + + + + + DVD + 2010 + PG--13 + Emma Stone = Hester Prynne + + + DVD,digital,Netflix + 2011 + Unrated + Tim (Rudd) is a rising executive + who 'succeeds' in finding the perfect guest, + IRS employee Barry (Carell), for his boss monthly event, + a so-called 'dinner for idiots,' which offers certain + advantages to the exec who shows up with the biggest buffoon. + + + + + + Online,VHS + 1984 + PG + Who ya gonna call? + + + + + Blu_Ray + 1991 + Unknown + Robin Hood slaying + + + + \ No newline at end of file diff --git a/newjupiter.ipynb b/newjupiter.ipynb new file mode 100644 index 0000000..9f291c4 --- /dev/null +++ b/newjupiter.ipynb @@ -0,0 +1,122 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "import mysql.connector as mariadb" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Connecting to MariaDB Database...\n" + ] + } + ], + "source": [ + "con= mariadb.connect(\n", + " host = \"localhost\",\n", + " user = \"root\",\n", + " password = \"password\",\n", + " database = \"classicmodels\"\n", + ")\n", + "\n", + "print(\"Connecting to MariaDB Database...\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "Let's check and see if we actually made a connection. to do this we need to create a cursor. We do this by calling the cursor method. \n" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "cur = con.cursor()\n", + "\n", + "st= \"SELECT productLine, COUNT(*) \\\n", + " FROM products \\\n", + " WHERE productLine= '{}'\"\n", + "\n", + "cur.execute(st.format('Motorcycles'))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "In the cell above we created and executed our sql statement. But we have not used ant methods to actually access this data from our select statement." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[('Motorcycles', 13)]\n" + ] + } + ], + "source": [ + "result= cur.fetchall()\n", + "print(result)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.0" + }, + "orig_nbformat": 4, + "vscode": { + "interpreter": { + "hash": "4f5b93e50f6a80533ecf44f008725c0e9b38700cb11e5b04c3ed3bdc4781a79c" + } + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/practice.py b/practice.py new file mode 100644 index 0000000..27a8538 --- /dev/null +++ b/practice.py @@ -0,0 +1,46 @@ +#Fizzbuzz- Create a function that will print numbers from 1 to 100, with certain exceptions: + #If the number is a multiple of 3, print “Fizz” instead of the number. + #If the number is a multiple of 5, print “Buzz” instead of the number. + #If the number is a multiple of 3 and 5, print “FizzBuzz” instead of the number. + +def fizzbuzz(): + for i in range(1,101): + if i % 3 == 0 and i % 5 == 0: + print("FizzBuzz") + elif i % 3 == 0: + print("Fizz") + elif i % 5 ==0: + print("buzz") + else: + print(i) + +#fizzbuzz + +#Use list comprehension for fizzbuzz problem + +fizzbuzzlist = ['Fizzbuzz' if i % 3 == 0 and i % 5 == 0 else 'fizz' if i % 3 == 0 else 'buzz' if i % 5 == 0 else i for i in range(1,51)] + +# print(fizzbuzzlist) + +# def dec(func, n): +# def wrapper(): +# for _ in range(n): +# func() +# return wrapper + +# @dec('say_hello', 5) +# def say_hello(): +# print('hello') + +# #say_hello = dec(say_hello, 5) +# say_hello() + +def dec(*args): + #print(type(args)) + #print(args) + n = args[0] + #print(n) + def wrapper(func): + for _ in range(n): + func() + return dec diff --git a/pythonpracticewebsite.py b/pythonpracticewebsite.py new file mode 100644 index 0000000..5319e6a --- /dev/null +++ b/pythonpracticewebsite.py @@ -0,0 +1,138 @@ +#4: Divisors +#num = int(input("Please choose a number to divide: ")) + +#listRange = list(range(1,num+1)) + +#divisorList = [] + +#for number in listRange: +# if num % number == 0: +# divisorList.append(number) + +#print(divisorList) + +#5: List Overlap +a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] +b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] + +c = [] +for y in b: + if y in a: + c.append(y) +#print(c) + +#One line solution +#print(list(set(a) & set(b))) + +#6: String Lists : Ask the user for a string and print out whether this string is a palindrome or not. (A palindrome is a string that reads the same forwards and backwards.) +# string = input("Input a string to see if it is a palindrome: ") +# reverse = string[::-1] +# print(reverse) +# if string == reverse: +# print("This word is a palindrome") +# else: +# print("This word is not a palindrome") + +#7: Let’s say I give you a list saved in a variable: a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. Write one line of Python that takes this list a and makes a new list that has only the even elements of this list in it. +# a = [1,4,9,16,25,36,49,64,81,100] + +# evens = [x for x in a if x % 2 == 0] + +# print(evens) + +#8: Make a two-player Rock-Paper-Scissors game. (Hint: Ask for player plays (using input), compare them, print out a message of congratulations to the winner, and ask if the players want to start a new game) +import sys + + +# user1_answer = input("Player 1:rock, paper or scissors? ") +# user2_answer = input("Player 2: rock, paper or scissors? ") + +# def compare(u1, u2): +# if u1 == u2: +# return("It's a tie!") +# elif u1 == 'rock': +# if u2 == 'scissors': +# return("Rock wins!") +# else: +# return("Paper wins!") +# elif u1 == 'scissors': +# if u2 == 'paper': +# return("Scissors win!") +# else: +# return("Rock wins!") +# elif u1 == 'paper': +# if u2 == 'rock': +# return("Paper wins!") +# else: +# return("Scissors win!") +# else: +# return("Invalid input! You have not entered rock, paper or scissors, try again.") +# sys.exit() + +# print(compare(user1_answer, user2_answer)) + +#Generate a random number between 1 and 9 (including 1 and 9). Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right. (Hint: remember to use the user input lessons from the very first exercise) +# import random +# number = random.randint(2,10) +# guess = 0 +# while guess != number: +# guess = int(input("Guess the number between 1 and 9: ")) +# if guess < number: +# print("Too low, try again") +# elif guess > number: +# print("Too high, try again") +# else: +# print("Yessirrrr!!" ) + +#10: List Overlap Comprehensions +import random + +# a = random.sample(range(1,30), 12) +# b = random.sample(range(1,30), 16) +# result = [i for i in a if i in b] +# print(result) + +#11: Check Primality: Ask the user for a number and determine whether the number is prime or not. +# import sys +# number = input("Please enter a number" + "\n" + ">>>") +# number = int(number) +# prime = False # initiate boolean for true false, default false +# if number > 0: +# for x in range(2, number - 1): #this range excludes number and 1, both of which the number is divisible by +# if number % x != 0: +# continue +# elif number % x ==0: +# sys.exit("The number is not prime") +# sys.exit("The number is prime.") +# elif number == 0: +# sys.exit("The number is not prime.") +# else: +# sys.exit("The number is not prime") + +#12 List Ends: Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25]) and makes a new list of only the first and last elements of the given list. For practice, write this code inside a function. + +# def list_ends(list): +# return [list[0], list[len(list)-1]] + +# print(list_ends([4,8,3,9,1])) + +#14 List Remove Duplicates - Write a program(function!) that takes a list and returns a new list that contains all the elements of the first list minus all the duplicates + +# def duplicate(x): +# y= [] +# for i in x: +# if i not in y: +# y.append(i) +# return y + +# print(duplicate([1,2,3,1,2,4,6,7,8,9])) + +#15 Reverse Word Order - Write a program (using functions!) that asks the user for a long string containing multiple words. Print back to the user the same string, except with the words in backwards order. +# def reverse_v1(x): +# y = x.split() +# result = [] +# for word in y: +# result.insert(0,word) +# return " ".join(result) + +#18 Cows and Bulls diff --git a/xml.practice.py b/xml.practice.py new file mode 100644 index 0000000..3843976 --- /dev/null +++ b/xml.practice.py @@ -0,0 +1,28 @@ +import xml.etree.ElementTree as ET + +tree = ET.parse('movies.xml') +root = tree.getroot() + + +#Creating anime genre + anime_genre = ET.SubElement(root, 'genre') + anime_genre.attrib['category'] = 'Anime' + anime = root.find("./genre[@category='Anime']") + new_dec = ET.SubElement(anime, 'decade') + new_dec.attrib["years"] = '2000s' + print(ET.tostring(anime_genre, encoding='utf8').decode('utf8')) + + tree.write("movies.xml") + + tree = ET.parse('movies.xml') + root = tree.getroot() + + print(ET.tostring(root, encoding='utf8').decode('utf8')) +#Moving batman to anime genre and removing from original +batman = root.find("./genre/decade/movie[@title='Batman: The Movie']") +animedec2000s = root.find("./genre[@category='Anime']/decade[@years='2000s']") +animedec2000s.append(batman) +dec1960s = root.find("./genre[@category='Comedy']/decade[@years='1960s']") +dec1960s.remove(batman) +print(ET.tostring(root, encoding='utf8').decode('utf8')) + diff --git a/xml_round2.py b/xml_round2.py new file mode 100644 index 0000000..525478d --- /dev/null +++ b/xml_round2.py @@ -0,0 +1,10 @@ +aliens = [] + +# Make 30 green aliens +for alien_number in range(30): + new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'} + aliens.append(new_alien) + +phones = ['apple', 'samsumg', 'oneplus'] +phones_iter = iter(phones) +print(next(phones_iter))