Run length decompression 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 2 years ago.
Improve this question
I'm trying to make a run length decoder that doesn't use 1s. For example a string that could be passed through would be something like ''' A2C3GTA'''. I made what i thought would work and am having trouble finding where I went wrong. I'm a beginner to python so I am sorry for the simple question. Thank you!
def decode(compressed):
decoded= ""
count = 0
for x in compressed :
if x.isdigit():
count += int(x)
y = compressed
decoded += y[int(x)+1] * count
count = 0
else :
decoded += x
print (decoded)

When you find a number-letter pair, you fail to skip the letter after you expand the pair. This is because you used a for loop, which is a more restrictive structure than your logic wants. Instead, try:
idx = 0
while idx < len(compressed):
char = compressed[idx]
if char.isdigit():
# replicate next character
idx += 2
else:
decoded += char
idx += 1
That will take care of your iteration.
Your in appropriate replication, the 22 in your output, this comes from an incorrect reference to the position:
decoded += y[int(x)+1] * count
Here, x is the run length, not the position of the character. If the input were A7B, this ill-formed expression would fault because of an index out of bounds.
In the code I gave you above, simply continue to use idx as the index.
I trust you can finish from here.

Related

Python index error when trying to make a mean [closed]

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 2 years ago.
Improve this question
I'm trying to make an average but for some reason when I try to make one it doesn't work.
I have global variables and array defined at the begining of my document :
vent_moyenne_km = []
compteur_moyenne=0
I have one of my function that is called every X time. In that one, I calculate a velocity with some value that are display on a label of my interface. that part is working, but not the mean
global compteur_moyenne
compteur_moyenne += 1
ventkmh = (vent_1[3][0]*256 + vent_1[4][0]) /100 *3.6
label_vent2_2.config(text= "%.2f" % ventkmh)
vent_moyenne_km.append("%.2f" % ventkmh)
vent_1.clear()
if compteur_moyenne == 5:
compteur_moyenne = 0
print(vent_moyenne_km)
label_vent4_2.config(text=statistics.mean(vent_moyenne_km))
vent_moyenne_km.clear()
of course in my imports I have :
import statistics
When I comment the line label_vent4_2.config(text=statistics.mean(vent_moyenne_km)), everything works and I see in the terminal my array with 5 values. I also tried numpy and even tried to make a for items in array: then add then manually, and everytime I get the error : class 'IndexError'
I'm really not sure how to fix that.
For calculating an average of a list just use numpy:
def function():
value = random.randint(0,1)
return value
list = []
for i in range(100):
list.append(function())
if i%5 == 0:
print(np.average(list))

Stop for loop when the if statement is true [closed]

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 2 years ago.
Improve this question
Use while and if statements to count how many 0’s are before the first 1 (from left to right).
code = '00000000101100110001111110110011'
num_zero_before_1 = 0
for i in code:
if i != '1':
num_zero_before_1+=1
print(num_zero_before_1)
I cannot seem to get the answer
loops in python have two control statements: continue and break. Continue skips the rest of the iteration and starts from the top and break completely leaves the loop. So what you want here is to break on the else condition.
You have made a small mistake. You are counting zeroes by if condition using i != '1' but you should add else also to break the loop whenever the first '1' encountered, otherwise your loop will go on counting all zeroes.
Here is correct solution:
code = '00000000101100110001111110110011'
num_zero_before_1 = 0
for i in code:
if i != '1':
num_zero_before_1+=1
else:
break
print(num_zero_before_1)
Shouldn't you use while loop instead of for... in loop?
This solution should fulfill exercise assumptions:
iterator = 0
while True:
if code[iterator] != '1':
iterator += 1
else:
break # it stops the loop, goes out of it
print(iterator) # number of zero before '1'
However, this solution is shorter and easier, maybe it'll be useful to you:
iterator = 0
while code[iterator] != '1':
iterator += 1
print(iterator) # number of zero before '1'

