<jupyter_start><jupyter_text>ASSIGNMENT - 02 <NAME> ID : 133014028 Class : MAT 201-(02)   ---------------------------------------------------------------------------------------------------------------  1.  Write a program that repeatedly asks the user to enter product names and prices. Store all of these in a dictionary whose keys are the product names and whose values are the prices. When the user is done entering products and prices, allow them to repeatedly enter a product name and print the corresponding price or a message if the product is not in the dictionary.<jupyter_code>dict = {}

while True:
    x = input("Product name: ")
    if x == "done":
        break
    y = input("Price: ")
    dict[x] = y
    
while True:
    x = input("What is the price of ")
    print(dict.get(x))
    break<jupyter_output>Product name: pen
Price: 20
Product name: apples
Price: 65
Product name: sticks
Price: 45
Product name: done
What is the price of sticks
45<jupyter_text>2. Using the dictionary created in the previous problem, allow the user to enter a dollar amount and print out all the products whose price is less than that amount.<jupyter_code>dict = {}

# x -> product
# y -> price

while (True):
    x = input("Product name: ")
    if x == "done":
        break
        
    y = int(input("Price (in $): ")) 
    dict[x] = y

    
w = int(input("\nShow products that cost less than "))

for x in dict:
    if dict.get(x) < w:
        print(x)<jupyter_output>Product name: apples
Price: 50
Product name: oranges
Price: 45
Product name: milk
Price: 100
Product name: grapes
Price: 71
Product name: done
Show products that cost less than 100
apples
oranges
grapes<jupyter_text>3. Write a program that uses a dictionary that contains ten user names and passwords. The program should ask the user to enter their username and password. If the username is not in the dictionary, the program should indicate that the person is not a valid user of the system. If the username is in the dictionary, but the user does not enter the right password, the program should say that the password is invalid. If the password is correct, then the program should tell the user that they are now logged in to the system.<jupyter_code>dict = {'Tom' : 'Dick2', 'Dick':'Harry3', 'Harry' : 'Tom1', 'Raz' : 'robin', 'Romiz' : 'romcomtom', 'Joy' : 'election18', 
        'Harrison' : 'Dexter', 'jill' : 'Credit', 'Runa' : 'jack33', '<NAME>' : 'VoldemortIsLife'}

x = input('User Name: ')
y = input('Password: ')

# error handling
if x in dict:
    if dict.get(x) == y :
        print("\nCorrect Password \nLog in Successful !")       
    else :    
        print ("Password Not Correct!")

else:
    print ("Username not in dictionary")<jupyter_output>User Name: Tom
Password: <PASSWORD>

Correct Password 
Log in Successful !<jupyter_text>4. Suppose you are given the following list of strings: L = [ ' aabaabac ' , ' cabaabca ' , ' aaabbcba ' , ' aabacbab ' , ' acababba ' ] Patterns like this show up in many places, including DNA sequencing. The user has a string of their own with only some letters filled in and the rest as asterisks. An example is aa** . The user would like to know which of the strings in the list fit with their pattern. In the example just given, the matching strings are the first and fourth. One way to solve this problem is to create a dictionary whose keys are the indices in the user’s string of the non- asterisk characters and whose values are those characters.  Write a program implementing this approach (or some other approach) to find the strings that match a user-entered string.<jupyter_code><jupyter_output><empty_output><jupyter_text>5. Dictionaries provide a convenient way to store structured data. Here is an example dictionary: d=[ { ' name ' : ' Todd ' , ' phone ' : ' 555-1414 ' , ' email ' : ' <EMAIL> ' },  { ' name ' : ' Helga ' , ' phone ' : ' 555-1618 ' , ' email ' : ' <EMAIL> ' }, { ' name ' : ' Princess ' , ' phone ' : ' 555-3141 ' , ' email ' : '' },  { ' name ' : ' LJ' , ' phone ' : ' 555-2718 ' , ' email ' : ' <EMAIL> ' } ] Write a program that reads through any dictionary like this and prints the following: (a) All the users whose phone number ends in an 8 (b) All the users that don’t have an email address listed<jupyter_code>dict = [{'name' : 'Todd', 'phone' : '555-1414', 'email' : '<EMAIL>'},
     {'name' : 'Helga', 'phone' : '555-1618', 'email' : '<EMAIL>'},
     {'name' : 'Princess', 'phone' : '555-2716', 'email' : ' '}]


