With Python editor I am trying to recreate this specific line pattern over here:
666666
6 6
6 6
6 6
66
6
This is the Code that I have created:
steps=6
for s in range(steps):
print('6' + (' ' * r) + '6')
However the output that I get instead is:
66
6 6
6 6
6 6
6 6
6 6
Thus as you can see it almost does the opposite operation to what I wanted in the opening output above. If there is a way to reverse this output I have to what I want please share.
You can use the built-in reversed function that returns an iterator that goes through the range in reverse.
steps=6
for r in reversed(range(steps)):
print('#' + (' ' * r) + '#')
Or you can use list splicing to revers the list like so:
steps=6
for r in range(steps)[::-1]:
print('#' + (' ' * r) + '#')
Aside from Martijn's comment on considering what kind of pattern you need to follow, i.e. how the number of spaces evolves from one line to the next, you may want to look into the documentation of the command range at PythonDocs on range(). Currently you are only providing one argument:
range(stop)
Python will then use default values for the remaining arguments: start=0 and step=1. However, you can provide these explicitly. The 'step' argument is where you can put in reversed counting:
range(start, stop[, step])
Let us start with building it in ascending order, that is like the diagram below
6
66
6 6
6 6
66666
There is a series to the number of spaces depending after height = 1, that is from height = 2 the number of spaces have the series 0,1,2 and so on, therefore if height is n then the series begins at 2 where the space = 0 and ends at n - 1 where the number of spaces is equal to n - 3, and at height = n the number of 6s is equal to n - 2.
The code for this would be
def print6(height):
... print 6
... for s in range(0, height - 2):
... print str(6) + ' '*s + str(6)
... print str(6)*2+str(6)*(height-2)
To reverse this
def print6(height):
... print str(6)*2+str(6)*(height-2)
... for s in range(0, height - 2):
... print str(6) + ' '*(height-3-s) + str(6)
... print 6
Related
I am trying to solve a problem of multiplication. I know that Python supports very large numbers and it can be done but what I want to do is
Enter 2 numbers as strings.
Multiply those two numbers in the same manner as we used to do in school.
Basic idea is to convert the code given in the link below to Python code but I am not very good at C++/Java. What I want to do is to understand the code given in the link below and apply it for Python.
https://www.geeksforgeeks.org/multiply-large-numbers-represented-as-strings/
I am stuck at the addition point.
I want to do it it like in the image given below
So I have made a list which stores the values of ith digit of first number to jth digit of second. Please help me to solve the addition part.
def mul(upper_no,lower_no):
upper_len=len(upper_no)
lower_len=len(lower_no)
list_to_add=[] #saves numbers in queue to add in the end
for lower_digit in range(lower_len-1,-1,-1):
q='' #A queue to store step by step multiplication of numbers
carry=0
for upper_digit in range(upper_len-1,-1,-1):
num2=int(lower_no[lower_digit])
num1=int(upper_no[upper_digit])
print(num2,num1)
x=(num2*num1)+carry
if upper_digit==0:
q=str(x)+q
else:
if x>9:
q=str(x%10)+q
carry=x//10
else:
q=str(x%10)+q
carry=0
num=x%10
print(q)
list_to_add.append(int(''.join(q)))
print(list_to_add)
mul('234','567')
I have [1638,1404,1170] as a result for the function call mul('234','567') I am supposed to add these numbers but stuck because these numbers have to be shifted for each list. for example 1638 is supposed to be added as 16380 + 1404 with 6 aligning with 4, 3 with 0 and 8 with 4 and so on. Like:
1638
1404x
1170xx
--------
132678
--------
I think this might help. I've added a place variable to keep track of what power of 10 each intermediate value should be multiplied by, and used the itertools.accumulate function to produce the intermediate accumulated sums that doing so produces (and you want to show).
Note I have also reformatted your code so it closely follows PEP 8 - Style Guide for Python Code in an effort to make it more readable.
from itertools import accumulate
import operator
def mul(upper_no, lower_no):
upper_len = len(upper_no)
lower_len = len(lower_no)
list_to_add = [] # Saves numbers in queue to add in the end
place = 0
for lower_digit in range(lower_len-1, -1, -1):
q = '' # A queue to store step by step multiplication of numbers
carry = 0
for upper_digit in range(upper_len-1, -1, -1):
num2 = int(lower_no[lower_digit])
num1 = int(upper_no[upper_digit])
print(num2, num1)
x = (num2*num1) + carry
if upper_digit == 0:
q = str(x) + q
else:
if x>9:
q = str(x%10) + q
carry = x//10
else:
q = str(x%10) + q
carry = 0
num = x%10
print(q)
list_to_add.append(int(''.join(q)) * (10**place))
place += 1
print(list_to_add)
print(list(accumulate(list_to_add, operator.add)))
mul('234', '567')
Output:
7 4
7 3
7 2
1638
6 4
6 3
6 2
1404
5 4
5 3
5 2
1170
[1638, 14040, 117000]
[1638, 15678, 132678]
I am not sure of inverse is the proper name, but I think it is.
This example will clarify what I need:
I have a max height, 5 for example, and so height can range from 0 to 4. In this case we're talking integers, so the options are: 0, 1, 2, 3, 4.
What I need, given an input ranging from 0 up to (and including) 4, is to get the inverse number.
Example:
input: 3
output: 1
visual:
0 1 2 3 4
4 3 2 1 0
I know I can do it like this:
position_list = list(range(5))
index_list = position_list[::-1]
index = index_list[3]
But this will probably use unnecessary memory, and probably unnecessary cpu usage creating two lists. The lists will be deleted after these lines of code, and will recreated every time the code is ran (within method). I'd rather find a way not needing the lists at all.
What is an efficient way to achieve the same? (while still keeping the code readable for someone new to the code)
Isn't it just max - in...?
>>> MAX=4
>>> def calc(in_val):
... out_val = MAX - in_val
... print('%s -> %s' % ( in_val, out_val ))
...
>>> calc(3)
3 -> 1
>>> calc(1)
1 -> 3
You just need to subtract from the max:
def return_inverse(n, mx):
return mx - n
For the proposed example:
position_list = list(range(5))
mx = max(position_list)
[return_inverse(i, mx) for i in position_list]
# [4, 3, 2, 1, 0]
You have maximum heigth, let's call it max_h.
Your numbers are counted from 0, so they are in [0; max_h - 1]
You want to find the complementation number that becomes max_h in sum with input number
It is max_h - 1 - your_number:
max_height = 5
input_number = 2
for input_number in range(5):
print('IN:', input_number, 'OUT:', max_height - input_number - 1)
IN: 1 OUT: 3
IN: 2 OUT: 2
IN: 3 OUT: 1
IN: 4 OUT: 0
Simply compute the reverse index and then directly access the corresponding element.
n = 5
inp = 3
position_list = list(range(n))
position_list[n-1-inp]
# 1
You can just derive the index from the list's length and the desired position, to arrive at the "inverse":
position_list = list(range(5))
position = 3
inverse = position_list[len(position_list)-1-position]
And:
for i in position_list:
print(i, position_list[len(position_list)-1-i])
In this case, you can just have the output = 4-input. If it's just increments of 1 up to some number a simple operation like that should be enough. For example, if the max was 10 and the min was 5, then you could just do 9-input+5. The 9 can be replaced by the max-1 and the 5 can be replaced with the min.
So max-1-input+min
I'm trying to create a histogram in python as a part of my python class
It is supposed to look like this:
However, I can't figure out the histogram. This is my code so far:
sumValues = []
print("Enter 10 integers")
for i in range( 10 ):
newValue = int( input("Enter integer %d: " % (i + 1) ))
sumValues.append(newValue)
print("\nCreating a histogram from values: ")
print("%s %10s %10s" %("Element", "Value", "Histogram"))
How do I create the actual histogram?
Some hints:
New-style Python formatting allows this:
In [1]: stars = '*' * 4 # '****'
In [2]: '{:<10s}'.format(stars)
Out[3]: '**** '
That is, you can take a string of 4 stars (formed by repetition of '*' four times) and place it in a string of length 10 characters, aligned to the left (<) and padded to the right with whitespace.
(If you don't need the histogram to have the same number of characters (stars or spaces), just print the stars; no need to format)
Just like this:
# fake data
sumValues = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
...
# calculate how long is the list and adjust the padding for 'Element'
padding = max(len(sumValues), len('Element'))
# now the padding for 'Value'
padding1 = max(len(str(max(sumValues))), len('Value'))
print("\nCreating a histogram from values: ")
print("%s %10s %10s" %("Element", "Value", "Histogram"))
# use enumerate to loop your list and giving the index started from 1
for i,n in enumerate(sumValues, start=1):
print '{0} {1} {2}'.format( # print each line with its elements
str(i).ljust(padding), # print with space using str.ljust
str(i).rjust(padding1), # print with space using str.rjust
'*'*n) # '*' * n = '*' multiply by 'n' times
Creating a histogram from values:
Element Value Histogram
1 1 *
2 2 **
3 3 ***
4 4 ****
5 5 *****
6 6 ******
7 7 *******
8 8 ********
9 9 *********
10 10 **********
I've been asked to do the following:
Using a while loop, you will write a program which will produce the following mathematical sequence:
1 * 9 + 2 = 11(you will compute this number)
12 * 9 + 3 = 111
123 * 9 + 4 = 1111
Then your program should run as far as the results contain only "1"s. You can build your numbers as string, then convert to ints before calculation. Then you can convert the result back to a string to see if it contains all "1"s.
Sample Output:
1 * 9 + 2 = 11
12 * 9 + 3 = 111
123 * 9 + 4 = 1111
1234 * 9 + 5 = 11111
Here is my code:
def main():
Current = 1
Next = 2
Addition = 2
output = funcCalculation(Current, Addition)
while (verifyAllOnes(output) == True):
print(output)
#string concat to get new current number
Current = int(str(Current) + str(Next))
Addition += 1
Next += 1
output = funcCalculation(Current, Next)
def funcCalculation(a,b):
return (a * 9 + b)
def verifyAllOnes(val):
Num_str = str(val)
for ch in Num_str:
if(str(ch)!= "1"):
return False
return True
main()
The bug is that the formula isn't printing next to the series of ones on each line. What am I doing wrong?
Pseudo-code:
a = 1
b = 2
result = a * 9 + b
while string representation of result contains only 1s:
a = concat a with the old value of b, as a number
b = b + 1
result = a * 9 + b
This can be literally converted into Python code.
Testing all ones
Well, for starters, here is one easy way to check that the value is all ones:
def only_ones(n):
n_str = str(n)
return set(n_str) == set(['1'])
You could do something more "mathy", but I'm not sure that it would be any faster. It would much more easily
generalize to other bases (than 10) if that's something you were interested in though
def only_ones(n):
return (n % 10 == 1) and (n == 1 or only_ones2(n / 10))
Uncertainty about how to generate the specific recurrence relation...
As for actually solving the problem though, it's actually not clear what the sequence should be.
What comes next?
123456
1234567
12345678
123456789
?
Is it 1234567890? Or 12345678910? Or 1234567900?
Without answering this, it's not possible to solve the problem in any general way (unless in fact the 111..s
terminate before you get to this issue).
I'm going to go with the most mathematically appealing assumption, which is that the value in question is the
sum of all the 11111... values before it (note that 12 = 11 + 1, 123 = 111 + 11 + 1, 1234 = 1111 + 111 + 11 + 1, etc...).
A solution
In this case, you could do something along these lines:
def sequence_gen():
a = 1
b = 1
i = 2
while only_ones(b):
yield b
b = a*9 + i
a += b
i += 1
Notice that I've put this in a generator in order to make it easier to only grab as many results from this
sequence as you actually want. It's entirely possible that this is an infinite sequence, so actually running
the while code by itself might take a while ;-)
s = sequence_gen()
s.next() #=> 1
s.next() #=> 11
A generator gives you a lot of flexibility for things like this. For instance, you could grab the first 10 values of the sequence using the itertools.islice
function:
import itertools as it
s = sequence_gen()
xs = [x for x in it.islice(s, 10)]
print xs
I am going through a past test and the output of the code is this:
Enter the height:
5
5
44
333
2222
11111
I have to write down the code - so far I know how to make a normal triangle with:
for i in range(5):
print('*'*i)
*
**
***
****
My main question is how do I get the body if the triangle to iterate over the numbers?
So what would the code of the first triangle be?
Help would be appreciated:)
The code for this is virtually the same, you just need to change the number of times you print each character, and change the * that you are printing to a number.
for i in range(5):
print(str(5-i) * (i+1))
This generates:
5
44
333
2222
11111
To make it right aligned, like in your example, just use string multiplication on a space character.
for i in range(5):
print(' ' * (4-i) + str(5-i) * (i+1))
This will get you:
5
44
333
2222
11111
You can use str:
for i in range(5):
print(str(i)*i)
Some of the other answers have been essentially correct, but this one right justifies your triangle like the original output.
def print_triangle(rows):
for i in range(rows + 1):
print((str(rows + 1-i)*i).rjust(rows))
height = 5
for i in range(height, 0, -1):
empty_chars = ' ' * (i - 1)
filler_chars = str(i) * (height - i + 1)
print('{}{}'.format(empty_chars, filler_chars))
Formatted string & spacing with an external array and a negated variable.
def height(num):
rangenum=range(num+1)
for i in rangenum:
print(("%"+str(num)+"s")%(i*str(rangenum[-i])))
print("%(spacing as a number)s"%(a string))
returns
(spacing as a number)-(a string)
example:
print("%10s"%"this")
returns:
" this"
side note:
%-(a number)s
is right justified.
(though python tries to cut down the millions of ways to do the same thing, there still are thousands)
https://docs.python.org/2/tutorial/inputoutput.html