Error adding list in loop condition in python [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
while dir_loop_water < water_lenth:
ds_water = gdal.Open('path'+ dirlist_water[dir_loop_water] , gdal.GA_ReadOnly)
numer_of_band_water = str(ds_water.RasterCount)
if numer_of_band_water == '3':
print('water condition matched')
rb_water = ds_water.GetRasterBand(1)
band1_water_tmp = rb_water.ReadAsArray()
band1_water = band1_water_tmp.tolist()
rb2_water = ds_water.GetRasterBand(2)
band2_water_tmp = rb2_water.ReadAsArray()
band2_water = band2_water_tmp.tolist()
rb3_water = ds_water.GetRasterBand(3)
band3_water_tmp = rb3_water.ReadAsArray()
band3_water = band3_water_tmp.tolist()
[cols_water,rows_water] = band1_water_tmp.shape
loop_water_cols = 0
while loop_water_cols < cols_water:
loop_water_rows = 0
while loop_water_rows < rows_water:
dataset.append([band1_water[loop_water_cols][loop_water_rows],band2_water[loop_water_cols][loop_water_rows],band3_water[loop_water_cols][loop_water_rows],0])
loop_water_rows = loop_water_rows +1
del dataset[0]
with open('path/dataset.csv', 'a') as f:
writer = csv.writer(f)
writer.writerows(dataset)
f.close()
dataset= [None]
loop_water_cols = loop_water_cols +1
dir_loop_water= dir_loop_water+1
With the above code, I want to add lists with length 4 to dataset.
but i print dataset's value(print(dataset[number])), it print like this.
[0.02672404982149601, 0.003426517592743039, 28.19584846496582, 0]
[0.02675003558397293, 0.00344488094560802, 28.192949295043945, 0]
In my opinion of above code, I add one list with four values.
However, the result is a combination of two lists with four values.
I could not find where the list would be merged.
Thanks for letting me know how to add only one list with 4 values at a time.

Your dataset.append() method is appending the entire list into your list (making a list of lists).
To append each item of the new list into the dataset (If I'm understanding you correctly) use += like so:
dataset += [band1_water[loop_water_cols][loop_water_rows],band2_water[loop_water_cols][loop_water_rows],band3_water[loop_water_cols][loop_water_rows],0]
this will result in a list like so:
[0.02672404982149601, 0.003426517592743039, 28.19584846496582, 0, 0.02675003558397293, 0.00344488094560802, 28.192949295043945, 0]

Related

How to solve the error in the following program which is written Functional Programming way? [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 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.

Using txt files to retrieve questions and multiple answers [duplicate]

This question already has answers here:
How to read a text file into a list or an array with Python
(6 answers)
Closed 1 year ago.
I am currently making a quiz through python and Tkinter. I’m trying to use txt files, one for my questions and one for my set of answers for the said question, as well as one for explanations for the answers. However, I’m not sure how to implement this into my code. I’m not sure how to retrieve a question from the txt file and represent it as a label while also having the correct set of answers for that question represented as buttons for the user to choose. As well as display the text for the correct explanation for the answer. Is there a simple way to do this? Should I rather use an array instead?
This should get you started on the idea of how I think you should proceed.
Store the question and answer and id in a dictionary like:
data = {question:[id,answer]}
# So it would be like
data = {'Who was the first prime minister of india?':[1,'Jawaharlal Nehru'],
'Tallest building in the world':[2,'Burj Khalifa'],
'Largest country in the world':[3,'Russia']}
Create a file explanation.txt and then store the id and explanation in the form of:
id - explanation
So the text file for explanation(explnation.txt) would be something like:
1 - Your explanation goes here: Tryst with destiny
2 - UAE
3 - WC 2018
So then the code for all this together would be something like:
import tkinter as tk
import random
root = tk.Tk()
# Store it here
data = {'Who was the first prime minister of india?':[1,'Jawaharlal Nehru'],
'Tallest building in the world':[2,'Burj Khalifa'],
'Largest country in the world':[3,'Russia']}
score = 0 # Score of correct answers
def get_question():
global id, answer, explanation
exp_label.config(text='') # Clear the previous explanation
question = random.choice(list(data.keys())) # Get the question
item = data[question] # Get the corresponding list
id = item[0] # Get the id from the list
answer = item[1] # Get the answer from the list
explanation = get_explanation(id) # Find the explanation using the id
q_label.config(text=question) # Update the question to this
def submit():
global score
if answer_ent.get().lower() == answer.lower(): # If correct answer
score += 1 # Increase the score by 1
score_label.config(text=f'Score: {score}') # Update the score label
else: # If wrong answer
exp_label.config(text=explanation) # Show the explanation
answer_ent.delete(0,'end') # Clear the entry
def get_explanation(id):
with open('explanation.txt','r') as file: # Open the file
lst = file.readlines() # Read each line and make it a list
for i in lst: # Looping through that list
fetched_id = i.split(' - ')[0] # Split the txt with ' - ' and get the id
if int(fetched_id) == id: # If fetched and our question id are same
explanation = i.split(' - ')[1][:-1] # Get the explanation and trim the \n
return explanation # Return it
q_label = tk.Label(root,font=(0,21))
q_label.grid(row=0,column=0)
answer_ent = tk.Entry(root)
answer_ent.grid(row=1,column=0,pady=10,padx=20)
exp_label = tk.Label(root,font=(0,13))
exp_label.grid(row=3,column=0,pady=10)
score_label = tk.Label(root,text='Score: 0',font=(0,13))
score_label.grid(row=4,column=0)
tk.Button(root,text='Submit',command=submit).grid(row=5,column=0,pady=10)
tk.Button(root,text='Next',command=get_question).grid(row=6,column=0,pady=10)
get_question() # Call the function immediately
root.mainloop()
I have explained the code using comments to make it understandable on-the-go. This is just a small scale example that you can take and expand and more features, like making sure no same question is repeated and so on. This way just seems easy for me using tkinter.

Add a tuple to a list of tuples [closed]

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 2 years ago.
Improve this question
I am trying to automate few of my DBA tasks using python3.
x = " ##Hostname: host1"
y = "##innodb_buffer_pool_size: 1"
z = " ##Max_connections: 150"
op = {}
a = tuple(x.split(':'))
b = tuple(y.split(':'))
c = tuple(z.split(':'))
host=""
if (a[0].strip()).lower() == "##hostname" and (a[1].strip()).lower() not in op:
host = a[1].strip()
op[host] = []
if (b[0].strip()).lower() == "##innodb_buffer_pool_size" and int(b[1].lstrip())<2:
#z = b[0].strip().lstrip('##'),b[1].strip()
op[host].append((b[0].strip().lstrip('##'),b[1].strip()))
if (c[0].strip()).lower() == "##Max_connections" and int(c[1].lstrip())<152:
op[host].append((c[0].strip().lstrip('##'),c[1].strip()))
#elif (a[0].strip()).lower() == "##log_bin" and int(a[1].strip()) == 0:
# op[host].append(tuple((a[0].strip()).lstrip('##'),a[1].strip()))
#elif (a[0].strip()).lower() == "##expire_logs_days" and int(a[1].strip()) == 0:
# op[host].append(tuple((a[0].strip()).lstrip('##'),a[1].strip()))
#else:
# pass
#print (c)
print (op)
Output i am getting:
{'host1': [('innodb_buffer_pool_size', '1')]}
Output i am expecting:
{'host1': [('innodb_buffer_pool_size', '1'),('max_connections','150')]}
If you look at my the code, my first append statement appends tuple to an empty list.
But my second append is not appending to the tuple to the list .
I cannot understand why this behaviour since this first python project and what should be done to append a tuple to an existing list for a specific key in a dictionary.
This is only part of the script, I am trying to iterate through several files and construct a list of tuples for each host with each unique host being the key, hence constructing a dictionary.
Thanks
When you have this kind of case, leanr to debug and split your code, here the problem from the if using Max_connections because that's the one missing
When printing the 2 conditions we have
print((c[0].strip()).lower() == "##Max_connections", int(c[1].lstrip()) < 152) # False True
Then looking further at the first, you set the value as lowercase but your testing stirng contains an uppercase : not valie
Correction
if (c[0].strip()).lower() == "##max_connections" and int(c[1].lstrip()) < 152:

Python create nested dict in for loop [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'm trying to created a nested dictionary but I have a problem inside the for loop, at least is what I'm thinking.
I do several requests based on args passed but when I try to add values to the nested dict created before it just adds the last arg passed.
I'll show the code and the output.
def api_metrics():
my_list = []
my_dict_1 = {}
number = len(my_metrics)
metricz = range(number)
for indice in metricz:
my_dict_1[indice] = {}
for metric in my_metrics:
urlnotoken = ""
urlnotoken = urlnotoken.replace(" ","%20")
preurl = urlnotoken + "&dateToken="+expirationDate
msg = preurl + apikey
token = calcMd5(msg)
finalurl = "http://"+host+preurl+"&token="+token
data_get = requests.get(finalurl, headers=app_headers)
json_data = json.loads(data_get.text)
metrics_path = json_data['data'][0]['metrics'][0]
metric_name = metrics_path['label']
metric_value = metrics_path['values'][0]['data'][0][1]
metric_unit = metrics_path['magnitudes']['y']
my_list.append(metric_name)
my_list.append(metric_value)
my_list.append(metric_unit)
number = len(my_metrics)
metricz = range(number)
my_values = metric
for entry in my_dict_1.keys():
my_dict_1[entry] = metric
return(my_dict_1)
And the output
{0: 'avgRenditionSwitchTime', 1: 'avgRenditionSwitchTime', 2: 'avgRenditionSwitchTime', 3: 'avgRenditionSwitchTime', 4: 'avgRenditionSwitchTime'}"
This should output the different args passed. I have moved the code inside and outside the loop, I've read lots of posts but I need further help!
Cheers.
In here:
for entry in my_dict_1.keys():
my_dict_1[entry] = metric
You are assigning the value of metric to all your dict (my_dict_1) items. Reason why 'it just adds the last arg passed'.
Without cleaning up your code, here's the patch to fix your issue:
for i, metric in enumerate(my_metrics):
...
my_dict_1[i] = metric

struggling with python homework [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 5 years ago.
Improve this question
I got a .txt file with some lines in it:
325255, Jan Jansen
334343, Erik Materus
235434, Ali Ahson
645345, Eva Versteeg
534545, Jan de Wilde
345355, Henk de Vries
Write a program that starts with opening the file kaartnummers.txt
Determine the number of lines and the largest card number in the file. Then print these data.
my code isnt finished yet but i tried atleast!:
def kaartinfo():
lst = []
infile = open('kaartnummers.txt', 'r')
content = infile.readlines()
print(len(content))
for i in content:
print(i.split())
kaartinfo()
I know that my program opens the file and counts the number of lines in it.. all after that is wrong <3
I can't figure out how to get the max number in the list.. Please if you got an answer use simple readable Python Language.
I'm not good at python, and there are probably much more elegant solutions, but this is how I would do it. Some may say this is like C++/Java in python, which many tend to avoid.
def kaartinfo():
lst = []
infile = open('kaartnummers.txt', 'r')
content = infile.readlines()
for i in content:
value = i.split(',')
value[0] = int(value[0])
lst.append(value)
return lst
Use the kaartinfo() function to retrieve a list
my_list = kaartinfo()
Assume first value is the maximum
maximumValue = my_list[0][0]
Go through every value in the list, check if they are greater than the current maximum
# if they are, set them as the new current maximum
for ele in my_list:
if ele[0] > maximumValue:
maximumValue = ele[0]
when the above loop finishes, maximum value will be the largest value in the list.
#Convert the integer back to a string, and print the result
print(str(maximumValue) + ' is the maximum value in the file!')
This should be enough to do the job:
with open('kaartnummers.txt', 'r') as f:
data = f.readlines()
print('There are %d lines in the file.' % len(data))
print('Max value is %s.' % max(line.split(',')[0] for line in data))
Given the input file you provided, the output would be:
There are 6 lines in the file.
Max value is 645345.
Of course, you can put it in a function if you like.

Categories

Resources