for x in dict:
    for y in x:
        str = x.get('phone')
        if str[len(str)-1] == '8':
            print(x.get('name'))
            break
for x in dict:
    for y in x:
        str = x.get('email')
        if str[len(str)-1] == ' ':
            print(x.get('name'))
            break<jupyter_output>Helga
Princess<jupyter_text>6. The keys in a dictionary are guaranteed to be unique, but the values are not. Write a function called count_values that takes a single dictionary as an argument and returns the number of dis- tinct values it contains. Given the input {’red’:1, ’green’:1, ’blue’:2} , for example, it would return 2.  7. A sparse vector is a vector whose entries are almost all zero, like [1, 0, 0, 0, 0, 0, 3, 0, 0, 0] . Storing all those zeroes in a list wastes memory, so programmers often use dictionaries instead to keep track of just the nonzero entries. For example, the vector shown earlier would be represented as {0:1, 6:3} , since the vector it is meant to represent has the value 1 at index 0 and the value 3 at index 6. a) Write a function called sparse_add that takes two sparse vec- tors stored as dictionaries and returns a new dictionary rep- resenting their sum.  ================================================================================================  CONDITIONALS  8. Write a program that uses a while loop (not a for loop) to read through a string and print the characters of the string one-by-one on separate lines.<jupyter_code>user_str = input("Enter a string: ")

i = 0
while(i < len(user_str)):
    print("{}\n".format(user_str[i]))
    i+=1<jupyter_output>Enter a string: alvie
a

l

v

i

e<jupyter_text>9. Modify the program above to print out every second character of the string.<jupyter_code>user_str = input("Enter a string: ")

i = 1
while(i < len(user_str)):
    print("{}\n".format(user_str[i]))
    i+=2<jupyter_output>Enter a string: aftabalvie
f

a

a

v

e<jupyter_text>10.  Write a program that asks the user to enter a password. If the user enters the right password, the program should tell them they are logged in to the system. Otherwise, the program should ask them to reenter the password. The user should only get five tries to enter the password, after which point the program should tell them that they are kicked off of the system.<jupyter_code>password = "<PASSWORD>"

for i in range(6):
    if i == 0:
        str = input("Enter a password: ")
    else:
        str = input("Re-enter your password: ")
    
    if str == password:
        print("You are logged in !")
        break
    else:
        if 5- i > 0 :
            x = 5 - i 
            print("Tries left : \t")
            print(x)
        
        if i == 5:
            print("You have been kicked out of the system !! ")<jupyter_output>Enter a password: gs
Tries left : 	
5
Re-enter your password: <PASSWORD>
Tries left : 	
4
Re-enter your password: <PASSWORD>
Tries left : 	
3
Re-enter your password: <PASSWORD>
Tries left : 	
2
Re-enter your password: <PASSWORD>
Tries left : 	
1
Re-enter your password: <PASSWORD>
You have been kicked out of the system !!<jupyter_text>11.   Recall that, given a string s , s.index( ' x ' ) returns the index of the first x in s and an error if there is no x. (a) Write a program that asks the user for a string and a letter. Using a while loop, the program should print the index of the first occurrence of that letter and a message if the string does not contain the letter. (b) Write the above program using a for/break loop instead of a while loop.<jupyter_code>i = 0
str = input("Enter a string. Add a space and then enter the number whose position in the string you want : ")

