Creating a Number Pyramid - python

I first off would like to say this may be classified as a duplicate post, based on my current research:
How to do print formatting in Python with chunks of strings?
and
Number Pyramid Nested for Loop
and
pyramid of numbers in python
[Edit: The reason I cannot use the conclusions to these previous questions very similar to mine is that I cannot use anything except what we have covered in my class so far. I am not allowed to use solutions such as: len, map, join, etc. I am limited to basic formats and string conversion.]
I'm in the process of working on an assignment for my Python class (using 3.0+) and I've reached a point where I'm stuck. This program is meant to allow the user to input a number from 1 to 15 as a line count and output a number pyramid based on their choice, such as the following example where the user would input 5:
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
So far I've gotten to the point where I can successfully print inputs 1 through 9, but have run into 2 issues.
Inputs from 10 to 15 the numbers become misaligned (which users in the above posts seemed to have as well).
I can't seem to correctly format the printed numbers to have spaces in between them like my example above
My current code for the program is:
print("This program creates a number pyramid with 1 to 15 lines")
lines = eval(input("Enter an integer from 1 to 15: "))
if lines < 16:
for i in range(1, lines + 1):
#Print leading space
for j in range(lines - i, 0, -1):
print(" ", end = '')
#Print left decreasing numbers
for j in range(i, 0, -1):
print(j, end = '')
#Print right increasing numbers
for j in range(2, i + 1):
print(j, end = '')
print("")
else:
print("The number you have entered is greater than 15.")
And my current output is:
Enter an integer from 1 to 15: 15
1
212
32123
4321234
543212345
65432123456
7654321234567
876543212345678
98765432123456789
109876543212345678910
1110987654321234567891011
12111098765432123456789101112
131211109876543212345678910111213
1413121110987654321234567891011121314
15141312111098765432123456789101112131415
I am asking you guys out of a desire to learn, not for anyone to code for me. I want to understand what I'm doing wrong so I can fix it. Thank you all in advance!

You need to print one space more for the numbers from 10 to 15 because there is an extra character you have to take into consideration. If you change your max number to 100, you will need another space(total of 3), and so on. This means that instead if print(" ") you have to use print(" " * len(str(j))), where * duplicates the space len(str(j)) times and len(str(j)) counts the number of digits from j. Also, if you want the pyramid properly aligned, you have to print another space, the one between numbers.
To add a space between numbers, you have to print the space
print(j, end=' ')

input_number=int (raw_input ())
for i in range (1, input_number+1):
string=''
k=i
while (k>0):
string=string+str (k)
k=k-1
m=2
while (m<=i):
string=string+str (m)
m+=1
space=(2* input_number-1)
string=string.center (space)
print (string)
This code works well.

Related

WAP in python script to input a multidigit number and find each of the number's factorial

The output shows a different result. Yes, the factorials of those numbers are right but the numbers outputted aren't right.
Here's the code:
input:
n = int(input("Enter a number: "))
s = 0
fact = 1
a = 1
for i in range(len(str(n))):
r = n % 10
s += r
n //= 10
while a <= s:
fact *= a
a += 1
print('The factorial of', s, 'is', fact)
Output:
Enter a number: 123
The factorial of 3 is 6
The factorial of 5 is 120
The factorial of 6 is 720
You're confusing yourself by doing it all in one logic block. The logic for finding a factorial is easy, as is the logic for parsing through strings character by character. However, it is easy to get lost in trying to keep the program "simple," as you have.
Programming is taking your problem, designing a solution, breaking that solution down into as many simple, repeatable individual logic steps as possible, and then telling the computer how to do every simple step you need, and what order they need to be done in to accomplish your goal.
Your program has 3 functions.
The first is taking in input data.
input("Give number. Now.")
The second is finding individual numbers in that input.
for character in input("Give number. Now."):
try:
int(character)
except:
pass
The third is calculating factorials for the number from step 2. I won't give an example of this.
Here is a working program, that is, in my opinion, much more readable and easier to look at than yours and others here. Edit: it also prevents a non numerical character from halting execution, as well as using only basic Python logic.
def factorialize(int_in):
int_out = int_in
int_multiplier = int_in - 1
while int_multiplier >= 1:
int_out = int_out * int_multiplier
int_multiplier -= 1
return int_out
def factorialize_multinumber_string(str_in):
for value in str_in:
print(value)
try:
print("The factorial of {} is {}".format(value, factorialize(int(value))))
except:
pass
factorialize_multinumber_string(input("Please enter a series of single digits."))
You can use map function to get every single digit from number:
n = int(input("Enter a number: "))
digits = map(int, str(n))
for i in digits:
fact = 1
a = 1
while a <= i:
fact *= a
a += 1
print('The factorial of', i, 'is', fact)
Ok, apart from the fact that you print the wrong variable, there's a bigger error. You are assuming that your digits are ever increasing, like in 123. Try your code with 321... (this is true of Karol's answer as well). And you need to handle digit zero, too
What you need is to restart the calculation of the factorial from scratch for every digit. For example:
n = '2063'
for ch in reversed(n):
x = int(ch)
if x == 0:
print(f'fact of {x} is 1')
else:
fact = 1
for k in range(2,x+1):
fact *= k
print(f'fact of {x} is {fact}')

