Print value until string index is 0 - python

I am passing dot separated key as a argument. I have used split(".") and then print the value data. Here is my code:
desc = str(sys.argv[1])
st = desc.split(".")
i = 0
print (len(st))
for i in range(len(st)):
for ch in st:
st[i] = ch
print (st[i])
i += 1
print(i)
#print(data[st1][st2]..[stn])
I am getting the output as
3
db
1
dap
2
nodes
3
db
2
db
3
Traceback (most recent call last):
File "getvar.py", line 17, in <module>
st[i] = ch
IndexError: list assignment index out of range
I want the data[db][dap][nodes] which will give me the correct value. How should I proceed?

You are confusing 2 loops : for item in items and for i in range.
When you use i in range the max value in length -1 because indexes are zero based.
when you have used split st is an array of values so the line st[i] = ch is reloading the value back where is was read from.
Here I give both syntaxes of the loop. You will observe that print(st) before the loops gives the result that you want.
desc="10.12.45.35.66.28"
#desc = str(sys.argv[1])
st = desc.split(".")
print([st])
print ("length:",len(st))
for j in range(len(st)-1):
print (j," -> ", st[j])
i = 0
for ch in st:
st[i] = ch
print (i," -> ", st[i])
i += 1

Related

Pancake Sort in python, and empty max() error message

pancake_sort sorts some numbers in descending order (flips the biggest number to top (end) of the array then back to the bottom), then prints the index at which it did that (+1). This means that the array [4,3,2,1,5] will flip from index 0 so that it becomes [5,1,2,3,4] and will print 1, then will flip from the index 1 and will become [5,4,3,2,1], and it will print 2. Once it has done all its flips, it should then print 0. I've tried to add the different parts of the arrays together (the part that flips and the part that stays the same), but it doesn't work. I get this output and error message:
1
1 Traceback (most recent call last):
File "/Users/khadijah/Documents/pypan.py", line 32, in <module>
pancake_sort(arr)
File "/Users/khadijah/Documents/pypan.py", line 19, in pancake_sort
mi = arr.index(max(arr[i:arr_len]))
ValueError: max() arg is an empty sequence
I know that it has something to do with the i in the mi value, but I think I need that there so that it only checks the numbers between i and arr_len. Using arr_len-1 doesn't work either. What do you think I'm doing wrong?
This is my code:
def pancake_sort(arr):
arr_len=len(arr)
i=0
for i in range(0,arr_len-1):
mi = arr.index(max(arr[i:arr_len]))
arr = arr[0:mi-1]+arr[mi::-1]
print()
if mi == arr_len-1:
print("1", end = " ")
else: print(mi+1, end = " ")
if i==0:
arr=arr[::-1]
else:
arr = arr[0:i-1]+arr[i::-1]
return arr
arr = [4,3,2,1,5]
pancake_sort(arr)
You can use subscript assignment with reversed() to "flip" the pancake:
def flipSort(A):
for i in range(len(A)-1):
p = A[i:].index(max(A[i:])) + i # index of max (to end)
if i==p: continue # nothing to flip, skip
A[i:p+1]=reversed(A[i:p+1]) # <-- here is how to flip a subrange
print(i+1,end=" ") # print index (why one-based?)
print("0")
output:
A = [4,3,2,1,5]
flipSort(A)
1 2 0
print(A)
[5, 4, 3, 2, 1]
you can use is :
def pancake_sort(arr):
cur = len(arr)
while cur > 1:
# Find the maximum number in arr
mi = arr.index(max(arr[0:cur]))
# Reverse from 0 to mi
arr = arr[mi::-1] + arr[mi + 1 : len(arr)]
# Reverse whole list
arr = arr[cur - 1 :: -1] + arr[cur : len(arr)]
cur -= 1
print(cur)
return arr
print(pancake_sort([4,3,2,1,5]))

Python Error: IndexError: string index out of range when getting every third letter of a string