while i < len(str)-2:
    if str[i] == str[len(str) - 1]:
        print ("Position [starting index = 0] : ")
        print(i)
        break
    i+=1
    
if i == len(str)-2:
    print("No \'{}\' found on this string". format(str[len(str) - 1]))

i = 0
str = input("Enter a string. Add a space and then enter the number whose position in the string you want : ")

for i in range(len(str)-2):
    if str[i] == str[len(str) - 1]:
        print ("Position [starting index = 0] : ")
        print(i)
        break
    i+=1
    
if i == len(str)-2:
    print("No \'{}\' found on this string". format(str[len(str) - 1]))<jupyter_output>Enter a string. Add a space and then enter the number whose position in the string you want : ert5gsgh 5
Position [starting index = 0] : 
3<jupyter_text>12. The GCD (greatest common divisor) of two numbers is the largest number that both are di- visible by. For instance, gcd (18, 42) is 6 because the largest number that both 18 and 42 are divisible by is 6. Write a program that asks the user for two numbers and computes their gcd. Shown below is a way to compute the GCD, called Euclid’s Algorithm.• First compute the remainder of dividing the larger number by the smaller number• Next, replace the larger number with the smaller number and the smaller number with the remainder.• Repeat this process until the smaller number is 0. The GCD is the last value of the larger number.<jupyter_code>num1 =int(input())
num2 =int(input())

x = 1
gcd = 0

while x <= num1 and x <= num2:
    if num1 % x == 0 and num2 % x == 0:
        gcd = x
    x+=1
print ("Greatest common Divisor: ")
print(gcd)<jupyter_output>18
42
Greatest common Divisor: 
6<jupyter_text>13. A 4000-year old method to compute the square root of 5 is as follows: Start with an initial guess, say 1. Then compute (1 + 5/1 )/2 = 3 Next, take that 3 and replace the 1’s in the previous formula with 3’s . This gives (3 + 5/3 )/2 = 7/3 = 2.33 Next replace the 3 in the previous formula with 7/3 . This gives (7/3 + 5/(7/3) )/2 = 47/22 = 2.24.  If you keep doing this process of computing the formula, getting a result, and plugging it back in, the values will eventually get closer and closer to 5 . This method works for numbers other than 5. Write a program that asks the user for a number and uses this method to estimate the square root of the number correct to within 10^( −10) . The estimate will be correct to within 10^( −10) when the absolute value of the difference between consecutive values is less than 10^(−10) .<jupyter_code>number = int(input())

i = 1

while i >= 0:
    x = i
    i = (i + number/i)/2
    if x == i:
        break
print("%.2f"%i)<jupyter_output>5
2.24<jupyter_text>14. Write a program that starts with an 5 × 5 list of zeroes and randomly changes exactly ten of those zeroes to ones.<jupyter_code>import random
myList = []
randomPosition = []

for i in range(25):
    myList.append(0)      # initial matrix of zeroes

for i in range(10):
    x = random.randrange(1, 25)
    while randomPosition.count(x) != 0:
        x = random.randrange(1, 25)
    randomPosition.append(x)
    myList[x] = 1
    
k = 0
for i in range (5):
    for j in range(5):
        if i+j == randomPosition[k]:
            print(myList[k], end=" ")
            k+=1
            continue
        print(myList[i+j], end=" ")
    print()<jupyter_output>0 0 0 1 1 
0 0 1 1 1 
0 1 1 1 0 
1 1 1 0 0 
1 1 0 0 0<jupyter_text>15. Write a program in which you have a list that contains seven integers that can be 0 or 1. Find the first nonzero entry in the list and change it to a 1. If there are no nonzero entries, print a message saying so.<jupyter_code>myList = [0,0,0,1,0,0,1]
k = True
for x in myList:
    if myList[x] != 0:
        myList[x] = 1
        k = False
        print(myList)
    break
