I'm trying to get a list to rotate, add a variable to the end, and the next time the function is called, the list rotates again ect etc. How ever, when I implement this code, the list doesn't rotate every time the function is ran.
var1 = "1";
var2 = "2";
var3 = "3";
var4 = "4";
var5 = "5";
check = [var1, var2, var3, var4, var5]
def checkIfExists(checkList):
var = input();
if var not in checkList:
check = checkList[1:] + checkList[:1]
check.append(var)
check.pop(1)
check = checkList[2:] + checkList[:2]
print(check)
its entirely possible I'm just goofing up and messing up somewhere, but I'm stuck. Any help?
def checkIfExists(checkList):
print('Input new number:')
var = input()
if var not in checkList:
check.pop(0)
check.append(var)
print('return new check:')
print(check)
test result:
>>> check = ['1', '2', '3', '4', '5']
>>> checkIfExists(check)
Input new number:
6
return new check:
['2', '3', '4', '5', '6']
>>> checkIfExists(check)
Input new number:
7
return new check:
['3', '4', '5', '6', '7']
If you move the input() outside the function it's easier to communicate the problem:
def checkIfExists(list, var):
if var not in list:
# assumes list is not empty
list.pop(0)
list.append(var)
return list
check = ['1', '2', '3', '4', '5']
for var in ['6', '7']:
check = checkIfExists(check, var)
print(check)
Will give you this output:
['2', '3', '4', '5', '6']
['3', '4', '5', '6', '7']
Related
I have this code:
lokk = []
nums = 7
for _ in range(nums):
inner = driver.find_element_by_xpath(
"/html/body/div[1]/div[2]/div/div/div/div[2]/div/div/div/div[2]/div[2]/div/div/div[2]/div[5]/span[1]").get_attribute(
"innerHTML")
lokk.append(inner)
time.sleep()
print(lokk)
which provides me with this data:
['1', '2', '3', '4', '5', '6', '7']
what I want to do is to save that data into two different lists, the first list containing the first six values e.g. ['1', '2', '3', '4', '5', '6'] and the second lists containing the the whole seven values e.g. ['1', '2', '3', '4', '5', '6', '7'] how ever i want it be so that the next sample of data collected contains the last value of the second list as the first value of the list pair of lists like so ['7', '8', '9', '10', '11', '12', '13']
i thought this was the code that would somewhat enable be to get the data in the different lists like i wanted but then soon realized that by the time it goes to fetch the second set of data for the second list of seven values, the data would have changed and that's not what I want
lok = []
num = 6
for _ in range(num):
inner = driver.find_element_by_xpath(
"/html/body/div[1]/div[2]/div/div/div/div[2]/div/div/div/div[2]/div[2]/div/div/div[2]/div[5]/span[1]").get_attribute(
"innerHTML")
lok.append(inner)
time.sleep(10)
print(lok)
lokk = []
nums = 7
for _ in range(nums):
inner = driver.find_element_by_xpath(
"/html/body/div[1]/div[2]/div/div/div/div[2]/div/div/div/div[2]/div[2]/div/div/div[2]/div[5]/span[1]").get_attribute(
"innerHTML")
lokk.append(inner)
time.sleep()
print(lokk)
Another flaw i saw in this is that when it was time to run the process again later, the seventh data would not be the first data for the new set of lists.
Meaning that instead of:
listA = ['1', '2', '3', '4', '5', '6']
listB = ['1', '2', '3', '4', '5', '6', '7']
ListC = ['7', '8', '9', '10', '11', '12']
listD = ['7', '8', '9', '10', '11', '12', '13']
it would be:
listA = ['1', '2', '3', '4', '5', '6']
listB = ['1', '2', '3', '4', '5', '6', '7']
ListC = ['8', '9', '10', '11', '12', '13']
listD = ['8', '9', '10', '11', '12', '13', '14']`
I really hope I was clear enough in what I am looking for assistance in, if not please let me know.
Please help :(
You can achieve this in many ways, try this:
For ListC:
lok_c = []
num_c = 13
for _ in range(num_c):
inner = driver.find_element_by_xpath("/html/body/div[1]/div[2]/div/div/div/div[2]/div/div/div/div[2]/div[2]/div/div/div[2]/div[5]/span[1]").
get_attribute("innerHTML")
if num_c > 7:
lok_c.append(inner)
time.sleep()
print(lok_c)
For ListD:
lok_d = []
num_d = 14
for _ in range(num_d):
inner = driver.find_element_by_xpath("/html/body/div[1]/div[2]/div/div/div/div[2]/div/div/div/div[2]/div[2]/div/div/div[2]/div[5]/span[1]").
get_attribute("innerHTML")
if num_d > 7:
lok_c.append(inner)
time.sleep()
print(lok_d)
Correct the indentation and variable name, if I missed anything.
def convert_to_list(VertexList):
VerticesList = []
items = VertexList.split(';')
for item in items:
i = item.split(',')
SubList = []
for item in i:
SubList.append(item)
VerticesList.append(SubList)
return VerticesList
This code converts string in this format to a 2D list. However, I am sure it can be optimized.
Input -> '1,2,4,5,6,7;2,3,4,5,6,7,8;1,2,4,5,6,8'
Output -> [['1', '2', '4', '5', '6', '7'], ['2', '3', '4', '5', '6', '7', '8'], ['1', '2', '4', '5', '6', '8']]
Use a comprehension.
inp = '1,2,4,5,6,7;2,3,4,5,6,7,8;1,2,4,5,6,8'
print([s.split(',') for s in inp.split(';')])
Results in
[['1', '2', '4', '5', '6', '7'], ['2', '3', '4', '5', '6', '7', '8'], ['1', '2', '4', '5', '6', '8']]
This is smaller, easier to read code, which is part of the optimization I expect you were looking for. It doesn't loop through things any fewer times, but it's executing fewer assignments, using less temporary variabels, and making fewer function calls (i.e. append()). Maybe some of those calls are being made behind the scenes in the comprehension, but you should be taking advantage of whatever optimizations Python does to its comprehensions in terms of what functions calls are made.
--update--
Check out this answer for a performance analysis of the OP and this answer.
-- update 2 --
To convert all strings to int, you can use map or another comprehension.
inp = '1,2,4,5,6,7;2,3,4,5,6,7,8;1,2,4,5,6,8'
print([list(map(int, s.split(','))) for s in inp.split(';')])
or
inp = '1,2,4,5,6,7;2,3,4,5,6,7,8;1,2,4,5,6,8'
print([[int(c) for c in s.split(',')] for s in inp.split(';')])
This is not a solution, but only a comparison of the optimality of the above codes in terms of actual performance:
from timeit import Timer
code1 = """\
def convert_to_list(VertexList):
VerticesList = []
items = VertexList.split(';')
for item in items:
i = item.split(',')
SubList = []
for item in i:
SubList.append(item)
VerticesList.append(SubList)
return VerticesList
inp = '1,2,4,5,6,7;2,3,4,5,6,7,8;1,2,4,5,6,8'
convert_to_list(inp)
"""
code2 = """\
inp = '1,2,4,5,6,7;2,3,4,5,6,7,8;1,2,4,5,6,8'
out = [s.split(',') for s in inp.split(';')]
"""
t = Timer(stmt=code1)
time1 = t.timeit() # 1000000 iteration by default
print(f"Original time:{round(time1, 6)} sec.")
t = Timer(stmt=code2)
time2 = t.timeit() # 1000000 iteration by default
print(f"New time: {round(time2, 6)} sec.")
print(f'New solution faster in = {round(time1 / time2, 1)} times')
Output:
Original time:1.812856 sec.
New time: 0.741987 sec.
New solution faster in = 2.4 times
How to pass command line to save into list
Disclaimer Please dont say print (ARGV1[0])
import sys
ARGV1 = []
for ARGV in sys.argv[2:]:
ARGV1.append(sys.argv[2:])
print (ARGV1)
My Out
[['2', '3', '4'], ['2', '3', '4'], ['2', '3', '4']]
My Expected out
['2', '3', '4']
Disclaimer Please dont say print (ARGV1[0])
Just do
ARGV1 = sys.argv[2:]
Since you have 3 values in input its adding same list 3 times.
i would like to slice a set within a list, but every time i do so, i get an empty list in return.
what i try to accomplish (maybe there is an easier way):
i got a list of sets
each set has 5 items
i would like to compare a new set against the list (if the set already exists in the list)
the first and the last item in the set is irrelevant for the comparison, so only the positions 2-4 are valid for the search of already existing sets
here is my code:
result_set = ['1', '2', '3', '4', '5']
result_matrix = []
result_matrix.append(result_set)
slicing the set is no problem:
print result_set[1:4]
['2', '3', '4']
print result_matrix[:][1:4]
[]
i would expect:
[['2', '3', '4']]
I think this is what you want to do:
>>> target_set = ['2', '3', '4']
>>> any([l for l in result_matrix if target_set == l[1:-1]])
True
>>> target_set = ['1', '2', '3']
>>> any([l for l in result_matrix if target_set == l[1:-1]])
False
Generalising and making that a function:
def is_set_in_matrix(target_set, matrix):
return any(True for l in matrix if list(target_set) == l[1:-1])
>>> result_matrix = [['1', '2', '3', '4', '5']]
>>> is_set_in_matrix(['1', '2', '3'], result_matrix)
False
>>> is_set_in_matrix(['2', '3', '4'], result_matrix)
True
# a quirk - it also works with strings...`
>>> s = '234'
>>> is_set_in_matrix(s, result_matrix)
True
Note that I have used l[1:-1] to ignore the first and last elements of the "set" in the comparison. This is more flexible should you ever need sets of different lengths.
>>> result_set = ['1', '2', '3', '4', '5']
>>> print result_set[1:4]
['2', '3', '4']
>>> result_matrix.append(result_set[1:4])
>>> result_matrix
[['2', '3', '4']]
Using result_matrix[:] returns the whole matrix as it is. You need to treat the result you want as a part of the array.
>>> result_matrix.append(result_set)
>>> result_matrix[:]
[['1', '2', '3', '4']]
>>> result_matrix[:][0]
['1', '2', '3', '4']
>>> result_matrix[0][1:4]
['2', '3', '4']
Also, as pointed out by falsetru:
>>> result_matrix.extend(result_set)
>>> result_matrix
['1', '2', '3', '4']
>>> result_matrix[1:4]
['2', '3', '4']
So, I was doing Project Euler 37
I need to circulate a list
input: 2345 # converted to list inside function
expected output: [[3,4,5,2],[4,5,2,3],[5,2,3,4],[2,3,4,5]]
Here is my function for that
def circulate(n): #2345
lst=list(str(n)) #[2,3,4,5]
res=[]
for i in range(len(lst)):
temp=lst.pop(0)
lst.append(temp)
print lst #print expected list
res.append(lst) #but doesn't append as expected
return res
print circulate(2345)
My output is:
['3', '4', '5', '2']
['4', '5', '2', '3']
['5', '2', '3', '4']
['2', '3', '4', '5']
[['2', '3', '4', '5'], ['2', '3', '4', '5'], ['2', '3', '4', '5'], ['2', '3', '4', '5']]
The function prints lst correct every time, but doesn't append as expected.
What I am doing wrong?
You need to append copies of your list to res:
res.append(lst[:])
You were appending a reference to the list being altered instead; all references reflect the changes made to the one object.
You may want to look at collections.deque() instead; this double-ended list object supports efficient rotation with a .rotate() method:
from collections import deque
def circulate(n):
lst = deque(str(n))
res = []
for i in range(len(lst)):
lst.rotate(1)
res.append(list(lst))
return res