I'm trying to write a program that prints a hidden message the user has input. The message should be discovered by reading every 3rd character in the input. For example if I input: "pbaynatnahproarnsm" it should print out the bolded letters, i.e. "python". But it comes up with this:
Message? pbaynatnahproarnsm
p y t h o n Traceback (most recent call last):
File "program.py", line 4, in <module>
print(msg[x], end= " ")
IndexError: string index out of range
Here is the code
x = 0
msg = input("Message? ")
for i in msg:
print(msg[x], end= " ")
x = x + 3
You can use Python's slice notation to get every third letter in a string:
msg = "pbaynatnahproarnsm"
print(msg[::3]) # "python"
seems like you've misunderstood how for loop works, the equlavent code with while loop:
x = 0
msg = input("Message? ")
while x < len(msg):
print(msg[x], end= " ")
x = x + 3
here is the equlavent for loop:
msg = input("Message? ")
for i in range(0, len(msg), 3):
## i will be 0, 3, 6, 9, 12, ... at each iteration
c = msg[i]
## c will be the 0th, 3rd, 6th, ... character at each iteration
print(c, end= " ")
even simpler
msg = input("Message? ")
print(' '.join([msg[i] for i in range(0, len(msg), 3)]))
the output is : p y t h o n
for i in msg: iterates over each character in msg. You're using x starting at 0 and incrementing by 3 in every loop - so when you do msg[x], the index x is 3 times the value of the index of the actual current character. Check by just printing x in your loop. When you're on the 8th char, with index 7, x is 21 which is longer than the length of msg (18).
To get the right output, the quickest/easiest way is using slice notation as per Boris' answer: msg[::3]. To get spaces, use str.join():
print(' '.join(msg[::3]))
If you want to use your method as a base, then increment x only by 1 (not 3) and print it only if its index is divisible by 3 (by checking that the remainder when divided by 3 is 0):
x = 0
for i in msg:
if x % 3 == 0: # `%` gives the remainder
print(i, end=' ')
x += 1 # increment by 1, not 3
# p y t h o n
But that's a complicated way to go about it. (Using enumerate() in the loop would be better; or just the slice notation, as mentioned.)

How is my python code going out of bound?

I've been trying to encode a string (ex: aabbbacc) to something like a2b3a1c2
this is the code i've tried:
string_value = "aabbbacc"
temp_string = ""
for i in range(0, len(string_value)):
if i != len(string_value) or i > len(string_value):
temp_count = 1
while string_value[i] == string_value[i+1]:
temp_count += 1
i += 1
temp_string += string_value[i] + str(temp_count)
print(temp_string)
the problem is even though I've added an if condition to stop out of bounds from happening, I still get the error
Traceback (most recent call last):
File "C:run_length_encoding.py", line 6, in <module>
while string_value[i] == string_value[i+1]:
IndexError: string index out of range
I've also tried
string_value = "aabbbacc"
temp_string = ""
for i in range(0, len(string_value)):
count = 1
while string_value[i] == string_value[i+1]:
count += 1
i += 1
if i == len(string_value):
break
temp_string += string_value[i]+ str(count)
print(temp_string)
now, I know there might be a better way to solve this, but I'm trying to understand why I'm getting the out of bounds exception even though i have an if condition to prevent it, at what part of the logic am I going wrong please explain...
The problem is here:
for i in range(0, len(string_value)): # if i is the last index of the string
count = 1
while string_value[i] == string_value[i+1]: # i+1 is now out of bounds
The easiest way to avoid out-of-bounds is to not index the strings at all:
def encode(s):
if s == '': # handle empty string
return s
current = s[0] # start with first character (won't fail since we checked for empty)
count = 1
temp = ''
for c in s[1:]: # iterate through remaining characters (string slicing won't fail)
if current == c:
count += 1
else: # character changed, output count and reset current character and count
temp += f'{current}{count}'
current = c
count = 1
temp += f'{current}{count}' # output last count accumulated
return temp
print(encode('aabbbacc'))
print(encode(''))
print(encode('a'))
print(encode('abc'))
print(encode('abb'))
Output:
a2b3a1c2
a1
a1b1c1
a1b2
First this check is odd :
if i != len(string_value) or i > len(string_value):
Second, you check i but read value for i+1, and potentially next...
So my suggestion is to put the condition inside of your while.
And do not allow string_value[i] to be read after you have checked that i==len(string_value).
(I remind you that : "The break statement, like in C, breaks out of the innermost enclosing for or while loop.")
Iterate thru each char in the string then check if the next char is the same with current. If yes, then add one else add the count to temp string and reset the count to 1.
string_value = "aabbbacc"
temp_string = ""
count = 1
for i in range(len(string_value)-1):
if string_value[i] == string_value[i+1]:
count += 1
else:
temp_string += string_value[i]+ str(count)
count = 1
#add the last char count
temp_string += string_value[i+1]+ str(count)
print(temp_string)
Out: a2b3a1c2

Print data between positions within a loop

