I'm new to Python so patience may be required on your behalf :) If this is not the right area for this then please let me know. I'm having trouble with a for loop navigating through a list. The idea here is to print "True" when a consecutive set of numbers are found in the list however it shouldn't print true if the sequence contains less than 3 consecutive iterations.
For example:
Ideally the program would say "You have 3 sequences in your list". In this case it would be (1,2,3), (10,11,12) and (22,23,24). Notice there are 2 other consecutive sets of numbers in the list (7,8) and (15,16) however the program should ignore them because it's less than 3 (as mentioned above). Please find code below however I'm at a slight road block. Appreciate any pointers you may have.
list1=[1,2,3,7,8,10,11,12,15,16,22,23,24]
for i in range(len(list1)-1):
if (list1[i] + 1 == list1[i+1]):
count+=1
if count >=3:
print("True")
else:
continue
continue
print(count)
I'm sure I have read the answer in similar posts but I would like to understand the code I'm missing rather than inserting code that doesn't make sense to me.
Thanks
As the query is to have only unique numbers in the sequences .. so below code will just work fine...
list1=[1,2,3,4,5,6,7,8,9,10]
count=0
i=0
while i < (len(list1)-3):
if list1[i]+1 == list1[i+1]:
if list1[i+1]+1 == list1[i+2]:
print(list1[i], list1[i+1], list1[i+2])
i=i+2
count=count+1
i=i+1
print(count)
Related
Below is my code for the leet code problem: here
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
tripletsList = []
uniqueNums = set(nums)
uniqueNums = list(nums)
for x in range(len(uniqueNums)):
for y in range(len(uniqueNums)):
for z in range(len(uniqueNums)):
print(uniqueNums[x],uniqueNums[y],uniqueNums[z])
if (uniqueNums[x] + uniqueNums[y] + uniqueNums[z]) == 0:
if [[uniqueNums[x],uniqueNums[y],uniqueNums[z]]] not in tripletsList:
tripletsList.append([uniqueNums[x],uniqueNums[y],uniqueNums[z]])
print(tripletsList)
I realize it isn't the optimal solution but in my print line the output shows the correct combination, yet my final triplets list is not eliminating anything which leads me to believe I am not using the "not in" function of python correctly. Any help is greatly appreciated and I must be missing something that is just trivial
I tried first printing every combination of the unique list (yes tons of overlap), then I tried limiting the triplets that made it pass the == 0 check to only triplets that were not already in the triplets list (failed)
Hey I have a list containing four lists and I would like to iterate over the entire thing and print the index for all occurrences of a specific number or variable. So for example I have:
list_of_lists = [[0,0,0,0],[0,0,0,0],[0,2,0,0],[0,0,0,0]]
lx = 0
for x in list_of_lists:
ly = 0
for a in x:
if a == 2:
print(lx,ly)
ly += 1
lx += 1
Now this does print "2 1" which is correct but rather than print once, it prints infinitely. I'm not sure what is wrong with my logic but I'm pretty sure I am making a simple error. I am new to programming as you may be able to tell. Thanks for any help!
I don't think you did anything wrong here. I tried your code and mine runs only once, are you sure your indentations are ok in your original code?
The goal is simple: there is a file with x numbers separated by ` . If there are dublicates of the number in the file they should be deleted. I decided to solve this by comparing the n member with all others from n to len(array). The code:
#deletes repeated numbers separated by `
questioned=open("key_file.txt",'r+')
numbers=questioned.read()
#print(numbers)
numb=[]
number=[]
for each in numbers:
if each=='`':
number.append(''.join(numb))
numb=[]
else:
numb.append(each)
i,j=0,0
for i in xrange(len(number)): #we don't need to compare last number
for j in xrange(i+1,len(number)-1):#don't need to compare to itself
#print(len(number)," ",i," ",j)
if number[i]==number[j]:
number.pop(j) #tried del number[j]
questioned.close()
However, it seems that I manage to get out of range during the process even though I specified that xrange should go to len(array). My guess is the len(number) is not being continually reassessed leading to the number being out of range because a bunch of numbers got deleted?
Any pointers/tips would be great. Thanks a lot for your time!
Alright, it seems like my fears were correct. In the 2nd loop j manages to go over len(number) which leads to the error...
#deletes repeated numbers separated by `
questioned=open("key_file.txt",'r+')
numbers=questioned.read()
#print(numbers)
numb=[]
number=[]
for each in numbers:
if each=='`':
number.append(''.join(numb))
numb=[]
else:
numb.append(each)
i,j=0,0
def compare(number,i,j):
if number[i]==number[j]:
number.pop(j)
compare(number,i,j)
return number
for i in xrange(len(number)):
for j in xrange(i+1,len(number)-1):
if j>len(number)-1:
break
#print(len(number)," ",i," ",j)
#try:
compare(number,i,j)
#except: print('i,j',i,' ',j,'len ',len(number))
questioned.close()
Works fine without try statement. I am not sure why this happens but it does seem to be the case. If you guys have an explanation that would be great :/
I tried all sorts of for loops but just can't seem to figure out how to print "n" number of lines from a dictionary at a time. I am new to programming so please pardon my terminology and expressions...
Example source:
{'majorkey1': [{'name':'j','age':'3','height':'6feet'},
{'name':'r','age':'4','height':'5feet'},
{'name':'o','age':'5','height':'3feet'}],
'majorkey2':[{'name':'n','age':'6','height':'4feet'},
{'name':'s','age':'7','height':'7feet'},
{'name':'q','age':'7','height':'8feet'}]}
This prints everything at once (undesired):
for majorkey in readerObj.keys():
for idx, line in enumerate(readerObj.get(majorkey)):
print line
{'name':'j','age':'3','height':'6feet'}
{'name':'r','age':'4','height':'5feet'}
{'name':'o','age':'5','height':'3feet'}
{'name':'n','age':'6','height':'4feet'}
{'name':'s','age':'7','height':'7feet'}
{'name':'q','age':'7','height':'8feet'}
I have gutted a lot of code to make this easier to read. The behaviour I would like is to print according to the number of lines specified. For now I will just use lines_to_execute=2. I would like to keep code as close as possible to minimize me rewriting this block. From this answer once working I will modify code so that it performs something chunks at a time.
Code block I want to stay close to:
Ill mix psudo code here as well
for majorkey in readerObj.keys():
lines_to_execute = 2
start_idx_position = 0
range_to_execute = lines_to_execute
for idx[start_idx_position:range_to_execute], line in enumerate(readerObj.get(majorkey)):
print line
increment start_idx_position by lines_to_execute
increment range_to_execute by lines_to_execute
time.sleep(1)
For this example if I want to print two lines or rows at a time, output would look like the below. Order is not important as same 2 don't get executed more than once:
Desired output:
{'name':'j','age':'3','height':'6feet'}
{'name':'r','age':'4','height':'5feet'}
One second delay...
{'name':'o','age':'5','height':'3feet'}
{'name':'n','age':'6','height':'4feet'}
One second delay.
{'name':'s','age':'7','height':'7feet'}
{'name':'q','age':'7','height':'8feet'}
I hope this is enough information to go on.
from pprint import pprint
import time
for key in obj.keys():
lines_to_execute = 2
pprint(obj[key][:lines_to_execute]) # that's all you need
time.sleep(1)
Keep it as simple as possible.
this is my first post to Stack Overflow. I have used it many times before but this is the first error that I have not found a solution to thus far. I am having a problem with a Python script where when I am changing an element in a list, the item replacing the element in the list drops the scientific notation aspect (i.e. E+08). Here is a snippet of the code and terminal output that is very strange to me. Thanks in advance for all help!
for i in range(0, len(EinsteinCof)):
for j in range(0, len(finalindexing)):
if i == finalindexing[j][0]:
if len(finalindexing[j]) == 3:
EinsteinFinal = float(EinsteinCof[finalindexing[j][0]]) + float(EinsteinCof[finalindexing[j][1]]) + float(EinsteinCof[finalindexing[j][2]])
print str(EinsteinFinal)
EinsteinCof[finalindexing[j][0]] = str(EinsteinFinal)
print str(EinsteinCof[finalindexing[j][0]])
Terminal Output:
4.1079763384e+13
4.1079763384 # <-- Where did e+13 go?
2269472400.0
2269472400.0
3.1777892e+12
3.1777892e+1 # <--where did e+12 go?
9.062911e+11
9.062911e+11