Using for loops over while loops - python

How would one produce some code that counts up using a for loop as opposed to a while loop? My code is as follows;
def square():
count = 1
number = input("How far?")
number = int(number)
if number < 1:
print ("broken")
elif number >= 1:
while count <= number:
square = count*count
print ("{0}*{0}={1}".format(count, square))
count = count+1
square()

You can do it like that:
def square():
number = input("How far?")
number = int(number)
if number < 1:
print ("broken")
elif number >= 1:
for count in range(1,number+1):
square = count*count
print ("{0}*{0}={1}".format(count, square))
square()
Using the line
for count in range(1,number+1):
counts iterates over the values 1,2,...,number.

U can do it with list comprehensions like:
def square():
number = int(input("How far?"))
# range will be from 1 to number +1, and will proceed square for all
return [val ** 2 for val in range (1, number+1)]
squares = square()
if not squares:
print('broken')
# u can iterate over result even if list is empty(if u pass broken number)
for val in squares:
print ("{0}*{0}={1}".format(count, square))

Related

How do you find a median without using lists?

My teacher wants me to find the median of 10 inputs from the user by using iterations.
This is how I used iterations to find the sum, number of odd numbers, the max, and the number of prime numbers. But I'm stuck on finding the median.
def Main(): #main function
sum=0
odd=0
temp=0
prime=0
median=0
for i in range(10):
x=float(input("Please enter a number")) #ask user for input 10 times
sum=sum+x #adds all inputs together
if x%2!=0: #all even numbers are divisible by 2
odd=odd+1
if x>=temp: #update temp with current largest input
temp=x
for p in range (2,int(math.sqrt(x))+1):#find prime numbers
if x>=2 and x%p==0: prime=prime+1
import math
def Main(): #main function
sum=0
odd=0
temp=0
prime=0
median=0
my_list =[]
for i in range(10):
x=float(input("Please enter a number: ")) #ask user for input 10 times
sum=sum+x #adds all inputs together
if x%2!=0: #all even numbers are divisible by 2
odd=odd+1
if x>=temp: #update temp with current largest input
temp=x
for p in range (2,int(math.sqrt(x))+1):#find prime numbers
if x>=2 and x%p==0: prime=prime+1
my_list.append(x)
my_list.sort()
size =len(my_list)
if size == 1:
median = my_list[0]
elif size % 2 == 0:
size = int(size/2)
median=(my_list[size-1]+my_list[size])/2
else:
median = my_list[int(size / 2)]
print("sum is ", sum, ",odd is ", odd, ",temp is ", temp, ",prime is ", prime, "median is ", median)
Main()
First of all, as a user pointed out in a comment to your question, your method to determine prime numbers is not correct. You only should increase that counter after all factors have been checked, not after each one.
There are a few questions on StackOverflow that show how to calculate primes in python; here is a slightly improved version of your code with that error fixed (and some style improvement suggestions):
def main():
sum = 0
counter_odd = 0
max_num = None
min_num = None
counter_prime = 0
median = 0
for i in range(10):
x = float(input("Please enter a number"))
sum += x
if x % 2 != 0:
counter_odd += 1
if max_num is None or max_num < x:
max_num = x
if min_num is None or min_num > x:
min_num = x
if x == 0 or x == 1:
counter_prime += 1
elif x > 1:
if not any(x % d == 0 for d in range(2, int(math.sqrt(x)) + 1)):
counter_prime += 1
As to your main question: there are several questions on SO about finding medians in unsorted lists (that would be very similar to searching for medians without having the whole list at the beginning). Maybe search for that without the Python tag, so you get to see some algorithms without tying to a specific language.
For example, in this question you can find the suggestion to use the median of medians approach (Wikipedia).

Python: Create two lists from loop and sum both

