How to print this diamond pattern using python? - python

I want to print this pattern in python:(10 rows rhombus increment-decrement numbers)
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
1234567891987654321
12345678987654321
123456787654321
1234567654321
12345654321
123454321
12321
121
1
Note : 1234321 is missing in the last but fourth line, so I think it is not a perfect rhombus. Plus instead of 10, 1 is printed in the tenth line.How to achieve this shape? Please let me know.
I had no idea on how to do this using numbers so,tried the below basic program using * but I don't know how to print the same using numbers as shown above.
n=11
for i in range(n):
print(''*(n-i-1)+'* '*(i+1))
for j in range(n-1,0,-1):
print(''*(n-j)+'* '*(j))
Also this prints half the shape only
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * *
* * * * * * * * *
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
How to print the pattern I mentioned(using increment-decrement numbers)?
Plus is the question wrong because it misses 1234321 line or it can be achieved?
Please help me.I am new to coding so how to achieve this using the simplest way i.e using looping constructs like for loop? Thanks in advance for your help and time.

Here is a possibility for how to generate the geometry:
n = 11
for i in range(n // 2 + 1):
print(' ' * (n // 2 - i) + '* ' * (i + 1))
for i in reversed(range(n // 2)):
print(' ' * (n // 2 - i) + '* ' * (i + 1))
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
EDIT: Here is an actual implementation with numbers, that fails at n = 10, unfortunately.
from itertools import chain
n = 9
ranges = chain(range(n), reversed(range(n - 1)))
for i in ranges:
print(' ' * (n - i - 1), *[x + 1 for x in range(i + 1)],
*[x + 1 for x in reversed(range(i))])
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 3 2 1
1 2 3 2 1
1 2 1
1

I'd do a function for one line, and run it twice, skipping the 4 at the end:
def oneline(i):
for j in range(i,10):
print(' ', end='')
for j in range(1, i+1):
print(j if j<10 else 1, end='')
for j in range(i-1, 0, -1):
print(j if j<10 else 1, end='')
print()
for i in range(1,11):
oneline(i)
for i in range(9,0,-1):
if i == 4:
continue
oneline(i)
Output:
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
1234567891987654321
12345678987654321
123456787654321
1234567654321
12345654321
123454321
12321
121
1

I believe this would be more pythonic:
size = 10
pattern = (size-1)*" " + size*"123456789" # indented pattern
rhombus = [ pattern[i:i+size] for i in range(size) ] # top-left
rhombus = [ d+d[-2::-1] for d in rhombus ] # horizontal mirror
rhombus = rhombus+rhombus[-2::-1] # vertical mirror
The approach leverages the horizontal and vertical symmetry of the output by only generating the top-left corner and then mirroring horizontally and vertically
output:
for line in rhombus: print(line)
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
1234567891987654321
12345678987654321
123456787654321
1234567654321
12345654321
123454321
1234321
12321
121
1
Alternatively, if you want to print as you go, you can work with the left side of the pattern for all the lines and print the horizontally mirrored substring of the pattern for each line:
size = 10
pattern = size*" " + size*"123456789" # indented pattern (1 based)
for i in range(1,size*2): # for each line (1 based)
line = pattern[size-abs(size-i):][:size] # left side of line
print(line + line[-2::-1]) # print mirrored line

Here's a simple version using for loops. Should work for large numbers.
def r(upper=10):
for i in range(-1 * (upper-1), upper):
j = upper - abs(i)
print(' ' * (abs(i)), end ='')
for k in range(-1 * (j-1), j):
print(str(j - abs(k))[0], end='')
print()
r(10)
..
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
1234567891987654321
12345678987654321
123456787654321
1234567654321
12345654321
123454321
1234321
12321
121
1
Hope it helps :)

Related

Cant exit while loop on Simpson's Rule

I am trying to calculate an integral using Simpson's Rule formula.The catch is that the value of the integral is the one that satisfies the following condition:You find the Ih and Ih/2.If the absolute of (Ih-Ih/2)<error the loop is complete.Otherwise you repeat the process with half the h,which means it calculates the absolute of (Ih/2-Ih/4) and so on and so on.
while True:
###Ih part
h = (b - a) / N
y1 = np.linspace(a, b, N)
Ez11 = (np.sqrt(ra ** 2 + R ** 2 - 2 * ra * R * np.cos(y1 - fa))) / (
(aa ** 2 - 2 * ra * R * np.cos(y1 - fa)) ** (3 / 2))
I11 = (h/3) * (Ez11[0] + 2*sum(Ez11[:N-2:2]) \
+ 4*sum(Ez11[1:N-1:2]) + Ez11[N-1])
#####Ih/2 part
h = (b-a)/(2*N)
y2 = np.linspace(a, b, 2*N)
Ez22 = (np.sqrt(ra ** 2 + R ** 2 - 2 * ra * R * np.cos(y2 - fa))) / (
(aa ** 2 - 2 * ra * R * np.cos(y2 - fa)) ** (3 / 2))
print(Ez22)
I22 = (h/ 3) * (Ez22[0] + 2 * sum(Ez22[:N - 2:2]) \
+ 4 * sum(Ez22[1:N - 1:2]) + Ez22[N - 1])
# error condition I1=Ih I2=Ih/2
if np.abs(I11 - I22) < error:
break
else:
N = 2*N # h/2
print(np.abs(I11 - I22))
As far as I can tell,my approach should be correct.However the loop goes on and on,never to stop.
My code is as follows:
import numpy as np
from scipy.integrate import simps
import scipy.integrate as integrate
import scipy.special as special
# variables
a = 0
b = np.pi * 2
N = 100
ra = 0.1 # ρα
R = 0.05
fa = 35 * (np.pi / 180) # φα
za = 0.4
Q = 10 ** (-6)
k = 9 * 10 ** 9
aa = np.sqrt(ra ** 2 + R ** 2 + za ** 2)
error = 0.55 * 10 ** (-8)
h=(b-a)/N
I1 = np.nan
I11 = np.nan
#Simpsons section
############ Ez
#automated Simpson
while True:
###Ih part
y1 = np.linspace(a, b, N)
Ez1 = (np.sqrt(ra ** 2 + R ** 2 - 2 * ra * R * np.cos(y1 - fa))) / (
(aa ** 2 - 2 * ra * R * np.cos(y1 - fa)) ** (3 / 2))
print(len(Ez1))
I1 = simps(Ez1, y1)
#####Ih/2 part
y2 = np.linspace(a, b, 2*N)
Ez2 = (np.sqrt(ra ** 2 + R ** 2 - 2 * ra * R * np.cos(y2 - fa))) / (
(aa ** 2 - 2 * ra * R * np.cos(y2 - fa)) ** (3 / 2))
I2 = simps(Ez2, y2)
# error condition I1=Ih I2=Ih/2
if np.abs(I1 - I2) < error:
break
else:
N *= 2 # h/2
#custom-made Simpson
N = 100
while True:
###Ih part
h = (b - a) / N
y1 = np.linspace(a, b, N)
Ez11 = (np.sqrt(ra ** 2 + R ** 2 - 2 * ra * R * np.cos(y1 - fa))) / (
(aa ** 2 - 2 * ra * R * np.cos(y1 - fa)) ** (3 / 2))
I11 = (h/3) * (Ez11[0] + 2*sum(Ez11[:N-2:2]) \
+ 4*sum(Ez11[1:N-1:2]) + Ez11[N-1])
#####Ih/2 part
h = (b-a)/(2*N)
y2 = np.linspace(a, b, 2*N)
Ez22 = (np.sqrt(ra ** 2 + R ** 2 - 2 * ra * R * np.cos(y2 - fa))) / (
(aa ** 2 - 2 * ra * R * np.cos(y2 - fa)) ** (3 / 2))
print(Ez22)
I22 = (h/ 3) * (Ez22[0] + 2 * sum(Ez22[:N - 2:2]) \
+ 4 * sum(Ez22[1:N - 1:2]) + Ez22[N - 1])
# error condition I1=Ih I2=Ih/2
if np.abs(I11 - I22) < error:
break
else:
N = 2*N # h/2
print(np.abs(I11 - I22))
print(I1)
print(I11)
Simpson's Rule is as follows:
After a while it's stuck in this situation
The 5.23 part is the absolute diff of those 2 which shouldnt be that high.

How can I write a program that prints a multiplication table of size m by n which is provided by the user in Python?

Examples:
m n: 2 3
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
m n: 4 2
1 * 1 = 1
1 * 2 = 2
2 * 1 = 2
2 * 2 = 4
3 * 1 = 3
3 * 2 = 6
4 * 1 = 4
4 * 2 = 8
I have written this code but i said "list assignment index out of range", how can I fix it? thanks
m, n = input('m n: ').split()
x = []
for i in range(0, int(m)):
for j in range(0, int(n)):
x[j] = int(m[i]) * int(n[j])
print(str(i) + ' * ' + str(j) + ' = ',x[j])
m, n = input('m n: ').split()
for i in range(1, int(m)+1):
for j in range(1, int(n)+1):
print(str(i) + ' * ' + str(j) + ' = ', i * j)

How to create python game board

I need help with creating something like this. (I´m just a beginner and I need some inspiration on how to create this board with these numbers, this board should parameter n, with this parameter i can choose how big will be this board [9x9 or 13x13]) Thx for every idea!
0 1 2 3 4 5 6 7 8
0 * * *
1 * D *
2 * D *
3 * * * * D * * * *
4 * D D D X D D D *
5 * * * * D * * * *
6 * D *
7 * D *
8 * * *
My Board list looks like this:
board = [[' ',' ',' ','*','*','*',' ',' ',' '],
[' ',' ',' ','*','D','*',' ',' ',' '],
[' ',' ',' ','*','D','*',' ',' ',' '],
['*','*','*','*','D','*','*','*','*'],
['*','D','D','D','X','D','D','D','*'],
['*','*','*','*','D','*','*','*','*'],
[' ',' ',' ','*','D','*',' ',' ',' '],
[' ',' ',' ','*','D','*',' ',' ',' '],
[' ',' ',' ','*','*','*',' ',' ',' ']]
These two lines would work:
print(' '+' '.join(map(str,range(9))))
print('\n'.join([' '.join([str(i)]+v) for i,v in enumerate(board)]))
Output:
0 1 2 3 4 5 6 7 8
0 * * *
1 * D *
2 * D *
3 * * * * D * * * *
4 * D D D X D D D *
5 * * * * D * * * *
6 * D *
7 * D *
8 * * *
Bunch of str.joins can do it!!!

Pivot table sorting

I have a pivot table result as below :
len
MERCHANT_NAME
MCC_CODE
0.0 58635982
742.0 7378
763.0 750
780.0 281
1520.0 974
frame_mcc_merchant_pvt=pd.pivot_table(frame_mcc_merchant,index=['MCC_CODE'],
values=['MERCHANT_NAME'],aggfunc=[len],fill_value=0)
I need to sort the pivot table by the values of the len of merchant name ?
Pls help
Remove [] for avoid MultiIndex and then sorting by sort_values:
frame_mcc_merchant_pvt=pd.pivot_table(frame_mcc_merchant,
index='MCC_CODE',
values='MERCHANT_NAME',
aggfunc=len,
fill_value=0).sort_values('MERCHANT_NAME')
my code here is copying over the pivot table results, and then checking for the average (arithmetic mean value) and the standard deviation of a batch.
At the section where i copied over the numbers, i am sure you could sort them for size, by getting max / min and then loop through.
Private Sub EvaluateButton_Click()
Dim EvaRange As Range 'Evaluation range
Dim i As Integer 'Counter for free columns
Dim n As Integer 'Counter for number of measurements
Dim a As Integer 'Counter for Abfragenummer
Dim AbfrageZahl As Variant 'Frage nach der Abfrage
Dim z As Integer 'counter für Abfrage
Worksheets("testsheet").Activate
'MsgBox "The name of the active sheet is " & ActiveSheet.Name
z = 0
AbfrageZahl = InputBox("Bitte geben Sie eine Zahl >1 ein für die Abfrage. Q2 2022: 2, Q4 2022: 3, Q2 2023: 3 usw.")
z = AbfrageZahl - 2
Set EvaRange = Range("C10:C999")
EvaRange.Copy Cells(15, 7 + 2 * z)
Range(Cells(15, 7 + 2 * z), (Cells(Rows.Count, 7 + 2 * z))).Select
i = 15
For Each self In Selection.SpecialCells(xlCellTypeConstants)
self.Copy Cells(i, 8 + 2 * z)
i = i + 1
Next
Cells(i - 1, 8 + 2 * z).Clear 'und jetzt die Auswertung
n = i - 16 'definiere mein n
Cells(1, 8 + 2 * z).Value = Date 'schreibe Abfragedatum
Cells(2, 8 + 2 * z).Value = n 'schreibe mein n
Cells(3, 8 + 2 * z).Value = Application.WorksheetFunction.Average(Range(Cells(15, 8 + 2 * z), Cells(Rows.Count, 8 + 2 * z)))
Cells(4, 8 + 2 * z).Value = Application.WorksheetFunction.StDev_S(Range(Cells(15, 8 + 2 * z), Cells(Rows.Count, 8 + 2 * z)))
Cells(5, 8 + 2 * z).Value = Range("C1").Value
Cells(6, 8 + 2 * z).Value = Range("C2").Value
Cells(7, 8 + 2 * z).Value = Range("C3").Value
Cells(8, 8 + 2 * z).Value = Range("C4").Value
Cells(9, 8 + 2 * z).Value = Range("C5").Value
Cells(10, 8 + 2 * z).Value = Range("C6").Value
Cells(11, 8 + 2 * z).Value = Tabelle2.Name
Cells(12, 8 + 2 * z).Value = AbfrageZahl
Cells(1, 7 + 2 * z).Value = "Date of Review"
Cells(2, 7 + 2 * z).Value = "n, Number of Measurements"
Cells(3, 7 + 2 * z).Value = "µ, arithmetic mean"
Cells(4, 7 + 2 * z).Value = "Sigma, stand. Dev. of a batch"
Cells(5, 7 + 2 * z).Value = Range("B1").Value
Cells(6, 7 + 2 * z).Value = Range("B2").Value
Cells(7, 7 + 2 * z).Value = Range("B3").Value
Cells(8, 7 + 2 * z).Value = Range("B4").Value
Cells(9, 7 + 2 * z).Value = Range("B5").Value
Cells(10, 7 + 2 * z).Value = Range("B6").Value
Cells(11, 7 + 2 * z).Value = "Test Name"
Cells(12, 7 + 2 * z).Value = "Review Cycle Nr."
End Sub

All + - / x combos for 4 numbers

4 one digit numbers and try to get all the possible combos
4511
like 4 + 5 + 1 x 1
Code to get first, 2nd 3rd and 4th numbers
numbers = input("Input 4 numbers separated with , : ")
numlist = numbers.split(",")
print (numlist)
No1 = int(numlist.pop(0))
No2 = int(numlist[0])
No3 = int(numlist[1])
No4 = int(numlist[2])
An exhaustive search:
from random import randrange
from itertools import permutations
def solve(digits):
for xs in permutations(digits):
for ops in permutations('+-*/', 3):
equation = reduce(lambda r, (x, op): '{0} {1} {2}'.format(r, op, float(x)), zip(xs[1:], ops), xs[0])
try:
if eval(equation) == 10:
yield equation.replace('.0','')
except ZeroDivisionError:
pass
digits = [randrange(0,10,1) for x in range(4)]
solutions = list(solve(digits))
if solutions:
print '\n'.join(solutions)
else:
print 'No solution for {0}'.format(digits)
Example output:
2 * 5 / 1 + 0
2 * 5 / 1 - 0
2 * 5 + 0 / 1
2 * 5 - 0 / 1
2 / 1 * 5 + 0
2 / 1 * 5 - 0
5 * 2 / 1 + 0
5 * 2 / 1 - 0
5 * 2 + 0 / 1
5 * 2 - 0 / 1
5 / 1 * 2 + 0
5 / 1 * 2 - 0
0 + 2 * 5 / 1
0 + 2 / 1 * 5
0 + 5 * 2 / 1
0 + 5 / 1 * 2
0 / 1 + 2 * 5
0 / 1 + 5 * 2
or
No solution for [7, 1, 0, 2]
Note: I like the recursive expression generator referred to in the comment above, but I just don't think recursively straight off.
Use a recursive approach:
numbers = input("Input 4 numbers separated with , : ")
numlist = list(numbers)
def f(lst,carry,result):
x = lst.pop(0)
if lst == []:
return carry+x == result or \
carry-x == result or \
carry*x == result or \
carry/x == result
elif carry==None:
carry = x
return f(lst,carry,result)
else:
return f(lst,carry+x,result) or\
f(lst,carry-x,result) or\
f(lst,carry*x,result) or\
f(lst,carry/x,result)
print(f(numlist, None, 10))
Your I/O is wrong (first two lines), and I don't know if this is something that you have already tried.

Categories