how do you draw random numbers from a list and put them in another - list

I do not know how to draw 2 or more different numbers and put them in another list, so far I have tried this:
import random
def jugar(m):
m = list(range(1, 14, 1)) * m
random.shuffle(m)
player1 = []
for n in m:
random.choice(m)
player1.append(n)
if n + n == 21:
print("Nano jack")
elif n + n < 21:
random.choice(m)
player1.append(n)
elif n + n > 21:
print("Loser")
return player1
jugar(1)
but this returns me 2 equal numbers, it is similar to the game of blackjack, I want it to keep adding random numbers until it reaches 21 or more, thanks for the help in advance

You can use choice method to randomly select an item from a given list.
Use it in a for loop to randomly select more items.
import random
the_list = [1, 2, 3, 4]
new_list = []
for i in range(3):
value = random.choice(the_list)
new_list.append(value)

Related

For Loop for Prime Factors in Python

I'm trying to return the factors of a number which are prime numbers in this code. For example, if someone enters in n = 55, they'll get back 5 and 11. I believe I have the first part correct in checking for the factors, but somehow I'm not sure what I'm missing in the second part of checking for prime numbers.
When I run the code for 55, I only get 5 (11 is missing).
Can someone please help review my code and provide feedback?
l = []
primefactors = []
def factor(n):
count = 0
print 'These are the factors:'
for num in range(2,n+1):
if n%num == 0: #checks that it is a factor
print num #These are the factors
l.append(num)
for i in l:
if i == 2 : #checks for two
primefactors.append(i)
else:
for x in range(3,i+1,2): #checks for odd numbers
if i%x == 0:
count += 1
if count == 1:
primefactors.append(i)
print "These are the prime factors:"
print primefactors
You can get all the factors by simply removing all unnecessary stuff, but that will not guaranty, that the number is prime number:
l = []
primefactors = []
def factor(n):
count = 0
for num in range(2,n+1):
if n%num == 0 and num != n: #checks that it is a factor
primefactors.append(num)
print ("These are the prime factors:")
print (primefactors)
del l[:]
del primefactors[:]
try this one, I added an additional check to see if number is a prime before appending to primefactors list.
primefactors = []
def factor(number):
for i in range(2,int(number//2)+1):
prime = True
for j in range(2,int(i**.5)+1):
if i%j == 0:
prime = False
break
if prime and number%i == 0:
primefactors.append(i)
print (primefactors)
factor(92)
factor(55)
output:
[2, 23]
[2, 23, 5, 11]

Selecting only one row at a time for iteration in PANDAS-PYTHON

I have this following code and a text file with 5 (X and Y) values The Image of the text file is here. I need to iterate 1000 times for every X and Y value. How can I achieve this?
import pandas as pd
data = pd.read_csv("test.txt", delim_whitespace=True, skipinitialspace=True,)
for every line in the text document:
for i in range(1, 1001, 1):
z = data["X"] + data["Y"]
z = z + 10
print z
The text file is like
X Y
1 10
2 20
3 30
4 40
5 50
The output must be:
10011
10022
10033
10044
10055
You can select one row at the time using .loc. Please read this documentation to fully understand how this work. Here is your data:
import pandas as pd
df = pd.DataFrame({'X':['1','2','3','4','5'], 'Y': ['10','20','30','40','50']})
This code
print df.loc[0]
will give you the first row (with index=0) as a pandas series (pd.Series), which is essentially like a dataframe with one column only: a vector.
X 1
Y 10
Name: 0, dtype: object
If you want the second row then: df.loc[1] and so on...
If you want to iterate one row at the time, you can select each row in the first for loop and perform your operations 1000 times in the second for loop:
for ix in df.index: # df.index gives [0,1,2,3,4]
for i in xrange(0,1000):
ser = df.loc[ix]
print ser['X'] + ser['Y'] + '10'
Try this,
data = pd.DataFrame({'X': [1, 2, 3, 4, 5], 'Y': [10,20,30,40,50]})
for each_line in data.index:
z = data['X'].loc[each_line] + data['Y'].loc[each_line]
for i in range(1,1001,1):
z +=10
print(z)
Output
10011
10022
10033
10044
10055
if you want to add new column to dataFrame:
data["total"] = sorted(set([(data.loc[ix]['X'].astype(int) + data.loc[ix]['Y'].astype(int)).astype(str) +"10" for ix in data.index for i in range(1,1001)]))
if you want concatenate the 'X' and 'Y' +'10' then:
[data.loc[ix]['X'].astype(str) + data.loc[ix]['Y'].astype(str) +"10" for ix in data.index for i in range(1,1001)]
And if you want to sum of 'X' + 'Y' and concat + '10' then:
final_data = [(data.loc[ix]['X'].astype(int) + data.loc[ix]['Y'].astype(int)).astype(str) +"10" for ix in data.index for i in range(1,1001)]

Python Query (Lottery coding practice)

I have a query relating to return only the last results, so here is my code:
import random
def Step_1():
Start_Game = raw_input("Enter \'Start' to continue \n")
if Start_Game == 'start':
print "Let the Lottery begin"
else:
return Step_1()
#-------------------------------------------------------------------
def Step_2():
random_list = []
for i in range(10):
while len(random_list) < 6:
random_number = random.randint(1,59)
while random_number not in random_list:
random_list.append(random_number)
print random_list
Step_1()
Step_2()
When i run this it gives me the below result,
Enter 'Start' to continue
start
Let the Lottery begin
[56]
[56, 20]
[56, 20, 32]
[56, 20, 32, 2]
[56, 20, 32, 2, 23]
[56, 20, 32, 2, 23, 30]
However how can i just display the last result generated and discard the previous 5. I know i need to change the last bit "print" within my Step_2 function, but what do I need to add?
Thanks .
A one liner:
random.sample(range(1, 59), 6) # genrates 6 unique random no's in the range
OR to modify existing code, use a list to store previously generated random no's
def Step_2():
random_list=[]
for i in range(6):
random_number = random.randint(1,59)
while random_number in random_list:
random_number = random.randint(1,59)
print random_number
list.append(random_number )
For your step2() function you will probably want to use a while loop, since you do not really know, how many random numbers you need to generate until you have 6 unique numbers.
def step2():
# Declare an empty list to hold the random numbers
numbers = []
# While we do not have 6 numbers in our list
while len(numbers) < 6:
# Generate a random number
rndnum = random.randint(1,59)
# If that random number is not yet in our list
if rndnum not in numbers:
# Append it to the list
numbers.append(rndnum)
return numbers

Python3: list index out of range

def initDeck(n):
cards = []
for i in range(n):
cards.append(i + 1)
return cards
def cutDeck(deck):
decklength = len(deck)
if((decklength % 2) != 0): #odds
numTop = decklength//2
numBot = numTop + 1
else: #evens
numTop = decklength//2
numBot = decklength//2
bottomDeck = []
bottomDeck = deck[:(numBot)]
topDeck = []
topDeck = deck[(numBot):]
return topDeck, bottomDeck
def shuffle(topDeck, bottomDeck):
newDeck = []
numcards = (len(topDeck)) + (len(bottomDeck))
for g in range(numcards):
newDeck.append(bottomDeck[g])
newDeck.append(topDeck[g])
return newDeck
#--------MAIN--------
n = int(input("How many cards do you want to shuffle? "))
numshuffles = int(input("How many times would you like to shuffle the deck? "))
deck = initDeck(n)
topDeck,bottomDeck = cutDeck(deck)
print(bottomDeck, '\n', topDeck, sep="")
while(numshuffles > 0):
shuffledDeck = shuffle(topDeck, bottomDeck)
numshuffles += -1
print(shuffledDeck)
The program takes how many cards you want, how many times you want to shuffle, then riffle shuffles the deck. The problem is when I try to run it, it takes my two inputs then outputs two errors.
Traceback (most recent call last):
File "C:\etc", line 51, in <module>
shuffledDeck = shuffle(topDeck, bottomDeck)
File "C:\etc", line 35, in shuffle
newDeck.append(bottomDeck[g])
IndexError: list index out of range
I'm not entirely sure what's wrong because it looks fine and makes sense to me. Any help would be very greatly appreciated as this is due at 8am!
In
numcards = (len(topDeck)) + (len(bottomDeck))
for g in range(numcards):
newDeck.append(bottomDeck[g])
newDeck.append(topDeck[g])
You are appending bottomDeck[g] and topDeck[g] to newDeck and g ranges from 0 to len(bottomDeck) + len (topDeck). Means that at some point g becomes greater than len(topDeck) or len(bottomDeck).
EDIT:
You can fix it like this.
for g in range(len(topDeck)):
newDeck.append(bottomDeck[g])
newDeck.append(topDeck[g])
# if total cards are odd, one card will be left in bottomDeck
if(len(topDeck) != len(bottomDeck)):
newDeck.append(bottomDeck[-1])
Also you should again cut the deck after shuffle
while(numshuffles > 0):
shuffledDeck = shuffle(topDeck, bottomDeck)
numshuffles += -1
print(shuffledDeck)
topDeck,bottomDeck = cutDeck(shuffledDeck)
numcards = (len(topDeck)) + (len(bottomDeck))
for g in range(numcards):
newDeck.append(bottomDeck[g])
Your g goes up to the sum of lengths of topDeck and bottomDeck, hence becomes greater than len(bottomDeck).

Python: simple list modify task

I need to remove the unique elements of the list, the first thought is:
def cut_uniq(data):
for x in data:
if data.count(x) == 1:
data.remove(x)
print(data)
cut_uniq([1, 2, 3, 4, 5,])
return
[2, 4]
please, tell me why?
Look at each iteration:
i x data
0 1 [1,2,3,4,5]
1 3 [2,3,4,5]
2 5 [2,4,5]
[2,4]
You can iterate over a different list than you are modifying. This returns a copy of the list
def cut_uniq(data):
return [x for x in data if data.count(x) > 1]
or more efficiently
from collection import Counter
def cut_uniq(data):
return [x for x, count in Counter(data) if count > 1]
If you really do want to modify the original list, and not return a copy
def cut_uniq(data):
i = 0
while i < len(data):
if data.count(data[i]) == 1:
del data[i]
else:
i += 1
or
from collections import Counter
def cut_uniq(data):
for x, count in Counter(data):
if count == 1:
data.remove(x)
95% of the time that you modify the same list as you're iterating over, you'll have problems.
When you use
for x in data:
it translates to
for i in [0,1,2,3,4]:
x = data[i]
So in the first loop, i = 0 data[i]=1. you remove 1 from data, the data is [2,3,4,5]
on the second loop , i = 1, because now data is [2,3,4,5], data[i] = 3. So 2 is left in the data list and never been visited.
Same as the number 4.
So when you finished your loop, the [2,4] leted in the list.