Coin Simulator - Python 3 - Using Lists & Count() - python-3.x

I'm just playing around with lists and have stumbled across an issue with my code. I can't figure out why my count() won't actually work and display the final total for the heads and tails. It prints 0 rather than what's in the new list..? I've tested the print newlist and it is showing that the list is updating once the loop has completed.
Can anyone help me fix this and explain what I am doing wrong?
Thanks!
import random
i = 0
spins = int(input ("How many spins do you want to do? "))
coin = ["heads", "tails"]
newList = []
while i < spins:
i = i+1
spin = random.sample(set(coin),1)
tallyCoin = spin
print (tallyCoin)
newList.append(tallyCoin)
if i >= spins:
print (newList)
totalHeads = newList.count("heads")
totalTails = newList.count("tails")
print ("the total heads for this round were: ", totalHeads)
print ("the total tails for this round were: ", totalTails)

random.sample returns a list so you are collecting lists with a single string in it instead of strings. Try random.sample(coin, 1)[0] instead.

Related

Python 3.7.3 Inconsistent code for song guessing code, stops working at random times

I have a python code that is a song guessing game, you are given the artist and the songs first letter, I used 2 2d arrays with on being the artist and the other being the song. I know I should've done a 3d array though to change it this late into my code I'd have to restructure the whole code and I wouldn't have time. Here is the appropriate code below:
attemptnum = 5
attempts = 0
for x in range (10):
ArtCount = len(artist)
print(ArtCount)
randNum = int(random.randint(0, ArtCount))
randArt = artist[randNum]
ArtInd = artist.index(randArt)# catches element position (number)
songSel = songs[randNum]
print ("The artist is " + randArt)
time.sleep(1)
print( "The songs first letter be " + songSel[0])
time.sleep(1)
print("")
question = input("What song do you believe it to be? ")
if question == (songSel) or ("c"):
songs.remove(songSel)
artist.remove(randArt)
print ("Correct")
print ("Next Question")
else:
attempts = attempts + 1
att = attemptnum = attemptnum - attempts
print("")
print("Wrong,")
print (att) and print (" attempts left.")
print("")
time.sleep(0.5)
if attempts == 5:
print("GAME OVER")
#input leaderboard here
print("Exiting in 3 seconds")
time.sleep(3)
exit()
Apologies if my code isn't so polished, this is a project for school. So what this code does is randomly a number from 0 to the number of how many elements the artist's list has. It then chooses an artist using the random number, it catches the number used with index so that it can be used on the songs array to get the corresponding song (I know very bad) It pitches the question and shows the first letter of the song. If you get the song you get the same code again but with the prior song and artist removed to prevent dupes. That's where the problem comes in, when usually running the code it'll randomly give me the error where the element I'm trying to output is not in the list:
randArt = artist[randNum]
IndexError: list index out of range
This can happen anywhere throughout the code when you're being asked a question, you can get to question 3 and get the error, or not even get to question 9 and get the error. It's completely random. I feel like its trying to occasionally get a hold of an artist and song that's been removed but that doesn't make sense since it only chooses from the amount counted on the list, not the original 10. I'm not sure if my way of saying it is right or if any one would understand, because I sure don't. To clarify, my code counts how many elements there are in the list, uses that number to find a song and artist, then removes it after to stop duping, but from what I can see it seems like it's trying to find and element simply out of the range of how many elements there actually are. Thanks for bearing with my amateur code.
random.randint is inclusive in both ends. randint(0, 10) will return a number in the range
0 <= _ <= 10.
However Python uses 0-based indexes.
If li is [1, 2, 3] then len(li) is 3, but li[3] does not exist.
Only li[0], li[1] and li[2] do.
When you are doing
ArtCount = len(artist)
randNum = int(random.randint(0, ArtCount))
randArt = artist[randNum]
You are asking for a number in the range 0 <= n <= len(artist). If n == len(artist) then artist[n] will cause an IndexError.
BTW, randint returns an int (hence the int in its name). int(randint(...)) is totally unnecessary.
You should either ask for a random number in the range 0 <= n <= len(artist) - 1 or simply use random.choice:
randArt = random.choice(artist)
You may want to catch an IndexError just in case artist is an empty list:
try:
randArt = random.choice(artist)
except IndexError:
print('artist list is empty')