I'm working on a credit project of CS50 and I have some problem with the verification of the credit card.
Here the function I create:
def main():
while True :
cardnumber = input("Please enter a credit card number: ")
if cardnumber.isdecimal() and int(cardnumber) > 0 :
break
count = len(cardnumber)
if count != 13 and count != 15 and count != 16:
print("INVALID")
else:
check(count, cardnumber)
def check(length, number):
lenght_max = 15
if length == 15 and int(number[0]) == 3 and (int(number[1]) == 4 or int(number[1]) == 7):
if validator(number):
print("AMEX")
elif length == 16 and int(number[0]) == 5 and int(number[1]) <= 5:
if validator(number):
print("MASTERCARD")
elif length == 16 or length == 13 and int(number[0]) == 4:
if validator(number):
print("VISA")
else:
print("INVALID")
return number
def validator(num):
sum = 0
while num > 0:
sum += num % 10
num = num // 10
return sum
odd = [int(num[i]) * 2 for i in range(1, len(num), 2)]
even = [int(num[i]) for i in range(0, len(num), 2)]
new_sum = sum(validator(x) for x in odd) + sum(even)
if(new_sum % 10 == 0):
return True
else:
print("INVALID")
main()
I found the way to print the evens and the odds(multiply also time 2) but now I have to sum booth and check if the remainder is 0
Here the complete instruction:
http://docs.cs50.net/problems/credit/credit.html
Write a helper function to sum your digits. You'll need to use it extensively.
def dig_sum(num):
sum = 0
while num > 0:
sum += num % 10
num = num // 10
return sum
num = '378282246310005' # your credit card number
odd = [int(num[i]) * 2 for i in range(1, len(num), 2)] # these two remain the same
even = [int(num[i]) for i in range(0, len(num), 2)]
new_sum = sum(dig_sum(x) for x in odd) + sum(even)
if(new_sum % 10 == 0):
print('Valid') #valid!
sum(dig_sum(x) for x in odd) will get the digit sum for each number in your odd list and sum(...) that finds the resultant sum.
Input:
'378282246310005'
Output:
Valid
A first problem with your function is that you do not store the even/odd digits somewhere: you construct a list with one element each time, and print that element.
Now since two times a digit, can only result in a two digit number, we can use:
def sum2(x):
return (2*x)//10 + (2*x)%10
You can construct a list of all the digits at odd index with:
odd = [int(number[i]) for i in range(1,length,2)]
The same for digits at even index:
even = [int(number[i]) for i in range(0,length,2)]
Now we can simply use the sum(..) builtin function to sum up the digits:
total = sum(sum2(oddi) for oddi in odd) + sum(even)
and check if it is a multiple of 10:
return total%10 == 0
Or putting it all together:
def validator(number, length):
odd = [int(number[i]) for i in range(1,length,2)]
even = [int(number[i]) for i in range(0,length,2)]
total = sum(sum2(oddi) for oddi in odd) + sum(even)
return total%10 == 0
Or we can use a the following one liner for experts:
from itertools import zip_longest
def validator(number,length):
numbi = iter(numbi)
return sum(x+sum2(y) for x,y in zip_longest(numbi,numbi,fillvalue=0))%10 == 0

finding emrips with python, what am i doing wrong?