Change in variable values upon recursion, Python 3

Hey so im pretty new to programming in general and I was having a crack at a question I found for the collatz function,
The code I wrote after some trial and error is as follows:
def collatz(number):
if number % 2 == 0:
number = number//2
print(number)
return number
elif number%2 != 0:
number = 3*number + 1
print(number)
return number
n = int(input("plz enter the number:"))
while n != 1:
n = collatz(n)
Output:
plz enter the number:3
10
5
16
8
4
2
1
This code works but im not sure how the variable values are being alloted, cuz after running this program I can see that in the shell "number = 3" but "n = 1", why is this the case? Shouldnt "number" also equal to 1? Because I am returning the value of number within the function?
Also just to clear my concepts, at the initial moment when I input n = 3, at that moment n = number = 3, then does this returned value of "number" automatically become the new value of n, when i call it in the while loop?
Just wanted to check cuz im a little weak when it comes to doing stuff that needs to pass parameters.
edit:
Why is this case diff then what was just answered?
def testfile(number):
number = number -1
print(number)
return number
n = int(input("enter:"))
while n != 2:
n = testfile(n)
Output:
enter:5
4
3
2
When the input is given as n = 5, then why does number = 3 instead of 5 as was just explained below?
Here's how your program works.
You ask for a number and store it in variable n.
You open a loop which continues until n is 1
Every time the loop repeats, you're calling your function and passing a COPY of n. If you add one to the copy inside the function, your original n will not change.
The COPY is called number. You perform your little tricks with number, output it to the screen, and here's the confusing part: you return a copy of number right back to your loop. And where does it go? It goes right back to n. This overwrites whatever was in n previously.

While loop ignores conditionals (if, else) and just prints first suggested print option

I am trying to create a program that prints out a list of numbers starting at 0 and leading up to a number the user inputs (represented by the variable "number"). I am required to use "while" loops to solve this problem (I already have a functional "for" loop version of the assignment). The program should mark anything in that list divisible by 3 with the word "Fizz," divisible by 5 with the word "Buzz," and anything divisible by both with "FizzBuzz" while also including unlabeled numbers outside of those specifications.
Every time I run this program, it ignores the conditions and just prints the word "FizzBuzz" however many times is represented by the number inputted. (I typically use 15 because it has at least one example of each condition, so that means I get 15 "FizzBuzz"s in a row).
To find out why it was doing that, I used print(i) instead of the rest of the program under the first conditional and it gave me 15 counts of the number 0, so there is reason to believe the program is completely ignoring the range I gave it and just outputting copies of i based on the user number input.
Any help would be appreciated!
number = int(input("Enter a Number"))
i = 0
while(i < number + 1):
if number % 3 == 0 and number % 5 == 0:
print("Fizzbuzz")
elif number % 5 == 0:
print("Buzz")
elif number % 3 == 0:
print("Fizz")
else:
print(number)
i += 1
print ("Done!")
You meant to check the divisibility of i, which increments every loop, not of number which doesn't change.
You also meant to print(i) in the else clause.

