'return' outside function (making text gradient) - python

line 18
i'm making a text gradient and cant seem to get this right. here's my code.
what the h*** is wrong with the indention here?
import math
gradient = ('FF24E9', 'F026EC', 'E128F0', 'D22AF3', 'C32CF7', 'A530FE', '8F3EFE', '7A4CFE', '655AFE', '5068FE', '3B76FE')
def gradientmadness(text):
leng = len(text)
output = ''
if leng < 11:
for i in range(0, leng):
output += '<c=#%s>' % gradient[i]
for i in range(0, leng):
output += text[i] + '</c>'
else :
output += '<c=#'
output += '><c=#'.join(gradient)
output += '>'
size = int(math.ceil(leng / 11.0))
for i in range(1, 11 + 1):
output += text[(i - 1) * size: i * size] + '</c>'
return output
gradientmadness.command = "gradient1"

Here is your code with correct formatting :
import math
gradient = ('FF24E9', 'F026EC', 'E128F0', 'D22AF3', 'C32CF7', 'A530FE', '8F3EFE', '7A4CFE', '655AFE', '5068FE', '3B76FE')
def gradientmadness(text):
leng = len(text)
output = ''
if leng < 11:
for i in range(0, leng):
output += '<c=#%s>' % gradient[i]
for i in range(0, leng):
output += text[i] + '</c>'
else :
output += '<c=#'
output += '><c=#'.join(gradient)
output += '>'
size = int(math.ceil(leng / 11.0))
for i in range(1, 11 + 1):
output += text[(i - 1) * size: i * size] + '</c>'
return output
gradientmadness.command = "gradient1"

Related

Output matches expected output. Yet submission is not being accepted

https://www.hackerrank.com/challenges/designer-door-mat/problem
Below is my submission:
n = input().split(' ')
rows, columns = int(n[0]), int(n[1])
if(rows % 2 == 1 and columns == 3*rows):
printale = ''
j = 1
k = rows - 7
for i in range(int(rows/2), -1, -1):
printale = '---'*i + '.|.'*j + '---'*i
if(i == 0):
print('-'*int(j+k/2) + 'Welcome' + '-'*int(j+k/2))
j -= 2
else:
print(printale)
j += 2
for l in range(1, int(rows/2)+1):
printale = '---'*l + '.|.'*j + '---'*l
print(printale)
j -= 2
Is there anything wrong with the code?
Yes, there is. The "WELCOME" in the problem statement is all-caps.

IndexError: list index out of range error while enter value like 1 2 3 in Python