An Emirp is a prime number whose reversal is also a prime. For
example, 17 is a prime and 71 is a prime, so 17 and 71 are emirps.
Write a program that prints out the first N emirps, five on each line.
Calculate the first N emirp (prime, spelled backwards) numbers, where
N is a positive number that the user provides as input.
Implementation Details
You are required to make use of 2 functions (which you must write).
isPrime(value) # Returns true if value is a prime number. reverse
(value) # Returns the reverse of the value (i.e. if value is 35,
returns 53). You should use these functions in conjunction with logic
in your main part of the program, to perform the computation of N
emirps and print them out according to the screenshot below.
The general outline for your program would be as follows:
Step 1: Ask user for positive number (input validation) Step 2:
Initialize a variable Test to 2 Step 3: While # emirps found is less
than the input:
Call isPrime with Test, and call it again with reverse(Test).
If both are prime, print and increment number of emirps found. Test++ Hint - to reverse the number, turn it into a string and then
reverse the string. Then turn it back into an int!
MY CODE:
n = 0
count = 0
i = 1
def isPrime(value):
test = 2
count = 0
while(test < value):
if( value % test == 0):
count+=count
test+=test
if(count == 0):
return 1
else:
return 0
def reverse(value):
reverse = 0
while(value > 0):
reverse = reverse * 10 + (value % 10)
value = value / 10
return reverse
n = float(input("Please enter a positive number: "))
while(count < n):
i+=i;
if(isPrime(i)):
if(isPrime(reverse(i))):
print("i" + "\n")
count+=count
if((count % (5)) == 0 ):
print("\n")
where are the mistakes?
UPDATED CODE BUT STILL NOT RUNNING:
n = 0
count = 0
i = 1
def isPrime(value):
test = 2
while(test < value):
if( value % test != 0):
test +=1
else:
return 0
def reverse(value):
return int(str(value)[::-1])
i = int(input("Please enter a positive number: "))
count = 0
while(count < 5):
if(isPrime(i)):
if(isPrime(reverse(i))):
print(str(i) + "\n")
count += 1
i += 1
else:
i += 1
else:
i +=1
There are a lot of issues with your code. I altered the function isPrime. There is among other no need for count here and if you want to increment test by 1 every loop use test +=1:
def isPrime(value):
test = 2
while(test < value):
if( value % test != 0):
test +=1
else:
return 0
return 1
There is an easy way to reverse digits by making value a string in reversed order and to convert this into an integer:
def reverse(value):
return int(str(value)[::-1])
You among other have to assign the input to i. n in your code is a constant 5. You have to increment i by one in any condition and increment the count by one if i is an emirp only:
i = int(input("Please enter a positive number: "))
count = 0
while(count < 5):
if(isPrime(i)):
if(isPrime(reverse(i))):
print(str(i) + "\n")
count += 1
i += 1
else:
i += 1
else:
i +=1
def emrip_no(num):
i=0
j=0
for i in range(1,num+1):
a=0
for j in range(1,i+1):
if(i%j==0):
a+=1
if(a==2):
print("Number is a prime number")
k=0
l=0
rv=0
while(num!=0):
r=num%10
rv=(rv*10)+r
num=num//10
print("It's reverse is: ",rv)
for k in range(1,rv+1):
b=0
for l in range(1,k+1):
if(k%l==0):
b+=1
if(b==2):
print("It's reverse is also a prime number")
else:
print("It's reverse is not a prime number")
n=int(input("Enter a number: "))
emrip_no(n)

(Python) Stuck on skipping range values for the sum of a randint list

I need to make a program in python that generates ten random numbers from 1-100 that stores it in a list using a loop. Then a second loop should display said list, then calculate the sums of the even and odd elements to display them. This is what I have so far, any help is greatly appreciated. Thanks
import random
def main():
numlist = [0] * 10
for r in range(10):
numlist[r] = random.randint(1,100)
print(numlist)
list_length = len(numlist)
print('The number of elements in the list is', list_length)
More specifically this is the part I'm stuck on. I have to add the sums of the odd and then even elements. Every work around I've tryed has only given me the sum of the total elements.
for x in range(0, 10, 2):
numlist[x] = numlist
print('The Sum of the odd numbers is ', sum(numlist))
main()
import random
nums = [random.randint(1,100) for _ in range(10)]
You can use lambdas and filter
evenSum = sum(filter(lambda i : i%2 == 0, nums))
oddSum = sum(filter(lambda i : i%2, nums))
Or make some quick helper functions
def isEven(x):
return x % 2 == 0
def isOdd(x):
return x % 2 == 1
evenSum = sum(filter(isEven, nums))
oddSum = sum(filter(isOdd, nums))
Using your own code:
def main():
numlist = [] # create empty list to add randints to
for r in range(10):
numlist.append(random.randint(1,100)) # append to the list
list_length = len(numlist)
print('The number of elements in the list is', list_length)
odd = 0
even = 0
for num in numlist:
if num % 2: # if num mod 2 has a remainder, num is odd
odd += num
else: # else num is even
even += num
print('The Sum of the odd numbers is {} and even numbers is {}'.format(odd,even))
You can replace the first loop with a list comp:
numlist = [random.randint(1,100) for _ in range(10)]
Can't Understand the actual problem (hahehehe !)
As far as I have understood, you want to print the sum of odd and even numbers of the list that is generated from randint(). Well I have just edited your code ;)
so here is the simple done code !
Vote If It Helps !
import random
def main():
odd_sum=0
even_sum=0
numlist = [0] * 10
for r in range(10):
numlist[r] = random.randint(1,100)
print numlist
list_length = len(numlist)
print('The number of elements in the list is', list_length)
for i in numlist:
if (i%2 == 1): #the remainder is 1 if the number is odd
odd_sum = odd_sum + i #add the odd_numbers
elif(i%2 == 0): #the remainder is 0 if the number is even
even_sum = even_sum + i #add the even_numbers
else:
print "No need of this else part !"
print "Odd_sum = ",odd_sum
print "Even_sum = ",even_sum
main()

