I have a code that is ridiculously long and I need to use it in many methods. I think there's definitely a better way to write it. But I'm struggling to find it. What the code does is that it:
Takes 12 numbers
It inputs them in a list(let us call it count)
Creates 12 stars variables
It needs to create some sort of matrix that looks like this:
******* count1
******** count2
********** maxcount (could be any count from count1 to 12, as long as it is the maximum
***** count5
etc..
So to explain that, we have 12 count variables, I needed to take the largest variable of them, so I put them in a list. After putting them in a list, I selected the max(count) in order to build my astericks representation.
The maximum number of astericks possible is 10. THerefore, the maximum amongst the 12 counts should have 10 stars next to it, and all the others will have their stars relatively.
This is my code, but it doesn't seem optimal at all to me, lots of variables created and initialized as well as it takes some time.
count = list()
count.append(count1)
count.append(count2)
count.append(count3)
count.append(count4)
count.append(count5)
count.append(count6)
count.append(count7)
count.append(count8)
count.append(count9)
count.append(count10)
count.append(count11)
count.append(count12)
stars1 = 0
stars2 = 0
stars3 = 0
stars4 = 0
stars5 = 0
stars6 = 0
stars7 = 0
stars8 = 0
stars9 = 0
stars10 = 0
stars11 = 0
stars12 = 0
stars1 = int((count1 * 10) / max(count))
stars2 = int((count2 * 10) / max(count))
stars3 = int(count3 * 10 / max(count))
stars4 = int(count4 * 10 / max(count))
stars5 = int(count5 * 10 / max(count))
stars6 = int(count6 * 10 / max(count))
stars7 = int(count7 * 10 / max(count))
stars8 = int(count8 * 10 / max(count))
stars9 = int(count9 * 10 / max(count))
stars10 = int(count10 * 10 / max(count))
stars11 = int(count11 * 10 / max(count))
stars12 = int(count12 * 10 / max(count))
astericks1 = ""
astericks2 = ""
astericks3 = ""
astericks4 = ""
astericks5 = ""
astericks6 = ""
astericks7 = ""
astericks8 = ""
astericks9 = ""
astericks10 = ""
astericks11 = ""
astericks12 = ""
for i in range(1, 11):
if (i <= stars1):
astericks1 += "*"
else:
astericks1 += " "
if (i <= stars2):
astericks2 += "*"
astericks2 += " "
if (i <= stars3):
astericks3 += "*"
else:
astericks3 += " "
if (i <= stars4):
astericks4 += "*"
else:
astericks4 += " "
if (i <= stars5):
astericks5 += "*"
else:
astericks5 += " "
if (i <= stars6):
astericks6 += "*"
else:
astericks6 += " "
if (i <= stars7):
astericks7 += "*"
else:
astericks7 += " "
if (i <= stars8):
astericks8 += "*"
else:
astericks8 += " "
if (i <= stars9):
astericks9 += "*"
else:
astericks9 += " "
if (i <= stars10):
astericks10 += "*"
else:
astericks10 += " "
if (i <= stars11):
astericks11 += "*"
else:
astericks11 += " "
if (i <= stars12):
astericks12 += "*"
else:
astericks12 += " "
First of all this kind of if,elif statements and variable creations are generally bad coding practice. Secondly, as a little advice you should always think that I can create same functionality with the list instead of two different variables for the same reason (count1,count2, etc.).
As I understand from your code you print maximum 10 stars for max value. So the code below should produce same behavior with yours using list comprehensions. Also I should mention that it can be written more efficiently but I wanted to be clear and simple for you.
variable_num = 12
count = [int(input()) for i in range(variable_num)]
max_num = max(count)
count = [(i*10)//max_num for i in count]
for ind,i in enumerate(count):
print("{} count {}".format(int(i)*"*",ind))
As simple as:
# Get 12 numbers as input
s = input("Input 12 numbers separated by a white space")
# Save them in a list and calculate the maximum
nums = [int(item) for item in s.split()]
max_num = max(nums)
for idx, item in enumerate(nums):
# Calcuate number of stars, ensuring number of stars are never more then 10
num_stars = int(item * 10 / max_num)
# print the stars
print('*' * num_stars, 'count{}'.format(idx))
Sample output will be
Input 12 numbers separated by a white space1 2 3 4 5 6 1 2 3 4 5 6
* count0
*** count1
***** count2
****** count3
******** count4
********** count5
* count6
*** count7
***** count8
****** count9
******** count10
********** count11
Related
It seems that my decoration sometimes appears just outside the triangle... How can I fix this?
import random
n = int(input('enter n: '))
x = 1
for i in range(n):
if i == 0:
count = 0
else:
count = random.randint(0, x)
print(' ' * (n - i), '*' * count, end = '')
if i == 0:
print('&', end = '')
else:
print('o', end = '')
print('*' * (x - count - 1))
x += 2
What do I get for value n = 10:
&
***o
*o***
o******
******o**
*********o*
*************o
*****o*********
*************o***
******************o
The random number you generate may return x as randint includes the second value in the set of possible values. So pass x - 1 to randint:
count = random.randint(0, x - 1)
It is also a pity that you have a check for i == 0 in your loop. In that case, why not deal with that first case outside of the loop, and start the loop at 1? It will make your code a bit more elegant.
def tree(n):
from random import sample
body = ["&"] + ["".join(sample("o" + "*" * (k:=x*2+1), k=k)) for x in range(1, n)]
spaces = [" " * (x-2) for x in range(n, 1, -1)]
return "\n".join("".join(tpl) for tpl in zip(spaces, body))
print(tree(10))
Output:
&
o**
****o
o******
*******o*
********o**
*******o*****
**************o
o****************
I love christmas tress! This is my take on the question :-)
import random
n = int(input('Enter tree height: '))
print(" " * (n-1) + "&")
for i in range(2, n+1):
decoration = random.randint(1, (i-1)*2 -1)
print(" " * (n - i) + "*" * decoration + "o" + "*" * ((i-1)*2 - decoration))
Enter tree height: 12
&
*o*
**o**
*o*****
*o*******
********o**
*******o*****
***********o***
********o********
****************o**
***o*****************
*********o*************
data = input("Input:")
def parse_to_int(dat): # parse input data to int list
individuals = dat.split(" ")
num = []
for individual in individuals:
num.append((int)(individual))
return num
def get_Max_and_MaxIndex_MinIndex(num_list): # get maximul value, its index and minimum value
sign = 1
val = 0
max_val = 0
min_val = 0
max_ind = 0
count = 0
for num in num_list:
count += 1
val = val + sign * num
sign = -1 * sign
if (max_val < val):
max_val = val
max_ind = count
if (min_val > val):
min_val = val
return max_val, max_ind, min_val
def sub_sum(ind): # calculate subsum until ind
global num_input
global subsum
subsum = 0
for i in range(ind + 1):
subsum += num_input[i]
return subsum
def sub_sum_with_sign(ind): # calculate subsum with sign until ind
global num_input
global subsum_withsign
subsum_withsign = 0
sign = 1
for i in range(ind + 1):
subsum_withsign += sign * num_input[i]
sign = -1 * sign
return subsum_withsign
def fill_data(ind): # fill data for print in empty data
global print_data
global cur_x
global cur_y
if ind % 2 == 0:
str = '/'
dx = 1
dy = 1
else:
str = '\\'
dx = 1
dy = -1
for _ in range(num_input[ind]):
print_data[cur_y][cur_x] = str
cur_x += dx
cur_y += dy
if ind % 2 == 0:
cur_y -= 1
else:
cur_y += 1
return print_data
# main program
num_input = parse_to_int(data)
col_num = 0 # column count
for elem in num_input:
col_num += elem
max_min_num = get_Max_and_MaxIndex_MinIndex(num_input)
row_num = max_min_num[0] - max_min_num[2] # row count
start_num = 0
for i in range(max_min_num[1]):
start_num += num_input[i] # maximum height element number
subsum = 0
subsum_withsign = 0
cur_x = 0
cur_y = -1 * max_min_num[2]
# start output
print("Output:\n")
print(" " * start_num + "o" + " " * (col_num - start_num))
print(" " * (start_num - 1) + "/|\\" + " " * (col_num - start_num - 1))
print(" " * (start_num - 1) + "< >" + " " * (col_num - start_num - 1))
# prepare data for print
print_data = []
for i in range(row_num):
print_data.append([])
for j in range(col_num):
print_data[i].append(" ")
for ind in range(len(num_input)):
fill_data(ind)
# print data
for indr in range(row_num - 1, -1, -1):
print("".join(print_data[indr]))
The above code will give this Output
In this code, a graph is generated using python without using any libraries. The Highest tip of the graph is marked.
I want to mark the lowest tip of the graph as shown in the image below. I completely have no idea about this one. which values should be changed in order to mark the lowest tip in the generated graph?
I am a newbie to stackoverflow, please comment if you need more clarity with this..
How to mark the lowest tip here Please Help me with this
def kaprekar_num(num):
count = 0
while count <= num:
n = 1
sqr = n ** 2
digits = str(sqr)
length = len(digits)
for x in range(1, length):
left = int("".join(digits[:x]))
right = int("".join(digits[x:]))
if (left + right) == n:
print("Number: " + str(n) + ", Left: " + str(left) + " + " + " Right: " + str(right) + " = " + str(n))
n += 1
count += 1
else:
n += 1
kaprekar_num(5)
hello guys,
I'm new to python programming and I got a task in class to print the first 5 kaprekar numbers.
(I only have C programming background...)
I have a problem with the "for x in range..." line.. the code doesn't enter the loop and I don't know why.
the program needs to print:
Number: 9, Left: 8 + Right: 1 = 9
Number: 10, Left: 10 + Right: 0 = 10
Number: 45, Left: 20 + Right: 25 = 45
Number: 55, Left: 30 + Right: 25 = 55
Number: 99, Left: 98 + Right: 1 = 99
I will appreciate some insights :)
for loop was fine, you had some logic issue, which you haven't handled, like when n==1 and when len(sqr)==1.
def kaprekar_num(num):
count = 0
n=1
while count <= num:
sqr = n ** 2
digits = str(sqr)
length = len(digits)
if sqr==1:
print("Number: " + str(n) + " = " + str(n))
count+=1
n+=1
elif length>1:
for x in range(1,length):
left = int("".join(digits[:x]))
right = int("".join(digits[x:]))
if (left + right) == n:
print("Number: " + str(n) + ", Left: " + str(left) + " + " + " Right: " + str(right) + " = " + str(n))
n += 1
count += 1
else:
n += 1
else:
n+=1
kaprekar_num(5)
How you're managing the n value is incorrect. It should be set before the loop starts, then after each try, regardless of the outcome, it should increment.
def kaprekar_num(num):
count = 0
# Start n at one, and don't reset it on each loop
n = 1
while count <= num:
sqr = n ** 2
digits = str(sqr)
length = len(digits)
for x in range(1, length):
left = int("".join(digits[:x]))
right = int("".join(digits[x:]))
if (left + right) == n:
print("Number: " + str(n) + ", Left: " + str(left) + " + " + " Right: " + str(right) + " = " + str(n))
count += 1
# This number is a Kaprekar number, so break out of the loop
break
# Regardless of the status of this number, try the next one
n += 1
kaprekar_num(5)
And as a recommendation: I'd highly recommend you look into stepping through the code with a debugger in the future. If you had done so, you'd have seen that n is not changing fairly quickly.
you've set the loop to repeat once i think, if you meant to put n instead of 1, i think thats the problem.
Try to set the loop to this instead
for x in range(n, length):
How to print text in stars box with loop
Example I want:
input1: input text
input2: high of stars
ex:
input1 = Your Name
input2 = 3
output:
***********
*Your Name*
***********
this my code i have now
def function(text):
"""start"""
name = len(text)
num = int(input())
for i in range(num):
for j in range(name + 2):
if i == 0 or j == 0 or i == num - 1:
print("*", end="")
print()
function(input())
output is
***********
*
***********
What should I do next.
You can multiply a string. "*" * 10 == '**********' - you don't need the inner for loop then.
Also, you need to print the thing as it should be, not make a border first - you can't just type onto what's already printed.
def function(text):
"""start"""
name_length = len(text) #renamed your variable, the name was confusing
num = int(input())
for i in range(num):
if i == 0 or i == num - 1: #removed inner loop
print("*" * (name_length+2))
else:
print("*{}*".format(text) #added printing the text and right border
function(input())
You didn't say what should happen for a higher number. I assumed the name should be repeated.
def function(text):
"""start"""
name = len(text)
num = int(input())
text_num = int((num - 1) / 2)
for i in range(num):
for j in range(name + 2):
if i == 0 or i == num - 1:
print("*", end="")
elif i == text_num:
if j == 0 or j == name + 1:
print("*", end="")
else:
print(text[j-1], end="")
print()
function(input())
Another option is to format by line as opposed to character.
Something like this could work:
def function(text):
"""start"""
name = len(text)
num = int(input())
for i in range(num):
if i == 0 or i == num - 1:
print('*' * (name + 2))
elif i == int(num / 2):
print('*' + text + '*')
else:
print('*' + ' ' * name + '*')
function(input())
With num = 3 outputs:
***********
*your name*
***********
With num = 5 outputs:
***********
* *
*your name*
* *
***********
You can build the box in a list and then substitute the name at the middle line:
name = "your name"
num = 3
box = ["*"+(" "*len(name))+"*"]*num
box[0] = box[-1] = "*" * (len(name)+2)
box[num//2] = f"*{name}*"
print("\n".join(box))
***********
*your name*
***********
my answer for finding the number of combinations given drawing 3 cards out of 52 is off by a spot. Like 0 cards from 52 should = 1, 1 should = 52, 2 = 1326 and so on. but I have 0 = 1, 1 = 1, 2 = 52 and so on. What would I modify to reach the desired result? I think the error is in def factorial() but I can not seem to fix/ find the issue, no matter what I try.
def factorial(num):
i = 2
if num == 0:
num = 1
print(num)
elif num > 1:
for i in range(i, num):
num = num * i
return num
def combinations(n,r):
l = n-r
nn = factorial(n)
rn = factorial(r)
ln = factorial(l)
result = nn / (rn * ln)
print(result)
return result
def main():
h = 52
a = 0
while a<4:
combinations(h,a)
a = a + 1
You're printing extra stuff in factorial which may lead to the confusion. I suggest you print out your final result with comparison to your a variable at the end of the combinations function like so:
print("For a=" + str(r) + ", result=" + str(result))
Here is the overall edited code:
def factorial(num):
if num == 0:
num = 1
elif num > 1:
for i in range(2, num): # Setting i=2 at the start is redundant
num = num * i
return num
def combinations(n,r):
l = n-r
nn = factorial(n)
rn = factorial(r)
ln = factorial(l)
result = nn / (rn*ln)
print("For a=" + str(r) + ", result=" + str(result))
return
h = 52
a = 0
while a<4:
combinations(h,a)
a = a + 1