Good day friends!
Tell me please, I have the following code:
all_users = UserProfile.objects.all()
for s,usera in enumerate(all_users):
name = usera.nickname
name_id = usera.id
print(s)
if int(s) <= 50:
print('1_iterator')
r = api.request(example)
elif int(s) <= 100:
r = api2.request(example)
elif #a total of seven compounds, api3,api4,api5,api6,api7
try:
for item in r.get_iterator():
#then loop adds data to the database
how do I get a cycle every 50 iterations connect to the new api, and if he reaches seven then again from the beginning, and so has not yet come to an end user in the database?
Advance thanks!
You could set up an itertools.cycle.
apis = itertools.cycle([api1, api2, api3, api4, api5, api6, api7])
for s,usera in enumerate(all_users):
if (s % 50) == 0:
current_api = apis.next()
name = usera.nickname
name_id = usera.id
print(s)
current_api.request(example)
...
Related
import random
MIN_LINES = 1
MAX_LINES = 3
MAX_BET = 100
MIN_BET = 1
ROW = 3
COL = 3
symbol_count = {
"A":2,
"B":4,
"C":6,
"D": 8,
}
def get_slot_machine_spin(rows,cols,symbols):
all_symbols = []
for symbol , symbol_count in symbols.items():
for _ in range(symbol_count):
all_symbols.append(symbol)
columns = [[],[],[]]
for _ in range(cols):
current_symbols = all_symbols[:]
for _ in range(rows):
value = random.choice(current_symbols)
current_symbols.remove(value)
columns.append(value)
columns.append(columns)
return columns
def print_slot_machine(colmuns):
for row in range(len(colmuns[0])):
for i , colmun in enumerate(colmuns):
if i != len(colmun) - 1:
print(colmun[row], end="|")
else:
print(colmun[row], end="")
print()
def deposit():
amount = input("inter the amount of deposit you'd like to add ")
if amount.isdigit():
amount = int(amount)
while amount > 0:
break
else: print("amount must be more than 0")
else: print("Please enter a number ")
return amount
def get_number_of_lines():
lines = input("inter the amount of lines you'd like to add ")
if lines.isdigit():
lines = int(lines)
while MIN_LINES <= lines <= MAX_LINES:
break
else: print("amount must be between 1~3")
else: print("Please enter a number ")
return lines
def get_bet():
while True:
amount = input("Inter the amount of deposit you'd like to bet \n")
if amount.isdigit():
amount = int(amount)
while MIN_BET <= amount <= MAX_BET:
break
else:
print(f"The amount must be between ${MIN_BET}and ${MAX_BET}\n ")
else:
print("Please enter a number ")
return amount
def main():
balance = deposit()
lines = get_number_of_lines()
while True:
bet = get_bet()
total_bet = bet *lines
if total_bet> balance:
print(f"you dont have enough to bet on that amount , your current balance is {balance}")
else:
break
print(f"you're betting {bet},on {lines} lines . total bet is = ${total_bet}")
slots = get_slot_machine_spin(ROW, COL,symbol_count)
print_slot_machine(slots)
main()
I tried changing the two lines in many different ways but it didnt work plz help
slots = get_slot_machine_spin(ROW, COL,symbol_count)
print_slot_machine(slots)
i got this code from a utube video called (Learn Python With This ONE Project!) i wrote the same code as but when he excute the code it shows him the Slot machine results ( abcd ) while am not getting it , i hope my question was clear ,,, all i want is to make the functions work and show the results of the random choices
Your problems are all in the get_slot_machine_spin function. Did you ever do a basic debug print of what it returns? You would have immediately seen that it was wrong.
Look at what you're asking. You're creating columns with three empty lists. You then generate a random thing and add it to THAT list, So, after three runs, you'd have [[], [], [], 'A', 'C', 'D']. Then you append THAT list to ITSELF, and repeat. When you see something like columns.append(columns), that's an immediate indication that something is wrong.
You need to create a separate list to hold the individual column values, then you append that list to your master column list, which should start out empty. Like this:
def get_slot_machine_spin(rows,cols,symbols):
all_symbols = []
for symbol , symbol_count in symbols.items():
for _ in range(symbol_count):
all_symbols.append(symbol)
columns = []
for _ in range(cols):
row = []
current_symbols = all_symbols[:]
for _ in range(rows):
value = random.choice(current_symbols)
current_symbols.remove(value)
row.append(value)
columns.append(row)
print(columns)
return columns
Here in this code else block is not printing the value Treasure locked
def counted(value):
if(value == 5):
return 1
else:
return 0
def numb(value1):
sam = 95
value = 0
stp = 97
h = {}
for i in range(0,26):
h.update({chr(stp) : (ord(chr(stp))-sam)})
sam = sam-1
stp = stp+1
for j in range(0,5):
value = h[value1[j]]+value
if(value > 80):
print('First lock-unlocked')
else:
print('Treasure locked')
string = input()
firstcheck = counted(len(string))
if(firstcheck == 1):
numb(string)
a good idea is to check what the condition is before entering the if statements, possibly check what value is printing before the if statement. the logic in def numb() has very little do with what's in def counted(). as long as one is 1 or 0 is being passed to numb() we know that function will run and seems like it.
else block is working properly. if you want to print Treasure Locked. you have to pass lower character string like 'aaaaa'. if value is > 80. then it always print First lock-unlocked.
I am developing a breadth-first-search algorithm for a factorization problem and am running into an interesting/confusing bug when attempting to break out of a while loop. If you run the code below, it will fail inside the "construct_path" method, stating :
File "main.py", line 96
break
SyntaxError: 'break' outside loop
but I am inside of a while loop! If anyone could give me some advice on this issue, I would really appreciate it. Thanks in advance.
from numpy import random
import itertools
import Queue
#Finding multiples, BFS problem
#Given input of list with unique integers 0 - 9 and n = range(0,1000000), calculate smallest multiple of n and unique combination of values in the list
#Example : Input : list = {0,1,2} , n = 3,
# output = 12
# Input : list = {0,1,2} , n = 50
# Output = 200
class Problem:
def __init__(self):
self.n = random.randint(0,10000000)
listSize = random.randint(1,9)
mainSet = set()
self.mainList = []
while True:
toAdd = random.randint(0,9)
if(toAdd not in self.mainList):
self.mainList.append(toAdd)
if(len(self.mainList) == listSize):
break
def get_start_state(self):
s = ''.join(map(str, self.mainList))
return int(s)
def is_goal(self, state):
return True
def get_sucessors(self):
print "Getting successors"
def breadth_first_search(problem):
# a FIFO open_set
open_set = Queue.Queue()
# an empty set to maintain visited nodes
closed_set = set()
# a dictionary to maintain meta information (used for path formation)
meta = dict() # key -> (parent state, action to reach child)
# initialize
start = problem.get_start_state()
meta[start] = (None, None)
open_set.put(start)
while not open_set.empty():
parent_state = open_set.get()
print "{} {}".format("parent_state is ", parent_state)
if problem.is_goal(parent_state):
return construct_path(parent_state, meta)
for (child_state, action) in problem.get_successors(parent_state):
if child_state in closed_set:
continue
if child_state not in open_set:
meta[child_state] = (parent_state, action)
open_set.put(child_state)
closed_set.add(parent_state)
#collect path to desired answer
def construct_path(state, meta):
action_list = list()
while True:
row = meta[state]
if (len(row) == 2):
state = row[0]
action = row[1]
action_list.append(action)
else:
break
return action_list.reverse()
x = Problem()
breadth_first_search(x)
Could be that you have a mix of tabs and spaces so that the break in line 96 looks like it is indented to be below action_list.append(action) but effectively it is below the while. That would explain the error at least.
It is just a guess. But it could be like this, using a visible tabwidth of 4 in the editor:
→ while True:
→ → row = meta[state]
if (len(row) == 2):
state = row[0]
action = row[1]
action_list.append(action)
else:
break
To the Python interpreter this looks like this (because it assumes a tabwidth of 8):
→ while True:
→ → row = meta[state]
if (len(row) == 2):
state = row[0]
action = row[1]
action_list.append(action)
else:
break
This is still valid but obviously means a different thing and would put your break outside of the while loop.
I am new to this, and I am looking for help. I currently am stuck in a program I'm trying to complete. Here it is:
def searchStock(stockList, stockPrice, s):
for i in range(len(stockList)):
if s == stockList[i]:
s = stockPrice[i]
elif s != stockList[i]:
s = -1
return s
def mainFun():
stockList= []
stockPrice = []
l = 1
while l > 0:
stocks = str(input("Enter the name of the stock:"))
stockList += [stocks]
if stocks == "done"or stocks == 'done':
l = l * -1
stockList.remove("done")
else:
price = int(input("Enter the price of the stock:"))
stockPrice += [price]
l = l + 1
print(stockList)
print(stockPrice)
s = input("Enter the name of the stock you're looking for:")
s = searchStock(stockList, stockPrice, s)
Every time I run the program to the end, it never returns the variable s for some reason. If i replace return with print, it always prints -1 instead of the stockPrice if its on the list. I cant seem to get it to work. Can someone please help me?
Try adding this print to help you debug:
def searchStock(stockList, stockPrice, s):
output = -1
for i in range(len(stockList)):
if s == stockList[i]:
output = stockPrice[i]
print i, output, stockList[i], stockPrice[i]
elif s != stockList[i]:
output = -1
return output
Also I changed one of your variables, it seems better than modifying your input value and then returning it.
i've searched the forum and found similar questions, but no luck in solving my problem.
My code is designed to swap every two letters of each word using recursion and print the result. For words with an even amount of letters, the word "None" is included in the output and i don't know how to fix...
here's the code:
def encryptLine(line, count):
headline = line[count:]
if length(headline) > 0:
if count == length(line) - 1:
new = headline
return new
elif count <= length(line):
new = head(tail(headline)) + head(headline)
new = new + str(encryptLine(line, count+2))
return new
print(encryptLine('abcd', 0))
the output for 'abcd' is badcNone, which is correct except for the word None. the output for 'abcde' is 'badce', which is correct...
thanks in advance for your help!
Add return "" to the function definition, that is
def encryptLine(line, count):
headline = line[count:]
if length(headline) > 0:
if count == length(line) - 1:
new = headline
return new
elif count <= length(line):
new = head(tail(headline)) + head(headline)
new = new + str(encryptLine(line, count+2))
return new
return ""
Otherwise, the function will return None if length(headline) > 0 does not hold.
None is here because your function return nothing.
There is 1 case where you return nothing it is
if length(headline) <= 0:
In Python, if there is no return to a function and you try to access to a return value, the value will be None.