Python Coin Toss

I am VERY new to Python and I have to create a game that simulates flipping a coin and ask the user to enter the number of times that a coin should be tossed. Based on that response the program has to choose a random number that is either 0 or 1 (and decide which represents “heads” and which represents “tails”) for that specified number of times. Count the number of “heads” and the number of “tails” produced, and present the following information to the user: a list consisting of the simulated coin tosses, and a summary of the number of heads and the number of tails produced. For example, if a user enters 5, the coin toss simulation may result in [‘heads’, ‘tails’, ‘tails’, ‘heads’, ‘heads’]. The program should print something like the following: “ [‘heads’, ‘tails’, ‘tails’, ‘heads’, ‘heads’]
This is what I have so far, and it isn't working at all...
import random
def coinToss():
number = input("Number of times to flip coin: ")
recordList = []
heads = 0
tails = 0
flip = random.randint(0, 1)
if (flip == 0):
print("Heads")
recordList.append("Heads")
else:
print("Tails")
recordList.append("Tails")
print(str(recordList))
print(str(recordList.count("Heads")) + str(recordList.count("Tails")))
You need a loop to do this. I suggest a for loop:
import random
def coinToss():
number = input("Number of times to flip coin: ")
recordList = []
heads = 0
tails = 0
for amount in range(number):
flip = random.randint(0, 1)
if (flip == 0):
print("Heads")
recordList.append("Heads")
else:
print("Tails")
recordList.append("Tails")
print(str(recordList))
print(str(recordList.count("Heads")) + str(recordList.count("Tails")))
I suggest you read this on for loops.
Also, you could pass number as a parameter to the function:
import random
def coinToss(number):
recordList, heads, tails = [], 0, 0 # multiple assignment
for i in range(number): # do this 'number' amount of times
flip = random.randint(0, 1)
if (flip == 0):
print("Heads")
recordList.append("Heads")
else:
print("Tails")
recordList.append("Tails")
print(str(recordList))
print(str(recordList.count("Heads")) + str(recordList.count("Tails")))
Then, you need to call the function in the end: coinToss().
You are nearly there:
1) You need to call the function:
coinToss()
2) You need to set up a loop to call random.randint() repeatedly.
I'd go with something along the lines of:
from random import randint
num = input('Number of times to flip coin: ')
flips = [randint(0,1) for r in range(num)]
results = []
for object in flips:
if object == 0:
results.append('Heads')
elif object == 1:
results.append('Tails')
print results
This is possibly more pythonic, although not everyone likes list comprehensions.
import random
def tossCoin(numFlips):
flips= ['Heads' if x==1 else 'Tails' for x in [random.randint(0,1) for x in range(numflips)]]
heads=sum([x=='Heads' for x in flips])
tails=numFlips-heads
import random
import time
flips = 0
heads = "Heads"
tails = "Tails"
heads_and_tails = [(heads),
(tails)]
while input("Do you want to coin flip? [y|n]") == 'y':
print(random.choice(heads_and_tails))
time.sleep(.5)
flips += 1
else:
print("You flipped the coin",flips,"times")
print("Good bye")
You could try this, i have it so it asks you if you want to flip the coin then when you say no or n it tells you how many times you flipped the coin. (this is in python 3.5)
Create a list with two elements head and tail, and use choice() from random to get the coin flip result. To get the count of how many times head or tail came, append the count to a list and then use Counter(list_name) from collections. Use uin() to call
##coin flip
import random
import collections
def tos():
a=['head','tail']
return(random.choice(a))
def uin():
y=[]
x=input("how many times you want to flip the coin: ")
for i in range(int(x)):
y.append(tos())
print(collections.Counter(y))
Instead of all that, you can do like this:
import random
options = ['Heads' , 'Tails']
number = int(input('no.of times to flip a coin : ')
for amount in range(number):
heads_or_tails = random.choice(options)
print(f" it's {heads_or_tails}")
print()
print('end')
I did it like this. Probably not the best and most efficient way, but hey now you have different options to choose from. I did the loop 10000 times because that was stated in the exercise.
#Coinflip program
import random
numberOfStreaks = 0
emptyArray = []
for experimentNumber in range(100):
#Code here that creates a list of 100 heads or tails values
headsCount = 0
tailsCount = 0
#print(experimentNumber)
for i in range(100):
if random.randint(0, 1) == 0:
emptyArray.append('H')
headsCount +=1
else:
emptyArray.append('T')
tailsCount += 1
#Code here that checks if the list contains a streak of either heads or tails of 6 in a row
heads = 0
tails = 0
headsStreakOfSix = 0
tailsStreakofSix = 0
for i in emptyArray:
if i == 'H':
heads +=1
tails = 0
if heads == 6:
headsStreakOfSix += 1
numberOfStreaks +=1
if i == 'T':
tails +=1
heads = 0
if tails == 6:
tailsStreakofSix += 1
numberOfStreaks +=1
#print('\n' + str(headsStreakOfSix))
#print('\n' + str(tailsStreakofSix))
#print('\n' + str(numberOfStreaks))
print('\nChance of streak: %s%%' % (numberOfStreaks / 10000))
#program to toss the coin as per user wish and count number of heads and tails
import random
toss=int(input("Enter number of times you want to toss the coin"))
tail=0
head=0
for i in range(toss):
val=random.randint(0,1)
if(val==0):
print("Tails")
tail=tail+1
else:
print("Heads")
head=head+1
print("The total number of tails is {} and head is {} while tossing the coin {} times".format(tail,head,toss))
Fixing the immediate issues
The highest voted answer doesn't actually run, because it passes a string into range() (as opposed to an int).
Here's a solution which fixes two issues: the range() issue just mentioned, and the fact that the calls to str() in the print() statements on the last two lines can be made redundant. This snippet was written to modify the original code as little as possible.
def coinToss():
number = int(input("Number of times to flip coin: "))
recordList = []
heads = 0
tails = 0
for _ in range(number):
flip = random.randint(0, 1)
if (flip == 0):
recordList.append("Heads")
else:
recordList.append("Tails")
print(recordList)
print(recordList.count("Tails"), recordList.count("Heads"))
A more concise approach
However, if you're looking for a more concise solution, you can use a list comprehension. There's only one other answer that has a list comprehension, but you can embed the mapping from {0, 1} to {"Heads", "Tails"} using one, rather than two, list comprehensions:
def coinToss():
number = int(input("Number of times to flip coin: "))
recordList = ["Heads" if random.randint(0, 1) else "Tails" for _ in range(number)]
print(recordList)
print(recordList.count("Tails"), recordList.count("Heads"))
import random
def coinToss(number):
heads = 0
tails = 0
for flip in range(number):
coinFlip = random.choice([1, 2])
if coinFlip == 1:
print("Heads")
recordList.append("Heads")
else:
print("Tails")
recordList.append("Tails")
number = input("Number of times to flip coin: ")
recordList = []
if type(number) == str and len(number)>0:
coinToss(int(number))
print("Heads:", str(recordList.count("Heads")) , "Tails:",str(recordList.count("Tails")))
All Possibilities in Coin Toss for N number of Coins
def Possible(n, a):
if n >= 1:
Possible(n // 2, a)
z = n % 2
z = "H" if z == 0 else "T"
a.append(z)
return a
def Comb(val):
for b in range(2 ** N):
A = Possible(b, [])
R = N - len(A)
c = []
for x in range(R):
c.append("H")
Temp = (c + A)
if len(Temp) > N:
val.append(Temp[abs(R):])
else:
val.append(Temp)
return val
N = int(input())
for c in Comb([]):
print(c)
heads = 1
tails = 0
input("choose 'heads' or 'tails'. ").upper()
random_side = random.randint(0, 1)
if random_side == 1:
print("heads you win")
else:
print("sorry you lose ")

Categories

Resources