I am generating a graph/drawing using pyhton.
When I am entering value from backward like 6 5 4 3 it's working fine but When I am giving input like 1 2 3 it's throwing list index out of range error.
I am new to python. Please help me to fix this.
**EDIT : ** it's only accepting when first value is greater than second value for example it's working with 7 6 but not with 6 7.
here is my python code:
HUMAN_HEIGHT = 3
HUMAN_WIDTH = 3
HUMAN_LEG_OFFSET = 1
def print_2d_array(arr):
"""Print the 2D Array"""
print(f"Height = {len(arr)}, Width = {len(arr[0])}")
for row in arr:
for item in row:
print(f"{item}", end="")
print()
def increasing_slope(index):
"""Returns if the slope is increasing which is the even number"""
return index % 2 == 0
def get_indicator(index):
"""Returns the indicator for increasing or decreasing slope"""
return "/" if increasing_slope(index) else "\\"
def add_human_at(new_arr, human_location, height):
"""Adds Human to the Array"""
human_x = human_location[0]
human_y = human_location[1]
new_arr[height - human_y - 1][human_x - 1] = " "
new_arr[height - human_y - 1][human_x] = "○"
new_arr[height - human_y - 1][human_x + 1] = " "
new_arr[height - human_y][human_x - 1] = "/"
new_arr[height - human_y][human_x] = "|"
new_arr[height - human_y][human_x + 1] = "\\"
new_arr[height - human_y + 1][human_x - 1] = "<"
new_arr[height - human_y + 1][human_x] = " "
new_arr[height - human_y + 1][human_x + 1] = ">"
def create_line(y0, x0, y1, x1, index):
"""Generator that Returns the diagonal line from x,y to x1,y1"""
yield y0, x0
while y0 != y1 and x0 != x1:
y0 = y0 + (-1 if increasing_slope(index) else 1)
x0 += 1
yield y0, x0
def get_2d_mountains_from_1d_sum(arr, height, width, human_location):
new_arr = []
for i in range(height + HUMAN_HEIGHT):
mountain_row = []
for j in range(width + HUMAN_LEG_OFFSET):
mountain_row.append(" ")
new_arr.append(mountain_row)
ground = height + HUMAN_HEIGHT
prev_x, prev_y = 0, 0
for index, [x, y] in enumerate(arr):
indicator = get_indicator(index)
if prev_x >= human_location[0]:
start_x, start_y = ground - prev_y - 1, prev_x + HUMAN_LEG_OFFSET
end_x, end_y = ground - y - 1, x - 1 + HUMAN_LEG_OFFSET
else:
start_x, start_y = ground - prev_y - 1, prev_x
end_x, end_y = ground - y - 1, x - 1
for (point_y, point_x) in create_line(start_x, start_y, end_x, end_y, index):
new_arr[point_y][point_x] = indicator
prev_y = y
prev_x = x
add_human_at(new_arr, human_location, height)
print_2d_array(new_arr)
def generate_mountains(nums):
sum_nums = []
sum_at_position = 0
previous_sum = 0
total_width = 0
max_height = 0
human_location = []
for index, item in enumerate(nums):
# + or - numbers to get prefix list
if index % 2 == 0:
sum_at_position += (item - 1)
else:
sum_at_position -= (item - 1)
total_width += abs(sum_at_position - previous_sum) + 1
if sum_at_position > max_height:
max_height = sum_at_position
human_location = [total_width, max_height]
previous_sum = sum_at_position
sum_nums.append([total_width, sum_at_position])
get_2d_mountains_from_1d_sum(sum_nums, max_height + 1, total_width, human_location)
def print_mountains_human_from_input(nums):
generate_mountains(nums)
print("Enter the inputs")
a = [int(x) for x in input().split()]
print_mountains_human_from_input(a)
I added the screenshot of error..
thanks in advance.
You can add a sorting to your function to avoid a wrong input error but it will not fix the actual error:
def print_mountains_human_from_input(nums):
nums.sort(reverse=True)
generate_mountains(nums)

python 2d array condition

