Python continue and break usage [closed] - python

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

Related

How would I add the results of a 'for' loop into a dictionary? [closed]

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)

Find the "1"s in a list [closed]

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

Linking elements of a list as a tree [closed]

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 3 years ago.
Improve this question
I have a python list that looks like this for example :
[Product(parent=tube,child=spokes), Product(parent=bicycle, child=wheel), Product(parent=wheel,child=tube)]
Where Product is a python class with two members parent and child.
The Products could appear in any order in the list.
What would be the most efficient one liner to achieve the following :
Given an input spokes for example , return the `root of the tree` , bicycle in this case.
What have i tried so far : inefficient for loops that does not give the right results when the Product does not appear in the same order each time.
You do not write how strong assumption you can apply to data (if it is always proper tree). So my code check some conditions to not stick in infinity loop.
def find_root(pr_list, child):
if len(pr_list) == 0:
return None
child_translate_dict = {x.child: x for x in pr_list}
potential_root = child
count = 0
while count < len(pr_list):
if potential_root not in child_translate_dict:
return potential_root
else:
potential_root = child_translate_dict[potential_root].parent
count += 1
return None
and shorter version
def find_root(pr_list, child):
child_translate_dict = {x.child: x for x in pr_list}
while child in child_translate_dict:
child = child_translate_dict[potential_root].parent
return child
Here is a pseudo code for your problem :
def recursiveRootFinder(child,theList):
for(i in theList):
if (i.child==child):
child=recursiveRootFinder(i.parent,theList)
return child
You can use lambda definition to implement it in one line like that :
lambda child,theList: recursiveRootFinder(i.parent,theList) for i in list if i.child==child if [1 for i in list if i.child==child]!=[] else child

while loop calling array outside [closed]

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".

Command line: Show list of options and let user choose [closed]

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 7 years ago.
Improve this question
Assuming I have a list of options:
options = ["Option 1", "Option 2", "Option 3"]
And I would like the user to choose an option on the command line, e.g. something like this:
Please choose:
1) Option 1
2) Option 2
3) Option 3
Enter number: <user input>
So I am looking for the implementation of the following:
choice = let_user_pick(options) # returns integer
How would one go about this in python?
def let_user_pick(options):
print("Please choose:")
for idx, element in enumerate(options):
print("{}) {}".format(idx+1,element))
i = input("Enter number: ")
try:
if 0 < int(i) <= len(options):
return int(i)
except:
pass
return None
You might want to instead return int(i)-1 in order to use the result as an index of your options list, or return the option directly. It might also be good to instead of returning None loop over the whole thing until the user enters a correct choice.

Categories

Resources