I am using tkinter to bring up a dialog box where the user can choose a file. I want to parse that file starting on line 11. The file looks like this:
(115,147)
(6,145)
(44,112)
(17,72)
(112,1)
(60,142)
(47,158)
(35,43)
(34,20)
(38,33)
11101111110111011111111110111111111111111111111011111111111111110111111111
111101111101111a11011122112011222222211112111221221111101111111111110111ab
..more down here
How do I retrieve each character when they are not separated by spaces? I know I have to start off like this:
# Bring up save dialog box
file_path = filedialog.askopenfilename(filetypes=[("Text files","*.txt")])
# Check if user clicked cancel
if file is None or file is '':
return False
# Read from file
with open(file, 'r') as f:
# Do something here with f.read()
I want to get these numbers in a list (each at their own index):
11101111110111011111111110111111111111111111111011111111111111110111111111
111101111101111a11011122112011222222211112111221221111101111111111110111ab
Any help would be appreciated, thank you!
Firstly, you need to read() data from the file, and then split by newlines to get a list of lines in the file:
lines=f.read().split("\n")
If you only need from line 11 to the end, you can use:
lines=lines[10:]
And then iterate through it, using list() to split into characters:
characters=[list(line)for line in lines]
Output:
[['1', '1', '1', '0', '1', '1', '1', '1', '1', '1', '0', '1', '1', '1', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1'], ['1', '1', '1', '1', '0', '1', '1', '1', '1', '1', '0', '1', '1', '1', '1', 'a', '1', '1', '0', '1', '1', '1', '2', '2', '1', '1', '2', '0', '1', '1', '2', '2', '2', '2', '2', '2', '2', '1', '1', '1', '1', '2', '1', '1', '1', '2', '2', '1', '2', '2', '1', '1', '1', '1', '1', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '0', '1', '1', '1', 'a', 'b']]
# consume 10 lines
for _ in range(10):
f.readline()
# read one character at a time
# f.read(1) will return '' when you reach eof
c = f.read(1)
while c:
# do something with c
c = f.read(1)
For that matter, since lists and strings are sort of the same in python, you could just say
# consume 10 lines
for _ in range(10):
f.readline()
rest = f.read()
and then rest would be a list/string with everything in it...i.e., rest[0] is the first char, rest[1] the next, etc. Be aware that you will capture newlines too this way.
Related
I want to know why is it that my if statements are not working. I have code that compares a recently compiled list to a bunch of other lists to see if there is a similar one.
The lists are made up of 12 values, direction of the list, and the number of times that same list has occurred. the comparison is done between the first 12 values of each list then what should happen is the position that is found with that list should be identified, however it seems I am unable to call that into action.
In essence this is what I want to do...
These are the lists I want to compare to one another:
list1 = [['1', '1', '1', '1', '1', '0', '1', '0', '1', '0', '1', 'up', 5], ['1', '0', '0', '1', '1', '0', '1', '0', '0', '0', '0', 'up', 2], ['1', '0', '1', '1', '0', '0', '1', '1', '1', '1', '1', 'up', 13], ['1', '0', '0', '1', '1', '0', '1', '1', '0', '0', '1', 'down', 5], ['0', '0', '1', '0', '1', '0', '1', '1', '1', '0', '1', 'up', 8], ['0', '1', '0', '1', '0', '1', '1', '1', '1', '0', '1', 'up', 10], ['0', '1', '1', '1', '0', '0', '0', '0', '1', '1', '0', 'up', 6], ['1', '1', '0', '1', '1', '1', '0', '0', '0', '0', '0', 'down', 8], ['0', '0', '1', '0', '1', '1', '1', '0', '1', '0', '1', 'up', 6], ['0', '1', '0', '1', '0', '0', '0', '0', '0', '0', '1', 'up', 1], ['0', '0', '0', '0', '0', '1', '1', '1', '0', '1', '0', 'up', 3], ['0', '0', '0', '1', '1', '0', '0', '1', '0', '1', '1', 'up', 7], ['1', '1', '1', '1', '1', '1', '1', '0', '1', '0', '1', 'up', 9], ['0', '0', '0', '1', '0', '0', '0', '0', '1', '0', '1', 'down', 7], ['0', '0', '0', '1', '0', '1', '1', '1', '1', '1', '1', 'down', 1]]
list2 = ['1', '0', '0', '1', '1', '0', '1', '0', '0', '0', '0']
This is the comparison code I want to use for the lists:
def fl(list1, list2):
index = -1
occ = 0
for i, l in enumerate(list2):
if l[:len(list1)] == list1:
if l[-1] > occ:
index = i
occ = l[-1]
if index == -1:
return "The first list is not present in the second one."
else:
print(f"The first lists appears in the second one at index {index} with a number of occurences equal too {occ}.")
u = "up"
y = "down"
lp = [(''.join(a[:6]), a[6]) for a in list2]
if (''.join(list1), u) in lp:
print("up")
elif (''.join(list1), y) in lp:
print("down")
print(fl(listB, listA))
This is the result I want to get:
The first lists appears in the second one at index 2 with a number of occurrences equal to 2.
up
However what I seem too get is this:
The first lists appears in the second one at index 2 with a number of occurrences equal too 2.
None
Why am I getting none and how can I solve this issue?
I think your problem is caused in the if/elif statement. In general if/elif should be used ONLY when you know that you covered ALL possible scenarios in your code.
I want a way to make it so that I can use list B to find out if a copy of it's self exists in list A.
I want a way to make it so that I can use list B to find out if a copy of it's self exists in list A.
this is the way data a has been collected:
for i in range(len(fsa)):
if fsa[i] < fsb[i]:
kol.append('1')
else:
kol.append('0')
start = 0
end = len(fsa)
j = [ ]
for x in range(start, end, 6):
m = fsb[x:x+6]
t = kol[x:x+6]
if m[0] < m[-1]:
t.append('up')
else:
t.append('down')
j.append(t)
counter = Counter(tuple(j) for j in j)
for members, count, in counter.items():
print(list(members), count)
output:
listA = ['1', '1', '0', '1', '0', '1', 'down'] 2
['0', '0', '1', '1', '1', '1', 'up'] 2
['1', '0', '0', '1', '0', '1', 'up'] 1
['0', '0', '0', '1', '1', '0', 'up'] 2
['1', '1', '0', '0', '0', '0', 'up'] 1
['0', '0', '1', '1', '0', '1', 'down'] 1
['1', '0', '0', '0', '0', '1', 'down'] 1
['1', '1', '1', '1', '1', '1', 'up'] 1
this is how data b was collected:
for _ in range(num):
inner = driver.find_element_by_xpath("//html/body/div[1]/div[2]/div/div/div/div[2]/div/div[2]/div[2]/div/div/div[2]/div[4]/span[1]").get_attribute("innerHTML")
print(inner)
lok.append(inner)
time.sleep(20)#the hour
print(lok)
lokk = []
num = 7
for _ in range(num):
inner = driver.find_element_by_xpath("//html/body/div[1]/div[2]/div/div/div/div[2]/div/div[2]/div[2]/div/div/div[2]/div[4]/span[1]").get_attribute("innerHTML")
print(inner)
lokk.append(inner)
time.sleep(20)
print(lokk)
output:
listB = ['1', '1', '1', '1', '1', '1']
list A also shows how many times that particular list has appeared
so I want a way to first find the repeating list of list B in list A, secondly to select the one with the most repetitions in the case that there are multiple versions of it.
I tried a bunch of things but non really helped as i am still quite new at coding
As many pointed out, the code provided is not properly formatted, so I made some assumptions. Here is a half-solution to get you unstuck, try to modify this to get what you want. You will learn more by modifying this code than if I were to give you the final solution.
from collections import Counter # for comparing lists' content
from typing import List # for annotations
listA = [
['1', '1', '0', '1', '0', '1', 'down'],
['0', '0', '1', '1', '1', '1', 'up'],
['1', '0', '0', '1', '0', '1', 'up'],
['0', '0', '0', '1', '1', '0', 'up'],
['1', '1', '0', '0', '0', '0', 'up'],
['0', '0', '1', '1', '0', '1', 'down'],
['1', '0', '0', '0', '0', '1', 'down'],
['1', '1', '1', '1', '1', '1', 'up'],
]
listB = ['1', '1', '1', '1', '1', '1']
def find_match(metrix: List[List[str]], list_: List[str]) -> List[List[str]]:
list_counter = Counter(list_)
# Solution 1: Pythonic solution
matches = [match for match in metrix if Counter(match[:-1]) == list_counter]
# Solution 2: beginner friendly solution
# matches = []
# for m_list in metrix:
# if Counter(m_list[:-1]) == list_counter:
# matches.append(m_list)
return matches
# Complexities
# if n == metrix.length and m == metrix[0].length; then
# Time: O(nm);
# Space: O(nm);
print(find_match(listA, listB))
# outputs: [['1', '1', '1', '1', '1', '1', 'up']]
Here's something that works. Not sure if it's exactly what you want, but you can modify it to fit your needs.
Note that it assumes listB has the same length as the first part of each of listA elements (before "up"/"down").
listA =[
['1', '1', '0', '1', '0', '1', 'down', 2],
['0', '0', '1', '1', '1', '1', 'up', 2],
['1', '0', '0', '1', '0', '1', 'up', 1],
['0', '0', '0', '1', '1', '0', 'up', 2],
['1', '1', '0', '0', '0', '0', 'up', 1],
['0', '0', '1', '1', '0', '1', 'down', 1],
['1', '0', '0', '0', '0', '1', 'down', 1],
['1', '1', '1', '1', '1', '1', 'up', 1]
]
listB = ['1', '1', '1', '1', '1', '1']
listC = ['0','0','0','0','0','0']
def find_list(list1,list2):
index = -1
occ = 0
for i,l in enumerate(list2):
if l[:len(list1)]==list1:
if l[-1]>occ:
index = i
occ = l[-1]
if index == -1:
return "The 1st list doesn't appear in the 2nd one."
else:
return f"The 1st list appears in the 2nd one at index {index} with a number of occurences equal to {occ}."
print(find_list(listB, listA))
# The 1st list appears in the 2nd one at index 7 with a number of occurences equal to 1.
print(find_list(listC, listA))
# The 1st list doesn't appear in the 2nd one.
I am cleaning up data in a .txt file. I use 3 different .txt. files to analyze and clean up three different constructs. The .txt files all have 10 respondents, the first and the last have 17 answers per respondent. The middle one has 16 answers per respondent. The problem I'm facing right now is that the first and last work, but the middle one with 16 questions has problems with the index. All three pieces of code look almost identical.
The error code:
Traceback (most recent call last):
File "main.py", line 161, in <module>
itemF = dataF[row,column]
IndexError: index 16 is out of bounds for axis 1 with size 16
Sample input:
['N.v.t.', '0', '1', '2', '1', 'N.v.t.', '0', '0', '2', '0', '0', '3', '2', '3', '1', '1']
['N.v.t.', '1', 'N.v.t.', '0', '0', 'N.v.t.', '2', '0', 'N.v.t.', '1', '0', '1', '1', '2', '0', '1']
['N.v.t.', '0', 'N.v.t.', '0', '0', 'N.v.t.', '0', '0', 'N.v.t.', '0', '0', '3', '0', '3', '0', '0']
['2', '2', 'N.v.t.', '1', '3', '1', '2', '1', '1', '3', '2', '2', '3', '1', '2', '3']
['1', '2', 'N.v.t.', '0', '0', 'N.v.t.', '2', '2', '0', '2', '1', '2', '2', '3', '1', '2']
['N.v.t.', '0', 'N.v.t.', '1', '0', 'N.v.t.', '1', '2', 'N.v.t.', '1', '0', '3', '1', '3', '2', '2']
['0', '3', 'N.v.t.', '0', '2', '3', '2', '1', '3', '2', '2', '2', '2', '3', '0', '1']
['1', '3', 'N.v.t.', '0', '2', 'N.v.t.', '0', '2', 'N.v.t.', '0', '1', '1', '0', '2', '2', '1']
['1', '2', '2', '2', '3', '3', '0', '2', '2', '2', '2', '2', '2', '2', '2', '1']
['1', '2', 'N.v.t.', '0', '2', 'N.v.t.', '1', '3', '2', '2', '1', '3', '2', '2', '2', '2']
The code:
import numpy
dataF = numpy.loadtxt("answersFEAR.txt", dtype = str, delimiter = ", ")
shapeF = dataF.shape
(shapeF[0] == 5)
print(dataF)
for i in range(0, shape[0]):
str1 = dataF[i, 0]
str2 = dataF[i, -1]
dataF[i, 0] = str1.replace('[', '')
dataF[i, -1] = str2.replace(']', '')
for column in range(0,shape[1]):
for row in range(0, shape[0]):
itemF = dataF[row,column]
dataF[rij,kolom] = itemF.replace("'", '')
dataF[dataF == 'N.v.t.'] = numpy.nan
print("DATA FEAR")
print(dataD)
scoresF = dataF[:,1:17]
scoresF = scoresF.astype(float)
average_score_fear = numpy.nanmean(scoresF, axis = 1)
print("")
print("AVERAGE SCORE FEAR")
print(average_score_fear)
The expected outcome should look like this (this is just one result):
["['1'" "'2'" "'2'" "'2'" "'3'" "'3'" "'0'" "'2'" "'2'" "'2'" "'2'" "'2'" '2'" "'2'" "'2'" "'1']"]
DATA FEAR
[['1', '2', '2', '2', '3', '3', '0', '2', '2', '2', '2', '2', '2', '2', '2', '1']]
AVERAGE SCORE FEAR
I need to take an input (ranging from 1-12) from the user and store the data as binary. (cannot use arrays)
For example: if the user inputs 3, it would return 000000000100. (the 3rd digit from the right)
I was thinking that this would be possible with a log algorithm, but I don't really know where to start. How would I do this? Any help is appreciated.
If I am reading this problem correctly you are being fed in numbers 1-12 and depending on what numbers are fed in you need to return a binary string where the bits at whatever positions are given are equal to one (without lists/arrays). To achieve this you could read in values to a set and then construct a string where the inputted values are one and everything else is zero. Like this:
def read_in():
positions = set()
while True:
print('Enter 1-12 or Q to stop:',end=' ')
entry = input()
if entry != 'Q':
positions.add(int(entry))
else:
break
ret = ''
for i in range(12,0,-1):
if i in positions:
ret += '1'
else:
ret += '0'
return ret
print(read_in())
If you want to update any index to 1 multiple times across multiple inputs, you might want to use a list containing 12 elements that you can tick. Then with that list, you can already get both the string value e.g. "000000000100" and the int value e.g. 4
# Initialize list that we will tick
bin_digits = ["0"] * 12
# Let's assume that the input from user is from 1 to 12
for num in range(1, 13):
# Tick the target index
bin_digits[-num] = "1"
bin_str = "".join(bin_digits) # String value
bin_int = int(bin_str, 2) # Int value
print(bin_digits, bin_str, bin_int)
Output
['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1'] 000000000001 1
['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1'] 000000000011 3
['0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1'] 000000000111 7
['0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1'] 000000001111 15
['0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1'] 000000011111 31
['0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1'] 000000111111 63
['0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1'] 000001111111 127
['0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1'] 000011111111 255
['0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1'] 000111111111 511
['0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'] 001111111111 1023
['0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'] 011111111111 2047
['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'] 111111111111 4095
I'm trying to append data to a google sheet from my python script. Each row has 49 values (49 columns to be updated for each row). However, when I run my code, it only updates 40 columns for each row and discards the last 9 values.
I've searched on google to find anything related to this, but I haven't been able to find anything.
Here's my code:
RANGE_NAME = 'Left Hand Tray' # the name of the sheet.
data_to_upload = [['FAN_ASSEMBLY', 'Right Nest', '2019-03-27 19:24:35', '142.968002', '1', '1', '1', '1', '1', '1', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'], ['FAN_ASSEMBLY', 'Left Nest', '2019-03-27 19:26:18', '94.480003', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'], ['FAN_ASSEMBLY', 'Right Nest', '2019-03-27 19:28:41', '143.207993', '1', '1', '1', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '0', '0', '0', '1', '1', '1', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'], ['FAN_ASSEMBLY', 'Left Nest', '2019-03-27 19:31:55', '193.112000', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1']]
body = {
'majorDimensions': 'ROWS',
'values': data_to_upload
}
request = sheet.values().append(spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME, body=body, valueInputOption='USER_ENTERED')
response = request.execute()
The last values for each data row does not get uploaded. Here is the response I get:
{'spreadsheetId': <the_spreadsheet_id>, 'tableRange': "'Left Hand Tray'!A1:AW4121", 'updates': {'spreadsheetId': <the_spreadsheet_id>, 'updatedRange': "'Left Hand Tray'!A4122:AN4125", 'updatedRows': 4, 'updatedColumns': 40, 'updatedCells': 160}}
You can see in the response, it says the sheet has columns till AW but in the updates part, you can see it only uploaded till column AN.
data_to_upload matrix only has 40 not 49 elements on each row as #glhr mentioned.
You are not passing the google sheet limits, that you can see here: https://gsuitetips.com/tips/sheets/google-spreadsheet-limitations/
Your code is doing exactly what it's supposed to. Check the size of your data_to_upload array:
print("Rows:",len(data_to_upload))
print("Columns:",len(data_to_upload[0]))
Returns:
Rows: 4
Columns: 40
Demo
Note that tableRange': "'Left Hand Tray'!A1:AW4121", means exactly that... the range of your whole table (4121 rows, 49 columns).
'updatedRange': "'Left Hand Tray'!A4122:AN4125" indicates the range of the table which was updated (4 rows, 40 columns), which matches the size of your input data.