I have one files.
File1 which has 3 columns. Data are tab separated
File1:
2 4 Apple
6 7 Samsung
Let's say if I run a loop of 10 iteration. If the iteration has value between column 1 and column 2 of File1, then print the corresponding 3rd column from File1, else print "0".
The columns may or may not be sorted, but 2nd column is always greater than 1st. Range of values in the two columns do not overlap between lines.
The output Result should look like this.
Result:
0
Apple
Apple
Apple
0
Samsung
Samsung
0
0
0
My program in python is here:
chr5_1 = [[]]
for line in file:
line = line.rstrip()
line = line.split("\t")
chr5_1.append([line[0],line[1],line[2]])
# Here I store all position information in chr5_1 list in list
chr5_1.pop(0)
for i in range (1,10):
for listo in chr5_1:
L1 = " ".join(str(x) for x in listo[:1])
L2 = " ".join(str(x) for x in listo[1:2])
L3 = " ".join(str(x) for x in listo[2:3])
if int(L1) <= i and int(L2) >= i:
print(L3)
break
else:
print ("0")
break
I am confused with loop iteration and it break point.
Try this:
chr5_1 = dict()
for line in file:
line = line.rstrip()
_from, _to, value = line.split("\t")
for i in range(int(_from), int(_to) + 1):
chr5_1[i] = value
for i in range (1, 10):
print chr5_1.get(i, "0")
I think this is a job for else:
position_information = []
with open('file1', 'rb') as f:
for line in f:
position_information.append(line.strip().split('\t'))
for i in range(1, 11):
for start, through, value in position_information:
if i >= int(start) and i <= int(through):
print value
# No need to continue searching for something to print on this line
break
else:
# We never found anything to print on this line, so print 0 instead
print 0
This gives the result you're looking for:
0
Apple
Apple
Apple
0
Samsung
Samsung
0
0
0
Setup:
import io
s = '''2 4 Apple
6 7 Samsung'''
# Python 2.x
f = io.BytesIO(s)
# Python 3.x
#f = io.StringIO(s)
If the lines of the file are not sorted by the first column:
import csv, operator
reader = csv.reader(f, delimiter = ' ', skipinitialspace = True)
f = list(reader)
f.sort(key = operator.itemgetter(0))
Read each line; do some math to figure out what to print and how many of them to print; print stuff; iterate
def print_stuff(thing, n):
while n > 0:
print(thing)
n -= 1
limit = 10
prev_end = 1
for line in f:
# if iterating over a file, separate the columns
begin, end, text = line.strip().split()
# if iterating over the sorted list of lines
#begin, end, text = line
begin, end = map(int, (begin, end))
# don't exceed the limit
begin = begin if begin < limit else limit
# how many zeros?
gap = begin - prev_end
print_stuff('0', gap)
if begin == limit:
break
# don't exceed the limit
end = end if end < limit else limit
# how many words?
span = (end - begin) + 1
print_stuff(text, span)
if end == limit:
break
prev_end = end
# any more zeros?
gap = limit - prev_end
print_stuff('0', gap)

Value Generator - IndexError: list index out of range - Python

I get this error when running the code below:
Traceback (most recent call last):
File "C:/Users/Reum/Desktop/Generator.py", line 35, in <module>
print(results[0], results[1])
IndexError: list index out of range
I use the while loop to seperate the values by commas instead of this:
"'value1', 'value2', ..."
I use the if loop inside the while loop to catch the latest output and modify it, so that it doesn't have a comma at the end.
I hope that you can solve my (possibly stupid) question.
import sys, time
mode = input('Mode:' + ' ')
if mode == 'letters' or mode == 'Letters':
chars = 'abcdefghijklmnopqrstuvwxyz'
letters = True
elif mode == 'numbers' or mode == 'Numbers':
chars = '0123456789'
numbers = True
elif mode == 'custom' or mode == 'Custom':
chars = 'abcde' #Enter some custom chars between the quotation marks.
custom = True
length = input('Length:' + ' ')
suffix = input('Suffix:' + ' ')
if letters:
variations = 26 ** int(length)
elif numbers:
variations = 10 ** int(length)
elif custom:
variations = 5 ** int(length) #Count the numbers of chars from above and replace the 5 with the outcome of your brain.
print('Generating...' + ' ' + '(' + str(variations) + ' ' + 'values)')
results = []
for counter in range(int(length)):
char = [x for x in chars]
for y in range(counter):
char = [z + x for x in chars for z in char]
results = results + char
print(results[0], results[1])
print('Results: \n')
counter = 0
while another_counter < variations:
sys.stdout.write(results[another_counter] + suffix + ',' + ' ')
time.sleep(0.005)
counter = counter + 1
if counter == variations -1: #Maybe not.
sys.stdout.write(results[counter] + suffix)
print('Finished generating and displaying the values!')
You get this error because if you use a length input of 1,
for y in range(counter):
is not going to be iterating over anything, so nothing shall be added to your results. Resultantly, you will not have anything in the index positions 0 or 1.
Perhaps you want to add 1 to your for-loop range.
Demo:
You can see this if you insert print('counter is ' + str(counter)) in your counter for-loop:
Mode: letters
Length: 1
Suffix: pup
Generating... (26 values)
counter is 0
Traceback (most recent call last):
File "", line 39, in 0
builtins.IndexError: list index out of range
Then evidently
>>>for x in range(0): print(x)
doesn't print anything (this is the behavior you are having).

Categories

Resources