Python random.randint() keeps returning 0 after certain time [closed]

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 5 years ago.
Improve this question
I was trying to get 3 random numbers within range in python without replacement. I did this
rand_lst = []
while(True):
rand = random.randint(0, length-1 )
if(len(rand_lst) == 3):
break
if(rand not in rand_lst):
rand_lst.append(rand)
This code is inside a for loop. This returns only 0 and thus an infinite loop. I also tried numpy.random.randint but some how random is keeping track of previously generated numbers and I endup with value error.
Trying putting print(length) right before your while True. You'll almost certainly find that the value of length is not what you expect it to be. (It's probably 0 or 1, when you want it to be 3 at least.)
if i understand you correctly,
you want something like this:
import random
rand_lst = []
length = 10
while(True):
rand = random.randint(0, length-1 )
if(len(rand_lst) == 3):
break
if(rand not in rand_lst):
rand_lst.append(rand)
print(rand_lst)
this way "length" has a value and will not throw an error
Explanation: https://stackoverflow.com/a/33806926/8386640
Use random.sample. Here is code.
import random
rand_lst = []
length = 3
while(len(rand_lst) < 3):
rand_lst.append(random.sample(range(length), 3))
print rand_lst

How to tackle this random number Python homework? [closed]

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 5 years ago.
Improve this question
Here is my homework:
Write a function that repeatedly generates random integers in the range [0,n[, until two consecutively generated numbers are identical.then return the number of generated numbers.
Here is what I did:
def function(n):
for i in range(100):
random.randint(0,n)
and this outputs a hundred numbers, however I need it to stop when it detects two identical numbers, how is that done?
For this you could use two names: one for the newly generated random number, and one for the previous one.
You need also to make your loop differently, as you don't know how long it needs to iterate before getting a match:
import random
def function(n):
a = -2
b = -1
i = 0
while a != b:
a, b = random.randint(0,n), a
i += 1
return i
# Sample run
times = function(400)
print (times)
See it run on repl.it
To do it without assigning a and b strange values, use an infinite while loop, then break when the values are the same. This is similar to #trincot's solution:
import random
def function(n):
a = None
i = 0
while True:
a, b = random.randint(0,n), a
i += 1
if a == b:
return i
# Sample run
times = function(400)
print(times)

Python read from list [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a question about lists in python and how to print from them. Which of the following code snippets prints all 7 words found in the list "words"? I have compiled and tried it but I still don't know which of this snippets is correct.
1.
i = 0
while i < 7:
print(words[i], end=" ")
i += 1
2.
i = 0
while i < 7:
print(words[i], end=" ")
i += 1
3.
i = 1
while i < 7:
print(words[i], end=" ")
i += 1
4.
i = 0
sum = ""
while i < 7:
sum += words[i]
i += 1
print(sum)
5.
i = 0
sum = ""
while i <= 7:
sum += words[i]
i += 1
print(sum)
If your list looks something like this, words = ["a","b","c"..],
All you have to do is iterate over them using the for statement,
for i in words:
print i
That should print out the words:
a
b
c
....
This shouldn't be all that difficult to follow as a dry run (use pen and paper if you need to).
You'll need to remember that if words has 7 elements, they are words[0]...words[6]. ie the list index starts at 0
Obviously you haven't been able to run them. How did you try to run them? What went wrong?
If you still can't work it out, a good strategy is to fall back to the answer that has the most in common with the other answers...answer 2 :)
Answer: None are correct. They are all wrong. Presuming to know how many words that should be found is the starting point of why this is wrong.
The point of putting the words you found into a list is so that you can separate the responsibility of finding results to printing them. To decouple them one can't know about the other. More specifically; you don't care how many are in the list, you just need to know how print the list. As such you are really just asking "How do I print a list".
Secondly, there is no compiling in python. Have you tried reading http://docs.python.org/2/tutorial/ ?
or http://docs.python.org/3/tutorial/
For code of a correct answer see #enginefree's answer.
Even if you are going to do it the way you are doing it with indexes i would suggest
for i in range(0..MAX_ELEMENTS-1):
print words[i]
I also would strongly discourage use of while loops for a problem with a definite knowable boundary of operations such as iteration over a collection from the outset of the operation. While generally implies changing conditions, unknowable endpoints and the need for custom increment control.

Categories