E5DD Sourcery refactored main branch by sourcery-ai[bot] · Pull Request #1 · ktriggsdev/Basic-Python-Programs · GitHub
[go: up one dir, main page]

Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions 1)knapsack_recursive.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
def knapsack_recursive(wt,val,W,n):
if n==0 or W==0:
return 0
if wt[n-1]<=W:
return max(val[n-1]+knapsack_recursive(wt,val,W-wt[n-1],n-1),knapsack_recursive(wt,val,W,n-1))
else:
if wt[n-1]<=W:
return max(val[n-1]+knapsack_recursive(wt,val,W-wt[n-1],n-1),knapsack_recursive(wt,val,W,n-1))
elif wt[n-1]>W:
return knapsack_recursive(wt,val,W,n-1)
return knapsack_recursive(wt,val,W,n-1)
Comment on lines +4 to +7
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function knapsack_recursive refactored with the following changes:

W = 6
wt = [1,2,3,6]
val = [1,2,4,6]
Expand Down
32 changes: 9 additions & 23 deletions 2048game.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,7 @@
# at the start
def start_game():

# declaring an empty list then
# appending 4 list each with four
# elements as 0.
mat =[]
for i in range(4):
mat.append([0] * 4)

mat = [[0] * 4 for _ in range(4)]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function start_game refactored with the following changes:

This removes the following comments ( why? ):

# elements as 0.
# appending 4 list each with four
# declaring an empty list then

# printing controls for user
print("Commands are as follows : ")
print("'W' or 'w' : Move Up")
Expand Down Expand Up @@ -75,19 +69,17 @@ def get_current_state(mat):
# cell then also game is not yet over
for i in range(3):
for j in range(3):
if(mat[i][j]== mat[i + 1][j] or mat[i][j]== mat[i][j + 1]):
if mat[i][j] in [mat[i + 1][j], mat[i][j + 1]]:
return 'GAME NOT OVER'

for j in range(3):
if(mat[3][j]== mat[3][j + 1]):
return 'GAME NOT OVER'

for i in range(3):
if(mat[i][3]== mat[i + 1][3]):
return 'GAME NOT OVER'

# else we have lost the game
return 'LOST'
return next(
('GAME NOT OVER' for i in range(3) if (mat[i][3] == mat[i + 1][3])),
'LOST',
)
Comment on lines -78 to +82
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_current_state refactored with the fol 1CF5 lowing changes:

  • Replace multiple comparisons of same variable with in operator (merge-comparisons)
  • Use the built-in function next instead of a for-loop (use-next)

This removes the following comments ( why? ):

# else we have lost the game


# all the functions defined below
# are for left swap initially.
Expand All @@ -101,13 +93,7 @@ def compress(mat):
# any change happened or not
changed = False

# empty grid
new_mat = []

# with all cells empty
for i in range(4):
new_mat.append([0] * 4)

new_mat = [[0] * 4 for _ in range(4)]
Comment on lines -104 to +96
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function compress refactored with the following changes:

This removes the following comments ( why? ):

# empty grid
# with all cells empty

# here we will shift entries
# of each cell to it's extreme
# left row by row
Expand All @@ -119,13 +105,13 @@ def compress(mat):
# in respective row
for j in range(4):
if(mat[i][j] != 0):

# if cell is non empty then
# we will shift it's number to
# previous empty cell in that row
# denoted by pos variable
new_mat[i][pos] = mat[i][j]

if(j != pos):
changed = True
pos += 1
Expand Down
8 changes: 4 additions & 4 deletions ATM.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
print("Please Press 2 To Make a Withdrawl.")
print("Please Press 3 To Pay in.")
print("Please Press 4 To Return Card.")

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1CF5

Lines 19-78 refactored with the following changes:

option = int(input("\nWhat Would you like to Choose?: "))

if option == 1:
Expand All @@ -31,7 +31,7 @@
option2 = ("y")
withdrawl = float(input("\nHow Much Would you like to withdraw? 10, 20, 40, 60, 80, 100 for other enter 1: "))

if withdrawl in [10, 20, 40, 60, 80, 100]:
if withdrawl in {10, 20, 40, 60, 80, 100}:
balance = balance - withdrawl
print(f"\nYour balance after the withdrawl is ${balance}")
restart = input("\nWould You like to do something else? ")
Expand Down Expand Up @@ -73,9 +73,9 @@
print("\nPlease enter a correct number.\n")
restart = ("y")

elif pin != (1234):
else:
print("\nINCORRECT PIN!!\n")
chances = chances - 1
chances -= 1