i'm working on 8 queen(Genetic Algorithm) program with python 3.4
i use a matrix for keep queens position. but i have an error in sort() function,i dont underestand this error.
please help me ...
my code:
from random import randrange
__author__ = 'Moein'
class NQueen:
NUM_COLS = 8
POPULATIONS = 100
current = [[]]
def __init__(self):
self.current = [[0 for col in range(self.NUM_COLS + 1)] for row in range(self.POPULATIONS)]
# generate first Generation
for i in range(0, self.POPULATIONS):
for j in range(0, self.NUM_COLS):
self.current[i][j] = randrange(self.NUM_COLS)
count = 0
condition = True
while condition:
self.crossover()
self.mutation()
self.fitness()
self.sort()
count += 1
print(self.current)
# print(self.current[0])
if self.current[0][self.NUM_COLS] == 0:
condition = False
print(self.current[0])
pass
def fitness(self):
count = 0
for i in range(0, self.POPULATIONS):
for j in range(0, self.NUM_COLS):
for x in range(j + 1, self.NUM_COLS):
if self.current[i][j] == self.current[i][x]:
count += 1
if abs(j - x) == abs(self.current[i][j] - self.current[i][x]):
count += 1
self.current[i][self.NUM_COLS] = count
count = 0
pass
def sort(self):
for i in range(0, self.POPULATIONS - 1):
for j in range(i + 1, self.POPULATIONS):
if self.current[i][self.NUM_COLS] > self.current[j][self.NUM_COLS]:
for x in range(0, self.NUM_COLS + 1):
temp = self.current[i][x]
self.current[i][x] = self.current
self.current[j][x] = temp
pass
def crossover(self):
_new = [[0 for x in range(self.NUM_COLS + 1)] for x in range(self.POPULATIONS)]
for i in range(0, int(self.POPULATIONS / 2)):
for j in range(0, int(self.NUM_COLS / 2)):
_new[i + 49][j] = self.current[i][j]
_new[i + 49 + 1][j] = self.current[i + 1][j]
for j in range(int(self.NUM_COLS / 2), self.NUM_COLS):
_new[i + 49][j] = self.current[i][j]
_new[i + 49 + 1][j] = self.current[i + 1][j]
self.current = _new
pass
def mutation(self):
for i in range(0, self.POPULATIONS):
self.current[i][randrange(self.NUM_COLS)] = randrange(self.NUM_COLS)
pass
nQueen = NQueen()
print(nQueen.current[0])
and my error:
Traceback (most recent call last):
File "C:/Users/Moein/PycharmProjects/NQueen/project.py", line 81, in <module>
nQueen = NQueen()
File "C:/Users/Moein/PycharmProjects/NQueen/project.py", line 27, in __init__
self.sort()
File "C:/Users/Moein/PycharmProjects/NQueen/project.py", line 54, in sort
if self.current[i][self.NUM_COLS] > self.current[j][self.NUM_COLS]:
TypeError: unorderable types: list() > int()
self.current[i][x] = self.current
I guess that its this line causing the problem, since
self.current
is a list, so you are setting
self.current[i][x]
to be a list instead of an int. So at this point:
if self.current[i][self.NUM_COLS] > self.current[j][self.NUM_COLS]:
when you try to compare those values it might happen, that you compare
an int with a list, which causes the error.
TypeError: unorderable types: list() > int()
Cheers
EDIT:
I just tried it out.
Replacing
self.current
with an int for example 2 prevents the Exception from occurring.

string index out of range list iteration

I am fairly new to python, I am not sure on how to fix a index string out of range. it happens right after the while loop when I want to send mylist[i][0] to formatting function. Any pointer on my code in general would be awesome!
def formatting(str1):
if str1 == '?':
return True
else:
return False
while(i <= len(mylist)):
val = formatting(mylist[i][0])
if val == True:
str1 = mylist[i]
str2 = mylist[i+1]
i = i + 2
format_set(str1, str2)
else:
if format == True:
if (margin + count + len(mylist[i])) <= width:
if (i == (len(mylist)-1)):
list2.append(mylist[i])
print(" " * margin + " ".join(list2))
break
list2.append(mylist[i])
count += len(mylist[i])
i += 1
else:
print(" " * margin + " ".join(list2))
list2 = []
count = 0
else:
temp_margin = margin
temp_width = width
width = 60
margin = 0
if (margin + count + len(mylist[i])) <= width:
if (i == (len(mylist)-1)):
list2.append(mylist[i])
print(" " * margin + " ".join(list2))
margin = temp_margin
width = temp_width
break
list2.append(mylist[i])
count += len(mylist[i])
i += 1
else:
print(" " * margin + " ".join(list2))
list2 = []
count = 0
change
i <= len(mylist)
to
i < len(mylist)
In the last iteration of the while loop, i is referring to the last value. Hence,
str2 = mylist[i+1]
is trying to reference a string outside the allowed range and you get an error.
EDIT: Also, as Wcrousse mentioned, the while (i <= len(...)) should be changed to i < len(...) because indexes go from 0 - (length-1).

Genetic algorithm suspends in python?