Python: Adding odd numbers together from an input

Have a little problem. I'm writing a simple program that takes an input of numbers (for example, 1567) and it adds the odd numbers together as well as lists them in the output. Here is my code:
import math
def oddsum(n):
y=n%10
if(y==0):
return
if(y%2!=0):
oddsum(int(n/10))
print (str(y),end="")
print (" ",end="")
else:
oddsum(int(n/10))
def main():
n=int(input("Enter a value : "))
print("The odd numbers are ",end="")
oddsum(n)
s = 0
while n!=0:
y=n%10
if(y%2!=0):
s += y
n //= 10
print("The sum would be ",end=' ')
print("=",s)
return
main()
It outputs just fine, in the example it will print 1 5 and 7 as the odd numbers. However, when it calculates the sum, it just says "7" instead of 13 like it should be. I can't really understand the logic behind what I'm doing wrong. If anyone could help me out a bit I'd appreciate it :)
I understand it's an issue with the "s += y" as it's just adding the 7 basically, but I'm not sure how to grab the 3 numbers of the output and add them together.
As #Anthony mentions, your code forever stays at 156 since it is an even num.
I would suggest you directly use the string input and loop through each element.
n = input("Enter a value : ") #'1567'
sum_of_input = sum(int(i) for i in n if int(i)%2) #1+5+7=13
[print(i, end="") for i in n if int(i)%2] #prints '157'
Note that int(i)%2 will return 1 if it is odd.
1567 % 10 will return 7. You might want to add the numbers you printed in oddsum to a list, and use the sum function on that list to return the right answer.
The immediate issue is that n only changes if the remainder is odd. eg 1,567 will correctly grab 7 and then n=156. 156 is even, so s fails to increment and n fails to divide by 10, instead sitting forever at 156.
More broadly, why aren't you taking advantage of your function? You're already looping through to figure out if a number is odd. You could add a global parameter (or just keep passing it down) to increment it.
And on a even more efficient scale, you don't need recursion to do this. You could take advantage of python's abilities to do lists. Convert your number (1567) into a string ('1567') and then loop through the string characters:
total = 0
for c in '1567':
c_int = int(c)
if c_int%2!= 0:
total += c_int
print(c)
print(total)

Python 3 - Program that requests positive integer and prints first 4 multiples of it

I'm working on a problem that involves putting in an input, integer n, that when doing so will print off the following 4 "multiples" of the integer. I need to do this for 3 integers, n = 5, n = 0, n = 3.
Original Question:
Implement a program that requests a positive
integer n from the user and prints the first four multiples of n: Test
your module for n = 5; n = 0 and n = 3.
The output of the code should look like:
>>>
Enter n: 5
5
10
15
20
So, what I've come up with so far is this
n = (input("Enter n:"))
This allows me to input an integer value.
Next using print(n), this will print the value I input (Ex. number 5), but I'm not sure how to print off multiples of it after. I realize it's a loop question, most likely involving if or in, but I'm not sure where to go after this.
You've pretty much figured out the question on your own. The correct code is:
n = int(input("Enter n:"))
for i in range(4):
print(n*(i+1))
So, what this for loop does for you is repeat your print statement 4 times, where you give i the values of the expression range(4).
If you just print(range(4)), you'll see that it evaluates to [0,1,2,3]. That's why I had to add 1 to it each time.
The int() function call is needed because input() returns a string, not a number. So if we want the mathematical operators to do what we expect, we need to first convert it to a number (in this case, an integer).
This is the general logic:
n = (input("enter n:"))
for(int i = 1; i <= 4; i++){
print(int(float((n))*i);
}
if you want the list to start with 0 you can do this, it has an error but it can be fixed...
number = int(input("Give a number:"))
for multiples in range(10):
getal1 = number * multiples
print("\t The", str(multiples + 1) + "e multiple of," + number, "is", str(getal1) + ".")

Categories

Resources