if chances == 0:
print("Calling the Police...\n")
Expand Down
2 changes: 1 addition & 1 deletion Age Calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def main():
age = calculate_age(datetime.date(year, month, day))

# Print the age
print("Your age is: {}".format(age))
print(f"Your age is: {age}")
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main refactored with the following changes:


if __name__ == '__main__':
main()
12 changes: 4 additions & 8 deletions Areas.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,17 @@
import math

def square(side):
area = side * side
return area
return side * side
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function square refactored with the following changes:


def rectangle(length, breadth):
area = length * breadth
return area
return length * breadth
Comment on lines -10 to +9
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function rectangle refactored with the following changes:


def triangle(side1, side2, side3):
s = (side1 + side2 + side3)/2
area = math.sqrt(s*(s-side1)*(s-side2)*(s-side3))
return area
return math.sqrt(s*(s-side1)*(s-side2)*(s-side3))
Comment on lines -15 to +13
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function triangle refactored with the following changes:


def circle(radius):
area = 3.14 * radius * radius
return area
return 3.14 * radius * radius
Comment on lines -19 to +16
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function circle refactored with the following changes:


final_area = 0.0
print("Choose the shape you want to calculate area of: ")
Expand Down
6 changes: 1 addition & 5 deletions ArmstrongNumberCheck.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
print("An Armstrong Number is a number which is equal to the sum of the cubes of it's digits.")
inputNumber = input("Enter a number to check if it's an Armstrong Number or not: ")
sumOfCubes=0

for digit in inputNumber:
sumOfCubes+=int(digit)**3

sumOfCubes = sum(int(digit)**3 for digit in inputNumber)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 3-7 refactored with the following changes:

if sumOfCubes==int(inputNumber): print(inputNumber,"is an Armstrong Number.")
else: print(inputNumber,"is NOT an Armstrong Number.")
2 changes: 1 addition & 1 deletion Average.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
n=int(input("Enter the number of elements to be inserted: "))
a=[]
for i in range(0,n):
for _ in range(0,n):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 3-3 refactored with the following changes:

elem=int(input("Enter element: "))
a.append(elem)
avg=sum(a)/n
Expand Down
59 changes: 28 additions & 31 deletions BankGame.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@
import random
class BankGame :
@staticmethod
def main( args) :
def main( args):
print("---WELCOME TO ELIX BANKING SERVICES---")
print("")
print("________________________")
print("Enter your name: ")
name = input()
# I am inserting do loop to make the program run forever under correct inputs.
print("Hi, " + name + "\bWelcome to my program!")
print(f"Hi, {name}" + "\bWelcome to my program!")
Comment on lines -5 to +12
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function BankGame.main refactored with the following changes:

This removes the following comments ( why? ):

# Using for statement to perform 5 operation on each login

