Generating Unique Numbers in Python without Using Lists, Sets, Etc - python

This was a take home test question (which I mailed 20 minutes ago if Prof. Gruhn is ruthlessly scouring stackoverflow). First computer science course, Intro using Python. Using the book "Starting Out With Python 2nd Ed." The test was basically on creating our own module libraries, reading and writing to a file, and try/except logic.
The first part asked to create a lottery mumber simulator. One that generated nonunique numbers, the other unique, non repeating numbers. Every answer I saw on here utilized lists, which is sadly the next chapter, and we were expressly forbidden from using them.
My code for this section:
import random
def ballPickerOne():
a = random.randint(1, 59)
b = random.randint(1, 59)
c = random.randint(1, 59)
d = random.randint(1, 59)
e = random.randint(1, 59)
f = random.randint(1, 35)
showNumbers(a,b,c,d,e,f)
def ballPickerTwo():
a = random.randrange(1,59,2)
b = random.randrange(1,59,3)
c = random.randrange(1,59,5)
d = random.randrange(1,59,7)
e = random.randrange(1,59,11)
f = random.randint(1,35)
showNumbers(a,b,c,d,e,f)
def showNumbers(a,b,c,d,e,f):
print("Your Numbers ...")
print()
print("Ball 1: ", a)
print("Ball 2: ", b)
print("Ball 3: ", c)
print("Ball 4: ", d)
print("Ball 5: ", e)
print("Red Ball: ", f)
print()
print("Good Luck")
We were required to use the showNumbers function to display the results, and in the format that would result from it. ballPickerTwo is the "unique" one, which I used prime number intervals in a failed attempt at uniqueness. I toyed with using a loop, but couldn't figure out how to display the numbers generated using showNumbers.

This is a really tedious way of doing it, but it doesn't use lists. It will pick random and unique values.
def ballPickerTwo():
a = random.randint(1, 59)
b = a
while b == a:
b = random.randint(1, 59)
c = b
while c == b or c == a:
c = random.randint(1, 59)
d = c
while d == c or d == b or d == a:
d = random.randint(1, 59)
...

Just return the values you have generated - use return in your functions. E.g.:
def ballPickerOne():
a = random.randint(1, 59)
b = random.randint(1, 59)
c = random.randint(1, 59)
d = random.randint(1, 59)
e = random.randint(1, 59)
f = random.randint(1, 35)
return a,b,c,d,e,f
showNumbers(a,b,c,d,e,f)
What if:
from random import sample, randint
def ballPickerOne():
a,b,c,d,e = sample(range(1,59), 5)
f = randint(1,35)
while f!=a and f!=b and f!=c and f!=d and f!=e:
f = randint(1,35)
return a,b,c,d,e,f

How about use an integer as the bitmap to check unique?
import random
def showNumbers(a,b,c,d,e,f):
print("Your Numbers ...")
print()
print("Ball 1: ", a)
print("Ball 2: ", b)
print("Ball 3: ", c)
print("Ball 4: ", d)
print("Ball 5: ", e)
print("Red Ball: ", f)
print()
print("Good Luck")
def ballPickerTwo():
while True:
a = random.randint(1, 59)
b = random.randint(1, 59)
c = random.randint(1, 59)
d = random.randint(1, 59)
e = random.randint(1, 59)
f = random.randint(1, 35)
m = 2**a + 2**b + 2**c + 2**d + 2**e + 2**f
if bin(m).count("1") == 6:
break
showNumbers(a,b,c,d,e,f)

This is similar to HYRY's answer in that it is using the bits in a number to remember which numbers have been selected already. This works because Python can handle arbitrarily large numbers.
import random
def showNumbers(a, b, c, d, e, f):
print("Your Numbers ...")
print()
print("Ball 1: ", a)
print("Ball 2: ", b)
print("Ball 3: ", c)
print("Ball 4: ", d)
print("Ball 5: ", e)
print("Red Ball: ", f)
print()
print("Good Luck")
def pick(cur_val):
while True:
v = random.randint(1, 59)
m = 2**v
if (cur_val & m) == 0: # bit not set, v never picked before
return (cur_val | m), v # return updated cur_val and bit number now set in it
def ballPickerTwo():
cur_val = 0
cur_val, a = pick(cur_val)
cur_val, b = pick(cur_val)
cur_val, c = pick(cur_val)
cur_val, d = pick(cur_val)
cur_val, e = pick(cur_val)
cur_val, f = pick(cur_val)
showNumbers(a, b, c, d, e, f)

