I am currently learning to program in python. I am trying to build a basic program that will output how many of each type of coin (quarter, nickel, dime, penny) based off of what number the user inputs. I currently have it so that it will print a 0. However, I'd like it to omit those values in the print statement. I'm not sure how to do that without making each of the different total values and having them print each off of an if statement.
#for if statement and to ask for what coin number it is
y = 1
#asks user for how many coins
x = int(input("How much change are you trying to give (in cents)? "))
while(y <= 1):
q = 25
d = 10
n = 5
p = 1
#Take total and divide by 25 as many times as you can output as quarter
totalq = x // 25
#Take total from that and divide by 10 as many times as you can and output as dime
totald = (x-(q*(totalq))) // 10
#Take total from above and divide by 5 as many times as you can and output as nickel
totaln = (x-(q*(totalq))-(d*(totald))) //5
#Finally take total from above and see how many is left over and output as penny
totalp = (x-(q*(totalq))-(d*(totald))-(n*(totaln))) // 1
y = y + 1
total = (str(totalq) +" quarters " + str(totald) +" dimes " + str(totaln) +" nickels " + str(totalp) + " pennies")
print(total)
I think the most straightforward way to approach this is, as you suggest, using a bunch of ifs - something like:
if totalq:
print(totalq, "quarters", end=' ')
if totald:
print(totalq, "dimes", end=' ')
if totaln:
print(totalq, "nickels", end=' ')
if totalp:
print(totalq, "pennies")
Or, you could make this a little less repetitive using a generator expression:
pairs = [(totalq, 'quarters'),
(totald, 'dimes'),
(totaln, 'nickels'),
(totalp, 'pennies')]
total = ' '.join(str(value) + ' ' + name
for value, name in pairs
if value)
print(total)
Personally, I think the latter approach is prettier, but it's also a bit more complicated. If there's something about this latter code you don't understand, let me know.
Related
Example 1:
Input:
n = 1
Output: 1
Explanation: Digital root of 1 is 1
Example 2:
Input:
n = 99999
Output: 9
Explanation: Sum of digits of 99999 is 45
which is not a single digit number, hence
sum of digit of 45 is 9 which is a single
digit number.
Could someone help what is the time complexity of my code? I think its O(loglog(N)) but not sure.
def sumOfDigits(n):
if n==0:
return 0
else:
return int(n%10) + sumOfDigits(n//10)
def digitalRoot(n):
ans = n
if n<=9:
return n
else:
while ans>9:
ans = sumOfDigits(ans)
return ans
Let's calculate the complexity for the first step
If an algorithm depends on the number of digits it contains the time complexity of such algorithm is:
O(log10(n))
This is because we represent numbers in base 10 notation.
For example, this would make the relation crystal clear:
O(log10(100)) = 2
O(log10(1000)) = 3
O(log10(10000)) = 4
Now this answers the question to some extent, if we were only adding all digits once, we'd stop here.
But since we're not, let's move forward. Now if all the digits are added once, we again add the digits of that resultant number. Making it a convergent series.
Thus the answer could be:
O(log10(n)) + O(log10(log10(n))) + O(log10(log10(log10(n)))) + ...
This is my best estimation for the upper bound of complexity.
I would like to receive help in understanding why my solution to Problem 3 of the Google CodeJam 2020 Qualifier does not work.
Link to problem: https://codingcompetitions.withgoogle.com/codejam/round/000000000019fd27/000000000020bdf9
My solution:
High-level overview:
take input
figure out if the given input is impossible by sorting according to start times and then checking if more than 2 subsequent activities are 'active' at once (which is impossible)
if it is, output accordingly; if it isn't, proceed with the procedure below
arbitrarily assign the first person: in my solution I choose Cameron (C).
next, since we know that a solution exists, and the array I iterate through is sorted according to start times, if the very next activity interval (chronologically) overlaps in its duration with the current, assign it to the person who is not currently busy. This is purely because a solution exists, and it clearly cannot be the current person, so it must be the other.
moreover, if the very next activity interval (chronologically) does not overlap with the current activity, then assign it to the person who is currently busy (because he will not be busy for the next activity)
in addition, quoted directly from the problem's official analysis: "If an assignment is possible, there cannot be any set of three activities that pairwise overlap, so by the contrapositive of the the previous argument, we will be able to assign the activity to at least one of Jamie or Cameron at every step."
At this moment, I believe that these arguments suffice to show that my logic is valid, although my code evidently does not always produce the correct answer. I would greatly appreciate any help on this, since I have spent hours trying to debug, un-reason, or find a counter-example to my code to no avail. I have included my code, for reference, below.
Code:
for p in range(int(input())):
s = int(input())
l = []
for i in range(s):
l.append(list(map(int, list(input().split()))))
unsort = l.copy()
l = sorted(l, key=lambda tup: (tup[0],tup[1]))
enumerated = list(enumerate(unsort))
enumerated.sort(key=lambda x: x[1][0])
impossible = False
endings = sorted([(x[1], False) for x in unsort])
startings = sorted([(x[0], True) for x in unsort])
total = sorted(endings + startings, key=lambda tup: (tup[0], tup[1]))
size = 0
for i in total:
if i[1] == True:
size += 1
else:
size -= 1
if size > 2:
impossible = True
def overlap(a,b):
if not max(a[0], b[0]) >= min(a[1], b[1]):
return True
else:
return False
ans = "C"
def opp(a):
if a == "C":
return "J"
else:
return "C"
if impossible == True:
print("Case #" + str(p+1) + ": " + "IMPOSSIBLE")
else:
for i in range(0, s-1):
if overlap(l[i], l[i+1]) == True:
ans = ans + opp(ans[len(ans)-1])
else:
ans = ans + opp(opp(ans[len(ans)-1]))
#the stuff below is to order the activity assignments according to input order
key_value = [(ans[i], l[i]) for i in range(s)]
fans = ""
for i in range(s):
for j in range(s):
if enumerated[j][0] == i:
fans = fans + key_value[j][0]
print("Case #" + str(p + 1) + ": " + fans)
this is my first time posting and I haven't been learning to code for very long. This is the first script I've tried to build on my own, please be nice.
The program is linked to a CSV of elements and their atomic mass. The user inputs a chemical formula and the return is the molecular mass and a breakdown of the molecular mass percentage. It runs fine but as it stands it requires 6 values, eg H 2 S 1 O 4 for H2SO4. Obviously I want to have the option for long formulae but for shorter ones the script returns an error saying it expected 6 variables but only had 4 to unpack eg: H2O1.
Is there a straightforward way to make the script skip/ignore variables if there is no user input/the input is only white-space? I've been Googling it but either it's more difficult than I imagine or I'm not using the search engine well enough. I messed around with for loops but couldn't get anything to play ball.
Attached is the code, I'm aware that it could probably be twice as simple/slick if I had a little more knowledge. Thanks in advance.
def formula():
element_1, element_1_size, element_2, element_2_size, element_3, element_3_size = input("Enter your formula: ").split()
element_1_mass = float(elements_data_symbols.loc[element_1, "Atomic Mass"])
element_2_mass = float(elements_data_symbols.loc[element_2, "Atomic Mass"])
element_3_mass = float(elements_data_symbols.loc[element_3, "Atomic Mass"])
element_1_molecular_mass = element_1_mass * int(element_1_size)
element_2_molecular_mass = element_2_mass * int(element_2_size)
element_3_molecular_mass = element_3_mass * int(element_3_size)
molecular_mass = element_1_molecular_mass + element_2_molecular_mass + element_3_molecular_mass
molecule_name = str(element_1 + element_1_size + element_2 + element_2_size + element_3 + element_3_size)
print("Molecular mass of " + molecule_name + ": " + str(molecular_mass) + " g/mol")
element_1_percentage = element_1_molecular_mass / molecular_mass * 100
element_2_percentage = element_2_molecular_mass / molecular_mass * 100
element_3_percentage = element_3_molecular_mass / molecular_mass * 100
print(element_1 + ": " + str(element_1_percentage) + " %")
print(element_2 + ": " + str(element_2_percentage) + " %")
print(element_3 + ": " + str(element_3_percentage) + " %")
print(" ")
You're right a more efficient way of doing this would be using a loop to go through each pair of elements within the array, but keeping it simple you could amend your code to conditionally set elements only if the input array is at a certain length:
# Receive user input as an array
elements = input("Enter your formula").split()
# First element should always exist (but could also do this conditionally)
element_1 = elements[0]
element_1_size = elements[1]
# Check if array has at least 4 elements
if len(elements) >= 4:
element_2 = elements[2]
element_2_size = elements[3]
# Check if array has at leat 6 elements
if len(elements) >= 6:
element_3 = elements[4]
element_3_size = elements[5]
I'm a beginner in Python , and I'm trying to make an improvement in the guessing the number game.
So far my guessing the number game consists of guessing a secret randomly integer selected by Python in the range of 1 to 100, inclusive, in 10 or fewer attempts.
"x" is the secret number.
The program should ask the user to type a guess "n" for the number "x".
Before typing each guess, the game program count and displays the number of attempts so far. If after 10 attempts have not guessed the number, the program scolds the user with a message like : Unfortunately you have not able to find out the number in 10 attempts.
The "x "number was 40 for give an example so the program looks like these:
Welcome to the game
The game consists of guessing a secret integer, selected randomly in the range of 1 to 100, in 10 or fewer attempts.
Attempt 1 ,type your guess: 50 # 50 is the input of the user
The program would display something like these:
Attempt 1 ,type your guess: 50
x < 50
Attempt 2 ,type your guess:
In addition, the program must keep accounts for the range of possible numbers on
What it is reasonable to make an attempt to guess.
After the first attempt, when the program told you how is "x" compared to "n", if the guess is not in this range, the program must draw attention with a message like "Ooops, we already knew that x < 60" (for example , if you already typed 50 and the program told you that x < 50)
The thing is that I don't know how to keep accounts for the range of possible numbers on which it is reasonable to make an attempt to guess.
Here is an example of what I want to do:
Welcome to the game
The game consists of guessing a secret integer, selected randomly in the range of 1 to 100, in 10 or fewer attempts.
Attempt 1 ,type your guess: 50
x < 50
Attempt 2 ,type your guess: 60
If someone type 60 , that is not within the possibilities within which you can find x , so what I want to do , is when something like these happens , the program will print for example :
Attempt 2 ,type your guess: 60
Ooops, we already knew that x < 60
Because the program already told the person that x < 50 , so it is not possible that x = 60
Here's my code so far:
#Guessing the number game
import random
attempt = 0
attempt = attempt + 1
print('Welcome to the game')
print('The game consists of guessing a secret integer, selected randomly in the range of 1 to 100, in 10 or fewer attempts.')
x = random.randint(1,100)
while attempt < 11:
print('Attempt', attempt , ',type your guess')
n = input()
n = int(n)
attempt = attempt + 1
if n < x:
print('x >',n)
if n > x :
print('x <',n)
if n == x:
break
if n == x:
attempt = str(attempt)
print('Congratulations, you have guessed the number in ' , int(attempt) -1 , 'attempts')
if n != x:
x = str(x)
print('Unfortunately you have not able to find out the number in 10 attempts. The number was' , x)
All you needed to do was add closestmin and closestmax values to the evaluation of the guessed number. Here's my suggestion as to how to do it
import random
attempt = 1
closestmin = 0
closestmax = 100
print('Welcome to the game')
print('The game consists of guessing a secret integer, selected randomly in the range of 1 to 100, in 10 or fewer attempts.')
x = random.randint(1, 100)
for guess in range(10):
print("Attempt", attempt)
n = int(input('Type your guess'))
if n == x:
attempt = str(attempt)
print('Congratulations, you have guessed the number in' , attempt, 'attempts')
break
elif n < x:
if n > closestmin: #if guess is closer than previous closest lowest guess
closestmin = n #update closest lowest guess with new number
print('x >', n)
elif n < closestmin:
print("We already know that x <", closestmin)
elif n > x :
if n < closestmax: #if guess is closer than previous closest lowest guess
closestmax = n #update closest largest guess with new number
print('x <', n)
elif n > closestmax:
print("We already know that x <", closestmax)
attempt = attempt + 1
if attempt > 10:
print('Unfortunately you have not able to find out the number in 10 attempts. The number was' , x)
break
As you can see, I've added a second if statement that checks to see if the guess was closer than the previous one, and otherwise remind them of their closest guess.
I've also replaced you while loop with a for loop, for greater simplicity.
Keep coding!
We received a file called USPopulation.txt, with instructions that basically say line 1 in the file is the year 1950 and the last line being 1990. we needed to store the data in a list and do 3 things with said data.
Find the average(somewhat easy i think i have this down)
Find the maximum rate of change in any 1 year
Find the minimum rate of change in any 1 year
The Average of the numbers code taken from a past program
list_of_numbers = []
with open('USPopulation.txt') as f:
for line in f:
if line.strip():
list_of_numbers.append(int(line.strip()))
print('Total ',len(list_of_numbers))
print('Average ',1.0 * sum(list_of_numbers) / len(list_of_numbers))
I need to combine the other elements and have no idea how any help would be great
The rate of change is the difference between two subsequent values in the list. To get that value, you basically need to store the previous value and compare it to the current one.
One way of doing this would be to simply loop through your list, and collect those values:
previous = None:
ratesOfChange = []
for num in list_of_numbers:
if previous:
ratesOfChange.append(abs(num - previous))
previous = num
Getting the maximum and minimum is then as easy as calling max() and min() on the ratesOfChange list.
Of course to improve this a bit, you might want to consider collecting those values while parsing the file already (so you save the second loop through the list). And you could even note down the minimum and maximum at the same time to save another loop through it (both max and min will loop over the list).
if USPopulation.txt is like
1950=10000
1951=10005
1952=10030
then by converting the above lines into dictionary so that one can access each year and its corresponding population
file1 = open("USPopulation.txt", "r+")
years_dict = dict()
arr = []
class population:
def __init__(self):<br>
self.average = 0
self.maximum = 0
self.minimum = 0
def average_method(self):
try:
for line in file1.readlines():
value1 = line.split('=', 1)
years_dict[value1[0]] = int(value1[1])
length_of_dictionary = len(years_dict.keys())
for values in years_dict.values():
self.average = self.average + values
self.average = (1.0 * self.average / length_of_dictionary)
except:
print "not able to read the lines from the file"
def maximum_method(self):
try:
i = 0
for year in range(1950, 1952):
arr.insert(i, (years_dict[str(year + 1)] - years_dict[str(year)]))
i = i + 1
self.minimum = min(arr)
self.maximum = max(arr)
except:
print "not able to insert the element"
obj = population()
obj.average_method()
obj.maximum_method()
print "Average of population: " + str(obj.average)
print "maximum rate of change: " + str(obj.maximum)
print "minimum rate of change: " + str(obj.minimum)