print("____________________________")
print("Do you want to start/repeat the program?")
print("Enter Y for Yes and N for No: ")
Expand All @@ -20,14 +20,12 @@ def main( args) :
print("If you don\'t know the password refer the first line of the program")
print("Please enter the password: ")
# Condition when the statement goes true i.e.- temp equals 1
while True :
if (temp == 'Y' or temp == 'y') :
if (passw == 4758) :
while True:
if temp in ['Y', 'y']:
if (passw == 4758):
print("")
print("Your initial account balance is Rs. 10000")
# Using for statement to perform 5 operation on each login
x = 0
while (x <= 6) :
for _ in range(7):
print("0. Exit")
print("1. Deposit")
print("2. Withdraw")
Expand All @@ -41,57 +39,56 @@ def main( args) :
print(captha)
print("Enter the number shown above: ")
verify = int(input())
if (verify == captha) :
if (verify == captha):
# If captha gets matched, then these switch statements are executed.
if (choice==0):
print("BYE!......" + name + " HAVE A NICE DAY!")
if choice == 0:
print(f"BYE!......{name} HAVE A NICE DAY!")
print("__________________________")
print("@author>[@programmer-yash")
print("Please comment here or open an issue if you have any queries or suggestions!")
print("")
print("#hacktoberfest")
return 0
elif(choice==1):
elif choice == 1:
print("You have chosen to deposit.")
print("Enter the amount to deposit : ")
deposit = int(input())
bal = bal + deposit
print(str(deposit) + " has been deposited to your account.")
print("Left balance is " + str(bal))
elif(choice==2):
print(f"{deposit} has been deposited to your account.")
print(f"Left balance is {str(bal)}")
elif choice == 2:
print("You have chosen to withdraw.")
print("Enter the amount to be withdrawn")
withdraw = int(input())
print(str(+withdraw) + " has been withdrawn from your account.")
print(f"{str(+withdraw)} has been withdrawn from your account.")
2323 bal = bal - withdraw
print("Check the cash printer.")
print("Left balance is " + str(bal))
elif(choice==3):
print(f"Left balance is {str(bal)}")
elif choice == 3:
print("You have chosen to change passcode.")
print("Enter the current passcode: ")
check = int(input())
if (check == passw) :
if (check == passw):
print("Enter the new passcode")
newP = int(input())
passw = newP
print("Your new password is " + str(newP))
else :
print(f"Your new password is {passw}")
else:
print("Wrong passcode!")
elif(choice==4):
elif choice == 4:
print("You have chosen to check balanace.")
print("Your current account balance is " + str(bal))
elif(choice==5):
print(f"Your current account balance is {str(bal)}")
elif choice == 5:
print("You have chosen for customer care.")
print("Contact us at:")
print(" Email: yash197911@gmail.com")
else:
print("Wrong choice!!! Choose again...!")
else :
else:
print("xCAPTHA NOT CORRECTx")
x += 1
continue
elif(temp == 'N' or temp == 'n') :
print("BYE!......" + name + " HAVE A NICE DAY!")
elif temp in ['N', 'n']:
print(f"BYE!......{name} HAVE A NICE DAY!")
print("__________________________")
print("@author>[@programmer-offbeat]")
print("Please comment here if you have any queries or suggestions!")
Expand All @@ -101,14 +98,14 @@ def main( args) :
print()
print("HAPPY CODING!:-)")
return 0
else :
else:
print("Err!..... You have entered a wrong choice!")
print("Try again....!")
# Comdition if password mismatches.
if (passw != 4758) :
print("You have entered wrong password.....Try again!")
if((temp < 100) == False) :
break
if temp >= 100:
break


if __name__=="__main__":
Expand Down
6 changes: 3 additions & 3 deletions Bifurcation diagram .py
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,14 @@ def bif(x0, r):
if __name__ == '__main__':
# create and configure the process pool
with Pool(4) as p:

for i,ch in enumerate(p.map(bif1,r,chunksize=2500)) :
x1=np.ones(len(ch))*r[i]
X.append(x1)
Y.append(ch)
print("--- %s seconds ---" % (time.time() - start_time))
print(f"--- {time.time() - start_time} seconds ---")

plt.style.use('dark_background')
plt.style.use('dark_background')
Comment on lines -50 to +57
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 50-57 refactored with the following changes:

plt.plot(X,Y, ".w", alpha=1, ms=1.2)
figure = plt.gcf() # get current figure
figure.set_size_inches(1920 / 40, 1080 / 40)
Expand Down
31 changes: 12 additions & 19 deletions Blackjack.py
2323
Original file line number Diff line number Diff line change
Expand Up @@ -13,25 +13,18 @@
print(logo)
cards=[11,2,3,4,5,6,7,8,9,10,10,10,10]

player=[]
computer=[]

player_sum=0
computer_sum=0

player.append(random.choice(cards))


player = [random.choice(cards)]
Comment on lines -16 to +19
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 16-57 refactored with the following changes:

rand = random.choice(cards)
if (rand == 11 and rand + computer_sum > 21):
player.append(1)
else:
player.append(rand)


computer.append(random.choice(cards))


computer = [random.choice(cards)]
randco = random.choice(cards)
if (rand == 11 and rand + computer_sum > 21):
computer.append(1)
Expand All @@ -41,21 +34,21 @@
player_sum+=player[0]+player[1]
computer_sum+=computer[0]+computer[1]

while(player_sum<=21):
while (player_sum<=21):
print(f"Your cards : {player} ,current score : {player_sum}")
print(f"Computer's first card : {computer[0]}")

accept=input("Type y to get another card , Type n to pass : ")
if(accept=='y'):
rand=random.choice(cards)
if(rand==11 and rand+player_sum>21):
player_sum+=1
player.append(1)
else:
player_sum+=rand
player.append(rand)
else:break
if accept != 'y':
break

rand=random.choice(cards)
if(rand==11 and rand+player_sum>21):
player_sum+=1
player.append(1)
else:
player_sum+=rand
player.append(rand)
if player_sum>21:
print(f"Your cards : {player} ,current score : {player_sum}")
print("You Lost")
Expand Down
Loading
0