Comparing spaces in python

I am creating a cipher script in python without any modules but I have come accross a problem that i cant solve. When I am comparing msg[3] which has the value (space) it should be equal to bet[26] which is also a space. If i compare msg[3] with bet[26] in the shell...
>>>msg[3] == bet[26]
True
The output is True. However when i run the program and output the value of enmsg there is no value 26 where the value 26 should be.
enmsg = []
msg = "try harder"
bet = "abcdefghijklmnopqrstuvwxyz "
for x in range(0, len(msg)):
for i in range(0, 26):
if msg[x] == bet[i]:
print(msg[x])
enmsg.append(i)
You should get out of the habit of iterating over a range of indices and then looking up the value at the index. Instead iterate directly over your iterables, using enumerate when necessary.
enmsg = []
msg = "try harder"
bet = "abcdefghijklmnopqrstuvwxyz "
for msg_char in msg:
for index, bet_char in enumerate(bet):
if msg_char == bet_char:
print(msg_char)
enmsg.append(index)
Your second loop iterations are too short so it is not reaching the space symbol.
Try with this:
enmsg = []
msg = "try harder"
bet = "abcdefghijklmnopqrstuvwxyz "
for x in range(0, len(msg)):
for i in range(len(bet)):
if msg[x] == bet[i]:
print(msg[x])
enmsg.append(i)
The upper bound of range is not inclusive; you'll need to extend this by one to actually check the 26th index of the string. Better yet, iterate up through len(bet) as you did for len(msg) for the outer loop.

while-loop to number 6174