Related

How to Remove the last few characters from console Python?

I am making a little math game, similar to zeta mac. Everything seems to be working well. Ideally I would like this console output to erase incorrect answers entered by the user, without reprinting the math problem again for them to solve. Is something like this possible?
For example, I may prompt the user to answer "57 + 37 = " in the console, then if they type 24 (console would look like this "57 + 37 = 24", I would like the 24 to be erased, and for the "57 + 37 = " to remain, allowing the user to guess again, without the same equation having to be printed again on a line below.
Here is the source code (sorry if its messy, I just started learning python):
import random
import time
def play(seconds):
start_time = time.time()
score = 0
while True:
current_time = time.time()
elapsed_time = current_time - start_time
a = random.randint(2, 100)
b = random.randint(2, 100)
d = random.randint(2, 12)
asmd = random.choice([1, 2, 3, 4])
if (asmd == 1):
solve = a + b
answer = input("%d + %d = " % (a, b))
elif (asmd == 2):
if (a > b):
solve = a - b
answer = input("%d - %d = " % (a, b))
else:
solve = b - a
answer = input("%d - %d = " % (b, a))
elif (asmd == 3):
solve = a * d
answer = input("%d * %d = " % (a, d))
else:
solve = d
c = a * d
answer = input("%d / %d = " % (c, a))
while (solve != int(answer)):
answer = input("= ")
score += 1
if elapsed_time > seconds:
print("Time\'s up! Your score was %d." % (score))
break
play(10)
Just use add these two lines after answer = input("= "):
sys.stdout.write("\033[F") #back to previous line
sys.stdout.write("\033[K") #clear line
import random
import time
import sys
def play(seconds):
start_time = time.time()
score = 0
while True:
current_time = time.time()
elapsed_time = current_time - start_time
a = random.randint(2, 100)
b = random.randint(2, 100)
d = random.randint(2, 12)
asmd = random.choice([1, 2, 3, 4])
if (asmd == 1):
solve = a + b
answer = input("%d + %d = " % (a, b))
elif (asmd == 2):
if (a > b):
solve = a - b
answer = input("%d - %d = " % (a, b))
else:
solve = b - a
answer = input("%d - %d = " % (b, a))
elif (asmd == 3):
solve = a * d
answer = input("%d * %d = " % (a, d))
else:
solve = d
c = a * d
answer = input("%d / %d = " % (c, a))
while (solve != int(answer)):
answer = input("= ")
if solve != int(answer):
sys.stdout.write("\033[F") #back to previous line
sys.stdout.write("\033[K") #clear line
score += 1
if elapsed_time > seconds:
print("Time\'s up! Your score was %d." % (score))
break
play(10)
Removing characters from the end of the input is probably not the best approach as you aren't quite sure how many characters there will be (depends on the number).
The answer from #QualidSai does clear the terminal but it doesn't show your formula string again. To solve this I'd store the formula string that you print as part of your input as a string variable, then you can use that when looping. For example:
import random
import time
import sys
def play(seconds):
start_time = time.time()
score = 0
while True:
current_time = time.time()
elapsed_time = current_time - start_time
a = random.randint(2, 100)
b = random.randint(2, 100)
d = random.randint(2, 12)
asmd = random.choice([1, 2, 3, 4])
if (asmd == 1):
solve = a + b
question = "%d + %d = " % (a, b)
elif (asmd == 2):
if (a > b):
solve = a - b
question = "%d - %d = " % (a, b)
else:
solve = b - a
question = "%d - %d = " % (b, a)
elif (asmd == 3):
solve = a * d
question = "%d * %d = " % (a, d)
else:
solve = d
c = a * d
question = "%d / %d = " % (c, a)
answer = False
while (solve != int(answer)):
answer = input(question)
sys.stdout.write("\033[F")
sys.stdout.write("\033[K")
score += 1
if elapsed_time > seconds:
print("Time\'s up! Your score was %d." % (score))
break
play(10)

Cant get my code to generate enough fields for bingo

I need my program to generate as many playing fields as the entered number of players playing the game. Currently it only generates 1 field. Cant wrap my head around this one.
s = int(input("Sisesta mängijate arv: "))
b = int(input("Sisesta väjaku suurus: "))
b = b + 1
bb = b
c = int(input("Sisesta korrutustabeli suurus: "))
for s in range (1 , s+1):
numberolemas = ['0']
t.write(str(s) + ". väljak \n\n")
print(str(s) + ". väljak \n")
for bb in range (1 , bb):
for b in range (1 , b):
import random
number = random.randint(1, c) * random.randint(1, c)
olemas = True
while olemas:
number = random.randint(1, c) * random.randint(1, c)
if number not in numberolemas:
olemas = False
t.write(str(number))
print(str(number), end = ' ')
if number <= 9:
t.write(" ")
print(" ", end = '')
elif number >= 100:
t.write(" ")
print(" ", end = '')
else: t.write(" ") and print(" ", end = '')
numberolemas.append(number)
b = b + 1
t.write("\n\n")
print(" ")
bb = bb + 1
print(" ")
t.close() ```

Sorting rectangular objects into a cupboard

So here we are packing objects and Both Length, Width and Height of object should be less than 50 for a good case and if any is more than 50 then the case is bad. I have written my program below but all cases are judged by the last case.
Sample input
2
20 20 20
1 2 51
Sample output
Case 1: good
Case 2: bad
T = int(input("Enter the number of test cases:\n"))
for i in range(1,T+1):
print("Enter the values of the Length, Width, Height")
case = input()
#Length_1.
if case[1] == " ":
L = int(case[0])
#Width and heigth.
if case[3] == " " and len(case) == 5:
W = int(case[2])
H = int(case[4])
if case[4] == " " and len(case) == 6:
W = int(case[2:4])
H = int(case[5])
if case[3] == " " and len(case) == 6:
W = int(case[2])
H = int(case[4:6])
if case[4] == " " and len(case) == 7:
W = int(case[2:4])
H = int(case[5:7])
#Length_2.
if case[2] == " ":
L = int(case[0:2])
#Width and height.
if case[4] == " " and len(case) == 6:
W = int(case[3])
H = int(case[5])
if case[5] == " " and len(case) == 7:
W = int(case[3:5])
H = int(case[6])
if case[4] == " " and len(case) == 7:
W = int(case[3])
H = int(case[5:7])
if case[5] == " " and len(case) == 8:
W = int(case[3:5])
H = int(case[6:8])
for i in range(1,T+1):
if L > 50 or W > 50 or H > 50:
print("Case ", i,":"," bad", sep='')
else:
print("Case ", i,":"," good", sep='')
If your problem is that all cases are judged by the properties of the last case (though, as has been noted, it is not clear what this means for the results of your code as given), then it could be because when case is assigned in:
T = int(input("Enter the number of test cases:\n"))
for i in range(1,T+1):
print("Enter the values of the Length, Width, Height")
case = input()
it is assigned anew during each iteration. Consequently, the previous input gets lost.
Edit:
The following code solves your problem by turning cases into a list:
T = int(input("Enter the number of test cases:\n"))
cases = []
for i in range(1,T+1):
print("Enter the values of the Length, Width, Height")
dimensions = input()
c = dimensions.split(" ")
cases.append(c)
for j, case in enumerate(cases):
if int(case[0]) > 50 or int(case[1]) > 50 or int(case[2]) > 50:
print("Case ", j,":"," bad", sep='')
else:
print("Case ", j,":"," good", sep='')
In this suggestion, the user input is automatically split into the different values using split() instead of manually doing it via if statements as it has been the case in your original post (this snippet assumes that the input provides values separated by a single space).

How can i make infite loop to ask user if he wants to input another number?

how can i make my code to ask user if wants to input another number? I could barely make my code run without errors, i am a toddler at python. I struggled a lot to write the code below. I know that stackoverflow is not a code writing service. But my little brain hurts now and i can't continue without help. I want to say simply "Do you want to convert another number?"
import math
# Global definition
#Base = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F]
Base = [str (x) for x in range (10)] + [chr (x) for x in range (ord ('A'), ord ('A') +6)]
h=[str(i) for i in range(10)]+["A","B","C","D","E","F"]
def BIN2DEC (string_num):
num = string_num
if num == 0:
return '0'
bin_str = ''
while num > 0:
bin_str = str(num % 2) + bin_str
num = num / 2
return bin_str
def HEX2DEC (string_num):
return str (int (string_num.upper (), 16))
# Dec2bin
# Decimal to binary
def dec2bin (string_num):
num = int (string_num)
mid = []
while True:
if num == 0: break
num, rem = divmod (num, 2)
mid.append (Base [rem])
return''. join ([str (x) for x in mid [:: -1]])
# Dec2hex
# Decimal to hexadecimal
def DEC2HEX (number):
n = long(number ,16)
if (n < 0):
print(0)
elif (n<=1):
print n,
else:
DEC2HEX( n / 16 )
x =(n%16)
if (x < 10):
print(x),
if (x == 10):
print("A"),
if (x == 11):
print("B"),
if (x == 12):
print("C"),
if (x == 13):
print("D"),
if (x == 14):
print("E"),
if (x == 15):
print ("F"),
# Hex2tobin
#The hexadecimal to bry
def HEX2BIN (hex_string):
s = int(hex_string, 16)
num_digits = int(math.ceil(math.log(s) / math.log(2)))
digit_lst = ['0'] * num_digits
idx = num_digits
while s > 0:
idx -= 1
if s % 2 == 1: digit_lst[idx] = '1'
s = s / 2
return ''.join(digit_lst)
# Bin2hex
# Binary to hexadecimal
def BIN2HEX (string_num):
return DEC2HEX (BIN2DEC (string_num))
my_num = 0
my_num = raw_input("Insert binary,decimal or hexadecimal:")
while(my_num != 0):
if my_num[0:2] == "0x" or my_num[0] == "x":
print HEX2BIN(my_num)
print HEX2DEC(my_num)
break
elif my_num[0:2] == "0b" or my_num[0] == "b" and all(x in "01" for x in my_num):
print""
print BIN2HEX(my_num)
print BIN2DEC(my_num)
break
else:
print dec2bin(my_num)
print HEX2BIN(my_num)
print long(my_num)
break
my_num = 0
my_num = raw_input(":")
print list(iter(lambda:raw_input("Enter Value, or 'q' to quit:"),"q"))
is my personal favorite way
iter makes an iterator (you need to look it up)
it takes an optional no-argument function that it will continually call until it receives the second argument

Invalid Syntax Error in Temperature Conversion Program

Alright, so I was working on a simple temperature conversion program but am stuck on an error message I keep getting. Whenever I try to run the program, the F in the line, F = (C * 9/5 + 32), gets highlighted and a window pops up that states "invalid syntax". I have no idea what the issue could be so i'm hoping it's something simple one of you can point out for me. Thanks in advance!
#Menu Interface
def menu():
print("1. C to F")
print("2. F to C")
print("3. Quit")
# C to F
def CtoF():
C = float(input("Temperature in Celsius:")
F = (C * 9/5 + 32)
print (F,"degrees Fahrenheit")
# F to C
def FtoC()
F = float(input("Temperature in Fahrenheit:")
C = (F-32) * 5/9
print (C,"degrees Celsius")
def option():
loop = 1
while loop == 1:
o = input("Choose an option:")
if o = 1:
CtoF()
elif o = 2:
FtoC()
elif o = 3:
loop = 0
option()
You're missing an end parenthesis on your line
C = float(input("Temperature in Celsius:")

Categories