PYTHON parameter passing with lists - python

When passing a parameter into my function, it will not recognize the list and output the string.
The game is called pass the pigs, and it is required to output a state that the pig lands on.
I know in places that the code is inefficient, though this is due to the fact that I have been trying different methods that have no succeeded :(
Thanks in advance for any help!
Here is code:
norolls = int(input("Enter the number of rolls: "))
counter = 0
def roll(nothrows,counter):
rollList = []
while counter < nothrows:
rollrand = randint(0,100)
rollList.append(rollrand)
counter = (counter + 1)
return rollList
rollList = roll(norolls,counter)
rollList = list(map(int, rollList))
listlen = len(rollList)
def rollout(List, listpos, ListLen):
listpos = 0
for x in range(ListLen):
if List[listpos] == 1< 35:
print("Pink")
elif List[listpos] == 35 < 65:
print("Dot")
elif List[listpos] == 65< 85:
print("Razorback")
elif List[listpos] == 85 < 95:
print("Trotter")
elif List[listpos] == 95 < 99:
print("Snouter")
else:
List[listpos] == 99 < 100
print("Leaning Jewler")
listpos = (listpos + 1)
rollout(rollList, counter, listlen)

I'm assuming you want if List[listpos] == 1< 35 to mean List[listpos] is between 1 and 35, with 35 not being included.
The way to write that is:
if 1 <= List[listpos] < 35:
But, in your case, you don't really need a 3 level condition, since the only the first true if statement will run. So, you can just simply do:
if List[listpos] < 35:
print("Pink")
elif List[listpos] < 65:
...
and so on.

I have too low reputation to comment, but I'm going to try and clarify the code a little and give my answer.
For starters, one thing you should know is that list is a reserved name, so I don't recommend passing it as an argument to any function. You should be passing rollList to rollout(), since that is the list that you are creating. The way to pass a list as an argument is like this:
list_name = [1,2,3,4,5]
def function_name(myList=[]):
for x in myList:
print x
function_name(list_name)
Note the myList=[] in the function definition.
I would also get rid of counter and listlen as arguments, since you are setting counter to 0 at the beginning of the function, and listlen can be found with the len() function.
Secondly, for your equality statements, type them in like this:
if list_name[listpos] >= 1 and list_name[listpos] < 35
I'm sure there's a shorter way to do it, but this would help you visualize it as a range of values.

Since there are only 100 possible rolls (you do not assign an interpretation to 0) there is an alternative approach: replace the if-elif-else change with a lookup table mapping rolls to names. The code below does this. It also creates a list of rolls with a list comprehension.
from random import randint
rollmap = [None]
for sublist in (35*['Pink'], 30*['Dot'], 20*['Razorback'],
10*['Trotter'], 4*['Snouter'], 1*['Leaning Jewler']):
rollmap.extend(sublist)
n = int(input("Enter the number of rolls: "))
rolls = [randint(1, len(rollmap-1)) for i in range(n)]
for roll in rolls:
print(rollmap[roll])

Related

How do I create a loop that squares an integer until it reaches a certain number of digits?

The task:
Using python, create a function that uses a loop to determine how many
times a number can be squared until it reaches at least a twenty eight
digit number.
Ex: It takes three times to reach a three digit number, starting with
2: 2^2 = 4, 4^2 = 16, 16^2 = 256
Below is what I've tried:
def squaring():
maximum = int(len(28))
for i in range(3, maximum):
print(i**2)
I've also tried:
def squaring():
i = 3
while len(str(i)) < 28:
i = i ** 2
print(i)
Your first example doesn't work, as len is not defined for integers.
Your second example is actually quite right: You can add a counter to check how many times you've multiplied the original number:
def squaring():
counter = 0
i = 3
while len(str(i)) < 28:
i = i ** 2
counter += 1
print(i)
return counter
print(f'The number of squares: {squaring()}')
It's not really necessary to convert anything to a string. It can be done like this:
def count_squares(n):
count = 0
while n < 10**27+1:
n *= n
count += 1
return count
print(count_squares(3))
Output:
6
A Update to the function you created, just passing a parameter to pass number of your choice and adding a iterator 'i' in order to get x-times the number is squared
def squaring(input_number):
number = input_number
i = 0
while len(str(number)) <= 28:
number = number ** 2
i += 1
print(number)
return str(i)+'x'
You can transform the number into a string and you evaluate the len len(str(i**2)) and put a condition
You can Use While True until your Conditions occur!
‍‍
_iter = 0
i = 2
while True:
i = i**2
_iter += 1
if len(str(i)) >=28:
break
print(_iter)

Counter through embedded if statements inside for loop

So, I have a script in python (2.7) that makes a list of 1000000 numbers between 1 and 5000 and then runs a for loop over the entire list checking each element against multiple embedded if statments.
ex:
i = 0
for number in random_list:
i += 1
if random_list[number] <= 3000:
i += 1
if random_list[number] <= 300:
i += 1
if random_list[number] <= 30:
i += 1
if random_list [number] <= 3:
i += 1
break
print i
the whole point being I want to see how many "checks" occur over the entire list.
unfortunately my i value is less than the total number of elements in the list which should not be the case since each element should be checked at least once. I'm getting something in the range of 1000's to 10000's.
I'm sure there's a more pythonic way of doing this, so any advice on how to achieve what I'm trying will be greatly appreciated.
extra = 0
values = (random_list[number] for i,number in enumerate(my_numbers))
for v in values:
extra += sum(v < x for x in [3000,300,30,3])
if v < 3:break;
print i+extra
maybe ...

Python3.4 - math with index numbers

My objective was to use the index of a list to do addition/subtraction with. Where by I turned the even index positive, and the odd index negative.
EX1: 1234508 Should be answered by a 0: 1-2+3-4+5-0+8 = 11, then the while loops it again and I get 1-2+1 = 0
Ex2: 12345 Should be answered by a 3: 1-2+3-5 = 3, so it shouldn't go through the loop again.
Ex3: 121 Should be answered by a 0: 1-2+1 = 0, so it shouldn't go throught he loop again.
def main():
print()
print("Program to determine if a number is evenly\ndivisible by 11")
print()
indexed = input("Enter a number: ",)
total = 0
num = 0
while num >= 10:
for item in indexed:
if num %2 == 0:
total = total + int(item)
else:
total = total - int(item)
num = num + 1
print(total)
main()
Note that this print statement above is a place holder for a if statement which is inactive on my code, but was printing as large bold print here.
Let's say you have a string st whose characters are all digits, and that you want to have the sum of these digits. You then define the following function
def sd(st):
return sum(int(d) for d in st)
that we can test in the interpreter
In [30]: sd('10101010101010101010')
Out[30]: 10
In [31]: sd('101010101010101010101')
Out[31]: 11
What you really want is to sum the odd digits and subtract the even ones, but this is equivalent to sum the odds, sum separately the evens and then take the difference, isn't it? so what you want is
step_1 = sd(odds(st)) - sd(evens(st))
How can you separate the odd digits from the even ones? Ah! no need for a function, we can use slices
step_2 = sd(st[::2]) - sd(st[1::2])
Now we want to test the slices in the interpreter
In [32]: '101010101010101010101'[::2]
Out[32]: '11111111111'
In [33]: '101010101010101010101'[1::2]
Out[33]: '0000000000'
But step_2 could be a negative number, that I don't want to manage... I'd rather use the abs builtin
step_3 = abs(sd(st[::2]) - sd(st[1::2]))
and this is exactly what you were looking for.
Eventually we can put all the above together, but we may need to iterate until the difference is less than 11 --- we'll use an infinite loop and a break statement to exit the loop when we'll have found the answer
def sd(st):
return sum(int(d) for d in st)
number = input('Give me a number: ')
trial = number
while True:
n = abs(sd(trial[::2]) - sd(trial[1::2]))
if n < 11: break
trial = str(n)
if n > 0:
...
else:
...
what exactly do you want to do with this?
evenindex = evenindex int(item)
"list" is a type, means the list type in python, so it cannot be the name of a variable. Furthermore, you have not defined this variable in your code.
I have figured out the answer to the question I asked above. As such, my answer here is in the event anyone stumbles upon my above question.
def main():
indexed = input("Enter a number: ",)
total = 0
num = 0
while num <= 10:
for item in indexed:
if num %2 == 0:
total = abs(total + int(item))
else:
total = abs(total - int(item))
num = num + 1
if total == 0:
print(indexed, "is evenly divisible by 11 \ncheck since", indexed, "modulus 11 is", int(indexed) % 11)
else:
print(indexed, "is not evenly divisible by 11 \ncheck since", indexed, "modulus 11 is", int(indexed) % 11)
input()
main()

Generate triangular numbers

This function is supposed to take an integer, generate the list of triangular numbers within range of that integer, check that list for the longest list of numbers whose sum == number and return them in a list, otherwise if there is no such list within that range of triangular numbers, return an empty list. I thought I had it somewhat, and it runs on python tutor.com, but when I run it in IDLE, nothing happens.
def checkio(number):
x = 4
lst = [1, 3, 6]
new = []
if number == 0:
return []
elif number == 1:
return [1]
elif number == 3:
return []
elif number == 6:
return []
elif number == 4:
return [1, 3]
elif number == 7:
return [1, 6]
elif number == 10:
return [1, 3, 6]
elif number > 10:
while number > lst[-1]: # Generates a list of all the triangular numbers up to number
for item in range(lst[-1]):
lst.append(x + lst[-1])
x += 1
go = []
start = 0
end = 0
count = 0
while count < len(lst) * 2:
if sum(lst[start:end+1]) < number:
end += 1
count += 1
elif sum(lst[start:end+1]) > number:
start += 1
count += 1
elif sum(lst[start:end+1]) == number:
go.append(lst[start:end+1])
break
return go
if count >= len(lst) * 2:
return []
In the code you post you are just declaring a function. In order to run it, you have to make a call to that function. In your case, it receives one argument, so you have to pass it inside the parentheses ():
number = 5 # for example
checkio(number) # this is the function call
As Bakuriu commented: If you want to get a result change the order of this lines:
elif sum(lst[start:end+1]) == number:
go.append(lst[start:end+1])
break
return go
To :
elif sum(lst[start:end+1]) == number:
go.append(lst[start:end+1])
return go
break
This will return a value before escaping the while loop. As noted in the comments (thanks Andrea Corbellini) you can also remove the break statement and it will work well. Because after the return statement by definition escapes the function.
Also to run in idle once defined (you copied the code and pressed return), call it as Christian says.
This way you will check if works.
Note that you don't check in the ifelse clauses for the numbers 2, 5, 8 and 9. If you call this function with checkio(5), like suggested by Crhistian, it will not return anything because it doesn't have anything to return!

Using Random To Assign Chance

Is there a way to set up an if statement like this where 1 if statement covers multiple integers?
variable = random.randrange(1,10)
if variable is between 1 - 3
then do this
if variable is between 4-5
then do this
if variable is between 6-9
then do this
or maybe something like this
a = 1,2,3,4,5,6,7,8,9,10
variable = random.randrange(1,10)
if variable == a:
then do this
What about choosing a random number for each player, then the player with the largest value gets to attack first.
Or, if this isn't turn based, then set a threshold, and if the random number is over the threshold, then the player can attack.
The threshold could also be a random number. For example:
player1.attack = randn ()
[player2 etc]
minval = randn ()
for player in players:
if player.attack > minval:
[...attack...]
The question at the bottom is easy to implement, basically exactly as you've written it:
variable = random.randrange(1,10)
if 0 <= variable < 3:
then do this
if 3 <= variable < 5:
then do this
if 5 <= variable < 9:
then do this

Categories

Resources