if k == True:
    print("There are no non-zero entry exists")<jupyter_output>There are no non-zero entry exists<jupyter_text>16. Write a program to play the following simple game. The player starts with 100 dollars. On each turn a coin is flipped and the player has to guess heads or tails. The player wins 9 dollars for each correct guess and loses 10 dollars for each incorrect guess. The game ends either when the player runs out of money or gets to 200 dollars.<jupyter_code>import random
player = 100

while player > 0 and player < 200:
    print("1. Head\n2.Tail")
    x = int(input("Choose: "))
    if (random.randrange(10)+1)%2==0 and x == 2:
        player+=9
    else:
        player-=10
print ("player has : ")
print (player)<jupyter_output>1. Head
2.Tail
Choose: 1
1. Head
2.Tail
Choose: 2
1. Head
2.Tail
Choose: 2
1. Head
2.Tail
Choose: 1
1. Head
2.Tail
Choose: 1
1. Head
2.Tail
Choose: 2
1. Head
2.Tail
Choose: 1
1. Head
2.Tail
Choose: 2
1. Head
2.Tail
Choose: 1
1. Head
2.Tail
Choose: 2
1. Head
2.Tail
Choose: 2
1. Head
2.Tail
Choose: 1
1. Head
2.Tail
Choose: 2
1. Head
2.Tail
Choose: 2
1. Head
2.Tail
Choose: 2
1. Head
2.Tail
Choose: 1
1. Head
2.Tail
Choose: 1
1. Head
2.Tail
Choose: 1
1. Head
2.Tail
Choose: 1
1. Head
2.Tail
Choose: 1
-5<jupyter_text>17. Randomly generate a 6 × 6 list that has exactly 12 ones placed in random locations in the list. The rest of the entries should be zeroes.<jupyter_code>import random
positions = []

for x in range(12):
    randomNumber = random.randrange(36)
    while positions.count(randomNumber) != 0:
        randomNumber = random.randrange(36)
    positions.append(randomNumber)
    positions.sort()

k = 0
j = -1
for x in range(6):
    for y in range(6):
        j+=1
        if j == positions[k]:
            print("1", end=" ")
            k+=1
            continue
        print("0", end=" ")
    print()<jupyter_output>1 1 0 0 1 0 
0 0 0 1 0 0 
0 1 0 1 0 0 
0 0 1 0 1 0 
0 1 0 0 0 0 
1 0 1 0 0 1<jupyter_text>18. Randomly generate a 9 × 9 list where the entries are integers between 1 and 9 with no repeat entries in any row or in any column.<jupyter_code>import random
positions = []

for x in range(9):
    for y in range(9):
        f = random.randrange(9)+1
        
        while positions.count(f)!=0:
            f = random.randrange(9)+1
        positions.append(f)
        print(f, end=" ")
        
    positions.clear()
    print()<jupyter_output>7 6 3 5 8 1 4 2 9 
5 7 6 4 9 3 2 8 1 
3 9 6 7 5 4 8 2 1 
6 8 9 7 3 5 2 1 4 
3 2 9 6 8 4 1 7 5 
4 9 6 3 7 2 5 1 8 
7 2 3 6 1 5 4 9 8 
8 9 7 5 3 4 2 1 6 
3 5 8 6 2 4 1 7 9
{'fraction_non_alphanumeric': 0.11133282873460401, 'fraction_numerical': 0.038326567123099155, 'mean_word_length': 2.9742958709324583, 'pattern_counts': {'":': 2, '<': 71, '<?xml version=': 0, '>': 69, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '16', 'dir': 'jupyter-structured-clean-dedup', 'id': '198754', 'license': 'MIT', 'n_tokens_mistral': 5009, 'n_tokens_neox': 4549, 'n_words': 2116, 'path': 'MAT201-(02)-Assignment-02.ipynb', 'repo_name': 'aftab-alvie/MAT-201-2--Assignment--02-', 'size': '14565'}