Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I need to find a book's page count. The pages have 689 1's in it. So it goes 1,2,3,..11,12,.. in order to find the page count, I need to count the 1's. I thought:
book = []
page = 0
while True:
page += 1
book.append(page)
if book.count(1) == 689:
print("The book is {} pages".format(page))
break
but .count(1) does not include 11,21,111 etc. What can I use instead of .count()?
In order to count the number of pages, you could try to just keep track of a counter variable accumlatively instead of using count on the whole book array.
# book = []
page = 0
count = 0
while True:
page += 1
# book.append(page)
count += str(page).count('1')
if count == 689:
print("The book is {} pages".format(page))
break
book = []
page = 0
sum_of_ones = 0
while True:
page += 1
book.append(page)
sum_of_ones += str(book[-1]).count("1")
if sum_of_ones == 689:
print(f"this book has {page} pages.")
break
#output
1234 pages
I believe this is an efficient way.
It keeps counting the newly added page to the book and increases the sum if possible then rechecks if it is ==689 . It breaks when the number is met.
Only issue is that it will keep iterating if 689 is not met
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
Improve this question
I am required to take 52 random outputs of cards. I got that in a for loop. The problem is, I need to save that output inside a variable.`
import random
r=random.randint(0, 9)
cards={'Spades':r, 'Clubs':r, 'Hearts':r, 'Diamonds':r,'Jack':10, 'King':10, 'queen':10,"Aces":1}
print(cards)
cards2={}
for i in range(52):
global res
res = key, val = random.choice(list(cards.items()))
print("Your deck contains " + str(res))
cards2.update(i) # All output should go in here
I tried using cards2.update, but it didn't work.
I also tried using cards2.(keys).
I just need to create 52 random samples and store them as dictionary value pairs.
First remove the double assignment (res = key, val). And I don't see any point in using a global variable here. Just do _dict[key] = value as shown below, and it will work fine. Also remember that you can’t get all 52 random cards, because if the key exists then the value will be replaced.
import random
r = random.randint(0, 9)
cards = {'Spades':r, 'Clubs':r, 'Hearts':r, 'Diamonds':r,'Jack':10, 'King':10, 'queen':10,"Aces":1}
print(cards)
cards2 = {}
for i in range(52):
key, val = random.choice(list(cards.items()))
cards2[key] = val
print(cards2)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 months ago.
Improve this question
I need to solve the following problem and I assume I have to use continue and break logic.
I have to create an empty to do list and iterate over the dictionary of tasks. I need to add tasks that contain the substring "organize" and once the length of the to do list reaches 2 tasks I break the loop. *
tasks = {
0 : ['Reorganize the cabinet'],
1 : ['Give the dog a bath', 'Create a twitter thread'],
2 : ['Learn python dictionary'],
3 : ['Take a walk'],
4 : ['Go grocery shopping'],
5 : ['Update Facebook'],
6 : ['Respond to emails'],
7 : ['Walk the dog']
}
I could solve the second part of adding the tasks that contain the substring "organize" and could iterate through the length of tasks to filter tasks that are not more than 2. Yet, I can't find the way how to combine two conditions into one.
Put an if statement in the loop that checks the length of the to do list, and breaks out of the loop when it reaches 2.
todo_list = []
for task in tasks.values():
if any('organize' in item for item in task):
todo_list.append(task)
if len(todo_list) == 2:
break
This will work :
to_do_list = []
for task in tasks.values():
for i in task :
if 'organize' in i:
to_do_list.append(i)
if len(to_do_list) == 2:
break
does this do the job:
to_do_list = []
for value in tasks.values():
to_do_list.append([val for val in value if 'organize' in val])
if len(to_do_list) == 2:
break
If you want a flattened list of items, replace to_do_list.append with to_do_list.extend
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am trying to pass my query value to an external API, but since the API has a throttling issue I can make only 500 calls per 5 mins and need to give 10 mins of cooling time. so what I am trying, I added a count increment method and if the count passes more than 400 then sleep for 2 mins, I know the mistake is in my code, but I don't know how to write a function to it.
for info in contact:
id = info[0]
name = info[1]
print(id)
count += 1
print(count)
if count > 400:
print('11111111')
time.sleep(120)
print ("count crossed 400....")
print ("sleep for 2 minutes")
else:
logging.info(count)
print(name)
try:
...
so this will check the count and if the count is more than 400 it will sleep 2 minutes for every other call till the completion.
I am trying to make it in such a way that for every 400 calls sleep for 2 mins how to write that in python. kindly guide
for info in contact:
id = info[0]
name = info[1]
print(id)
count += 1
print(count)
if count > 400:
print('11111111')
time.sleep(120)
count = 0
print ("count crossed 400....")
print ("sleep for 2 minutes")
else:
logging.info(count)
print(name)
add the line : count = 0, it reset the variable count to 0 if count > 400
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Ill start again and thank you all for replying.
I have a log file, and i take the entry and remove all rubbish from it.
the array or list i am left with is this
23
23.23.23.23
45
45.45.45.45
100
34.34.54.13
how i call each line i want is with this.
a = 1
while a < 18:
a = a + 2
#logging.debug(line.split(PID_ANDROID)[a])
countIP = a
trySomething()
if a == 20:
break
but i have to do things after i call it.
i want to be able to use the first entry,
> do something
> see if something is happening
> if its not goto 3rd entry
> try the same thing again.
this is what I am stuck on.
because when I call it from inside something else and I use global to store.
python tells me I cant us a str or turp. or with code below gives me a continues output of everything in the list.
atm i have this code.
def trySomething():
global countIP
global LOG_SPLITER
#logging.debug('Processing Number: %s' % (countIP,))
logging.debug(LOG_SPLITER.split(PID_ANDROID)[countIP])
time.sleep(.5)
clearScreen()
#grabBox90()
#lineGoto()
my question is.
how can i do the loop, and pull out only one at a time to do something with it, and when i get to a finished loop goto the next one?
It looks as if you should use a for loop with an initial index of 1 and a step size of 2. Alternatively, use the explicit debug statement for value 1 and then loop over the rest, starting at 3, to avoid the if test. If the remainder of the code is to increment by 1 instead of 2, then that allows you to do the initial skip properly while still having the loop.
Instead of
c = 1
#do my stuff
while c < 20:
if c == 1:
logging.debug(line.split(PID_ANDROID)[c])
c = + 2
else:
logging.debug('Moving on to a refresh')
# You do not incremennt c
# c += 2 should go here to increment every time
Python 2
for i in xrange(1,20,2):
# do your processing
Python 3
for i in range(1,20,2):
# do you processing
If you simply want to log every entry in line you could do:
entries = line.split(PID_ANDROID)
for e in entries[::2]: # take every other element
logging.debug(e)
Iterating over the entries is "more pythonic".
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am currently studying computer science as a GCSE student. Me and my teacher are struggling with task 3. The requirements of the task are:
It then needs to ask the user what class they would like to view
After this it will need to ask if they would like to view the file sorted alphabetically, the high scores of the particular class or if they would like to view the average of each student in the selected class
import csv
print("1 for Class A\n2 for Class B\n3 for Class C")
choosen=int(input())
class_a = open('class_a.csv')
class_b = open('class_b.txt')
class_c = open('class_c.txt')
if choosen == 1:
print("1 for for alphabetical orderwith each students highest score\n2 for highest score, highest to lowest\n3 for average score, highest to lowest")
cho_two=int(input())
csv_a = csv.reader(class_a)
a_list = []
for row in csv_a:
row[1] = int(row[1])
row[2] = int(row[2])
row[3] = int(row[4])
minimum = min(row[1:2])
row.append(minimum)
maximum = max(row[1:2])
row.append(maximum)
average = sum(row[1:2])//3
row.append(average)
a_list.append(row[0:9])
if cho_two == 1:
alphabetical = [[x[0],x[6]] for x in a_list]
print("\nCLASS A\nEach students highest by alphabetical order \n")
for alpha_order in sorted(alphabetical):
print(alpha_order)
class_a.close()
elif cho_two == 2:
print("\nCLASS A\nThe highest score to the lowest \n")
for high_scr in sorted(highest_score,reverse = True):
print(high_scr)
class_a.close()
elif cho_two == 3:
average_score = [[x[8],x[0]] for x in a_list]
print("\nCLASS A\nThe average score from highest to lowest \n")
for ave_scr in sorted(average_score,reverse = True):
print(ave_scr)
class_a.close()
My code when run in python tells me there is a problem on line 13 with "index out of range"
My text file contains:
Roo,2,3,
Roo,4,4,
Alfie,5,8,
Alfie,2,8,
Bob,2,8,
Connor,3,5,
Connor,5,3,
Ellis,5,6,
George,5,4,
Ellis,4,9,
Nathan,5,6,
George,5,5,
Alfie,9,4,
George,4,7,
Celis,4,5,
Leo,3,2,
Celis,6,1,
Leo,5,2,
When I run the program the code, row1 = into(row1) tells me it's out of range? Any solutions?
Python - like most programming languages - uses zero-based indexing, which means the first element of a sequence is at index 0 and the last one at index len(sequence) - 1.
In your code you have rows with three elements each, and you are trying to access row[3], which would be the index of an (inexistant) fourth element, hence your error.
Also if your teacher is "struggling" with such a basic problem, you should probably find a competent teacher instead.