I'am beginner in programming and have struggled for a while with one task.
Want to write a program wich finds out how many iterations is needed to arrive at the number 6174 from the specified number.
For example.: if I take number 2341 and sort it.
1) 4321-1234=3087
2) 8730-378=8352
3) 8532-2358=6174 (in this case it`s needed 3 iterations.)
And I have to use ,,while loop,, that it runs a code until it comes to number 6174 and stops.
I wrote a code:
n =input('write for nummbers ')
n=str(n)
i=0
i+=1 #"i" show how many times iteration happend.
large = "".join(sorted(n, reverse=True))
little = "".join(sorted(n,))
n = int(large) - int(little)
print(n, i)
Can you give mee some hint how I could run it with while loop.
# untested, all bugs are free ;)
n = input('write for nummbers ')
n = int(n) # you need n as a number
i=0
while n != 6174:
i += 1 #"i" show how many times iteration happened.
large = "".join(sorted(str(n), reverse=True))
little = "".join(sorted(str(n),))
n = int(large) - int(little)
print(n, i)

Finding the additive and multiplicative roots of a number using python

http://www.cs.uni.edu/~diesburg/courses/cs1510_sp15/homework/PA04/index.htm
So I have this assignment. I have been trying to work out the code to find the additive and multiplicative roots of a user given input. I am new to python and know how to work the problem out, but without the tools (coding know how) have been just running in circles for quite a while now. So if anyone could be so kind as to help me figure out the coding. I have tried slicing the list, but keep getting an error if I try to make the string an int and if I leave it as an string it just doesn't seem to run. I know there is probably a way using modulous as well, but have yet to quite master it.
Thank you for any help any of you are able to leave me.
Edit
Here is the code I have so far.
import sys
userStr = input("What number should I use for my \
calculations? ")
userInt = int (userStr)
original = userStr #Save Copy of original value
originalTwo = userStr #Save second Copy of original value
addCount = 0
mulCount = 0
#Stop the program if the integer is less than or equal to 0
while userInt <= 0:
print ("Thanks for playing along!")
sys.exit()
#Use a while loop to repeat the process of splitting an integer into single digits and then adding the individual digits.
print = ("Addition")
while userInt > 9:
userInt = sum(map(int, userStr))
print("New Value: ",userStr)
addCount = addCount + 1
#Use a while loop to repeat the process of splitting an integer into single digits and then multiplying the individual digits.
print = ("Multiplication")
while original > 9:
original = (map (int, original))
print("New Value: ",original)
mulCount = mulCount + 1
#Print the outputs to the screen for the user.
print("For the Integer: ",userInt)
print(" Additive Persistence= ",addCount,", Additive Root= ", userInt)
print(" Multiplicative Persistence= ",mulCount,",
Multiplicative Root= ", original)

Beginner Python: Where to "while"?

tl;dr: My code "works", in that it gives me the answer I need. I just can't get it to stop running when it reaches that answer. I'm stuck with scrolling back through the output.
I'm a complete novice at programming/Python. In order to hone my skills, I decided to see if I could program my own "solver" for Implied Equity Risk Premium from Prof. Damodaran's Valuation class. Essentially, the code takes some inputs and "guesses and tests" a series of interest rates until it gets a "close" value to the input.
Right now my code spits out an output list, and I can scroll back through it to find the answer. It's correct. However, I cannot for the life of me get the code to "stop" at the correct value with the while function.
I have the following code:
per = int(input("Enter the # of periods forecast ->"))
divbb = float(input("Enter the initial dividend + buyback value ->"))
divgr = float(input("Enter the div + buyback growth rate ->"))
tbondr = float(input("Enter the T-Bond rate ->"))+0.000001
sp = int(input("Enter the S&P value->"))
total=0
pv=0
for i in range(1,10000):
erp = float(i/10000)
a = divbb
b = divgr
pv = 0
temppv = 0
print (sp-total, erp)
for i in range(0, per):
a=a * (1+b)
temppv = a / pow((1+erp),i)
pv=pv+temppv
lastterm=(a*1+tbondr)/((erp-tbondr)*pow(1+erp,per))
total=(pv+lastterm)
From his example, with the inputs:
per = 5
divbb = 69.46
divgr = 0.0527
tbondr = 0.0176
sp = 1430
By scrolling back through the output, I can see my code produces the correct minimum at epr=0.0755.
My question is: where do I stick the while to stop this code at that minimum? I've tried a lot of variations, but can't get it. What I'm looking for is, basically:
while (sp-total) > |1|, keep running the code.
per = 5
divbb = 69.46
divgr = 0.0527
tbondr = 0.0176
sp = 1430
total=0
pv=0
i = 1
while(abs(sp-total)) > 1:
erp = i/10000.
a = divbb
b = divgr
pv = 0
temppv = 0
print (sp-total, erp)
for j in range(0, per):
a=a * (1+b)
temppv = a / pow((1+erp),j)
pv=pv+temppv
lastterm=(a*1+tbondr)/((erp-tbondr)*pow(1+erp,per))
total=(pv+lastterm)
i += 1
should work. Obviously, there are a million ways to do this. But the general gist here is that the while loop will stop as soon as it meets the condition. You could also test every time in the for loop and include a break statement, but because you don't know when it will stop, I think a while loop is better in this case.
Let me give you a quick rundown of two different ways you could solve a problem like this:
Using a while loop:
iterator = start value
while condition(iterator):
do some stuff
increment iterator
Using a for loop:
for i in xrange(startvalue, maxvalue):
do some stuff
if condition:
break
Two more thing: if you're doing large ranges, use the generator xrange. Also, it's probably a bad idea to reuse i inside your for loop.
I recommend CS101 from Udacity.com for learning Python. Also, if you're interested in algorithms, work through the problems at projecteuler.com

Resources