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".
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 months ago.
Improve this question
I'm trying to do a number guessing game where the computer selects a random number and you have to guess it and get an output that's either: Your number is too high, too low or correct number + needed attempts.
However with this code:
import numbers
from random import randint
#set x to a random number between 1 and 50
randomnummer = randint(1,51)
print (randomnummer)
#counter = 0
#ask to input a number between 1 and 50 and check if input is valid
def nummer_eingabe():
usernummer = (input("Please enter a number between 1 and 50: "))
usernummer = int(usernummer)
#counter = counter + 1
if usernummer >= 1 and usernummer <= 50:
return usernummer
else:
print("Pleae enter a valid number.")
return nummer_eingabe()
#declare number from function
checked_user_nummer = nummer_eingabe()
#define counter
counter = 0
while checked_user_nummer != randomnummer:
counter += 1
if checked_user_nummer > randomnummer:
print("You need to guess lower. Try again :)")
nummer_eingabe()
continue
elif checked_user_nummer < randomnummer:
print("You need to guess higher. Try again :)")
nummer_eingabe()
continue
elif checked_user_nummer == randomnummer:
strcounter = str(counter)
print("Nice! You needed " + strcounter + " tries to find the right number")
break
#dont allow console to close right away
input()
it goes well until it gets stuck giving the same feedback (either too high or too low)
How do I get out of the While loop? I tried changing up the continue statement with a break but that just causes the code to stop after the second time the input was given.
Also please dont mind the print(randomnummer) on line 5; that's just for debugging purposes.
You never reassign the variable. You call nummer_eingabe() but you discard the result.
You're now in a stage where you no longer want to debug your code using print() statements but learn how to debug small programs.
Make sure you don't write code in Notepad and use a decent IDE like Pycharm instead. Set a breakpoint wherever your code gets stuck (just click left of the code and right of the line number)
and hit the little bug icon to debug it. You will be able to see the variables on the go. After each single line of code, check if they match your expectation
After entering a value of 10, you'll see that the variable is still 50 - a clear indicator that the value did not get updated because you didn't make use of the return value of the function.
Don't call the function again on the while, instead do a while to check for a "trigger" and then use your while checked_user_number != randomnummer:
Then instead of break use the trigger = False and end the while.
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 is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
Below is my first python program. I am trying idea not yet covered in class as i hate staying stagnant and want to solve issues that may arise if i were to just use the info we've learned in class. As for my question, the program works but what were be ways to condense the code, if any? Thanks!
#This is a program to provide an itemized receipt for a campsite
# CONSTANTS
ELECTRICITY=10.00 #one time electricity charge
class colors:
ERROR = "\033[91m"
END = "\033[0m"
#input validation
while True:
while True:
try:
nightly_rate=float(input("Enter the Basic Nightly Rate:$"))
except ValueError:
print(colors.ERROR +"ERROR: Please Enter the Dollar Amount"+colors.END)
else:
break
while True:
try:
number_of_nights=int(input("Enter the Number of Nights You Will Be Staying:"))
except ValueError:
print(colors.ERROR +"ERROR: Please Enter a Number"+colors.END)
else:
break
while True:
try:
campers=int(input("Enter the Number of Campers:"))
except ValueError:
print(colors.ERROR +"ERROR: Please Enter a Number"+colors.END)
else:
break
break
#processing
while True:
try:
campsite=nightly_rate*number_of_nights
tax=(ELECTRICITY*0.07)+(campsite*0.07)
ranger=(campsite+ELECTRICITY+tax)*0.15 #gratuity paid towards Ranger
total=campsite+ELECTRICITY+tax+ranger #total paid per camper
total_per=total/campers
except ZeroDivisionError: #attempt to work around ZeroDivisionError
total_per=0 #total per set to zero as the user inputed 0 for number-
break #-of campers
#Output #Cant figure out how to get only the output colored
print("Nightly Rate-----------------------",nightly_rate)
print("Number of Nights-------------------",number_of_nights)
print("Number of Campers------------------",campers)
print()
print("Campsite--------------------------- $%4.2f"%campsite)
print("Electricity------------------------ $%4.2f"%ELECTRICITY)
print("Tax-------------------------------- $%4.2f"%tax)
print("Ranger----------------------------- $%4.2f"%ranger)
print("Total------------------------------ $%4.2f"%total)
print()
print("Cost Per Camper------------------- $%4.2f"%total_per)
The else in try statement is unnecessary. You can just put the break in the the end of the try statement. REF
In the end, in the print statements, I recommend you to use another types of formatting. You can use '...{}..'.format(..) or further pythonic is f'...{val}'. Your method is the oldest. More ref
You can remove both the outer while loops, as break is seen there at the top level, so the loops runs once only.
You can convert colors to an Enum class if desired (this is more of a stylistic choice tbh)
The line tax=(ELECTRICITY*0.07)+(campsite*0.07) can be represented as x*0.07 + y*0.07, which can be simplified to 0.07(x+y) or 0.07 * (ELECTRICITY + campsite) in this case.
Instead of manually padding the - characters in the print statements, you can use f-strings with simple formatting trick.
For example, try this out:
width = 40
fill = '-'
tax = 1.2345
print(f'{"Tax":{fill}<{width}} ${tax:4.2f}')
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 1 year ago.
Improve this question
Question: Write a program that reads table with given columns from input stream. Columns are name, amount, debt. Then filter the table (condition: debt is equal to 0). After that increase debt by 42% then print results.
I am a beginner in Python and have tried multiple times but still couldn't fixed the problem. Help will be much appreciated.
Input:
10
Tatiana Santos 411889 36881
Yuvraj Holden 121877 0
Theia Nicholson 783887 591951
Raife Padilla 445511 0
Hamaad Millington 818507 276592
Maksim Whitehead 310884 0
Iosif Portillo 773233 0
Lachlan Daniels 115100 0
Evie-Grace Reese 545083 0
Ashlea Cooper 68771 0
Required Output:
Tatiana Santos 411889 52371.02
Theia Nicholson 783887 840570.42
Hamaad Millington 818507 392760.64
My Solution:
def input_data(n):
tup = []
if n>0:
tup.append(tuple(map(str,input().split(" "))))
input_data(n-1) #I know there's a problem in the recursion. I am not #doing anything with the return value. Please help
return tup
def filtertuple(* tup): # After debugged I got to know at this point only one row is passed to function
newtuple = filter(lambda i: i[2]!=0,tup)
return tuple(newtuple)
def increasedebt(newtuple):
newtuple1 = tuple(map(lambda i:(i[2])*(142/100)),newtuple)
return (newtuple1)
def output_data():
n=int(input())
return n
print(increasedebt(filtertuple(input_data(output_data()))))
Error: Traceback (most recent call last):
File "C:\Users\msi-pc\PycharmProjects\ProgramminglanguageTask3\main.py",
line 28, in <module>
print(increasedebt(filtertuple(input_data(output_data()))))
File "C:\Users\msi-pc\PycharmProjects\ProgramminglanguageTask3\main.py",
line 14, in filtertuple
return tuple(newtuple)
File "C:\Users\msi-pc\PycharmProjects\ProgramminglanguageTask3\main.py",
line 12, in <lambda>
newtuple = filter(lambda i: i[2] != 0, tup)
IndexError: list index out of range
I see two main issues with how your code passes the data from input_data to filtertuple.
The first issue is that your recursion in input_data is messed up, you never do anything with the results of the recursive calls so only the first row of input data gets included in the final return value. Recursion really isn't an ideal approach to this problem, a loop would be a lot simpler and cleaner. But you could make the recursion work, if you do something with the value returned to you, like tup.extend(intput_data(n-1)). If you stick with recursion, you'll also need to make the base case return something appropriate (or add an extra check for None), like an empty list (or tuple).
The second issue is that filtertuple is written to expect many arguments, but you're only passing it one. So tup will always be a 1-tuple containing the actual argument. If you're expecting the one argument to be a list of tuples (or tuple of tuples, I'm not sure exactly what API you're aiming for), you shouldn't use *tup in the argument list, just tup is good without the star. You could call filtertuple(*input_data(...)) which would unpack your tuple of tuples into many arguments, but that would be silly if the function is just going to pack them back up into tup again.
There may be other issues further along in the code, I was only focused on the input_data and filtertuple interactions, since that's what you were asking about.
Here's my take on solving your problem:
def gather_data(num_lines):
if num_lines == 0: # base case
return [] # returns an empty list
data = gather_data(num_lines-1) # recursive case, always gives us a list
row = tuple(map(int, input().split(" "))) # get one new row
data.append(row) # add it to the existing list
return data
def filter_zeros(data): # note, we only expect one argument (a list of tuples)
return list(filter(lambda i: i[1] != 0, data))
def adjust_debt(data): # this only returns a single column, should it return
return list(map(lambda i: (i[1]) * (142 / 100), data)) # the whole table?
# calling code:
num_lines = int(input()) # this code really didn't deserve its own function
data = gather_data(num_lines) # extra variables help debugging
filtered = filter_zeros(data) # but they could be dropped later
adjusted = adjust_debt(filtered)
print(adjusted)
I did find one extra issue, you had the parentheses wrong in the function I renamed to adjust_debt.
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