I have implemented a simple genetic algorithm in python - here is the most of the code:
import random
ings = (('w1', 200, 25, 80),
('su1', 50, 55, 150),
('su2', 400, 100, 203),
('sy1', 10, 150, 355),
('sy2', 123, 88, 101),
('sy3', 225, 5, 30),
('sy4', 1, 44, 99),
('sy5', 500, 220, 300))
mutationRate = 0.2
crossoverRate = 0.9
iterations = 100
file = open('D:\\logfile2.txt', 'a')
class Ingredient:
def __init__(self, n, p, mi, ma):
self.name = n
self.price = p
self.min = mi
self.max = ma
self.perc = random.randrange(self.min, self.max)
class Drink:
def __init__(self):
self.ing = [Ingredient(*x) for x in ings]
self.normalize()
self.fitness = self.evaluate()
def normalize(self):
sum = 0
for x in self.ing:
sum += x.perc
if sum < 1000:
offset = 1000 - sum
while not offset == 0:
index = random.randrange(len(self.ing))
val = self.ing[index].max - self.ing[index].perc
threshold = random.randrange(val) if val > 0 else 0
threshold = threshold if threshold < offset else offset
self.ing[index].perc += threshold
offset -= threshold
if sum > 1000:
offset = sum - 1000
while not offset == 0:
index = random.randrange(len(self.ing))
val = self.ing[index].perc - self.ing[index].min
threshold = random.randrange(val) if val > 0 else 0
threshold = threshold if threshold < offset else offset
self.ing[index].perc -= threshold
offset -= threshold
def evaluate(self):
fitness = 0
for x in self.ing:
fitness += x.perc * x.price
return 300000 - fitness
class GeneticAlgorithm:
def __init__(self):
self.drinkList = [Drink() for x in range(8)]
self.pool = []
def mutate(self, index):
ing1, ing2 = random.randrange(8), random.randrange(8)
while ing1 == ing2:
ing2 = random.randrange(8)
ptr = self.drinkList[index].ing
ing1thr = ptr[ing1].max - ptr[ing1].perc
ing2thr = ptr[ing2].perc - ptr[ing2].min
if ing1thr & ing2thr:
change = random.randrange(ing1thr if ing1thr < ing2thr else ing2thr)
ptr[ing1].perc += change
ptr[ing2].perc -= change
def crossover(self, index1, index2):
ing1, ing2 = random.randrange(8), random.randrange(8)
while ing1 == ing2:
ing2 = random.randrange(8)
ptr1 = self.drinkList[index1].ing[:]
ptr2 = self.drinkList[index2].ing[:]
resultIndex1 = random.randrange(len(self.drinkList))
while True:
resultIndex2 = random.randrange(len(self.drinkList))
if not resultIndex1 == resultIndex2:
break
bias = 1 if ptr1[ing1].perc > ptr2[ing1].perc else -1
if bias == 1:
maxChange = min(ptr1[ing1].perc - ptr1[ing1].min,
ptr1[ing2].max - ptr1[ing2].perc,
ptr2[ing1].max - ptr2[ing1].perc,
ptr2[ing2].perc - ptr2[ing2].min)
if maxChange:
change = random.randrange(maxChange)
ptr1[ing1].perc -= change
ptr1[ing2].perc += change
ptr2[ing1].perc += change
ptr2[ing2].perc -= change
self.drinkList[resultIndex1].ing = ptr1[:]
self.drinkList[resultIndex2].ing = ptr2[:]
if bias == -1:
maxChange = min(ptr1[ing1].max - ptr1[ing1].perc,
ptr1[ing2].perc - ptr1[ing2].min,
ptr2[ing1].perc - ptr2[ing1].min,
ptr2[ing2].max - ptr2[ing2].perc)
if maxChange:
change = random.randrange(maxChange)
ptr1[ing1].perc += change
ptr1[ing2].perc -= change
ptr2[ing1].perc -= change
ptr2[ing2].perc += change
self.drinkList[resultIndex1].ing = ptr1[:]
self.drinkList[resultIndex2].ing = ptr2[:]
def roulette(self):
sum = 0
lst = []
for x in self.drinkList:
sum += x.fitness
lst.append(sum)
return lst
def selectOne(self):
selection = random.randrange(self.pool[-1])
index = 0
while selection >= self.pool[index]:
index += 1
return index
def selectCouple(self):
selection1 = random.randrange(self.pool[-1])
index1, index2 = 0, 0
while selection1 >= self.pool[index1]:
index1 += 1
while True:
selection2 = random.randrange(self.pool[-1])
while selection2 >= self.pool[index2]:
index2 += 1
if not index1 == index2: break
return (index1, index2)
def save(self, text):
file.write(text)
for x in self.drinkList:
for y in x.ing:
file.write('min: ' + str(y.min) +
' max: ' + str(y.max) +
' value: ' + str(y.perc) + '\n')
file.write('\n\n')
file.write('\nPopulation fitness: ' +
str(self.calculatePopulationFitness()) +
'\n\n----------------------------------------------\n\n')
def run(self):
file.write("Genetic algorithm\n\nAttributes values:\n" +
"Mutation rate: " + str(mutationRate) +
"\nCrossover rate: " + str(crossoverRate) +
"\nIterations: " + str(iterations) +
"\nIngredients:\n\n" + str(ings))
self.save('\n\n--First population--\n\n')
for cnt in range(iterations):
self.updateFitness()
self.pool = self.roulette()
if random.random() < mutationRate:
index = self.selectOne()
self.showFitness('Mutation in iteration ' + str(cnt))
self.mutate(index)
self.updateFitness()
self.showFitness('Results: ')
if random.random() < crossoverRate:
index1, index2 = self.selectCouple()
self.showFitness('Crossover in iteration ' + str(cnt))
self.crossover(index1, index2)
self.updateFitness()
self.showFitness('Results: ')
self.save('--Final population--\n\n')
def calculatePopulationFitness(self):
sum = 0
for x in self.drinkList:
sum += x.fitness
return sum
def updateFitness(self):
for x in self.drinkList:
x.fitness = x.evaluate()
def showFitness(self, text):
lst = [x.fitness for x in self.drinkList]
all = sum(lst)
file.write(text + '\n' + str(lst) + '||' + str(all) + '\n')
To run it I create an instance of GeneticAlgorithm and launch it through run() method.
The problem is, for low level of iterations the program works more or less fine, but if I set iteration to 50 for example, it seems to fall in infinite loop or suspend at random iteration (the logfile is not updated anymore and the program does not stop - happenes at random iteration). What can be the cause of this?
PS: Can you suggest any changes to the coding style? I'm quite new to python and i don't know all the conventions yet.
I don't completely understand your algorithm but it looks like your code hangs in this loop here:
while True:
selection2 = random.randrange(self.pool[-1])
while selection2 >= self.pool[index2]:
index2 += 1
if not index1 == index2: break
It gets to a point where you never get a value where index1 != index2. This could either indicate you have a mistake somewhere in your code, or that there isn't a situation that meets this condition. You could try putting a cap on the number of iterations of this, for example:
iters = 0
while iters < 5000:
selection2 = random.randrange(self.pool[-1])
while selection2 >= self.pool[index2]:
index2 += 1
iters += 1
if index1 != index2: break
if iters == 5000:
# Deal with not being able to identify a Couple
I know the question is more than a year old. Still I wanted a GA code in python to start with and found the problem.
while True:
selection2 = random.randrange(self.pool[-1])
while selection2 >= self.pool[index2]:
index2 += 1
if not index1 == index2: break
The problem is in this loop. once index2 is found to be equal it is not reset back to zero before trying to find a new value.
while True:
index2 = 0
selection2 = random.randrange(self.pool[-1])
while selection2 >= self.pool[index2]:
index2 += 1
if not index1 == index2: break

Categories