So I have question about my homework.
Program must do:
* Asks from user the number of clients ( not negative int number )
* Uses while and gets total number of flowers
* Print final sum to screen.
We have text like:
It's womens day and flowershop decided to give flowers to women. But thing is, only odd number gets them.
So first one gets 1, second one gets nothing, third gets 3 , fifth gets 5 and so on. If you insert 7, then sum of odd numbers is 16 : 1 + 3 + 5 + 7 = 16. If user inserts 8, then sum is also 16 : 1 + 3 + 5 + 7 = 16.
The odd number can't be bigger than number of women.
You have to insert the number of women.
I have done this:
women = int(input("Insert number of buyers: "))
i = 1
sum = 0
while i < women:
i = i + 2
sum = sum + i
print("Total of flowers is: " + str(women))
But it dosent work and my brain is totally out of ideas already :(
Final result must look like this:
Insert number of buyers: 7
Total of flowers is : 16
There are three flaws in your code:
Incrementing i before incrementing sum (meaning the first lady gets 3 flowers)
Using 1 based indices to count the women, but using the wrong loop condition (with women=7 the loop body will not execute if i==7, so it should be i <= women)
Not printing the answer (sum) but the input (women)
Here is a fixed version:
women = int(input("Insert number of buyers: "))
i = 1
sum = 0
while i <= women:
sum = sum + i
i = i + 2
print("Total of flowers is: " + str(sum))
Using a for loop would, to my opinion, be simpler.
women = int(input("Insert number of buyers: "))
sum = 0
for i in range(1,women+1):
if i%2 != 0: # If i is odd
sum += 1
print("Total of flowers is: " + str(sum))
or
women = int(input("Insert number of buyers: "))
sum = sum(i for i in range(1,women+1) if i%2 != 0)
print("Total of flowers is: " + str(sum))
Do this with a list comprehension:
women = int(input("Insert number of buyers: "))
flowers = sum(i for i in range(1, women+1) if i%2 == 1)
print("Total of flowers is:", flowers)
Or using range's step parameter:
women = int(input("Insert number of buyers: "))
flowers = sum(range(1, women+1, 2))
print("Total of flowers is:", flowers)
Alternatively with a loop it could look like this:
women = int(input("Insert number of buyers: "))
flowers = 0
for i in range(1, women+1):
if i%2 == 1:
flowers += i
print("Total of flowers is:", flowers)
Or look like this using a loop and range's step parameter:
women = int(input("Insert number of buyers: "))
flowers = 0
for i in range(1, women+1, 2):
flowers += i
print("Total of flowers is:", flowers)
In future production code, you would go for variant 1 or 2.
Your Simply Revised code:
women = int(input("Insert number of buyers: "));
i = 1;
sum = i;
if women%2==0:
women=women-1;
while i < women:
i = i + 2;
sum = sum + i;
print("Total of flowers is: " + str(sum));
Related
I have this Python assigment to complete where I need to write a program that reads in X whole numbers and outputs (1) the sum of all positive numbers, (2) the sum of all negative numbers, and (3) the sum of all positive and negative numbers. The user can enter the X numbers in any different order every time, and can repeat the program if desired. This is what I've got so far:
x = int(input('How many numbers would you like to enter?: '))
sumAll = 0
sumNeg = 0
sumPos = 0
for k in range (0,x,1):
num = int(input("please enter number %i :" %(k+1)))
sumAll = sumAll + num
if num < 0:
sumNeg += num
if num > 0:
sumPos += num
if k == 0:
smallest = num
largest = num
else:
if num < smallest:
smallest = num
if num > largest:
largest = num
print("The sum of negative numbers is: " , sumNeg)
print("The sum of positive numbers is: " , sumPos)
print("The sum of all numbers is: " , sumAll)
count = 0
repeat = input('Would you like to repeat? y/n: ')
repeat = 'y'
while y == 'y':
I'm just a little stuck after this point. Any ideas on what I should do?
A simple while loop would suffice.
run = True
while run is True:
x = int(input('How many numbers would you like to enter?: '))
sumAll = 0
sumNeg = 0
sumPos = 0
for k in range (0,x,1):
num = int(input("please enter number %i :" %(k+1)))
sumAll = sumAll + num
if num < 0:
sumNeg += num
if num > 0:
sumPos += num
if k == 0:
smallest = num
largest = num
else:
if num < smallest:
smallest = num
if num > largest:
largest = num
print("The sum of negative numbers is: " , sumNeg)
print("The sum of positive numbers is: " , sumPos)
print("The sum of all numbers is: " , sumAll)
repeat = input('Would you like to repeat? y/n: ')
if repeat != 'y':
run = False
Example of the output:
How many numbers would you like to enter?: 4
please enter number 1 : 3
please enter number 2 : 2
please enter number 3 : 4
please enter number 4 : 5
The sum of negative numbers is: 0
The sum of positive numbers is: 14
The sum of all numbers is: 14
Would you like to repeat? y/n: y
How many numbers would you like to enter?: 3
please enter number 1 : 2
please enter number 2 : 4
please enter number 3 : 3
The sum of negative numbers is: 0
The sum of positive numbers is: 9
The sum of all numbers is: 9
Would you like to repeat? y/n: n
You just need to place your code inside an outer loop, that might start it all over again if the user wants to repeat.
while True:
# all your current code until the prints
repeat = input('Would you like to repeat? y/n: ')
if repeat is not 'y':
break
The inputs would be:
The initial number of organisms
The rate of growth (a real number greater than 1)
The number of hours it takes to achieve this rate
A number of hours during which the population grows
I have:
Population = int(input("The initial number of organisms: " ))
RateOfGrowth = int(input("The rate of growth (a real number > 0): " ))
HrToAchieve = int(input("The number of hours it takes to achieve this rate: " ))
Input_Hrs = int(input("Enter the total hours of growth: " ))
NewGrowth = 0
Passes = Input_Hrs/HrToAchieve
while Passes > 0:
NewGrowth = (Population * RateOfGrowth)-Population
Population += NewGrowth
Passes -= 1
print("The total population is", Population )
New at loops and not sure how I'm missing a pass
partially working with input 10,2,2,6 providing correct answer of 80
But when using 100 organisms with growth rate of 5 over 2 hrs over 25 hrs total, I get 7000 NOT
24414062500 which would be proper.
You can do that in one line and Im assuming if the growth rate of x is there in y hours and there are less than y hours left, then there wont be any growth whatsoever.
import math
ORG = int(input("The initial number of organisms: " ))
GR = int(input("The rate of growth (a real number > 0): " ))
GR_Hr = int(input("The number of hours it takes to achieve this rate: " ))
PG_Hr = int(input("Enter the total hours of growth: " ))
Growth = ORG * int(math.pow(GR, PG_Hr//GR_Hr)) # or Growth = ORG * int(GR ** (PG_Hr // GR_Hr))
EDIT USING LOOPS
Growth_using_loops = ORG
loop_counter = PG_Hr//GR_Hr # double slash // returns a integer instead of float
for i in range(loop_counter):
Growth_using_loops = Growth_using_loops * GR
print(Growth)
print(Growth_using_loops)
Output :
The initial number of organisms: 100
The rate of growth (a real number > 0): 5
The number of hours it takes to achieve this rate: 2
Enter the total hours of growth: 25
24414062500
24414062500
import random
sample_size = int(input("Enter the number of times you want me to roll the die: "))
if (sample_size <=0):
print("Please enter a positive number!")
else:
counter1 = 0
counter2 = 0
final = 0
while (counter1<= sample_size):
dice_value = random.randint(1,6)
if ((dice_value) == 6):
counter1 += 1
else:
counter2 +=1
final = (counter2)/(sample_size) # fixing indention
print("Estimation of the expected number of rolls before pigging out: " + str(final))
Is the logic used here correct? It will repeat rolling a die till a one is rolled, while keeping track of the number of rolls it took before a one showed up. It gives a value of 0.85 when I run it for high values(500+)
Thanks
import random
while True:
sample_size = int(input("Enter the number of times you want me to roll a die: "))
if sample_size > 0:
break
roll_with_6 = 0
roll_count = 0
while roll_count < sample_size:
roll_count += 1
n = random.randint(1, 6)
#print(n)
if n == 6:
roll_with_6 += 1
print(f'Probability to get a 6 is = {roll_with_6/roll_count}')
One sample output:
Enter the number of times you want me to roll a dile: 10
Probability to get a 6 is = 0.2
Another sample output:
Enter the number of times you want me to roll a die: 1000000
Probability to get a 6 is = 0.167414
Sticking with your concept, I would create a list that contains each roll then use enumerate to count the amount of indices between each 1 and sum those, using the indicies as markers.
the variable that stores the sum of the number of rolls it took before a 1 showed up - OP
from random import randint
sample_size = 0
while sample_size <= 0:
sample_size = int(input('Enter amount of rolls: '))
l = [randint(1, 6) for i in range(sample_size)]
start = 0
count = 0
for idx, item in enumerate(l):
if item == 1:
count += idx - start
start = idx + 1
print(l)
print(count)
print(count/sample_size)
Enter amount of rolls: 10
[5, 3, 2, 6, 2, 3, 1, 3, 1, 1]
7
0.7
Sameple Size 500:
Enter amount of rolls: 500
406
0.812
1) upon entering input >> 1 2 3 4 5 6 7
the result returned nothing. Must be the while loop i supposed?
2) Also for input such as >> 1 1 1 5 5 7 7 7 7
how do i remove duplicate of 1 and 7? ; meaning duplicate of min and max.
I plan to average the number input by removing duplicate of min and max.
Do i combine max() min() function with list(set(x)) or is there another way round?
New to python here. WHILE permitted only. Do not suggest For
even_sum, odd_sum = 0,0
evencount, oddcount = 0,0
count=0
n=0
s = raw_input("Please Input a series of numbers")
numbers = map(int, s.split())
while count<numbers:
if numbers[n]%2==0:
evencount = evencount +1# len(numbers)
even_sum += num
count=count+1
n=n+1
else:
oddcount = oddcount+1#len(numbers)
odd_sum += num
count=count+1
n=n+1
max123 = max(numbers)
min123 = min(numbers)
difference = max123 - min123
print numbers
numbers.remove(max(numbers))
numbers.remove(min(numbers))
average = sum(numbers)/float(len(numbers))
print "The summation of even and odd numbers are " + str(even_sum) + " and " + str(odd_sum)
print "The difference between biggest and smallest number is " + str(difference)
print "The count of even numbers and odd numbers are " + str(evencount) + " & " + str(oddcount)
print average
This is wrong:
while count<numbers:
You are comparing a number to a list. That is valid, but it does not do what you might expect. count<numbers is always true, so you are stuck in an infinite loop. Try it:
>>> 1000000 < [1, 2]
True
What you want to do instead is iterate through all numbers.
for number in numbers:
if number % 2 == 0:
...
You don't need count and you don't need n either.
Also, the else: should be indented, otherwise it will never be executed with this code.
Handicap mode (without for)
n = 0
odd_count = 0
odd_sum = 0
while n < len(numbers):
number = numbers[n]
if number % 2:
odd_count += 1
odd_sum += number
n += 1
# "even" values can be calculated from odds and totals
#This is modified code i did mark (#error) where your program didn't work
even_sum, odd_sum = 0,0
evencount, oddcount = 0,0
count=0
n=0
s = raw_input("Please Input a series of numbers")
numbers = map(int, s.split())
print (numbers)
while count<len(numbers): #error thats a list you have to convert that in to int
if numbers[n]%2==0:
evencount = evencount +1# len(numbers)
even_sum += numbers[n] #error index and variable not defined
count=count+1
n=n+1
else: #indented error
oddcount = oddcount+1#len(numbers)
odd_sum += numbers[n] #error index and variable not defined
count=count+1
n=n+1
max123 = max(numbers)
min123 = min(numbers)
difference = max123 - min123
numbers.remove(max(numbers))
numbers.remove(min(numbers))
average = sum(numbers)/float(len(numbers))
print "The summation of even and odd numbers are " + str(even_sum) + " and " + str(odd_sum)
print "The difference between biggest and smallest number is " + str(difference)
print "The count of even numbers and odd numbers are " + str(evencount) + " & " + str(oddcount)
Ask for an amount and whether it is taxable; calculate the sales tax and show the tax amount and the total including the tax; allow the user to do the sales tax calculation for multiple items.
Use 9.5% as the sales tax rate.
When the user finishes, tell what the grand total, tax and total, comes to.
Here is the data your demo.
Amount Taxable?
1 $10.00 Y
2 11.00 N
3 1.50 N
4 2.99 Y
5 12.00 Y
here is what i did , I don't know how to get the total in for loop in clist
alist = []
amount = eval(input("How many amount do you want to calculate?"))
for i in range(amount):
alist.append(input("amount" + str(i+1) + ":"))
print(alist)
blist = []
taxable = eval(input("How many amount taxable?"))
for n in range(taxable):
blist.append(input("amount_taxable" + str(n+1) + ":"))
print(blist)
clist = list(zip(alist,blist))
print(clist)
for a,b in clist:
print(a,b)
if b =='Y':
print("grand total" + ":", eval(a)*1.095)
print("tax" + ":" , eval(a)*.095)
print("total_of_taxable" + ":",len(clist)*eval(a)*1.095)
elif b == 'N':
print("not taxable")
print("total_of_not_taxable" + ":",eval(a)*len(clist))
I addition to Redi43's comment you should also
convert the values that you are appending to your lists to ints
not worry about starting the range at 0, as 0 is the default starting value
Something like this is a little better.
alist = []
blist = []
amount = int(input("How many amount do you want to calculate?"))
for i in range(amount):
alist.append(int(input("amount" + str(i+1) + ":")))
taxable = int(input("How many amount taxable?"))
for n in range(taxable):
blist.append(int(input("amount_taxable" + str(n+1) + ":")))
clist = list(zip(alist,blist))
print(clist)