It's supposed to be a roll of dice (random) then adjacent values (runs) are supposed to be in ( ). One challenge is using the current - 1 with the 0 index (think I got that resolved by using range(len(dieRun) -1). But another challenge is using 'current + 1' as it tends to 'out of range' errors.
One thought I have is to maybe build a function to compare the values for adjacents? Then use whatever return I get from that to reference a variable, then use that variable in a formatted Print of the dieRun? But, I don't see how that would be better as then I'd still have to figure out how to place that variable as a "(" or ")" with the print(dieRun) list.
Still a newb.
def main():
from random import randint
counter = 0
inRun = 0
dieRun = []
while counter < 20:
roll = randint(0,6)
dieRun.append(roll)
counter = counter +1
index = 0
counter = 0
value = 0
inRun == False
print(dieRun) # just to see what I'm working with
while counter < len(dieRun):
for i in range(0, len(dieRun)-1):
if dieRun[i] != dieRun[i-1]:
print(")" , end= "")
inRun = False
counter = counter + 1
if dieRun[i] == dieRun[i+1]:
inRun = True
print("(")
counter = counter + 1
print(dieRun[i])
if inRun:
print("(")
if inRun :
print(")", end="")
main()
if you want the output like: 1(3 3) 4 5 (6 6 6) 2 1 3 (2 2) 1 (4 4) 5 6 1 2
from random import randint
dieRun = []
for i in range(20):
roll = randint(0,6)
dieRun.append(roll)
inRun = False
print(dieRun)
for i, n in enumerate(dieRun):
if i < len(dieRun)-1:
if not inRun:
if n == dieRun[i+1]:
print('(', n,' ', end='')
inRun = True
else:
print(n,' ', end='')
else:
if n != dieRun[i+1]:
print(n, ')',' ', end='')
inRun = False
else:
print(n,' ', end='')
else:
if dieRun[i-1] == n:
print(n, ')')
else:
print(n)
just a thought, hope it help.
Just a quick fix, I have commented in the code.
For the inline print, you have provided the solution 'print(")" , end= "")', but I don't know why you didn't make it for every print().
if dieRun[i] != dieRun[i-1]: # will check the first number with last number
dieRun[0] != dieRun[-1]: # [-1] is the last item in the list
if dieRun[i] == dieRun[i+1]: # will index out of length
dieRun[len(..)-1] != dieRun[len(..)]: # [len(..)] wil be out of range
Since the head and tail of the list will always cause problem, I just chopped them off from the for loop, and do it manually.
There must be some cleaner solution:
from random import randint
counter = 0
inRun = 0
dieRun = []
while counter < 20:
roll = randint(0,6)
dieRun.append(roll)
counter = counter +1
index = 0
counter = 0
value = 0
inRun == False
print(dieRun)
# while counter < len(dieRun): # while loop is redundant with the for loop
print('(', dieRun[0],' ', end='') # print the first number manually
for i in range(1, len(dieRun)-1):
if dieRun[i] != dieRun[i-1]:
print(")(" , end= "") # change ")" to ")("
inRun = False
counter = counter + 1
"""
these are redundant, just like if True, don't need elif not True
# if dieRun[i] == dieRun[i+1]:
# inRun == True
# print("(", end='')
# counter = counter + 1
"""
print(dieRun[i],' ', end='')
print(dieRun[-1],')', end='') # print the last number manually
Related
I have created some code long ago which helps to create a table in BBcode used in forums.
counter = 0
counter2 = 0
while True:
UserInput = input("")
if counter2 == 0:
print ("[tr]")
print ("[td][center]Label\n" + "[img]" + str(UserInput) + "[/img][/center][/td]")
counter += 1
counter2 += 1
if counter % 5 == 0:
print ("[/tr]")
So if i input Image1.jpg ~ Image7.jpg on seperate lines, the output is as shown below
> [tr]
> [td][center]Label[img]Image1.jpg[/img][/center][/td]
> [td][center]Label[img]Image2.jpg[/img][/center][/td]
> [td][center]Label[img]Image3.jpg[/img][/center][/td]
> [td][center]Label[img]Image4.jpg[/img][/center][/td]
> [td][center]Label[img]Image5.jpg[/img][/center][/td]
> [/tr]
> [td][center]Label[img]Image6.jpg[/img][/center][/td]
> [td][center]Label[img]Image7.jpg[/img][/center][/td]
Currently, the code only inserts [/tr] at the end of ever 5 images.How does one make it so that [/tr] is also printed at the end of output no matter how many jpgs are entered?
How can I print [tr] at the start and join it with the line below, and then not print again until a [/tr] has been printed?
Apologies for my crap English & explanation skills.
(Current progress)
counter = 0
while True:
UserInput = input("")
if counter == 0 or counter % 5 == 0:
print("[tr]", end = "")
print ("[td][center]Label\n" + "[img]" + str(UserInput) + "[/img][/center][/td]")
counter += 1
if counter % 5 == 0:
print("[/tr]")
After reading what you wrote 5 times I believe what you want is:
print("[tr]")
while True:
counter = 0
UserInput = input("")
if UserInput == "exit":
exit(0)
print("[tr]", end = "")
while (counter !=5):
print ("[td][center]Label\n" + "[img]" + str(UserInput) + "[/img][/center][/td]")
counter += 1
print ("[/tr]")
print("[/tr]")
So what happens here is you print [tr] in the same line as the first print from the inside while as you wanted. the [/tr] is in a new line but you can put it in the same by adding end = "" to the second print as well.
Separate the functions. Get the list of images, then process it:
def bbcode(images):
for i in range(0,len(images),5):
print('[tr]')
for image in images[i:i+5]:
print(f'[td][center]Label[img]{image}[/img][/center][/td]')
print('[/tr]')
def get_images():
images = []
while True:
image = input('Image? ')
if not image: break
images.append(image)
return images
images = get_images()
bbcode(images)
You can do it as one long script, but it isn't as clear:
count = 0
while True:
image = input('Image? ')
if not image:
break
count = (count + 1) % 5
if count == 1:
print('[tr]')
print(f'[td][center]Label[img]{image}[/img][/center][/td]')
if count == 0:
print('[/tr]')
if count != 0:
print('[/tr]')
Below is the result with some commentary. To update for your specifications, just set the max_item_blocks variable to whatever you want.
### your main body element with {} to pass a number
element = '[td][center]Label[img]Image{}.jpg[/img][/center][/td]'
### The number of "blocks" you want to print.
max_item_blocks = 3
### Define a start value of 1
start = 1
### Our simple loop with join() function
while max_item_blocks > 0:
### End value is start + 5
end = start + 5
print('[tr]\n' + '\n'.join([element.format(i) for i in range(start, end)]) + '\n[\\tr]')
### Start takes ending value
start = end
### Ending value is now start + 5
end = start + 5
### Reduce our block counts by 1
max_item_blocks -= 1
Output for 3 blocks:
[tr]
[td][center]Label[img]Image1.jpg[/img][/center][/td]
[td][center]Label[img]Image2.jpg[/img][/center][/td]
[td][center]Label[img]Image3.jpg[/img][/center][/td]
[td][center]Label[img]Image4.jpg[/img][/center][/td]
[td][center]Label[img]Image5.jpg[/img][/center][/td]
[\tr]
[tr]
[td][center]Label[img]Image6.jpg[/img][/center][/td]
[td][center]Label[img]Image7.jpg[/img][/center][/td]
[td][center]Label[img]Image8.jpg[/img][/center][/td]
[td][center]Label[img]Image9.jpg[/img][/center][/td]
[td][center]Label[img]Image10.jpg[/img][/center][/td]
[\tr]
[tr]
[td][center]Label[img]Image11.jpg[/img][/center][/td]
[td][center]Label[img]Image12.jpg[/img][/center][/td]
[td][center]Label[img]Image13.jpg[/img][/center][/td]
[td][center]Label[img]Image14.jpg[/img][/center][/td]
[td][center]Label[img]Image15.jpg[/img][/center][/td]
[\tr]
Given a paragraph of space-separated lowercase English words and a list of unique lowercase English keywords, find the minimum length of the substring of which contains all the keywords that are separated by space in any order.
i put the following code where is the error ? How can i decrease time complexity.
import sys
def minimumLength(text, keys):
answer = 10000000
text += " $"
for i in xrange(len(text) - 1):
dup = list(keys)
word = ""
if i > 0 and text[i - 1] != ' ':
continue
for j in xrange(i, len(text)):
if text[j] == ' ':
for k in xrange(len(dup)):
if dup[k] == word:
del(dup[k])
break
word = ""
else:
word += text[j]
if not dup:
answer = min(answer, j - i)
break
if(answer == 10000000):
answer = -1
return answer
text = raw_input()
keyWords = int(raw_input())
keys = []
for i in xrange(keyWords):
keys.append(raw_input())
print(minimumLength(text, keys))
The trick is to scan from left to right and, once you find a window containing all the keys, try to reduce it on the left and enlarge it on the right preserving the property that all the terms remain inside the window.
Using this strategy you can solve the task in linear time.
The following code is a draft of the code that I tested on few strings, I hope the comments are enough to highlight the most critical steps:
def minimum_length(text, keys):
assert isinstance(text, str) and (isinstance(keys, set) or len(keys) == len(set(keys)))
minimum_length = None
key_to_occ = dict((k, 0) for k in keys)
text_words = [word if word in key_to_occ else None for word in text.split()]
missing_words = len(keys)
left_pos, last_right_pos = 0, 0
# find an interval with all the keys
for right_pos, right_word in enumerate(text_words):
if right_word is None:
continue
key_to_occ[right_word] += 1
occ_word = key_to_occ[right_word]
if occ_word == 1: # the first time we see this word in the current interval
missing_words -= 1
if missing_words == 0: # we saw all the words in this interval
key_to_occ[right_word] -= 1
last_right_pos = right_pos
break
if missing_words > 0:
return None
# reduce the interval on the left and enlarge it on the right preserving the property that all the keys are inside
for right_pos in xrange(last_right_pos, len(text_words)):
right_word = text_words[right_pos]
if right_word is None:
continue
key_to_occ[right_word] += 1
while left_pos < right_pos: # let's try to reduce the interval on the left
left_word = text_words[left_pos]
if left_word is None:
left_pos += 1
continue
if key_to_occ[left_word] == 1: # reduce the interval only if it doesn't decrease the number of occurrences
interval_size = right_pos + 1 - left_pos
if minimum_length is None or interval_size < minimum_length:
minimum_length = interval_size
break
else:
left_pos += 1
key_to_occ[left_word] -= 1
return minimum_length
old = [[0 for x in range(3)] for y in range(10)]
count =0
# check if the number has non-repeating digits
def different(number):
digit_list = [0] * 4
i = 0
while i:
digit_list[i] = number%10
number /= 10
i += 1
for x in range(0,3):
for y in range(x+1,3):
if digit_list[x] == digit_list[y]:
return False
return True
# save the tried numbers, plus and minus values
# for prediction of the next number
def save(number,plus,minus):
global count
old[count][0] = number
old[count][1] = plus
old[count][2] = minus
count += 1
return
# compare for plus values
def get_plus(number1,number2):
ret_value = 0
for x in range(0, 3):
if number1 % 10 == number2 % 10:
ret_value += 1
number1 /= 10
number2 /= 10
return ret_value
# compare for minus values
def get_minus(number1,number2):
temp = [[0]*4 for i in range(2)]
ret_value = 0
for x in range(0,3):
temp[0][x] = number1 % 10
temp[0][x] = number2 % 10
number1 /= 10
number2 /= 10
for x in range(0,3):
for y in range(0,3):
if x != y:
if temp[0][x] == temp[1][y]:
ret_value += 1
return ret_value
# compare the number to be asked with the numbers in the array
def control(number):
for x in range(0,count-1):
if get_plus(old[x][0],number) != old[x][1]:
return False
if get_minus(old[x][0],number) != old[x][2]:
return False
return True
def main():
flag = False
print('1023 ??')
plus = input('plus ?')
minus = input('minus ?')
save(1023, plus, minus)
print('4567 ??')
plus = input('plus ?')
minus = input('minus ?')
save(4567, plus, minus)
for i in range(1024, 9876):
if different(i):
if control(i):
print(i + ' ??')
plus = input('plus ?')
minus = input('minus ?')
save(i, plus, minus)
if plus == 4 and minus == 0:
print('I WON !!!')
flag = True
break
if not flag:
print('False')
return
main()
I am trying to make an AI for mindgame in python. But in this function it doesn't even start the for loop. Can anyone know why ?
The while loop in your different() function does nothing as while(0) will prevent the loop from running. Even if that would run, your different() function will always return false. At least in the last loop it will compare digit_list[3] == digit_list[3] as both loop range until 3. This is always true and the function will return false. Thus the code within your main loop will never be entered.
def different(number):
digit_list = [0] * 4
i = 0
while i:
digit_list[i] = number%10
number /= 10
i += 1
for x in range(0,3):
for y in range(x+1,3):
if digit_list[x] == digit_list[y]:
return False
return True
Try this one:
import random
def different(num):
digits = []
while num >= 1:
cur = num%10
if cur in digits:
return False
digits.append(cur)
num = (num - cur) / 10
return True
for i in range(0, 10000):
rand = random.randrange(1000, 10000)
if not different(rand):
print(rand)
I made a code that measure number of steps it takes to return to 1 in a Collatz Conjecture. Here Is my code
counter = 0
def collatz(n):
global counter
counter += 1
if n <= 0 :
return "Invalid Number"
elif n == 1 :
return counter
elif n % 2 == 1 :
n = 3*n + 1
return collatz(n)
elif n % 2 == 0 :
n = n/2
return collatz(n)
print(collatz(9921615699))
print(collatz(9921615699))
I expect the Last two print commands to print 311 and 311. Instead, they print 311 and 622. I guess that was easy enough to see in the code what is wrong. How can i fix that? how can counter reset each time a command is completed and not when the function is run.
Instead of using global variable you could make the counter a parameter with default value:
def collatz(n, counter=0):
counter += 1
if n <= 0 :
return "Invalid Number"
elif n == 1 :
return counter
elif n % 2 == 1 :
n = 3*n + 1
return collatz(n, counter)
elif n % 2 == 0 :
n = n/2
return collatz(n, counter)
You're using recursion, so just use it properly:
def collatz(n, counter=0):
counter += 1
if n <= 0 :
return "Invalid Number"
elif n == 1 :
return counter
elif n % 2 == 1 :
n = 3*n + 1
return collatz(n, counter)
elif n % 2 == 0 :
n = n/2
return collatz(n, counter)
print(collatz(9921615699))
print(collatz(9921615699))
You were using global in your original version which is usually not what you want to do. You got to see first-hand why.
You could have reset the counter, e.g.
result = counter
counter = 0
return result
But that's pretty nasty, let's not do that. When you're implementing a recursive algorithm there's probably no good reason to have a global variable.
I am new in python and I don't know why this program is not updating the 'i' variable when I am incrementing it in the execution of for loop.
len(a) = 10
you can see in the code that I am incrementing 'i' time after time but after the increment when I comes into loop iteration it nullifies the update made in the body of loop. Why is this is ? It should be updated in general and loop execution should be less than 10. Please help.
final_result = 0
a= '3 4 4 5 6'
for i in range(0,len(a)):
print('iteration')
print('i is = ')
print(i)
if a[i] is ' ' and a[i+1] is not ' ':
if i-1 is 0:
final_result = int(a[i-1]) + int(a[i+1])
i += 2 //here goes the increment
print('1a- m here')
print(final_result)
print('i is = ')
print(i)
else:
final_result = final_result + int(a[i+1])
i += 2 //here goes the increment
print('1b- m here')
print(final_result)
elif a[i] is ' ' and a[i+1] is ' ':
if i-1 is 0:
final_result = int(a[i-1]) - int(a[i+1])
i += 3 //here goes the increment
print('2a- m here')
print(final_result)
else:
final_result = final_result - int(a[i+2])
i += 3 //here goes the increment
print('2b- m here')
print(final_result)
print('i is = ')
print(i)
print(final_result)
So several things:
Use a while loop.
Initialize i = 0
Increment i += 1 when none of your conditions match
Comments in Python are written with # comment, not // comment.
Example:
final_result = 0
a = '3 4 4 5 6'
i = 0
while i < len(a):
print('iteration')
print('i is = ')
print(i)
if a[i] is ' ' and a[i + 1] is not ' ':
if i - 1 is 0:
final_result = int(a[i - 1]) + int(a[i + 1])
i += 2 # here goes the increment
print('1a- m here')
print(final_result)
print('i is = ')
print(i)
else:
final_result = final_result + int(a[i + 1])
i += 2 # here goes the increment
print('1b- m here')
print(final_result)
elif a[i] is ' ' and a[i + 1] is ' ':
if i - 1 is 0:
final_result = int(a[i - 1]) - int(a[i + 1])
i += 3 # here goes the increment
print('2a- m here')
print(final_result)
else:
final_result = final_result - int(a[i + 2])
i += 3 # here goes the increment
print('2b- m here')
print(final_result)
print('i is = ')
print(i)
else:
i += 1
print(final_result)
Output:
$ python3.4 foo.py
iteration
i is =
0
iteration
i is =
1
1a- m here
7
i is =
3
iteration
i is =
3
2b- m here
3
i is =
6
iteration
i is =
6
1b- m here
8
iteration
i is =
8
1b- m here
14
14