blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
c1313fd43e568a5feea7c9ac97405399a9b0d92c
Rusty33/tic-tac
/game_ai_no_d.py
18,325
3.875
4
import random board = [[0,0,0],[0,0,0],[0,0,0]] turn = 1 game = True go = True ##################################################### def print_board(): global board to_print = [""," 1 "," 2 "," 3 ","\n"] x = 0 y = 0 while y <= 2: if board[y][x] == 0: to_print.append(" ") if board[y][x] == 1: to_print.append(" X ") if board[y][x] == 2: to_print.append(" O ") if x == 2: x = -1 y += 1 to_print.append("\n") x += 1 to_print.append("tic_tac_toe") to_print.append("\n") to_print.append(" player%s " % (turn)) for p in to_print: print(p,end="|") ##################################################### def play(): global turn print("\n") x = int(input("|Please pick a row|")) x -= 1 y = int(input("|And how far down |")) y -= 1 if x >= 3 or y >= 3: print("|Please choose a blank space|") else: if board[y][x] != 0: print("|Please choose a blank space|") play() else: board[y][x] = 1 ##################################################### def check_x(): x = 0 y = 0 O = 0 X = 0 blank = 0 global board,game,go while y <= 2: if board[y][x] == 0: blank += 1 if board[y][x] == 1: X += 1 if board[y][x] == 2: O += 1 if x == 2: x = -1 y += 1 if O == 3: print("\n") print("|Player2 wins!|") #print("X") game = False if X == 3: print("\n") print("|Player1 wins!|") game = False go = False X = 0 O = 0 x += 1 ##################################################### def check_y(): x = 0 y = 0 O = 0 X = 0 blank = 0 global board,game,go while x <= 2: if board[y][x] == 0: blank += 1 if board[y][x] == 1: X += 1 if board[y][x] == 2: O += 1 if y == 2: y = -1 x += 1 if O == 3: print("\n") print("|Player2 wins!|") #print("Y") game = False if X == 3: print("\n") print("|Player1 wins!|") game = False go = False X = 0 O = 0 y += 1 if blank == 0: print("\n") print("|Its a tie!|") game = False ##################################################### def check_d(): x = 0 y = 0 O = 0 X = 0 blank = 0 global board,game,go for g in range(3): if board[y][x] == 0: blank += 1 if board[y][x] == 1: X += 1 if board[y][x] == 2: O += 1 if y == 2: y -= 1 x += 1 if O == 3: print("\n") #print("D") print("|Player2 wins!|") game = False if X == 3: print("\n") print("|Player1 wins!|") game = False go = False y += 1 x += 1 ######################################################### def check_d2(): x = 0 y = 0 O = 0 X = 0 blank = 0 global board,game,go if board[0][2] == 1: X += 1 if board[0][2] == 2: O += 1 if board[1][1] == 1: X += 1 if board[1][1] == 2: O += 1 if board[2][0] == 1: X += 1 if board[2][0] == 2: O += 1 if O == 3: print("\n") #print("d2") print("|Player2 wins!|") game = False if X == 3: print("\n") print("|Player1 wins!|") game = False go = False if game == True: go = True ##################################################################### def check_d_c_2(): x = 0 y = 0 O = 0 X = 0 blank = 0 blank_x = [] blank_y = [] global board,game,go for g in range(3): if board[y][x] == 0: blank += 1 blank_x.append(x) blank_y.append(y) if board[y][x] == 1: X += 1 if board[y][x] == 2: O += 1 if y == 2: y -= 1 x += 1 if O == 2 and go == True and blank == 1 : board[blank_y[0]][blank_x[0]] = 2 print("\n") print_board() print("\n") print("|Player2 wins!|") game = False go = False y += 1 x += 1 ##################################################################### def check_d2_c_2(): x = 0 y = 0 O = 0 X = 0 blank = 0 blank_x = [] blank_y = [] global board,game,go if board[0][2] == 0: blank += 1 blank_x.append(x) blank_y.append(y) if board[0][2] == 1: X += 1 if board[0][2] == 2: O += 1 if board[1][1] == 0: blank += 1 blank_x.append(x) blank_y.append(y) if board[1][1] == 1: X += 1 if board[1][1] == 2: O += 1 if board[2][0] == 0: blank += 1 blank_x.append(x) blank_y.append(y) if board[2][0] == 1: X += 1 if board[2][0] == 2: O += 1 if O == 2 and go == True and blank == 1 : board[blank_y[0]][blank_x[0]] = 2 print("\n") print_board() print("\n") print("|Player2 wins!|") game = False go = False ##################################################################### def d2_stopper(): x = 0 y = 0 O = 0 X = 0 blank = 0 blank_x = [] blank_y = [] global board,game,go if board[0][2] == 0: blank += 1 blank_x.append(2) blank_y.append(0) if board[0][2] == 1: X += 1 if board[0][2] == 2: O += 1 if board[1][1] == 0: blank += 1 blank_x.append(1) blank_y.append(1) if board[1][1] == 1: X += 1 if board[1][1] == 2: O += 1 if board[2][0] == 0: blank += 1 blank_x.append(0) blank_y.append(2) if board[2][0] == 1: X += 1 if board[2][0] == 2: O += 1 if X == 2 and go == True and blank == 1 : board[blank_y[0]][blank_x[0]] = 2 go = False ##################################################################### def d_stopper(): x = 0 y = 0 O = 0 X = 0 blank = 0 blank_x = [] blank_y = [] global board,game,go if board[0][0] == 0: blank += 1 blank_x.append(0) blank_y.append(0) if board[0][0] == 1: X += 1 if board[0][0] == 2: O += 1 if board[1][1] == 0: blank += 1 blank_x.append(1) blank_y.append(1) if board[1][1] == 1: X += 1 if board[1][1] == 2: O += 1 if board[2][2] == 0: blank += 1 blank_x.append(2) blank_y.append(2) if board[2][2] == 1: X += 1 if board[2][2] == 2: O += 1 if X == 2 and go == True and blank == 1 : board[blank_y[0]][blank_x[0]] = 2 go = False ##################################################################### def check_d_c_1(): x = 0 y = 0 O = 0 X = 0 blank = 0 blank_x = [] blank_y = [] global board,game,go if board[0][0] == 0: blank += 1 blank_x.append(0) blank_y.append(0) if board[0][0] == 2: O += 1 if board[1][1] == 0: blank += 1 blank_x.append(1) blank_y.append(1) if board[1][1] == 2: O += 1 if board[2][2] == 0: blank += 1 blank_x.append(2) blank_y.append(2) if board[2][2] == 2: O += 1 if O == 1 and go == True and blank == 2 : num = random.randint(0,blank - 1) board[blank_y[num]][blank_x[num]] = 2 go = False ##################################################################### def check_d2_c_1(): x = 0 y = 0 O = 0 X = 0 blank = 0 blank_x = [] blank_y = [] global board,game,go if board[0][2] == 0: blank += 1 blank_x.append(2) blank_y.append(0) if board[0][2] == 1: X += 1 if board[0][2] == 2: O += 1 if board[1][1] == 0: blank += 1 blank_x.append(1) blank_y.append(1) if board[1][1] == 1: X += 1 if board[1][1] == 2: O += 1 if board[2][0] == 0: blank += 1 blank_x.append(0) blank_y.append(2) if board[2][0] == 1: X += 1 if board[2][0] == 2: O += 1 if O == 1 and go == True and blank == 2 : num = random.randint(0,blank - 1) board[blank_y[num]][blank_x[num]] = 2 go = False ##################################################################### def check_x_c_2(): x = 0 y = 0 O = 0 X = 0 blank = 0 blank_x = [] blank_y = [] global board,game,go while y <= 2: if board[y][x] == 0: blank += 1 blank_x.append(x) blank_y.append(y) if board[y][x] == 1: X += 1 if board[y][x] == 2: O += 1 if x == 2: x = -1 y += 1 if O == 2 and go == True and blank == 1 : board[blank_y[0]][blank_x[0]] = 2 print("\n") print_board() print("\n") #print("x2") print("|Player2 wins!|") game = False go = False X = 0 O = 0 blank = 0 blank_x = [] blank_y = [] x += 1 ################################################################################# def x_stopper(): x = 0 y = 0 O = 0 X = 0 blank = 0 blank_x = [] blank_y = [] global board,game,go while y <= 2: if board[y][x] == 0: blank += 1 blank_x.append(x) blank_y.append(y) if board[y][x] == 1: X += 1 if board[y][x] == 2: O += 1 if x == 2: x = -1 y += 1 if X == 2 and go == True and blank == 1: board[blank_y[0]][blank_x[0]] = 2 go = False #print("x stoper") X = 0 O = 0 blank = 0 blank = 0 blank_x = [] blank_y = [] x += 1 ###################################################################### def check_x_c_1(): x = 0 y = 0 O = 0 X = 0 blank = 0 blank_x = [] blank_y = [] global board,game,go while y <= 2: if board[y][x] == 0: blank += 1 blank_x.append(x) blank_y.append(y) if board[y][x] == 1: X += 1 if board[y][x] == 2: O += 1 if x == 2: x = -1 y += 1 if O == 1 and go == True and blank == 2: num = random.randint(0,blank - 1) board[0][blank_x[num]] = 2 go = False #print("x random") X = 0 O = 0 blank = 0 blank_x = [] blank_y = [] x += 1 ###################################################################### def check_r_c(): x = 0 y = 0 O = 0 X = 0 blank = 0 blank_x = [] blank_y = [] global board,game,go while x <= 2: if board[y][x] == 0: blank += 1 blank_x.append(x) blank_y.append(y) if y == 2: y = -1 x += 1 y += 1 if go == True and blank >= 1 : num = random.randint(0,blank - 1) board[blank_y[num]][blank_x[num]] = 2 go = False ###################################################################### def check_y_c_2(): x = 0 y = 0 O = 0 X = 0 blank = 0 blank_x = [] blank_y = [] global board,game,go while x <= 2: if board[y][x] == 0: blank += 1 blank_x.append(x) blank_y.append(y) if board[y][x] == 1: X += 1 if board[y][x] == 2: O += 1 if y == 2: y = -1 x += 1 if O == 2 and go == True and blank == 1 : board[blank_y[0]][blank_x[0]] = 2 print("\n") print_board() print("\n") #print("y2") print("|Player2 wins!|") game = False go = False X = 0 O = 0 blank = 0 blank_x = [] blank_y = [] y += 1 ######################################################################### def y_stopper(): x = 0 y = 0 O = 0 X = 0 blank = 0 blank_x = [] blank_y = [] global board,game,go while x <= 2: if board[y][x] == 0: blank += 1 blank_x.append(x) blank_y.append(y) if board[y][x] == 1: X += 1 if board[y][x] == 2: O += 1 if y == 2: y = -1 x += 1 if X == 2 and go == True and blank == 1: board[blank_y[0]][blank_x[0]] = 2 go = False #print("y stoper") X = 0 O = 0 blank = 0 blank_x = [] blank_y = [] y += 1 ########################################################################## def check_y_c_1(): x = 0 y = 0 O = 0 X = 0 blank = 0 blank_x = [] blank_y = [] global board,game,go while x <= 2: if board[y][x] == 0: blank += 1 blank_x.append(x) blank_y.append(y) if board[y][x] == 1: X += 1 if board[y][x] == 2: O += 1 if y == 2: y = -1 x += 1 if O == 1 and go == True and blank == 2 : board[blank_y[random.randint(0,1)]][blank_x[0]] = 2 go = False #print("y random") X = 0 O = 0 blank = 0 blank_x = [] blank_y = [] y += 1 ############################### print_board() while game == True: play() print_board() check_x() check_y() check_d() check_d2() check_x_c_2() check_y_c_2() check_d_c_2() check_d2_c_2() y_stopper() x_stopper() d_stopper() d2_stopper() ran = random.randint(1,10) if ran == 1: check_d_c_1() check_d2_c_1() check_x_c_1() check_y_c_1() check_r_c() if ran == 2: check_d_c_1() check_d2_c_1() check_y_c_1() check_x_c_1() check_r_c() if ran == 3: check_d_c_1() check_y_c_1() check_d2_c_1() check_x_c_1() check_r_c() if ran == 4: check_y_c_1() check_d_c_1() check_d2_c_1() check_x_c_1() check_r_c() if ran == 5: check_y_c_1() check_d_c_1() check_x_c_1() check_d2_c_1() check_r_c() if ran == 6: check_y_c_1() check_x_c_1() check_d_c_1() check_d2_c_1() check_r_c() if ran == 7: check_y_c_1() check_x_c_1() check_d2_c_1() check_d_c_1() check_r_c() if ran == 8: check_x_c_1() check_y_c_1() check_d2_c_1() check_d_c_1() check_r_c() if ran == 9: check_x_c_1() check_d2_c_1() check_y_c_1() check_d_c_1() check_r_c() if ran == 10: check_x_c_1() check_d2_c_1() check_d_c_1() check_y_c_1() check_r_c() if game == True: print("\n") print_board()
0558a60ba427ae4f2ec0b709c0911ec09e6fa3e7
Liraz-Benbenishti/Python-Code-I-Wrote
/hangman/hangman/hangman-unit5/hangman-ex5.3.4.py
282
3.625
4
def last_early(my_str): my_str = my_str.lower() last_char = my_str[-1] if (my_str[:-1].find(last_char) != -1): return True return False print(last_early("happy birthday")) print(last_early("best of luck")) print(last_early("Wow")) print(last_early("X"))
f3a101700e9798aac4030891e843eaa3d59c0f93
Liraz-Benbenishti/Python-Code-I-Wrote
/next_py/next-py.1.1.2.py
505
3.828125
4
from functools import reduce def add_dbl_char(list, char): list.append(char * 2) return list def double_letter(my_str): """ :param my_str: string to change. :type my_str: string :return: a new string that built from two double appearance of each char in the string. rtype: string """ return "".join(list(reduce(add_dbl_char, list(my_str), []))) def main(): print(double_letter("python")) print(double_letter("we are the champion!")) if __name__ == "__main__": main()
c1b15e76e674ba8482922ef77a5a3b1993c4cb7c
Liraz-Benbenishti/Python-Code-I-Wrote
/next_py/next-py.4.1.2.py
430
3.828125
4
def translate(sentence): words = {'esta': 'is', 'la': 'the', 'en': 'in', 'gato': 'cat', 'casa': 'house', 'el': 'the'} translate_generator = (words[i] for i in sentence.split(' ')) ret_lst = [] for string_generator in translate_generator: ret_lst.append(string_generator) ret_str = " ".join(ret_lst) return ret_str def main(): print(translate("el gato esta en la casa")) if __name__ == "__main__": main()
59f598f7eabaadbda9ed96866d3da91bccb63512
Liraz-Benbenishti/Python-Code-I-Wrote
/next_py/next-py.4.1.3.py
518
3.671875
4
def is_prime(n): # Corner case if (n <= 1): return False # Check from 2 to n-1 for i in range(2, n): if (n % i == 0): return False return True def first_prime_over(n): prime_generator = (i for i in range(n+1, (n+2) ** 10) if is_prime(i)) return next(prime_generator) def main(): print(first_prime_over(0)) print(first_prime_over(1)) print(first_prime_over(2)) print(first_prime_over(-1000000)) print(first_prime_over(1000000)) if __name__ == "__main__": main()
cfaf15f6ce9c635ee1a87c2892b9a09cdb91dc47
Liraz-Benbenishti/Python-Code-I-Wrote
/hangman/hangman/hangman-unit7/hangman-ex7.2.4.py
557
3.921875
4
def seven_boom(end_number): """ :param end_number: the number to end the loop. :type end_param: int :return: list in range of 0 and end_number (including), where some numbers replaced by "BOOM". rtype: list """ list_of_numbers = [] for number in range(end_number + 1): list_of_numbers.append(number) if (number % 7 == 0): list_of_numbers[number] = 'BOOM' if (str(7) in str(number)): list_of_numbers[number] = 'BOOM' return list_of_numbers def main(): print(seven_boom(17)) if __name__ == "__main__": main()
371ed66d667edb14d59347994462ddf30dde6a84
Liraz-Benbenishti/Python-Code-I-Wrote
/hangman/hangman/hangman-unit7/hangman-ex7.3.1.py
836
4.25
4
def show_hidden_word(secret_word, old_letters_guessed): """ :param secret_word: represent the hidden word the player need to guess. :param old_letters_guessed: the list that contain the letters the player guessed by now. :type secret_word: string :type old_letters_guessed: list :return: string that comprised of the letters and underscores. Shows the letter from the list that contained in the secret word in their location. rtype: string """ new_word = [] for letter in secret_word: if (letter in old_letters_guessed): new_word.append(letter) else: new_word.append("_") return " ".join(new_word) def main(): secret_word = "mammals" old_letters_guessed = ['s', 'p', 'j', 'i', 'm', 'k'] print(show_hidden_word(secret_word, old_letters_guessed)) if __name__ == "__main__": main()
ad1a0de49caddf1372e5ae9f749e06577ec2320c
shaoormunir/programming-problems
/Google Problem 1.py
309
3.671875
4
array = [1, 11, 3, 7, 2, 6, 5, 10, 4] sum = 12 for i in range(len(array)): temp_sum = 0 for k in range (i, len(array)): temp_sum += array[k] if temp_sum == sum: print("Starting: {} Ending: {}".format(i, k)) break elif temp_sum > sum: break
0d59a25163228056e84201221068235042726a1c
momotofu/algorithms
/math/fib_even.py
211
4
4
def fib_even(n): sum = 2 a = 1 b = 2 while True: c = 3*b + 2*a if c >= n: break sum += c a += 2*b b = c return sum print(fib_even(100))
b3110a0495a6d52ab0cd4e98f0ef25dbc0c501de
aanzolaavila/competitive-problems
/codeforces/Resueltos/watermelon.py
253
3.578125
4
from sys import stdin def main(): linea = stdin.readline().strip() while len(linea) != 0: w = int(linea) if w % 2 == 0 and w != 2: print("YES") else: print("NO") linea = stdin.readline().strip() main()
8ff7e9be23a5ad7a679ac582e18c59d29eee51f5
aanzolaavila/competitive-problems
/codeforces/Resueltos/A.petya_and_strings.py
542
3.625
4
from sys import stdin import string letters = string.ascii_lowercase def lex(l1, l2) -> str: for i in range(len(l1)): if letters.index(l1[i]) < letters.index(l2[i]): return "-1" elif letters.index(l1[i]) > letters.index(l2[i]): return "1" return "0" def main(): line1 = stdin.readline().strip() SALIDA = [] while len(line1) != 0: line2 = stdin.readline().strip() SALIDA.append(lex(line1.lower(), line2.lower())) line1 = stdin.readline().strip() print("\n".join(SALIDA)) main()
210414121ff25d50588e6e766b23cf2109219ecc
Leonardra/parsel_tongue_mastered
/oluwatobi/chapter_seven/question_26.py
114
3.515625
4
number_list = [] for num in range(2, 41): if num % 2 == 0: number_list.append(num) print(number_list)
f41f85c5ade58c5591f6c53abc6f4f3832daf675
mdarifuddin1/Create-a-Dictionary-to-store-names-of-students-and-marks-in-5-subjects
/dictionaries containing.py
556
4.09375
4
students = dict() list1 = [] n = int(input("How many students are there: ")) for i in range(n): sname = input("Enter name of the student: ") marks = [] for j in range(5): mark = float(input("Enter marks: ")) marks.append(mark) students = {'name':sname,"marks" :marks} list1.append(students) print("Create a dictionary students is ",list1) """ name = input ("Enter name of the student ") if name in students.keys(): print(students[name]) else: print("No student found this name") """
fda16aa729c019888cb2305fcfb00d782e620db6
cnulenka/Coffee-Machine
/models/Beverage.py
1,434
4.34375
4
class Beverage: """ Beverage class represents a beverage, which has a name and is made up of a list of ingredients. self._composition is a python dict with ingredient name as key and ingredient quantity as value """ def __init__(self, beverage_name: str, beverage_composition: dict): self._name: str = beverage_name self._composition: dict = beverage_composition def get_name(self): return self._name def get_composition(self): return self._composition """ CANDIDATE NOTE: one other idea here was to make a abstract Beverage class and inherit and create child classes of hot_coffee, black_coffee, hot_tea etc where each of them over ride get_composition and store the composition info with in class. So orders will be a list of Beverage objects having child class instances. But this would hard code the composition and types of Beverages, hence extensibility will be affected, but may be we can have a custom child class also where user can create any beverage object by setting name and composition. Same approach can be followed for Ingredients Class. I don't have a Ingredients class though. Each ingredient can have a different warning limit, hence get_warning_limit will be implemented differently. For example water is most used resource so that can have a warning limit of 50% may be. -Shakti Prasad Lenka """
3a2adf0295f13820e2732cc77c5eaa1976d2fc62
akashgiri/merchant
/change_to_roman_numerals.py
501
3.796875
4
#!/usr/local/bin/python # -*- coding: utf-8 -*- def change_to_roman_numerals(input_content): change_to_roman = [] currency = {} print(input_content) for key, value in input_content.items(): if key == 'roman_attributes': for index, number in enumerate(value): change_to_roman.append(number.split()) ## Currency is the end index for i in change_to_roman: if i: currency[i[0]] = i[-1] print("change_to_roman: ", change_to_roman) print("currency: ", currency) return currency
d434667f4c4eeb56c074ed47146921bb0c0013dc
efahmad/laitec-data-science
/002-session/pandas_test.py
536
3.5625
4
import pandas as pan import os import matplotlib.pyplot as plt data = pan.read_csv(os.path.join(os.path.dirname(__file__), "movie_metadata.csv")) likes = [ (name, sum(data['actor_1_facebook_likes'][data['actor_1_name'] == name].values)) for name in data['actor_1_name'].unique() ] likes = sorted(likes, key=lambda l: l[1], reverse=True)[:10] x = [item for item in range(len(likes))] y = [item[1] for item in likes] plt.bar(x, y) plt.xticks(x, [item[0] for item in likes]) # print([item[0] for item in likes]) plt.show()
80a3b9c03c7b525182ddc05ee3f3405f552e7b57
priyankapednekar/Graph
/dfs_print_graph.py
1,247
3.875
4
class Node(): ''' node has value and the list of edges it connects to''' def __init__(self,src): self.src = src self.dest = {} self.visit=False class GF(): """docstring for .""" '''key- node data and value is Node''' def __init__(self): self.graph={} def insert_node(self,data): temp=Node(data) self.graph[data]=temp ''' destination and weight for given node''' def insert_edge(self,u,v,w): if self.graph.get(u,None): self.graph[u].dest[v]=w else: print("Node doesnt exist!!") def dfs_print_rec(self,data): print(self.graph[data].src, end = " ") self.graph[data].visit=True for i in self.graph[data].dest.keys(): if not self.graph[i].visit: self.dfs_print_rec(i) def main(): gf1=GF() gf1.insert_node(0) gf1.insert_node(1) gf1.insert_node(2) gf1.insert_node(3) gf1.insert_edge(0,1,1) gf1.insert_edge(0,2,1) gf1.insert_edge(1,2,1) gf1.insert_edge(2,0,1) gf1.insert_edge(2,3,1) gf1.insert_edge(3,3,1) gf1.dfs_print_rec(2) if __name__ == '__main__': main()
7762d9a8c0b8ebb97551f2071f9377fe896b686f
itstooloud/boring_stuff
/chapter_3/global_local_scope.py
922
4.1875
4
## ####def spam(): #### global eggs #### eggs = 'spam' #### ####eggs = 'global' ####spam() ####print(eggs) ## ####using the word global inside the def means that when you refer to that variable within ####the function, you are referring to the global variable and can change it. ## ####def spam(): #### global eggs #### eggs = 'spam' #this is a the global #### ####def bacon(): #### eggs = 'bacon' #this is a local variable #### ####def ham(): #### print(eggs) #this is the global #### ####eggs = 42 #this is the global ####spam() ####print(eggs) ## #### if you try to use a global variable inside a function without assigning a value to it, you'll get an error ## ##def spam(): ## print(eggs) #this will give an error ## ## eggs = 'spam local' ## ##eggs = 'global' ## ##spam() ## #### it only throws the error because the function assigns a value to eggs. Commenting it out should remove the error
46c128c433288c3eed04ecb148693e52828c6975
itstooloud/boring_stuff
/hello_age.py
358
4.15625
4
#if/elif will exit as soon as one condition is met print('Hello! What is your name?') my_name = input() if my_name == "Chris": print('Hello Chris! Youre me!') print('Your age?') my_age = input() my_age = int(my_age) if my_age > 20: print("you're old") elif my_age <= 10: print("you're young") else: print('you are a spring chicken!')
cb62ae43d94a2e7f99ad875e58cdff60f9d971ef
AlexSamarsky/seabattle
/game.py
5,660
3.546875
4
import os from board import Board from errors import WrongCoords, CoordOccupied, BoardShipsError class Game(): _computer_board = None _player_board = None _playing = False _mounting_ships = False _computer_turn = False def __init__(self): self._playing = True self._mounting_ships = True print('Добро пожаловать в игру морской бой!') self._computer_board = Board() self._player_board = Board() self.fill_board(self._computer_board) print('Корабли компьютера установлены!') def fill_board(self, board): cnt = 0 while True: if cnt >= 10: raise BoardShipsError('Не установлены корабли, что-то пошло не так. Обратитесь к разработчику!') try: board.set_ships_random() break except BoardShipsError: board.new_board() cnt += 1 def input_player_ships(self): cnt = 0 while True: cnt += 1 if cnt == 10: print('Видимо вы не хотите играть, раз не отвечаете корректно! Игра прекращена') response = input('Корабли можно поставить автоматически, хотите это сделать? (y/n): ') if response == 'y': self.fill_board(self._player_board) self._mounting_ships = False return elif response == 'n': while True: unmounted_ships = self._player_board.get_unmounted_ships() if unmounted_ships and not len(unmounted_ships): self._mounting_ships = False return val = [] for ship in unmounted_ships: val.append(str(ship)) print (self._player_board.to_str()) str_ships = ', '.join(val) print (f'Остались корабли {str_ships}') coords = input('Введите координаты установки корабля в формате A1 или A1 A2: ') try: self._player_board.set_next_ship(coords) except WrongCoords as msg: print(msg) except CoordOccupied as msg: print(msg) def make_moves(self): while True: print('\n\nВаша доска получилась такой:') print(self._player_board) print('Ваши выстрелы по доске компьютера:') print(self._computer_board.to_str(hidden=True)) if self._computer_turn: print('################## Ход компьютера ###') try: coord = self._player_board.get_random_not_hit_coord() print(f'Компьютер выстрелил по координатам {coord}') os.system('read -s -n 1 -p "Нажмите любую клавишу для продолжения...\n"') if self._player_board.make_shot_and_hit(coord): print('И компьютер попал!') if self._player_board.all_ships_sunk(): print('Компьютер уничтожил все ваши корабли! Вы проиграли! Спасибо за игру!') return else: print('Еще один ход за компьютером!') else: self._computer_turn = not self._computer_turn print('Компьютер промазал') except BoardShipsError as msg: print('Ошибка!!! Игра завершена') print(msg) return else: print('################## Ваш ход ###') coord = input('Введите координаты куда хотие выстрелить в формате A1: ') try: coord = Board.get_hit_coord(coord) if self._computer_board.make_shot_and_hit(coord): print('Вы попали!') if self._computer_board.all_ships_sunk(): print('ПОЗДРАВЛЯЮ! Вы уничтожили все корабли противника!') return else: self._computer_turn = not self._computer_turn print('И вы промазали') except WrongCoords as msg: print('!!!!ОШИБКА!!!!') print(msg) except CoordOccupied as msg: print('!!!!ОШИБКА!!!!') print(msg) def start_game(self): self.input_player_ships() print ('Все корабли установлены!') self.make_moves() if __name__ == '__main__': try: game = Game() game.start_game() except BoardShipsError as msg: print(msg)
b643e9a0d72242ed831b4e20b8edcc08258d50ad
summergirl21/Advent-of-Code-2016
/Day03/Day3.py
1,209
3.90625
4
def main(): print("Hello") input = open("Day3_input.txt", "r") #input = open("Day3_input_test.txt", "r") newinput = {0:[], 1:[], 2:[]} for line in input: line = [int(x) for x in line.split()] for i in range(0, 3): newinput[i].append(line[i]) print(newinput[0]) print(newinput[1]) print(newinput[2]) count = 0 for i in range(0, 3): input = newinput[i] index = 0 while index < len(input): sides = [input[index], input[index+1], input[index+2]] sides.sort() if sides[0] + sides[1] > sides[2]: print ("is valid triangle " + str(sides[0]) + " " + str(sides[1]) + " " + str(sides[2])) count += 1 else: print("is not valid triangle " + str(sides[0]) + " " + str(sides[1]) + " " + str(sides[2])) index += 3 print(count) # count = 0 # for line in input: # sides = [0, 0, 0] # #line = [int(x) for x in line.split()] # line.sort() # #print(line) # if line[0] + line[1] > line[2]: # count += 1 # print(count) if __name__ == "__main__": main()
f85f89d07de9f394d7f95646c0a490232bc3b7bc
whoismaruf/usermanager
/app.py
2,605
4.15625
4
from scripts.user import User print('\nWelcome to user management CLI application') user_list = {} def create_account(): name = input('\nSay your name: ') while True: email = input('\nEnter email: ') if '@' in email: temp = [i for i in email[email.find('@'):]] if '.' in temp: user = User(name, email) break else: print("\nInvalid Email address! Please enter the correct one.") continue else: print("\nInvalid Email address! Please enter the correct one.") continue uname = user.set_username() current_user = { 'name': name, 'email': email } while True: if uname in user_list: new_uname = input(f'\nSorry your username "{uname}" has been taken, choose another one: ') uname = new_uname.replace(" ", '') else: break user_list[f'{uname}'] = current_user print(f"\nHello, {name}! Your account has been created as {uname}.\n\nChoose what to do next - ") while True: user_input = input(''' A --> Create account S --> Show account info Q --> Quit ''') if user_input == 'A' or user_input == 'a': create_account() elif user_input == 'S' or user_input == 's': if len(user_list) == 0: print("\nThere is no account, please create one") continue else: while True: search = input('\nEnter username: ') if search not in user_list: print(f"\nYour searched '{search}' user not found.") pop = input(''' S --> Search again M --> Back to main menu ''') if pop == 'S' or pop == 's': continue elif pop == 'M' or pop == 'm': break else: print('Bad input') break else: res = user_list[search] print(f''' Account information for {search} Name: {res['name']} Email: {res['email']} ''') break elif user_input == 'Q' or user_input == 'q': break elif user_input == '': print('Please input something') continue else: print('\nBad input, try again\n')
59406c79354db2ff825e18a503fa35a4883ca51d
avadesh02/fml-project
/srcpy/robot_env/two_dof_manipulator.py
10,894
3.96875
4
## This is the implementation of a 2 degree of manipulator ## Author: Avadesh Meduri ## Date : 9/11/2020 import numpy as np from matplotlib import pyplot as plt # these packages for animating the robot env import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib.animation import FuncAnimation class TwoDOFManipulator: def __init__(self, l1, l2, m1, m2): self.dt = 0.001 # discretization step in seconds self.g = 9.81 # gravity vector self.l1 = l1 self.l2 = l2 self.m1 = m1 self.m2 = m2 self.Il1 = self.m1*(self.l1**2)/12.0 #inertia of link 1 around the center of mass axis self.Il2 = self.m2*(self.l2**2)/12.0 #inertia of link 2 around the center of mass axis self.Im1 = 4*self.Il1 #inertia of link 1 around the rotor axis self.Im2 = 4*self.Il2 #inertia of link 2 around the rotor axis def dynamics(self, th1, th2, thd1, thd2, tau1, tau2): ''' This function computes the dynamics (dy/dt = f(y,t)) given the current state of the robot (Joint Position, Joint velocities, tau). Input: th1 : joint position of first link (closest to the base) th2 : joint position of second link thd1 : joint velocity of the first link thd2 : joint velocity of the second link tau1 : torque input to the first link tau2 : torque input to the second link ''' xd = np.zeros(4) xd[0] = thd1 xd[1] = thd2 # defining the matrix A, b such that A * [thdd1, thdd2] = b. b is function of # tau and th1, th2, thd1, thd2 A = np.zeros((2, 2)) A[0,0] = self.Im1 + self.m2*self.l1**2 + self.Im2 + self.m2*self.l1*self.l2*np.cos(th2) A[0,1] = self.Im2 + self.m2*self.l1*self.l2*np.cos(th2)/2.0 A[1,0] = self.Im2 + self.m2*self.l1*self.l2*np.cos(th2)/2.0 A[1,1] = self.Im2 b = np.zeros(2) b[0] = tau1 + self.m2*self.l1*self.l2*thd1*thd2*np.sin(th2) + \ self.m2*self.l1*self.l2*(thd2**2)*np.sin(th2)/2.0 - self.m2*self.l2*self.g*np.cos(th1+th2)/2.0 \ - (self.m1*self.l1/2.0 + self.m2*self.l1)*self.g*np.cos(th1) b[1] = tau2 - self.m2*self.l1*self.l2*(thd1**2)*np.sin(th2)/2.0 - self.m2*self.l2*self.g*np.cos(th1+th2)/2.0 #computing inv A_inv = np.zeros((2,2)) A_inv[0,0] = A[1, 1] A_inv[1,1] = A[0, 0] A_inv[0,1] = -A[0,1] A_inv[1,0] = -A[1,0] A_inv = (1/np.linalg.det(A))*A_inv xd[2:] = np.matmul(A_inv, b.T) return xd[0], xd[1], xd[2], xd[3] def integrate_dynamics_euler(self, th1_t, th2_t, thd1_t, thd2_t, tau1_t, tau2_t): ''' This funciton integrates the dynamics for one time step using euler integration Input: th1_t : joint position of first link (closest to the base) th2_t : joint position of second link thd1_t : joint velocity of the first link thd2_t : joint velocity of the second link tau1_t : torque input to the first link tau2_t : torque input to the second link ''' # computing joint velocities, joint acceleration jt_vel1, jt_vel2, jt_acc1, jt_acc2 = self.dynamics(th1_t, th2_t, thd1_t, thd2_t, tau1_t, tau2_t) # integrating using euler scheme th1_t_1 = th1_t + jt_vel1*self.dt th2_t_1 = th2_t + jt_vel2*self.dt thd1_t_1 = thd1_t + jt_acc1*self.dt thd2_t_1 = thd2_t + jt_acc2*self.dt return th1_t_1, th2_t_1, thd1_t_1, thd2_t_1 def integrate_dynamics_runga_kutta(self, th1_t, th2_t, thd1_t, thd2_t, tau1_t, tau2_t): ''' This funciton integrates the dynamics for one time step using runga kutta integration Input: th1_t : joint position of first link (closest to the base) th2_t : joint position of second link thd1_t : joint velocity of the first link thd2_t : joint velocity of the second link tau1_t : torque input to the first link tau2_t : torque input to the second link ''' k1_jt_vel1, k1_jt_vel2, k1_jt_acc1, k1_jt_acc2 = self.dynamics(th1_t, th2_t, thd1_t, thd2_t, tau1_t, tau2_t) k2_jt_vel1, k2_jt_vel2, k2_jt_acc1, k2_jt_acc2 = \ self.dynamics(th1_t + 0.5*self.dt*k1_jt_vel1, th2_t + 0.5*self.dt*k1_jt_vel2, thd1_t + 0.5*self.dt*k1_jt_acc1, thd2_t + 0.5*self.dt*k1_jt_acc2, tau1_t, tau2_t) k3_jt_vel1, k3_jt_vel2, k3_jt_acc1, k3_jt_acc2 = \ self.dynamics(th1_t + 0.5*self.dt*k2_jt_vel1, th2_t + 0.5*self.dt*k2_jt_vel2, thd1_t + 0.5*self.dt*k2_jt_acc1, thd2_t + 0.5*self.dt*k2_jt_acc2, tau1_t, tau2_t) k4_jt_vel1, k4_jt_vel2, k4_jt_acc1, k4_jt_acc2 = \ self.dynamics(th1_t + self.dt*k3_jt_vel1, th2_t + self.dt*k3_jt_vel2, thd1_t + self.dt*k3_jt_acc1, thd2_t + self.dt*k3_jt_acc2, tau1_t, tau2_t) th1_t_1 = th1_t + (1/6)*self.dt*(k1_jt_vel1 + 2*k2_jt_vel1 + 2*k3_jt_vel1 + k4_jt_vel1) th2_t_1 = th2_t + (1/6)*self.dt*(k1_jt_vel2 + 2*k2_jt_vel2 + 2*k3_jt_vel2 + k4_jt_vel2) thd1_t_1 = thd1_t + (1/6)*self.dt*(k1_jt_acc1 + 2*k2_jt_acc1 + 2*k3_jt_acc1 + k4_jt_acc1) thd2_t_1 = thd2_t + (1/6)*self.dt*(k1_jt_acc2 + 2*k2_jt_acc2 + 2*k3_jt_acc2 + k4_jt_acc2) return th1_t_1, th2_t_1, thd1_t_1, thd2_t_1 def reset_manipulator(self, init_th1, init_th2, init_thd1, init_thd2): ''' This function resets the manipulator to the initial position Input: init_th1 : initial joint position 1 (in degrees) init_th2 : initial joint position 2 (in degrees) init_thd1 : initial joint velocity 1 init_thd2 : initial joint velocity 2 ''' # converting to radians init_th1 = init_th1 init_th2 = init_th2 # Creating an array to store the history of robot states as the dynamics are integrated # each row corresponds to one state just as in the case of the 1DOF env self.sim_data = np.array([[init_th1], [init_th2], [init_thd1], [init_thd2], [0.0], [0.0]]) self.t = 0 # time counter in milli seconds def step_manipulator(self, tau1, tau2, use_euler = False): ''' This function integrated dynamics using the input torques Input: tau1 : joint 1 torque tau2 : joint 2 torque ''' self.sim_data[:,self.t][4:6] = [tau1, tau2] th1_t = self.sim_data[:,self.t][0] th2_t = self.sim_data[:,self.t][1] thd1_t = self.sim_data[:,self.t][2] thd2_t = self.sim_data[:,self.t][3] if use_euler: th1_t_1, th2_t_1, thd1_t_1, thd2_t_1 = \ self.integrate_dynamics_euler(th1_t, th2_t, thd1_t, thd2_t, tau1, tau2) else: th1_t_1, th2_t_1, thd1_t_1, thd2_t_1 = \ self.integrate_dynamics_runga_kutta(th1_t, th2_t, thd1_t, thd2_t, tau1, tau2) # making sure that joint positions lie within 0, 360 th1_t_1 = np.sign(th1_t_1)*(np.abs(th1_t_1)%(2*np.pi)) th2_t_1 = np.sign(th2_t_1)*(np.abs(th2_t_1)%(2*np.pi)) sim_data_t_1 = np.array([[th1_t_1], [th2_t_1], [thd1_t_1], [thd2_t_1], [0.0], [0.0]]) # adding the data to sim_data self.sim_data = np.concatenate((self.sim_data, sim_data_t_1), axis = 1) # incrementing time self.t += 1 def get_joint_position(self): ''' This function returns the current joint position (degrees) of the mainpulator ''' return self.sim_data[:,self.t][0], self.sim_data[:,self.t][1] def get_joint_velocity(self): ''' This function returns the current joint velocity (degrees/sec) of the mainpulator ''' return self.sim_data[:,self.t][2], self.sim_data[:,self.t][3] def animate(self, freq = 25): sim_data = self.sim_data[:,::freq] fig = plt.figure() ax = plt.axes(xlim=(-self.l1 - self.l2 -1, self.l1 + self.l2 + 1), ylim=(-self.l1 - self.l2 -1, self.l1 + self.l2 + 1)) text_str = "Two Dof Manipulator Animation" arm1, = ax.plot([], [], lw=4) arm2, = ax.plot([], [], lw=4) base, = ax.plot([], [], 'o', color='black') joint, = ax.plot([], [], 'o', color='green') hand, = ax.plot([], [], 'o', color='pink') def init(): arm1.set_data([], []) arm2.set_data([], []) base.set_data([], []) joint.set_data([], []) hand.set_data([], []) return arm1, arm2, base, joint, hand def animate(i): theta1_t = sim_data[:,i][0] theta2_t = sim_data[:,i][1] joint_x = self.l1*np.cos(theta1_t) joint_y = self.l1*np.sin(theta1_t) hand_x = joint_x + self.l2*np.cos(theta1_t + theta2_t) hand_y = joint_y + self.l2*np.sin(theta1_t + theta2_t) base.set_data([0, 0]) arm1.set_data([0,joint_x], [0,joint_y]) joint.set_data([joint_x, joint_y]) arm2.set_data([joint_x, hand_x], [joint_y, hand_y]) hand.set_data([hand_x, hand_y]) return base, arm1, joint, arm2, hand props = dict(boxstyle='round', facecolor='wheat', alpha=0.5) ax.text(0.05, 0.95, text_str, transform=ax.transAxes, fontsize=15, verticalalignment='top', bbox=props) ax.grid() anim = FuncAnimation(fig, animate, init_func=init, frames=np.shape(sim_data)[1], interval=25, blit=True) plt.show() def plot(self): ''' This function plots the joint positions, velocities and torques ''' fig, axs = plt.subplots(3,1, figsize = (10, 10)) axs[0].plot((180/np.pi)*self.sim_data[0], label = 'joint position_1') axs[0].plot((180/np.pi)*self.sim_data[1], label = 'joint position_2') axs[0].grid() axs[0].legend() axs[0].set_ylabel("degrees") axs[1].plot(self.sim_data[2], label = 'joint velocity_1') axs[1].plot(self.sim_data[3], label = 'joint velocity_2') axs[1].grid() axs[1].legend() axs[1].set_ylabel("rad/sec") axs[2].plot(self.sim_data[4,:-1], label = 'torque_1') axs[2].plot(self.sim_data[5,:-1], label = 'torque_2') axs[2].grid() axs[2].legend() axs[2].set_ylabel("Newton/(Meter Second)") plt.show()
f7691a737227df28f71e8c9d647858bf020523e7
sidduGIT/Files_examples
/count_capitals.py
163
3.671875
4
with open('content.txt','r') as fh: count=0 for line in fh: for char in line: if char.isupper(): count+=1 print(count)
ec458e18c02717868cd756367b3c7c1f7eb8b241
pavdemesh/stepik_67
/stepik_67_ex_2_6_spiral_v1.py
512
3.703125
4
number = int(input()) matrix = [[0] * number for h in range(number)] row, col = 0, 0 for num in range(1, number * number + 1): matrix[row][col] = num if num == number * number: break if row <= col + 1 and row + col < number - 1: col += 1 elif row < col and row+col >= number-1: row += 1 elif row >= col and row+col > number-1: col -= 1 elif row > col + 1 and row + col <= number - 1: row -= 1 for row in range(number): print(*matrix[row])
d9247e91833eb5a66e7388dc3f8e4e1ea99de9d3
pavdemesh/stepik_67
/stepik_67_ex_2_6_4.py
827
3.8125
4
# Create empty list matrix = list() # Get input from user while True: line = input() # Check if input == "end", break if line == "end": break # Else convert input to a list of ints and append to the matrix list else: matrix.append([int(i) for i in line.split()]) # Create variables to store the count of row and cols in the matrix row_count = len(matrix) col_count = len(matrix[0]) # Generate matrix of same size populated with 0 res = [[0] * col_count for i in range(row_count)] for row in range(row_count): for col in range(col_count): n_1 = matrix[row - 1][col] n_2 = matrix[row - row_count + 1][col] n_3 = matrix[row][col - 1] n_4 = matrix[row][col - col_count + 1] res[row][col] = n_1 + n_2 + n_3 + n_4 for item in res: print(*item)
23051e5670e7af0274ea6226d679cf8bed225244
cnguyen-uk/Blockchain
/block.py
1,420
3.609375
4
# -*- coding: utf-8 -*- """ This is our Block class for transaction storage. Note that although every block has a timestamp, a proper implementation should have a timestamp which is static from when a block is finally placed into the blockchain. In our implementation this timestamp changes every time the code is run. Our hashing function is SHA-256 as it is used in most cryptocurrencies. Information about SHA-256 can be found here: https://en.wikipedia.org/wiki/SHA-2 """ from datetime import datetime from hashlib import sha256 class Block: def __init__(self, transactions, previous_hash): self.timestamp = datetime.now() self.transactions = transactions self.previous_hash = previous_hash self.nonce = 0 # Initial guess for future Proof-of-Work self.hash = self.generate_hash() def __repr__(self): return ("Timestamp: " + str(self.timestamp) + "\n" + "Transactions: " + str(self.transactions) + "\n" + "Current hash: " + str(self.generate_hash())) def generate_hash(self): """Return a hash based on key block information.""" block_contents = (str(self.timestamp) + str(self.transactions) + str(self.previous_hash) + str(self.nonce)) block_hash = sha256(block_contents.encode()) return block_hash.hexdigest()
aab62b602367c12b4ebbf827a5b79ff4f1de84b9
18lkent/AFPwork
/GC-content.py
682
3.53125
4
dnaSequence = "ACTGATCGATTACGTATAGTATTTGCTATCATACATATATATCGATGCGTTCAT" #The sequence being counted from print("This program will display the gc content of a DNA sequence") seqLen = len(dnaSequence) #Length of the sequence gAmount = dnaSequence.count('G') #Amount of G's in the sequence cAmount = dnaSequence.count('C') #Amount of C's in the sequence seqPer1 = gAmount + cAmount #Adds number of C's and number of G's seqPer2 = seqPer1/seqLen*100 #Calculates percentage of G's and C's of sequence print("The GC content of the sequence is {0:.2f}".format(seqPer2)) #The format method allows me to change the amount of decimal places print(str(round(seqPer2, 2))+"%") #Prints Percentage
0ea8e85c1cc8eee1846c38d7adf6dcbb8de16aa5
cmniccum/Exploring-BikeShare-Data
/bikeshare.py
10,201
3.78125
4
import time import pandas as pd import sys CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } fname = "" separate = False def log(): """ This is a logging function which will determine whether to log the information to a given file or output it to the console based on the arugments given when executing this file. """ def log_func(func): def func_wrapper(*var): try: global fname if separate: fname = func.__name__ + ".txt" #Will log to a file if the fname is not blank otherwise will #go to the except block. with open(fname,"a") as f: holder = sys.stdout sys.stdout = f if func.__name__ == "time_stats": sys.stdout.write('\nCalculating The Most Frequent Times of Travel...\n') elif func.__name__ == "station_stats": sys.stdout.write('\nCalculating The Most Popular Stations and Trip...\n') elif func.__name__ == "trip_duration_stats": sys.stdout.write('\nCalculating Trip Duration...\n') elif func.__name__ == "user_stats": sys.stdout.write('\nCalculating User Stats...\n') start_time = time.time() func(*var) sys.stdout.write("\nThis took {0:.5f} seconds. \n".format(time.time() - start_time)) sys.stdout.write("-"*40 + "\n") sys.stdout = holder f.close() except Exception: #If no file is available to write to it will execute this code #and output the information to the console. if func.__name__ == "time_stats": print('\nCalculating The Most Frequent Times of Travel...\n') elif func.__name__ == "station_stats": print('\nCalculating The Most Popular Stations and Trip...\n') elif func.__name__ == "trip_duration_stats": print('\nCalculating Trip Duration...\n') elif func.__name__ == "user_stats": print('\nCalculating User Stats...\n') start_time = time.time() func(*var) print("\nThis took {0:.5f} seconds. \n".format(time.time() - start_time)) print("-"*40 + "\n") return func_wrapper return log_func def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter """ print('\nHello! Let\'s explore some US bikeshare data!\n') # get user input for city (chicago, new york city, washington). while True: city = input("What city would you like to explore: Chicago, New York,"+ "or Washington?\n").lower() if city in ('chicago', 'new york', 'washington'): break print("Sorry you chose a city with no data. Please try again.") # get user input for month (all, january, february, ... , june) while True: choice = input("\nWould you like data for a month, day, or both?\n").lower() if choice in ("month", "both"): while True: month = input("\nWhat month would you like data for: January, February,"+ "March, April, May, June, or all.\n").lower() if (month in ("january", "february", "march", "april", "may", "june", "all")): if choice == "month": day = "all" break print("Sorry you chose a month with no data. Please try again.") # get user input for day of week (all, monday, tuesday, ... sunday) if choice in ("day", "both"): while True: day = input("\nWhat day would you like data for: Monday, Tuesday, "+ "Wednesday, Thursday, Friday, Saturday, Sunday, or all \n").lower() if (day in ("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", "all")): if choice == "day": month == "all" break print("\nSorry you chose an invalid day. Please try again.\n") if choice in ("day", "month", "both"): break print("\nInvalid choice Please try again.\n") print('-'*40) return city, month, day def load_data(city, month, day): """ Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter Returns: df - Pandas DataFrame containing city data filtered by month and day """ # load data file into a dataframe df = pd.read_csv(CITY_DATA[city]) # convert the Start Time column to datetime df['Start Time'] = pd.to_datetime(df['Start Time']) # extract month, day of week, and hours from Start Time to create new columns df['month'] = df['Start Time'].dt.month df['day_of_week'] = df['Start Time'].dt.weekday_name df['hour'] = df['Start Time'].dt.hour # filter by month if applicable if month != 'all': # use the index of the months list to get the corresponding int months = ['january', 'february', 'march', 'april', 'may', 'june'] month = months.index(month) + 1 # filter by month to create the new dataframe df = df[df['month'] == month] # filter by day of week if applicable if day != 'all': # filter by day of week to create the new dataframe df = df[df['day_of_week'] == day.title()] return df @log() def time_stats(df): """Displays statistics on the most frequent times of travel.""" months = ['January', 'February', 'March', 'April', 'May', 'June'] # Most common month print("\nMost common month:") print(months[df['month'].mode()[0] - 1]) # Most common day of week print("\nMost common day of week:") print(df['day_of_week'].mode()[0]) # Most common start hour print("\nMost common start hour:") print(df['hour'].mode()[0]) @log() def station_stats(df): """Displays statistics on the most popular stations and trip.""" # Most commonly used start station print("\nMost commonly used start station:") print(df['Start Station'].value_counts().index[0]) # Most commonly used end station print("\nMost commonly used end station:") print(df['End Station'].value_counts().index[0]) # Most frequent combination of start station and end station trip df['Station Combo'] = df['Start Station'] +", "+ df['End Station'] print("\nMost frequent combination of start station and end station trip:") print(str(df['Station Combo'].value_counts().index[0]) + "\t" +str(df['Station Combo'].value_counts().max())) @log() def trip_duration_stats(df): """Displays statistics on the total and average trip duration.""" # Total Travel Time print("\nTotal Travel Time:") print(str(df['Trip Duration'].sum()) + " seconds") # Mean Travel Time print("\nMean Travel Time:") print(str(df['Trip Duration'].mean()) + " seconds") @log() def user_stats(df): """Displays statistics on bikeshare users.""" # Diplays the counts of each user type print("\nTypes of Users:") print(df['User Type'].value_counts()) # Displays the number of each gender print("\nMakeup of individuals by Gender:") print(df['Gender'].value_counts()) # Oldest Individuals print("\nOldest year of birth:") print(int(df['Birth Year'].min())) # Youngest individuals print("\nMost recent year of birth:") print(int(df['Birth Year'].max())) # Most common year of birth of individuals print("\nMost common year of birth:") print(int(df['Birth Year'].mode()[0])) def get_args(arguments): """ This function handles all arguments given when the file has been executed. additional options: -on -on 'filename' -on -s If there are no additional options given it will print everything to console. """ global fname global separate if len(arguments) == 2: if arguments[1] == '-on': fname = "log.txt" print("\n\nPlease note that your output will be logged in file '{}'.\n".format(fname)) elif len(arguments) == 3: if arguments[1] == '-on': if arguments[2] == '-s': separate = True print("\n\nPlease note that each function output will be logged separately.\n") else: fname = arguments[2] print("\n\nPlease note that your output will be logged in file '{}'.\n".format(fname)) def main(): while True: city, month, day = get_filters() df = load_data(city, month, day) time_stats(df) station_stats(df) trip_duration_stats(df) user_stats(df) restart = input('\nWould you like to restart? Enter yes or no.\n') if restart.lower() != 'yes': break if __name__ == "__main__": get_args(sys.argv) main()
7e43010151fd990c1962e1c5847230315ff80d5c
kaka0525/data-strutctures-partII
/merge_sort.py
1,792
3.703125
4
from __future__ import unicode_literals from time import time from random import shuffle def merge_sort(init_list): if len(init_list) <= 1: return init_list list_left = init_list[:len(init_list) // 2] list_right = init_list[len(init_list) // 2:] left = merge_sort(list_left) right = merge_sort(list_right) return merge(left, right) def merge(left, right): return_list = [] while left and right: if left[0] <= right[0]: return_list.append(left[0]) left = left[1:] else: return_list.append(right[0]) right = right[1:] while left: return_list.append(left[0]) left = left[1:] while right: return_list.append(right[0]) right = right[1:] return return_list if __name__ == '__main__': def build_list(iterations): return_list = range(iterations) return return_list iteration_list = [10, 100, 1000, 10000] random_list = [[] for x in range(4)] sorted_list = [[] for x in range(4)] for i in range(len(iteration_list)): random_list[i].extend(build_list(iteration_list[i])) shuffle(random_list[i]) sorted_list[i].extend(build_list(iteration_list[i])) count = 0 for test in random_list: t0 = time() merge_sort(test) worst_time = time() - t0 print "A random list with {} entries, takes {} seconds with mergesort"\ .format(len(test), worst_time) count += 1 count = 0 for test in sorted_list: t0 = time() merge_sort(test) worst_time = time() - t0 print "An already sorted list with {} entries, takes {} seconds with merge sort"\ .format(len(test), worst_time) count += 1
d827875540a6004a7680a82649bdb58dc6f3431a
Aaron-Ramos/parcial-python
/py-parcial-q3-2020/clave_B/clave_b.py
2,257
4.0625
4
from math import pi """ *************************************************************** @@ ejercicio 1 @@ un metodo python que haga la suma de 3 numeros 2+4+6 = 12 """ # start--> def suma(numero1,numero2,numero3): result = numero1 + numero2 + numero3 return result """ *************************************************************** @@ ejercicio 2 @@ la suma de los numeros impares del 1 al 1000 """ # start--> def sumaImpares(contador, result) contador = 1 result= 0 while contador <=1000 if contador % 2 != 0 result += contador contador+=1 return result """ *************************************************************** @@ ejercicio 3 @@ encontrar el perimetro, area y el volumen de un esfera radio = 12 m perimetro: 2*pi*r area: 4*pi*r^2 volumen: (4/3)*pi*r^3 """ # start--> def definicionEsfera(radio): result = print(obtenerPerimetro(result)) print (obtenerArea(result)) print (obtenerVolumen(result)) return result def obtenerPerimetro(radio): result = 2 * pi * radio return result def obtenerArea(radio): result = 4 * pi * radio^2 return result def obtenerVolumen(radio): result = 4/3 * pi * radio^3 return result """ *************************************************************** @@ ejercicio 4 @@ el ejercicio numero 3 convertirlo en una clase """ # start--> class Esfera: def definicionEsfera(self): return 0 """ *************************************************************** @@ ejercicio 5 @@ Banco Cliente nombre lugar numero de cuenta transaccion - retiro o abono monto """ class Banco: def procesar(self): return 0 def abonosSanSalvador(self): return 0 def abonosBalYRod(self): return 0 class Cliente: pass """ *************************************************************** @@ ejercicio 6 @@ colocar este proyecto en github colocar aca debajo la url ademas colocar la url en un archivo github_<nombre>_<codigo>.txt y subirlo a moodle """ # github url--> def getGithubUrl(numeroCarnet): if numeroCarnet == "20195452" return ""
590e8b488d96bf5961cd747a44386b563a34b76f
richnamk/python_nov_2017
/richardN/pythFundamentals/multSumAve/multSumAve.py
248
3.5
4
#Mult #part 1 for x in range (0,1000): if (x % 2 == 1): print x #part 2 for x in range (5,1000000): if (x % 5 == 0): print x #Sum a = [1, 2, 5, 10, 255, 3] print sum (a) #Ave a = [1, 2, 5, 10, 255, 3] print sum (a) / (len(a))
a5bb79e5269dfb2ac5076f11585d078e404202f5
zazaho/SimImg
/simimg/dialogs/infowindow.py
994
3.765625
4
from tkinter import messagebox as tkmessagebox def showInfoDialog(): """ show basic info about this program """ msg = """ SiMilar ImaGe finder: This program is designed to display groups of pictures that are similar. In particular, it aims to group together pictures that show the same scene. The use case is to be able to quickly inspect these pictures and keep only the best ones. The program in not designed to find copies of the same image that have been slightly altered or identical copies, although it can be use for this. There are already many good (better) solutions available to do this. The workflow is as follows: * Activate some selection criterion of the left by clicking on its label * Adapt the parameters * The matching groups are updated * Select images by clicking on the thumbnail (background turns blue) * Click the play button to inspect the selected images * Click the delete button to delete selected images """ tkmessagebox.showinfo("Information", msg)
b9f24efdbaffa1d8c8968c95cafe3025fc01d7e7
nithinp300/texteditor
/texteditor.py
1,377
3.578125
4
from Tkinter import * import tkFileDialog root = Tk("Text Editor") text = Text(root) text.grid() savelocation = "none" # creates a new file and writes to it def saveas(): global text global savelocation t = text.get("1.0", "end-1c") savelocation = tkFileDialog.asksaveasfilename() file1 = open(savelocation, "w") file1.write(t) file1.close() button = Button(root, text="Save As", command=saveas) button.grid() # opens a textedit file def openfile(): global text global savelocation savelocation = tkFileDialog.askopenfilename() file1 = open(savelocation, "r") text.insert("1.0", file1.read()) file1.close() button = Button(root, text="Open", command=openfile) button.grid() # overwrites the file that is currenly opened def save(): global text t = text.get("1.0", "end-1c") file1 = open(savelocation, "w") file1.write(t) file1.close() button = Button(root, text="Save", command=save) button.grid() # changes font style def fontArial(): global text text.config(font="Arial") def fontCourier(): global text text.config(font="Courier") font = Menubutton(root, text="Font") font.grid() font.menu = Menu(font, tearoff=0) font["menu"] = font.menu arial = IntVar() courier = IntVar() font.menu.add_checkbutton(label="Arial", variable=arial, command=fontArial) font.menu.add_checkbutton(label="Courier", variable=courier, command=fontCourier) root.mainloop()
d76be366cdc01b27a2071c7e88a63fa5b8cbb1e5
attainu/python-project-Shiva-dwivedi-au9
/Saanp_Seedhi/Saanp_Seedhi.py
11,487
3.671875
4
import random import time import sys class Saanp_Seedhi: def __init__(self): self.DELAY_IN_ACTIONS = 1 self.DESTINATION = 100 self.DICE_FACE = 6 self.text = [ "Your move.", "Go on.", "Let's GO .", "You can win this." ] self.bitten_by_snake = [ "Aeeee kataaaaaaaaaaa", "gaya gaya gaya gaya", "bitten :P", "oh damn", "damn" ] self.ladder_climb = [ "NOICEEE", "GREATTTT", "AWESOME", "HURRAH...", "WOWWWW" ] self.snakes = {} self.ladders = {} self.players = [] self.num_of_players = int(input("Enter the num of players(2 or 4):")) if self.num_of_players == 2 or self.num_of_players == 4: for _ in range(self.num_of_players): self.pl_name = input("Name of player " + str(_ + 1) + " : ") self.players.append(self.pl_name) print("\nMatch will be played between: ", end=" ") print(",".join(self.players[:len(self.players)-1]), end=" ") print("and", self.players[-1]) else: print("Enter either 2 or 4") self.num_of_players = int(input("Enter no. of players(2 or 4):")) for _ in range(self.num_of_players): self.pl_name = input("Name of player " + str(_ + 1) + " : ") self.players.append(self.pl_name) print("\nMatch will be played between: ", end=" ") print(",".join(self.players[:len(self.players)-1]), end=" ") print("and", self.players[-1]) def Snakes(self): num_of_snakes = int(input("No. of snakes on your board :")) if num_of_snakes > 0: print("\n Enter Head and Tail separated by a space") i = 0 while i < (num_of_snakes): head, tail = map(int, input("\n Head and Tail: ").split()) if head <= 100 and tail > 0: if tail >= head: print("\n The tail of snake should be less than head") i = i-1 elif head == 100: print("\n Snake not possible at position 100.") i = i-1 elif head in self.snakes.keys(): print("\n Snake already present") i = i-1 else: self.snakes[head] = tail i += 1 else: print("Invalid! kindly choose b/w 0 to 100") print("\n Your Snakes are at : ", self.snakes, "\n") else: print("Please enter valid number of snakes") self.Snakes() return self.snakes def Ladders(self): num_of_ladders = int(input("No. of ladders on your board :")) if num_of_ladders > 0: print("\n Enter Start and End separated by a space") i = 0 while i < (num_of_ladders): flag = 0 start, end = map(int, input("\n Start and End: ").split()) if start > 0 and end < 100: if end <= start: print("\n The end should be greater than Start") flag = 1 i -= 1 elif start in self.ladders.keys(): print("\n Ladder already present") flag = 1 i -= 1 for k, v in self.snakes.items(): if k == end and v == start: print("\nSnake present(will create infinite loop)") print("\nPlease Enter valid Ladder") flag = 1 i -= 1 else: if flag == 0: self.ladders[start] = end else: pass i += 1 else: print("Invalid! kindly choose b/w 0 to 100") print("\n Your Ladders are at: ", self.ladders, "\n") else: print("Please select valid number of ladders") self.Ladders() return self.ladders def get_player_names(self): if self.num_of_players == 2: pl_1 = self.players[0] pl_2 = self.players[1] return pl_1, pl_2 elif(self.num_of_players == 4): pl_1 = self.players[0] pl_2 = self.players[1] pl_3 = self.players[2] pl_4 = self.players[3] return pl_1, pl_2, pl_3, pl_4 else: return("Invalid choice") def welcome_to_the_game(self): message = """ Welcome to Saanp Seedhi. GAME RULES 1. When a piece comes on a number which lies on the head of a snake, then the piece will land below to the tail of the snake that can also be said as an unlucky move. 2. If somehow the piece falls on the ladder base, it will climb to the top of the ladder (which is considered to be a lucky move). 3. Whereas if a player lands on the tail of the snake or top of a ladder, the player will remain in the same spot (same number) and will not get affected by any particular rule. The players can never move down ladders. 4. The pieces of different players can overlap each other without knocking out anyone.There is no concept of knocking out by opponent players in Snakes and Ladders. 5. To win, the player needs to roll the exact number of die to land on the number 100. If they fails to do so, then the player needs to roll the die again in the next turn. For eg, if a player is on the number 98 and the die roll shows the number 4, then they cannot move its piece until they gets a 2 to win or 1 to be on 99th number. """ print(message) def roll_the_dice(self): time.sleep(self.DELAY_IN_ACTIONS) dice_val = random.randint(1, self.DICE_FACE) print("Great.You got a " + str(dice_val)) return dice_val def you_got_bitten(self, old_val, curr_val, pl_name): print("\n" + random.choice(self.bitten_by_snake).upper() + " :(:(:(:(") print("\n" + pl_name + " bitten. Dropped from ", end=" ") print(str(old_val) + " to " + str(curr_val)) def climbing_ladder(self, old_val, curr_val, pl_name): print("\n" + random.choice(self.ladder_climb).upper() + " :):):):)") print("\n" + pl_name + " climbed from ", end=" ") print(str(old_val) + " to " + str(curr_val)) def saanp_seedhi(self, pl_name, curr_val, dice_val): time.sleep(self.DELAY_IN_ACTIONS) old_val = curr_val curr_val = curr_val + dice_val if curr_val > self.DESTINATION: print("You now need " + str(self.DESTINATION - old_val), end=" ") print(" more to win this game.", end=" ") print("Keep trying.You'll win") return old_val print("\n" + pl_name + " moved from " + str(old_val), end=" ") print(" to " + str(curr_val)) if curr_val in self.snakes: final_value = self.snakes.get(curr_val) self.you_got_bitten(curr_val, final_value, pl_name) elif curr_val in self.ladders: final_value = self.ladders.get(curr_val) self.climbing_ladder(curr_val, final_value, pl_name) else: final_value = curr_val return final_value def Winner(self, pl_name, position): time.sleep(self.DELAY_IN_ACTIONS) if self.DESTINATION == position: print("\n\n\nBRAVO!!!!!.\n\n" + pl_name + " WON THE GAME.") print("CONGRATULATIONS " + pl_name) print("\nThank you for playing the game.") sys.exit(1) class Start(Saanp_Seedhi): def start_the_game(self): time.sleep(self.DELAY_IN_ACTIONS) if self.num_of_players == 2: pl_1, pl_2 = self.get_player_names() elif self.num_of_players == 4: pl_1, pl_2, pl_3, pl_4 = self.get_player_names() time.sleep(self.DELAY_IN_ACTIONS) pl_1_cur_pos = 0 pl_2_cur_pos = 0 pl_3_cur_pos = 0 pl_4_cur_pos = 0 while True: time.sleep(self.DELAY_IN_ACTIONS) if self.num_of_players == 2: s = " Press enter to roll dice: " _ = input(pl_1 + ": " + random.choice(self.text) + s) print("\nRolling the dice...") dice_val = self.roll_the_dice() time.sleep(self.DELAY_IN_ACTIONS) print(pl_1 + " moving....") pl_1_cur_pos = self.saanp_seedhi(pl_1, pl_1_cur_pos, dice_val) self.Winner(pl_1, pl_1_cur_pos) _ = input(pl_2 + ": " + random.choice(self.text) + s) print("\nRolling dice...") dice_val = self.roll_the_dice() time.sleep(self.DELAY_IN_ACTIONS) print(pl_2 + " moving....") pl_2_cur_pos = self.saanp_seedhi(pl_2, pl_2_cur_pos, dice_val) self.Winner(pl_2, pl_2_cur_pos) elif(self.num_of_players == 4): s = " Press enter to roll dice: " _ = input(pl_1 + ": " + random.choice(self.text) + s) print("\nRolling the dice...") dice_val = self.roll_the_dice() time.sleep(self.DELAY_IN_ACTIONS) print(pl_1 + " moving....") pl_1_cur_pos = self.saanp_seedhi(pl_1, pl_1_cur_pos, dice_val) self.Winner(pl_1, pl_1_cur_pos) _ = input(pl_2 + ": " + random.choice(self.text) + s) print("\nRolling dice...") dice_val = self.roll_the_dice() time.sleep(self.DELAY_IN_ACTIONS) print(pl_2 + " moving....") pl_2_cur_pos = self.saanp_seedhi(pl_2, pl_2_cur_pos, dice_val) self.Winner(pl_2, pl_2_cur_pos) _ = input(pl_3 + ": " + random.choice(self.text) + s) print("\nRolling dice...") dice_val = self.roll_the_dice() time.sleep(self.DELAY_IN_ACTIONS) print(pl_3 + " moving....") pl_3_cur_pos = self.saanp_seedhi(pl_3, pl_3_cur_pos, dice_val) self.Winner(pl_3, pl_3_cur_pos) _ = input(pl_4 + ": " + random.choice(self.text) + s) print("\nRolling dice...") dice_val = self.roll_the_dice() time.sleep(self.DELAY_IN_ACTIONS) print(pl_4 + " moving....") pl_4_cur_pos = self.saanp_seedhi(pl_4, pl_4_cur_pos, dice_val) self.Winner(pl_4, pl_4_cur_pos) if __name__ == "__main__": lets_play_the_game = Start() time.sleep(1) lets_play_the_game.welcome_to_the_game() lets_play_the_game.Snakes() lets_play_the_game.Ladders() lets_play_the_game.start_the_game()
c1ba8dbefafd9ea87f4fe74c93e76afa47766fd4
yrachkov/Python_2_online
/lesson9/hw3.py
83
3.609375
4
s = {'n':2,'d':6,'h':4,'u':11} for y,l in s.items(): if l ==2: print(y)
0ab6be587b51f02f0db4f53534281be61c664c01
GuiBritoPy/SimplesPySimples
/Jogo.py
2,323
3.84375
4
# -*- coding: utf-8 -*- while True: ok = "Ok, vamos continuar" nome = str(input("Olá, qual o seu nome? ")) idade = str(input("Quantos anos você tem? ")) sexo = str(input("Qual o seu sexo? (M - Masculino e S - Feminino) ")).upper() if sexo == "F": sexo = Feminino if sexo == "S": sexo = Masculino ch = 0 print("Ok, vamos começar") p1 = str(input("Telefonou para a vítima? (S - Sim e N - Não) ")).upper() if p1 != "S" and p1 != "N": print("Entrada Inválida") elif p1 == "S": ch += 1 print(ok) else: ch += 0 print(ok) p2 = str(input("Esteve no local do crime? (S - Sim e N - Não) ")).upper() if p2 != "S" and p2 != "N": print("Entrada Inválida") elif p2 == "S": ch += 1 print(ok) else: ch += 0 print(ok) p3 = str(input("Mora perto da vítima? (S - Sim e N - Não) ")).upper() if p3 != "S" and p3 != "N": print("Entrada Inválida") elif p3 == "S": ch += 1 print(ok) else: ch += 0 print(ok) p4 = str(input("Devia para a vítima? (S - Sim e N - Não) ")).upper() if p4 != "S" and p4 != "N": print("Entrada Inválida") elif p4 == "S": ch += 1 print(ok) else: ch += 0 print(ok) p5 = str(input("Já trabalhou para a vítima? (S - Sim e N - Não) ")).upper() if p5 != "S" and p5 != "N": print("Entrada Inválida") elif p5 == "S": ch += 1 print("Ok") else: ch += 0 print ("Ok") #2 questões ela deve ser classificada como "Suspeita", entre 3 e 4 como "Cúmplice" e 5 como "Assassino". Caso contrário, ele será classificado como "Inocente". print ("#*"*10) print("Vamos ao relatório") print ("#*"*10) if ch == 2: print("{} de {} anos do sexo {} é considerado(a) Suspeito(a)".format(nome,idade)) elif 2 < ch <= 4: print("{} de {} anos do sexo {} é considerado(a) Cúmplice.".format(nome,idade)) elif ch == 5: print("{} de {} anos do sexo {} é considerado(a) Assassino(a) do crime.".format(nome,idade)) else: print("{} de {} anos do sexo {} é considerado(a) Inocente.".format(nome,idade)) print("Próxima Pessoa")
33d262c8ef0f4f7de82ecab4a9fa9783c511e3ec
Italodias32/Python-Repository
/Animal.py
1,486
3.6875
4
class Animal(): def __init__(self, aux_nome, aux_peso): self.__nome = aux_nome self.__peso = aux_peso #Getter e Setters do Nome def get_nome(self): return self.__nome def set_nome(self, aux_nome): if isinstance(aux_nome, str): self.__nome = aux_nome else: self.__nome = None #Property do Nome @property def __nome(self): return self._nome @__nome.setter def __nome(self, aux_nome): if isinstance(aux_nome, str): self._nome = aux_nome else: self._nome = str(aux_nome) #Getter e Setter do Peso def get_peso(self): return self.__peso def set_peso(self, aux_peso): if isinstance(aux_peso, float): self.__peso = aux_peso else: self.__peso = float(aux_peso) #Property do Peso @property def __peso(self): return self._peso @__peso.setter def __peso(self, aux_peso): if isinstance(aux_peso, float): self._peso = aux_peso else: self._peso = float(aux_peso) def __str__(self): return "Nome: " + self.__nome + ", Peso: " + str(self.__peso) + '\n' #Metodos da Classe def imprime_animal(self): print("Nome: " + self.__nome + ", Peso: " + str(self.__peso)) def alimentacao(self, peso_comida): self.__peso += peso_comida
411a14d6899d35beeab715b621d75d8052b288c5
Italodias32/Python-Repository
/campeonato.py
1,335
3.65625
4
def vencedor(lista): maior = -1 for i in lista: if i.get_pontos() >= maior: maior = i.get_pontos() campeao = i.get_nome() return campeao class Participante(): def __init__(self, nome, index): self.__nome = nome self.__pontos = 0 self.__index = index def get_nome(self): return self.__nome def get_pontos(self): return self.__pontos def get_index(self): return self.__index def set_pontos(self, aux): self.__pontos += aux def duelo(self, other): print('Duelo de ' + self.get_nome() + ' contra ' + other.get_nome()) p1 = int(input('Quantos duelos ' + self.get_nome() + ' venceu ? ')) p2 = int(input('Quantos duelos ' + other.get_nome() + ' venceu ? ')) if p1 == 2 and p2 == 0: self.set_pontos(4) elif p1 == 2 and p2 == 1: self.set_pontos(3) other.set_pontos(1) elif p1 == 0 and p2 == 2: other.set_pontos(4) elif p1 == 1 and p2 == 2: other.set_pontos(3) self.set_pontos(1) def pontucao_final(self): print('A pontução final de ' + self.get_nome() + ' foi de: ' + str(self.get_pontos()) + ' pontos')
c4eff3bd9244d150afd43170f9d11e910237e416
Alparse/artificial_intelligence
/tic_tac_toe.py
7,445
3.765625
4
""" Classic tic tac toe system implemented by Serhat Alpar. Copied from Xxxxxxxxxxxxxxxxx permalink: Xxxxxxxxxxxxxx """ import math import gym from gym import spaces, logger from gym.utils import seeding import numpy as np class TicTacToeEnv(): """ Description: A game of classical tic tac toe is played until either a draw (all 9 spaces filled without a win condition being met) or a win (a player claims three horizontally or vertically connected cells in the game obs_space: Game obs_space is represented by a 2 dimensional array of shape 3,3 Observation Space: Type: Box(4) Num Observation Values 0 [0,0]position (P1) 0,1 1 [0,1]position (P1) 0,1 2 [0,2]position (P1) 0,1 3 [1,0]position (P1) 0,1 4 [1,1]position (P1) 0,1 5 [1,2]position (P1) 0,1 6 [2,0]position (P1) 0,1 7 [2,1]position (P1) 0,1 8 [2,2]position (P1) 0,1 9 [0,0]position (P2) 0,1 10 [0,1]position (P2) 0,1 11 [0,2]position (P2) 0,1 12 [1,0]position (P2) 0,1 13 [1,1]position (P2) 0,1 14 [1,2]position (P2) 0,1 15 [2,0]position (P2) 0,1 16 [2,1]position (P2) 0,1 17 [2,2]position (P2) 0,1 Actions: Type: Discrete(9) Num Action(Claim) Values 0 [0,0]position (P1) 0,1 1 [0,1]position (P1) 0,1 2 [0,2]position (P1) 0,1 3 [1,0]position (P1) 0,1 4 [1,1]position (P1) 0,1 5 [1,2]position (P1) 0,1 6 [2,0]position (P1) 0,1 7 [2,1]position (P1) 0,1 8 [2,2]position (P1) 0,1 9 [0,0]position (P2) 0,1 10 [0,1]position (P2) 0,1 11 [0,2]position (P2) 0,1 12 [1,0]position (P2) 0,1 13 [1,1]position (P2) 0,1 14 [1,2]position (P2) 0,1 15 [2,0]position (P2) 0,1 16 [2,1]position (P2) 0,1 17 [2,2]position (P2) 0,1 Reward 1 for win .5 for draw .1 for move 0 for loss Starting State: All observations are set to 0 Episode Termination Win/Loss/Draw Condition Met """ def __init__(self): self.obs_space = np.zeros([1, 18]) self.allowed_action_space = np.arange(18) self.allowed_total_action_space=np.zeros((1,9)) self.state = None self.game_status = 0 # game status 0 = playing # game status 1 = player 1 win # game status 2 = player 2 win # game status 3 = draw self.turn = 1 self.yrl_ = np.zeros([1, 9]) self.reward1 = 0.0 self.total_rewards1 = 0 self.reward2 = 0.0 self.total_rewards2 = 0 self.reward_dictionary1=[] def check_if_move_legal(self, player, move): if player == 1: if move not in self.allowed_action_space: return False else: return True if player == 2: # if move not in self.allowed_action_space_player2: if move not in self.allowed_action_space: return False else: return True def check_if_game_won(self, player): if player == 1: os = 0 # offset else: os = 9 # offset if 1 == self.obs_space[0, 0 + os] == self.obs_space[0, 1 + os] == self.obs_space[0, 2 + os] \ or 1 == self.obs_space[0, 3 + os] == self.obs_space[0, 4 + os] == self.obs_space[0, 5 + os] \ or 1 == self.obs_space[0, 6 + os] == self.obs_space[0, 7 + os] == self.obs_space[0, 8 + os] \ or 1 == self.obs_space[0, 0 + os] == self.obs_space[0, 3 + os] == self.obs_space[0, 6 + os] \ or 1 == self.obs_space[0, 1 + os] == self.obs_space[0, 4 + os] == self.obs_space[0, 7 + os] \ or 1 == self.obs_space[0, 2 + os] == self.obs_space[0, 5 + os] == self.obs_space[0, 8 + os] \ or 1 == self.obs_space[0, 0 + os] == self.obs_space[0, 4 + os] == self.obs_space[0, 8 + os] \ or 1 == self.obs_space[0, 2 + os] == self.obs_space[0, 4 + os] == self.obs_space[0, 6 + os]: return True else: return False def check_if_draw(self): if np.sum(self.obs_space) >= 8.5: return True else: return False def pick_random_legal_move(self, player): if not self.check_if_draw(): if player == 1: random_pool = len(self.allowed_action_space[self.allowed_action_space < 9]) random_pick = np.random.randint(0, random_pool) random_action = self.allowed_action_space[random_pick] return random_action if player == 2: random_pool = len(self.allowed_action_space[self.allowed_action_space >= 9]) random_pick = np.random.randint(0, random_pool) random_action = self.allowed_action_space[random_pick + random_pool] return random_action else: return False def render(self): player1_space = self.obs_space[0, :9] player2_space = self.obs_space[0, 9:] self.allowed_total_action_space=np.add(player1_space,player2_space) self.allowed_total_action_space[np.where(self.allowed_total_action_space==2)]=1 player2_space = self.obs_space[0, 9:] * 2 render_space = np.add(player1_space, player2_space) render_space = np.reshape(render_space, (3, 3)) print(render_space) if self.game_status==1: print("Player 1 Wins") if self.game_status==2: print("Player 2 Wins") if self.game_status==3: print ("Draw!") if self.game_status==0: print ("Player moved", self.turn) def make_move(self, player, move): try: # assert (self.game_status ==0),"Game Over" #assert (not self.check_if_draw()), "Game Over Drawn" #assert (not self.check_if_game_won(player)), "Game Over Won" #assert (self.check_if_move_legal(player, move)), "Illegal Move" if player == 1: self.obs_space[0][move] = 1 move_index = np.argwhere(self.allowed_action_space == move) self.allowed_action_space = np.delete(self.allowed_action_space, move_index) move_indexp2 = np.argwhere(self.allowed_action_space == move + 9) self.allowed_action_space = np.delete(self.allowed_action_space, move_indexp2) elif player == 2: self.obs_space[0][move] = 1 move_index = np.argwhere(self.allowed_action_space == move) self.allowed_action_space = np.delete(self.allowed_action_space, move_index) move_indexp1 = np.argwhere(self.allowed_action_space == move - 9) self.allowed_action_space = np.delete(self.allowed_action_space, move_indexp1) except: print("Illegal Move")
7f0d06254acda9ae0f22b35ddefa6f5d9bf53487
league-python-student/level0-module1-samus114
/_04_int/_2_simple_number_adder/simple_adder.py
523
4.0625
4
""" * Write a Python program that asks the user for two numbers. * Display the sum of the two numbers to the user """ import tkinter as tk from tkinter import messagebox, simpledialog, Tk if __name__ == '__main__': window = tk.Tk() window.withdraw() num1 = simpledialog.askinteger('', 'what is your first number to be added?') num2 = simpledialog.askinteger('', 'what is the second number to be added?') messagebox.showinfo('', 'your number is ' + str(num1+num2)) window.mainloop()
19ed2bdb0d0e8098568d9cb987ddb8997124082b
Samson26/code
/minmax.py
146
3.546875
4
a=int(input()) arr=[int(i) for i in input().split()] mini=min(arr) mini1=int(mini) maxi=max(arr) maxi1=int(maxi) print(str(mini1)+' '+str(maxi1))
15e7518c82297499f59d448a23822ee7c8859a8c
Samson26/code
/yesorno.py
74
3.65625
4
b=int(input()) if(b<=10 and b>=1): print("yes") else: print("no")
525d87507fad34cf9a6ae9a4afa5c0f97b9af1aa
Samson26/code
/alpha.py
97
3.75
4
user=raw_input() check=str(user.isalpha()) if check=='True': print "Alphabet" else: print "No"
7190442863bed270614b64bd3e8e6055ec1f4960
akansal1/statsintro_python
/Code/S10_normCheck.py
930
3.515625
4
'''Solution for Exercise "Normality Check" ''' from scipy import stats import matplotlib.pyplot as plt import statsmodels.formula.api as sm import seaborn as sns # We don't need to invent the wheel twice ;) from S12_correlation import getModelData if __name__== '__main__': # get the data data = getModelData(show=False) # Fit the model model = sm.ols('AvgTmp ~ year', data) results = model.fit() # Normality check ---------------------------------------------------- res_data = results.resid # Get the values for the residuals # QQ-plot, for a visual check stats.probplot(res_data, plot=plt) plt.show() # Normality test, for a quantitative check: _, pVal = stats.normaltest(res_data) if pVal < 0.05: print('WARNING: The data are not normally distributed (p = {0})'.format(pVal)) else: print('Data are normally distributed.')
63e81f354f4ecbb4d2689d70815dfbec926c2013
drashti2210/180_Interview_Questions
/merge_sorted_array.py
1,444
3.84375
4
import sys sys.stdout = open('d:/Coding/output.txt','w') sys.stdin = open('d:/Coding/input.txt','r') # Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. # Example # INPUT # nums1 = [1,2,3,0,0,0], m = 3 # nums2 = [2,5,6], n = 3 # OUTPUT # [1,2,2,3,5,6] nums1=list(map(int,input().split())) m=int(input()) nums2=list(map(int,input().split())) n=int(input()) def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ # Solution 1 # check greater & append in nums1 if n==0: return elif m == 0: j = 0 for j in range(n): nums1[j] = nums2[j] i, j = m-1, n-1 temp = 0 while i>=0 and j>=0: if nums1[i] >= nums2[j]: nums1[m+n-temp-1] = nums1[i] i-=1 temp+=1 else: nums1[m+n-temp-1] = nums2[j] j-=1 temp+=1 if j < 0: return else: while j>=0: nums1[m+n-temp-1]=nums2[j] j-=1 temp+=1 print(nums1) return # Solution 2 # Using Sort for i in range(n): nums1[i+m] = nums2[i] nums1.sort() merge(nums1,m,nums2,n) print(nums1)
45ba4bf16bf612a0b2c9be396a77290ba419215a
drashti2210/180_Interview_Questions
/Mid_of_Linked_List.py
932
3.921875
4
import sys #Day 5 # 2. Middle of Linked List # INPUT:- # 1->2->3->4->5->NULL # OUTPUT: - # 3 # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None def middleNode(head): # solution 1 # find the length of linked list # iterate upto mid & return mid element l=0 temp=head while temp.next!=None: temp=temp.next l+=1 if l%2!=0: l=(l//2)+1 else: l=l//2 for i in range(l): head=head.next return head # solution 2 # using array arr = [head] while arr[-1].next: arr.append(arr[-1].next) return A[len(arr) // 2] # solution 3 # using slow & fast poiter # When fast reaches the end of the list, slow must be in the middle. slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next return slow
b929e51eb223e63930330838af02d7d9fd37c9b7
drashti2210/180_Interview_Questions
/Add_numbers_Linked_List.py
1,159
3.875
4
import sys # Add two numbers as LinkedLis # INPUT:- # 2 linked list # 1->2->3->->NULL # 1->2->3->->NULL # OUTPUT: - # addition # 2->4->6->NULL # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: # sotion 1 # using another linked list to store sum dummy = cur = ListNode(-1) carry = 0 while l1 or l2 or carry: if l1: carry += l1.val l1 = l1.next if l2: carry += l2.val l2 = l2.next cur.next = ListNode(carry%10) cur = cur.next carry //= 10 return dummy.next # solution 2 # recursive approach temp = l1.val + l2.val digit, tenth = temp% 10, temp// 10 answer = ListNode(digit) if any((l1.next, l2.next, tenth)): if l1.next: l1 = l1.next else: l1 = ListNode(0) if l2.next: l2 = l2.next else: l2=ListNode(0) l1.val += tenth answer.next = self.addTwoNumbers(l1, l2) return answer
4e4019378a59f2b0eb3668cc4c4fbb0abcfa2139
drashti2210/180_Interview_Questions
/merge_sorted_LL.py
973
4.03125
4
import sys # Day 1 # 4. Merge Sorted Linked List #Example:- #INPUT:- # 2 sorted linked list # 1->2->4, 1->3->4 #OUTPUT:- # Merged Linked List # 1->1->2->3->4->4 class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: if n==0: return elif m == 0: j = 0 for j in range(n): nums1[j] = nums2[j] i, j = m-1, n-1 temp = 0 while i>=0 and j>=0: if nums1[i] >= nums2[j]: nums1[m+n-temp-1] = nums1[i] i-=1 temp+=1 else: nums1[m+n-temp-1] = nums2[j] j-=1 temp+=1 if j < 0: return else: while j>=0: nums1[m+n-temp-1]=nums2[j] j-=1 temp+=1 return
5eb0dc3ddab738e7e7d60960ce8e49142ab87a1f
mbaybay/cs686-2018-01
/knn.py
2,023
3.671875
4
from classifier import classifier import pandas as pd import numpy as np from sklearn.model_selection import train_test_split class KNN(classifier): def __init__(self, k=3): self.x = None self.y = None self.k = k def fit(self, x, y): """ :param X: pandas data frame, with rows as observations and columns as observation features :param Y: pandas series, encoded as categorical classes :return: """ # compute distances self.x = x self.y = y def predict(self, x): """ :param x: :return: """ pred = x.apply(self.__get_majority_class, axis=1) return pred.tolist() def __get_majority_class(self, obs): """ :param obs: one observation of test x :return: """ # distances = pd.Series(index=self.x.index) def __calc_euclidean_distance(row): # https://en.wikipedia.org/wiki/Euclidean_distance # d(p,q) = sqrt(sum((p_i-q_i)**2)) euc_dist = np.sqrt(np.square(row.subtract(obs)).sum()) # row - sub return euc_dist # calculate euclidean distance to all points distances = self.x.apply(func=__calc_euclidean_distance, axis=1) # sort by distance distances.sort_values(ascending=False, inplace=True) # take top-k observations by index top_k = distances[0:self.k].index # get majority class from y majority_class = self.y[top_k].value_counts() majority_class = majority_class.index[0] return majority_class if __name__ == '__main__': import util data = util.read_arff_as_df("../../data/PhishingData.arff.txt") x = data.loc[:, data.columns != 'Result'] y = data['Result'] train_x, test_x, train_y, test_y = train_test_split(x, y) clf = KNN(k=3) clf.fit(train_x, train_y) pred = clf.predict(test_x) util.print_confusion_matrix(test_y, pred, labels=[-1, 0, 1])
bd5d648e9f62bc9ba12ade748eddcaf9aba03474
cmdavis4/senior-thesis
/spherical_geo.py
3,242
3.65625
4
#+++++++++++++++++++++++++++++++++++++++ # # Spherical Geometry # # Description: # This file contains the functions for # spherical geometry calcuations # including rotations, coordinate transformations # and angular separations # #--------------------------------------- import numpy as np import numpy.linalg as LA def to_sphere(point): """accepts a x,y,z, coordinate and returns the same point in spherical coords (r, theta, phi) i.e. (r, azimuthal angle, altitude angle) with phi=0 in the zhat direction and theta=0 in the xhat direction""" coord = (np.sqrt(np.sum(point**2)), np.arctan2(point[1],point[0]), np.pi/2.0 - np.arctan2(np.sqrt(point[0]**2 + point[1]**2),point[2]) ) return np.array(coord) def to_cartesian(point): """accepts point in spherical coords (r, theta, phi) i.e. (r, azimuthal angle, altitude angle) with phi=0 in the zhat direction and theta=0 in the xhat direction and returns a x,y,z, coordinate""" coord = point[0]*np.array([np.cos(point[2])*np.cos(point[1]), np.cos(point[2])*np.sin(point[1]), np.sin(point[2])]) return coord def rotate(p1, p2, p3): """rotates coordinate axis so that p1 is at the pole of a new spherical coordinate system and p2 lies on phi (or azimuthal angle) = 0 inputs: p1: vector in spherical coords (phi, theta, r) where phi is azimuthal angle (0 to 2 pi), theta is zenith angle or altitude (0 to pi), r is radius p2: vector of same format p3: vector of same format Output: s1:vector in (r, theta, phi) with p1 on the z axis s2:vector in (r,, theta, phi) with p2 on the phi-hat axis s3:transformed vector of p3 """ p1_cc=to_cartesian(p1) p2_cc=to_cartesian(p2) p3_cc=map(to_cartesian, p3) p1norm = p1_cc/LA.norm(p1_cc) p2norm = p2_cc/LA.norm(p2_cc) p3norm = map(lambda x: x/LA.norm(x), p3_cc) zhat_new = p1norm x_new = p2norm - np.dot(p2norm, p1norm) * p1norm xhat_new = x_new/LA.norm(x_new) yhat_new = np.cross(zhat_new, xhat_new) dot_with_units = lambda x: [np.dot(x, xhat_new), np.dot(x, yhat_new), np.dot(x, zhat_new)] s1 = np.array(dot_with_units(p1_cc)) s2 = np.array(dot_with_units(p2_cc)) s3 = np.array(map(dot_with_units, p3_cc)) s1=to_sphere(s1) s2=to_sphere(s2) s3=np.array(map(to_sphere, s3)) return s1, s2, s3 def calc_distance(center, points): '''Calculate the circular angular distance of two points on a sphere.''' center = np.array(center) points = np.array(points) lambda_diff = center[0] - points[:,0] cos1 = np.cos(center[1]) cos2 = map(np.cos, points[:,1]) sin1 = np.sin(center[1]) sin2 = map(np.sin, points[:,1]) num1 = np.power(np.multiply(cos2, map(np.sin, lambda_diff)), 2.0) num2 = np.subtract(np.multiply(cos1, sin2), np.multiply(np.multiply(sin1, cos2), map(np.cos, lambda_diff))) num = np.add(num1, np.power(num2, 2.0)) denom1 = np.multiply(sin1, sin2) denom2 = np.multiply(np.multiply(cos1, cos2), map(np.cos, lambda_diff)) denom = np.add(denom1, denom2) return map(np.arctan2, map(np.sqrt, num), denom)
dd50743885e2a849652cef7243486196ce364b33
vikramdayal/RaspberryMotors
/example_simple_servo.py
2,287
4.0625
4
#!/usr/bin/env python3 ''' simple example of how to use the servos interface. In this example, we are connecting a sinle servo control to GPIO pin 11 (RaspberryPi 4 and 3 are good with it) Wiring diagram servo-1 (referred to S1 in the example code) --------------------------------------------- | servo wire | connected to GPIO pin on Pi | |------------|------------------------------| | Brown | 6 (GND) | | Red | 2 (5v power) | | Yellow | 11(GPIO 17 on Pi-4) | --------------------------------------------- Code of this example: #create a servo object, connected to GPIO board pin #11 s1 = servos.servo(11) #operate the servos. Note, we are using setAngleAndWait function #which waits for a specific time (default 1 sec) for the servo to react s1.setAngleAndWait(0) # move to default position of zero degrees s1.setAngleAndWait(180) # move to position of 180 degrees #in the above examples, the servo will wait for default 1 second to respond, we #can change the respond time in seconds, in this example, we will wait 0.5 seconds s1.setAngleAndWait(0, 0.5) # move back to position of zero degrees and wait 0.5 #we are done with the servo pin shut it down s1.shutdown() ''' # Name: example_simple_servo.py # Author: Vikram Dayal ############################################################## #import the servos package from motors module from RaspberryMotors.motors import servos def main(): print("starting example") #create a servo object, connected to GPIO board pin #11 s1 = servos.servo(11) #operate the servos. Note, we are using setAngleAndWait function #which waits for a specific time (default 1 sec) for the servo to react s1.setAngleAndWait(0) # move to default position of zero degrees s1.setAngleAndWait(180) # move to position of 180 degrees #in the above examples, the servo will wait for default 1 second to respond, we #can change the respond time in seconds, in this example, we will wait 0.5 seconds s1.setAngleAndWait(0, 0.5) # move back to position of zero degrees # we are done with the servo pin shut it down s1.shutdown() if __name__ == "__main__": main()
13a7cd02724849f25e7775b0fd1045364f3a5b98
Dan609/code_learn
/ipython_log1.py
3,943
3.75
4
# IPython log file get_ipython().run_line_magic('logstart', '') class Car: speed = 5 car1 = Car() car2 = Car() car1.engine car2.engine car1.engine = 'V8 Turbo' car1.engine car2.engine Car.wheels = 'Wagon wheels (' c1.wheels car1.wheels Car = Car() Car new_car = Car() Car.speed car1.speed car2.wheels car2.engine Car.engine # Classes can have both methods and fields class Window: is_opened = False def open(self): self.is_opened = True print('Window is now', self.is_opened) def close(self): self.is_opened = False print('Window is now', self.is_opened) window1 = Window() window2 = Window() window1.open() window2.is_opened dir(window2) class Car: speed = 0 Car.engine = 'V8' class Car: engine = 'V8' speed = 0 window2.__class__ class Car: speed = 0 def __init__(self, color): print('Constructor is called!') print('Self is the object itself!', self) self.color = color car1 = Car() car1 = Car('red') car2 = Car('black') car1.speed car2.speed car2.color car1.color class Car: speed = 0 def __init__(self, color, transmission='Auto'): print('Constructor is called!') print('Self is the object itself!', self) self.color = color self.transmission = transmission car1 = Car('black') car2 = Car('yellow', 'Manual') car1.transmission car1.color car1.transmission class Car: speed = 0 def __init__(self, color='black', transmission='Auto'): print('Constructor is called!') print('Self is the object itself!', self) self.color = color self.transmission = transmission car1 = Car(transmission='Manual') car1 = Car(,'Manual') Car() c3 = Car() car1.speed class Test(object): # it is the same as the code above (py3 only) pass class Test: # it is the same as the code above (py3 only) pass class Person(object): biological_name = 'homo sapiens' def __init__(self, name, age): self.name = name self.age = age def walk(self): print('Walking...') def say_hello(self): print('I am a person', self.name, self.age) person = Person('Ivan', 25) person.walk() person.say_hello() class Student(Person): def say_hello(self): print('I am a student', self.name, self.age) student = Student('Fedor', 19) student.walk() student.say_hello() class Car: pass class CarWithManualTransmission(Car): pass class CarWithAutoTransmission(Car): pass type(student) isinstance(student, Student) isinstance(student, Person) class Child(Person): def walk(self): raise ValueError('Can not walk') def say_hello(self): raise ValueError('Can not talk') def crawl(self): print('Haha!') new_child = Child() new_child = Child('Petr', 1) new_child.walk() new_child.say_hello() new_child.crawl() student.crawl() person.crawl() class Example(object): def __init__(self): self.a = 1 self._b = 2 self.__c = 3 print('{} {} {}'.format( self.a, self._b, self.__c)) def call(self): print('Called!') def _protected_method(self): pass def __private_method(self): pass try: print(example.__c) except AttributeError as ex: print(ex) example = Example() try: print(example.__c) except AttributeError as ex: print(ex) dir(example) example._Example__c class Parent(object): def call(self): print('Parent') class Child(Parent): def call(self): print('Child') len((1,3,4,)) len(['a', 'g', 'b']) len("string") def call_obj(obj): obj.call() call_obj(Child()) call_obj(Parent())
ecb3c2aa29cc645e011d5e599a0ed24eb1f983b2
PraneshASP/LeetCode-Solutions-2
/69 - Sqrt(x).py
817
3.9375
4
# Solution 1: Brute force # Runtime: O(sqrt(n)) class Solution(object): def mySqrt(self, x): """ :type x: int :rtype: int """ sqrt = 1 while sqrt*sqrt <= x: sqrt += 1 return sqrt-1 # Solution 2: Use Newton's iterative method to repeatively "guess" sqrt(n) # Say we want sqrt(4) # Guess: 4 # Improve our guess to (4+(4/4)) / 2 = 2.5 # Guess: 2.5 # Improve our guess to (2.5+(4/2.5)) / 2 = 2.05 # ... # We get to 2 very quickly # Runtime: O(logn) class Solution(object): def mySqrt(self, x): """ :type x: int :rtype: int """ # Use newton's iterative method delta = 0.0001 guess = x while guess**2 - x > delta: guess = (guess+(x/guess))/2.0 return int(guess)
3785a9becaf8fad4904ea2ec560aec3e6da7de03
PraneshASP/LeetCode-Solutions-2
/277 - Find the Celebrity.py
1,748
3.796875
4
# Solution 1: This problem is the same as finding a "universal sink" in a graph. # A universal sink in the graph => there is no other sink in the graph, so # we can just iterate through the nodes until we find a sink. Then check if it's universal. # O(n) runtime, O(n) space class Solution(object): def findCelebrity(self, n): """ :type n: int :rtype: int """ visited = set() node = 0 while len(visited) < n: visited.add(node) sink = True for i in range(0, n): if i == node: continue if i not in visited and knows(node,i): # Visit i node = i sink = False break if sink: # Found sink, check if it's universal for i in range(0,n): if i == node: continue if not knows(i, node): return -1 if knows(node,i): return -1 return node return -1 # Solution 4: Let's shorten the code and use O(1) space class Solution(object): def findCelebrity(self, n): """ :type n: int :rtype: int """ # find a sink in the graph sink = 0 for i in range(1,n): if knows(sink,i): sink = i # check if it's universal for i in range(0,n): if i == sink: continue if not knows(i, sink): return -1 if knows(sink,i): return -1 return sink
b535625fb73b96be2ba8156e9f77c789b9b6e29a
PraneshASP/LeetCode-Solutions-2
/90 - Subsets II.py
2,191
3.78125
4
# Solution 1: It is sufficient to just do a lookup to see if we # have already made an existing subset. Runtime = O(nlogn * (2^n)) # You may see the sort in the loop and say it's O(nlogn * (2^n)), which # isn't wrong, but note that there is actually only one subset of length n. # There are exponentially more subsets of length 1 (2^n / 2) or length 2 (2^n / 4), etc, # so our sort is actually going to take much less than O(nlogn) on average. That's # why this solution will still AC on LeetCode. class Solution(object): def subsetsWithDup(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ pset = [] size = 2 ** len(nums) lookup = set() for i in range(size): subset = [] for j in range(len(nums)): if (2**j) & i == (2**j): subset.append(nums[j]) subset.sort() if tuple(subset) not in lookup: pset.append(subset) lookup.add(tuple(subset)) return pset # Solution 2: We can still make our solution faster if we take the # sort outside of the loop. In order to do this we need to observe that # we can treat duplicates as special numbers. # ex. if an element is duplicated 3 times, we add this element 0 -> 3 times to # every existing subset in our list # For some reason this solution only works with Python 3 on LeetCode, # maybe due to the list comprehension. # Runtime = O(n * (2^n)) class Solution(object): def subsetsWithDup(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ nums.sort() pset = [[]] i = 0 while i < len(nums): num = nums[i] dupes = 1 # number of duplicates curr = i+1 while curr < len(nums) and nums[curr] == nums[curr-1]: dupes += 1 curr += 1 # Add the num 0 -> dupes times to each subset for k in range(len(pset)): for j in range(1, dupes+1): pset += [pset[k] + [num for k in range(j)]] i += dupes return pset
d68997dde4826ce9781322db961198d8ac537173
PraneshASP/LeetCode-Solutions-2
/300 - Longest Increasing Subsequence.py
5,129
3.828125
4
# Solution 1: An O(n^2) algorithm is to start from the back of the array. # Observe that the last element creates an LIS of size 1. Move to the # next element, this will either create an LIS of size 2 (if it is smaller # than the last element), or a new LIS of size 1. # Repeat this process by moving backwards through the array and keeping track # of <start of LIS, length of LIS>. # tldr; Each element will either start a new LIS of size 1, or add to an existing LIS. class Solution(object): def lengthOfLIS(self, nums): """ :type nums: List[int] :rtype: int """ if(len(nums) <= 1): return len(nums) lis = [] # list of <start of LIS, length of LIS> for i in range(len(nums)-1,-1,-1): lisLength = None # Check if there's an existing LIS we can add to for j in range(0, len(lis)): if nums[i] < lis[j][0]: if lisLength is None: lisLength = lis[j][1] elif lis[j][1] > lisLength: lisLength = lis[j][1] # Add to existing LIS, or start a new one if lisLength: lis.append([nums[i],lisLength+1]) else: lis.append([nums[i], 1]) maxLis = 1 for i in range(0, len(lis)): if(lis[i][1] > maxLis): maxLis = lis[i][1] return maxLis # Solution 2: Let's make a small optimization. # Observe that we only need to store the LARGEST element that starts an LIS. # Ex. Let's say our list is [1, 110, 100] # 100 starts an LIS of length 1. When we get to 110, rather than adding a new LIS of length 1, # we can just update our existing LIS to use 110 instead of 100. This is because # every element that would create a longer LIS with 100 will also create a longer LIS # with 110. # We can see how this logic works with the following example. # Ex. Our list is [1,3,6,7,9,4,10,5,6] # <length of LIS, largest element that starts LIS> # 1st iteration: <1,6> # 2nd iteration: <1,6>, <2,5> # 3rd iteration: <1,10>, <2,5> *** UPDATE # 4th iteration: <1,10>, <2,5>, <3,5> # 5th iteration: <1,10>, <2,5>, <3,5>, <4, 4> # 6th iteration: <1,10>, <2,9>, <3,5>, <4, 4> *** UPDATE # 7th iteration: <1,10>, <2,9>, <3,6>, <4, 4> *** UPDATE # 8th iteration: <1,10>, <2,9>, <3,6>, <4, 4>, <5, 3> # 9th iteration: <1,10>, <2,9>, <3,6>, <4, 4>, <5, 3>, <6, 1> # Longest LIS = length 6, starting with element 1 class Solution(object): def lengthOfLIS(self, nums): """ :type nums: List[int] :rtype: int """ if(len(nums) <= 1): return len(nums) lis = [] # list of <length of LIS, largest element that starts LIS> for i in range(len(nums)-1,-1,-1): update = 0 for j in range(0, len(lis)): if nums[i] == lis[j][1]: update = 1 # if there's a duplicate element, don't do anything break if nums[i] > lis[j][1]: lis[j][1] = nums[i] update = 2 break if update == 0: lis.append([len(lis)+1, nums[i]]) return len(lis) # Solution #3: Notice that we don't actually need to store tuples anymore. # We can just use the array index to represent the LIS length. # I also noticed when writing this that we don't actually need to look # from the back of the array :) Let's write the forloop from 0 -> n class Solution(object): def lengthOfLIS(self, nums): """ :type nums: List[int] :rtype: int """ if(len(nums) <= 1): return len(nums) lis = [] # lis[i] = smallest element that starts an LIS of length i for i in range(0,len(nums)): update = 0 for j in range(0, len(lis)): if nums[i] == lis[j]: update = 1 # if there's a duplicate LIS, don't do anything break if nums[i] < lis[j]: lis[j] = nums[i] update = 2 break if update == 0: lis.append(nums[i]) return len(lis) # Solution #4: O(nlogn) solution. Notice the lis list is always sorted. So we can # use a binary search to determine where to update instead of a linear search. import bisect class Solution(object): def lengthOfLIS(self, nums): """ :type nums: List[int] :rtype: int """ if(len(nums) <= 1): return len(nums) lis = [nums[0]] # lis[i] = smallest element that starts an LIS of length i for i in range(1,len(nums)): binarySearchIndex = bisect.bisect(lis,nums[i]) # Avoid duplicate LIS if binarySearchIndex > 0 and lis[binarySearchIndex-1] == nums[i]: continue if binarySearchIndex == len(lis): lis.append(nums[i]) else: lis[binarySearchIndex] = nums[i] return len(lis)
4da19128caf20616ecbd36b297022b1d3ccb92ce
PraneshASP/LeetCode-Solutions-2
/234 - Palindrome Linked List.py
1,548
4.1875
4
# Solution: The idea is that we can reverse the first half of the LinkedList, and then # compare the first half with the second half to see if it's a palindrome. # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def isPalindrome(self, head): """ :type head: ListNode :rtype: bool """ if head is None or head.next is None: return True slow = head fast = head # Move through the list with fast and slow pointers, # when fast reaches the end, slow will be in the middle # Trick #1: At the same time we can also reverse the first half of the list tmp = slow.next while fast is not None and fast.next is not None: fast = fast.next.next prev = slow slow = tmp tmp = slow.next slow.next = prev head.next = None # Trick #2: If fast is None, the string is even length evenCheck = (fast is None) if evenCheck: if slow.val != slow.next.val: return False slow = slow.next.next else: slow = slow.next # Check that the reversed first half matches the second half while slow is not None: if tmp is None or slow.val != tmp.val: return False slow = slow.next tmp = tmp.next return True
9fa0f80646fcba2e31f4d42327304c335459cf81
indefinitelee/Interview-Stuff
/numbers.py
918
3.703125
4
def main(): f("12365212354", 26) def f(numbers, target): for i in range(1, len(numbers)): current = int(numbers[0:i]) to_end = numbers[i:-1] evaluate(0, current, to_end, target, current) def evaluate(sum, previous, numbers, target, out): if len(numbers) == 0: if sum + previous == int(target): print str(out) + "=" + str(target) else: for i in range(1, len(numbers)): current = int(numbers[0:i]) to_end = numbers[i:-1] evaluate(sum + previous, int(current), to_end, target, str(out) + "+" + str(current)) evaluate(sum, previous * int(current), to_end, target, str(out) + "*" + str(current)) evaluate(sum, previous / int(current), to_end, target, str(out) + "/" + str(current)) evaluate(sum + previous, -int(current), to_end, target, str(out) + "-" + str(current)) main()
e1557d11a69c703d33d90b123f65d8b34d0c69d2
iainhemstock/Katas
/BinarySearch/python/BinarySearch.py
468
3.78125
4
def find_index_of(value, list): index = -1 if len(list) == 0: index = -1 else: lowpoint = 0 highpoint = len(list) while lowpoint < highpoint: midpoint = int((lowpoint + highpoint) / 2) if value == list[midpoint]: index = midpoint break if value > list[midpoint]: lowpoint = midpoint + 1 if value < list[midpoint]: highpoint = midpoint return index
9598e90194eb277fd04ea04f0bb09b10083ab33d
iainhemstock/Katas
/LcdDisplay/python/main.py
1,000
3.703125
4
from lcd_digits import one, two, three, four, five, six, seven, eight, nine, zero def parse(input): switcher = { "1" : one, "2" : two, "3" : three, "4" : four, "5" : five, "6" : six, "7" : seven, "8" : eight, "9" : nine, "0" : zero } lcd_digits = [] for char in input: lcd_digits.append(switcher.get(char)) return lcd_digits def buildOutput(lcd_digits, spacing): output = "" digit_height = len(lcd_digits[0]) if len(lcd_digits) >= 1 else 0 for i in range(digit_height): for digit in lcd_digits: output += digit[i] + (' ' * spacing) output += "\n" return output def convertToLcd(input, spacing): lcd_digits = parse(input) return buildOutput(lcd_digits, spacing) def main(): number = input("Enter a number:") spacing = int(input("Enter spacing:")) print (convertToLcd(number, spacing)) if __name__ == "__main__": main()
ac95a08e0f92a66b9d1df15cddf154c33bc1befa
iainhemstock/Katas
/PrimeFactors/python/main.py
916
3.828125
4
import unittest class PrimeFactors(): def of(n): list = [] divisor = 2 while n >= 2: while n % divisor == 0: list.append(divisor) n /= divisor divisor += 1 return list class PrimeFactororizerShould(unittest.TestCase): def test_return_prime_factors_of_integer(self): self.assertEqual(PrimeFactors.of(1), []) self.assertEqual(PrimeFactors.of(2), [2]) self.assertEqual(PrimeFactors.of(3), [3]) self.assertEqual(PrimeFactors.of(4), [2,2]) self.assertEqual(PrimeFactors.of(5), [5]) self.assertEqual(PrimeFactors.of(6), [2,3]) self.assertEqual(PrimeFactors.of(7), [7]) self.assertEqual(PrimeFactors.of(8), [2,2,2]) self.assertEqual(PrimeFactors.of(9), [3,3]) self.assertEqual(PrimeFactors.of(10), [2,5])
b551eb195b0f3f912eb56fbb774f6054488ee8bd
jigarshah2811/Python-Programming
/6-DS-Graph/test_graph.py
1,804
3.796875
4
from Graph import Graph """ TEST CASES """ print("\n============ Directed Graph ==============\n") g = Graph() edges = [ ("A", "B", 7), ("A", "D", 5), ("B", "C", 8), ("B", "D", 9), ("B", "E", 7), ("C", "E", 5), ("D", "E", 15), ("D", "F", 6), ("E", "F", 8), ("E", "G", 9), ("F", "G", 11), ("H", "I", 20) ] for edge in edges: src, dest = edge[0], edge[1] g.add_edge(src, dest) print(("Graph: {0}".format(sorted(iter(g.graph.items()), key=lambda x:x[0])))) print("DFS---> connected graph") print((g.dfs_connected_graph("A"))) print("DFS---> Disconnected graph") print((g.dfs_disconnected_graph())) print("BFS---> connected graph") print((g.bfs_connected_graph('A'))) print("BFS---> Disconnected graph") print((g.bfs_disconnected_graph())) print("\n============ Weighted directed Graph ==============\n") g = Graph() edges = [ ("A", "B", 7), ("A", "D", 5), ("B", "C", 8), ("B", "D", 9), ("B", "E", 7), ("C", "E", 5), ("D", "E", 15), ("D", "F", 6), ("E", "F", 8), ("E", "G", 9), ("G", "A", 9), ("F", "G", 11), ("H", "I", 20) ] for edge in edges: src, dest, weight = edge[0], edge[1], edge[2] g.add_edge(src, dest, weight) print(("Graph: {0}".format(sorted(iter(g.graph.items()), key=lambda x:x[0])))) print("DFS---> Weighted Disconnected graph") print((g.dfs_disconnected_graph())) print("BFS---> Weighted Disconnected graph") print((g.bfs_disconnected_graph())) print("Detect Cycle---> Weighted Disconnected graph") print((g.is_cycle())) print("Find Path from Src to Dest---> Weighted Disconnected graph") print((g.find_path("A", "G"))) clonedGraph = g.cloneGraph("A") print("Original Graph: -->") print(g.printGraph()) print("Cloned Graph: -->") print(clonedGraph.printGraph())
869edf4c975e41ccdee0eacfbda1a636576578fc
jigarshah2811/Python-Programming
/Matrix_Print_Spiral.py
1,741
4.6875
5
""" http://www.geeksforgeeks.org/print-a-given-matrix-in-spiral-form/ Print a given matrix in spiral form Given a 2D array, print it in spiral form. See the following examples. Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 Output: 1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11 spiral-matrix """ def print_spiral(matrix): '''matrix is a list of list -- a 2-d matrix.''' first_row = 0 last_row = len(matrix) - 1 first_column = 0 last_column = len(matrix[0]) - 1 while True: # Print first row for col_idx in range(first_column, last_column + 1): print(matrix[first_row][col_idx]) first_row += 1 if first_row > last_row: return # Print last column for row_idx in range(first_row, last_row + 1): print(matrix[row_idx][last_column]) last_column -= 1 if last_column < first_column: return # Print last row, in reverse for col_idx in reversed(range(first_column, last_column + 1)): print(matrix[last_row][col_idx]) last_row -= 1 if last_row < first_row: return # Print first column, bottom to top for row_idx in reversed(range(first_row, last_row + 1)): print(matrix[row_idx][first_column]) first_column += 1 if first_column > last_column: return if __name__ == '__main__': mat = [[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16]] print_spiral(mat)
4d07e9f7c2199352a664077c93d640d55304e84a
jigarshah2811/Python-Programming
/Interviews/Meta/SlidingWindow-PartitionArray.py
1,479
3.859375
4
""" Q: Partition Array so that Sum of all partitions are SAME Given an array of integers greater than zero, find if there is a way to split the array in two (without reordering any elements) such that the numbers before the split add up to the numbers after the split. If so, print the two resulting arrays. === Test cases === In [1]: can_partition([5, 2, 3]) Output [1]: ([5], [2, 3]) Return [1]: True In [2]: can_partition([2, 3, 2, 1, 1, 1, 2, 1, 1]) Output [2]([2, 3, 2], [1, 1, 1, 2, 1, 1]) Return [2]: True In [3]: can_partition([1, 1, 3]) Return [3]: False In [4]: can_partition([1, 1, 3, 1]) Return [4]: False """ class Solution: def can_partition(self, nums): Lsum, Rsum = 0, sum(nums) for i, num in enumerate(nums): Lsum += num Rsum -= num if Lsum == Rsum: print(f"Found split at:{i}, LeftSum: {Lsum}, RightSum: {Rsum}") L = nums[:i+1] # <--- ..i (includes 0.....i) R = nums[i+1:] # ----> i... (includes i+1....) return(L, R) return None s = Solution() nums = [5, 2, 3] print(s.can_partition(nums)) # output Output [1]: ([5], [2, 3]) nums = [2, 3, 2, 1, 1, 1, 2, 1, 1] print(s.can_partition(nums)) # output ([2, 3, 2], [1, 1, 1, 2, 1, 1]) nums = [1, 1, 3] print(s.can_partition(nums)) # output: None, FALSE nums = [1, 1, 3, 1] print(s.can_partition(nums)) # Output: None, False
5ea6b05ac7cd8c380f3e58b0f667c3ee021a0214
jigarshah2811/Python-Programming
/4-DS-LinkedList/LinkedList.py
1,839
3.953125
4
class Node: def __init__(self, val, next=None): self.val = val self.next = next class LinkedList: def __init__(self, val=0): self.head = None def __append__(self, val): if self.head is None: self.head = self.Node(val) return # Append at the end of list cur = self.head while cur.next: cur = cur.next cur.next = self.Node(val) """ Let's find out if this keyboard is working as expected254BTGBNBG """ def __insertAtPos__(self, pos, val):| cur = self.head while cur and pos > 1: pos -= 1 cur = cur.next # Either we reached to pos or reached end newNode = self.Node(val) newNode.next = cur.next cur.next = newNode def __pop__(self): headVal = self.head.val self.head = self.head.next return headVal def __popAtPos__(self, pos): if self.head is None: # Empty list raise IndexError cur = self.head while cur.next and pos > 0: cur = cur.next pos -= 1 if cur.next is None: # Trying to remove invalid index raise IndexError cur.next = cur.next.next def __remove__(self, val): if self.head is None: # Empty list raise IndexError cur = self.head while cur.next and cur.next.val != val: cur = cur.next # cur is at point where next node is to be removed if cur.next is None: # Trying to remove invalid index raise IndexError cur.next = cur.next.next def __hasNext__(self): return self.cur is None def __print__(self): cur = self.head while cur: print(cur.val,) cur = cur.next
0fdb0ee310f777deb4a7de34085615bfe3d5802b
jigarshah2811/Python-Programming
/1-DS-Array-String/CarParking.py
1,080
3.734375
4
class Solution: def parkingCars(self, parking): freeSlot = len(parking)-1 for i, car in enumerate(parking): if car == i: # If Car#K is already at ParkingSlot#K then no movement required continue # For car#i find target slot#i targetSlot = car if parking[targetSlot] != -1: # If target slot is NOT available, # make it available by moving the car from targetSlot to freeSlot parking[targetSlot], parking[freeSlot] = parking[freeSlot], parking[targetSlot] # Target Slot is now available, simply move the car to target slot from current slot parking[targetSlot], parking[i] = parking[i], parking[targetSlot] return parking s = Solution() parking = [1, 0, -1] # spots: 3 and cars: 2 print(s.parkingCars(parking)) parking = [3, 1, 2, 0, -1] # spots: 5 and cars: 4 print(s.parkingCars(parking)) parking = [3, 5, 2, 0, 1, 4, -1] # spots: 5 and cars: 4 print(s.parkingCars(parking))
1c89bf03246ff0284b01255ec5827ff2866c8041
jigarshah2811/Python-Programming
/Algo-Sorting-Searching/BinarySearch.py
1,014
4.09375
4
from typing import List class Solution: def BinarySearch(self, nums: List[int], target: int) -> int: # Binary search works only for sorted array, so make sure array is sorted # Setup indexes, low and high and move them around low++ or high-- based on mid value low, high = 0, len(nums)-1 while low <= high: mid = low // 2 # Works for even and odd size arr pretty well, left side will have 1 more element if nums[mid] == target: # FOUND! return mid elif nums[mid] > target: # We are too much on right side, move to left high = mid-1 # <---- High else: # We are too much on left side, move to right low = mid+1 # Low ----> return -1 # if target element not found, return -1 == NOT_FOUND s = Solution() arr = [1, 2, 3, 4, 5, 6, 7] print(s.BinarySearch(arr, target=6)) arr = [-1,0,3,5,9,12] print(s.BinarySearch(arr, target=9))
3a369371f4bfaf5ebade5192a371a1d3e0214101
jigarshah2811/Python-Programming
/1-DS-Array-String/Array-Misc-Easy.py
3,101
4
4
from typing import List, Tuple """ STRATEGY: Map, Modify as you go... """ class Solution: def insertionSort(nums): for i, num in enumerate(nums): # Move elements of arr[0..i-1], that are # greater than key, to one position ahead # of their current position j = i-1 while j >=0 and num < nums[j] : nums[j+1] = nums[j] j -= 1 nums[j+1] = num return nums def firstTwoMaxNums(self, nums: List) -> tuple(): firstMax, secondMax = float('-inf'), float('-inf') for i, num in enumerate(nums): if num > firstMax: # Found bigger firstMax secondMax = firstMax # Backup previous firstMax as secondMax firstMax = num # New firstMax return (firstMax, secondMax) """ https://www.geeksforgeeks.org/sieve-of-eratosthenes/ """ def countPrimes(self, n): # Edge case if n < 3: return 0 # Create a table of all numbers are prime: True prime = [True for i in range(n)] prime[0] = prime[1] = False # Iterate through each number in table starting from 1st prime number=2 for i in range(2, int(n ** 0.5) + 1): if prime[i]: # Mark all multiplication... prime=False! # Start with 2*2 and mark all increments of 2 # Start with 3*3 and mark all increments of 3 # Start with 5*5 and mark all increments of 5 for p in range(i*i, n, i): prime[p] = False return sum(prime) def firstNonRepeatingNum(self, nums): from sys import maxsize d = {} # Build a freq map but also store index # {Num --> (freq, index)} for i, num in enumerate(nums): if num in d: d[num] = (d[num][0]+1, i) else: d[num] = (1, i) print(d) # Walk through dict key to find num with freq=1 and with min index resIndex = float('inf') for num, (freq, index) in list(d.items()): # OPTIMIZE: Iterate only on keys not the entire nums array again!!! if freq == 1: # Non repeating number resIndex = min(resIndex, index) # First non repeating number print(resIndex) return nums[resIndex] if resIndex == float('inf') else -1 s = Solution() print("First two maximum numbers from the array") nums = [] print(s.firstTwoMaxNums(nums)) nums = [1] print(s.firstTwoMaxNums(nums)) nums = [1, 2] print(s.firstTwoMaxNums(nums)) nums = [3, 6, 1, 4, 2] print(s.firstTwoMaxNums(nums)) nums = [0,1,0,3,12] print(s.firstTwoMaxNums(nums)) #print ("Total prime numbers till value: {0}, are: {1}".format(50, s.countPrimes(50))) #print ("Total prime numbers till value: {0}, are: {1}".format(50, s.countPrimes(9999999))) nums = [3,4,1,2,5,2,1,4,2] # 3 and 5 don't repeat, so return 3 print(("First non repeating number is: ", s.firstNonRepeatingNum(nums)))
8d68737c1826c508a060af1873b139fa083af8f5
jigarshah2811/Python-Programming
/Algo-Sorting-Searching/BS-RandomPickUniformDistribution.py
1,736
3.5625
4
import random class Solution: def __init__(self, w: List[int]): # Generate [1/8, 3/8, 4/8] totalWeight = sum(w) for i, weight in enumerate(w): w[i] = weight / totalWeight # Generate on number line for uniform distribtion betwee 0%-100% # [1/8, 4/8, 1] See last weight will always be 1 (=100%) for i, weight in enumerate(w): if i == 0: # skip 1st continue w[i] += w[i-1] self.w = w def pickIndex_orderN(self) -> int: # Generate a random uniformity between 0...1 pickedWeight = random.uniform(0, 1) for i, weight in enumerate(self.w): if pickedWeight <= weight: return i """ Pattern: Binary Search ---- Get Index of value between (0, ..., 1) If the value does not exists, return index of closest value target=0.26 in [0.1, 0.25, 0.75] would return index=1 """ def pickIndex_BinarySearch(self): target = random.uniform(0, 1) # print(f"target: {target}") # Make it unform by selecting the index based on probability weight low, high = 0, len(self.weights)-1 while low < high: mid = (low + high) >> 1 # print(f"mid: {mid}, val: {self.weights[mid]}") if self.weights[mid] == target: return mid if target > self.weights[mid]: # print(f"Searching on R ---> ") low = mid + 1 else: # print(f"Searching on L <----") high = mid # At this point low and high would be same return min(low, high)
dddd4ff528366a9bde62d630ef80f23abaeaa390
jigarshah2811/Python-Programming
/5-DS-Tree/LL.py
14,608
3.984375
4
from TREE import TreeNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next class DLLNode(object): def __init__(self, item): self.val = item self.next = None self.prev = None # Definition for a Node. class RandomListNode: def __init__(self, val, next=None, random=None): self.val = val self.next = next self.random = random """ LL Tricks 1. Always check Current.next for condition, you have to mostly stop one node (current) before to operate upon 2. Where you can't check Current.next for condition, maintain prev 3. Head ?? validation """ class LinkedList: def __init__(self, item=0): self.head = ListNode(item) pass def insert(self, item): newNode = ListNode(item) if self.head is None: # 1st Node, Make it head self.head = newNode # Otherwise find end of list current = self.head while current.next is not None: current = current.next # We are at end of list, insert self.insertNode_Util(current, newNode) def insertNode_Util(self, current, newNode): # Link changes savedNext = current.next current.next = newNode newNode.next = savedNext def insertAtPosition(self, item, position): newNode = ListNode(item) if position == 0: self.head = newNode # edge case: what happens if position is given more than what list contains # Find the right pos to insert current = self.head i = 0 while i < position-1: current = current.next i += 1 # We are at pos, insert now self.insertNode_Util(current, newNode) def insertInSortedOrder(self, item): newNode = ListNode(item) # Head ?? if self.head.val > item: self.insertNode_Util(self.head, newNode) # Search for right pos current = self.head while current.next.val < item: current = current.next self.insertNode_Util(current, newNode) def remove(self, item): # Head ?? if self.head.val == item: newHeadRef = self.head.next del self.head self.head = newHeadRef return self.remove_node(ListNode(item)) def remove_node(self, node): if isinstance(type(node), Node): return -1 # Head with no next? Delete head with next is None! if self.head == node and self.head.next is None: del self.head current = self.head prev = self.head while current is not None and current.val != node.val: current = current.next prev = current # Tail ? if current is None: # Not found return -1 elif current.next is None: # Tail node to be deleted prev.val = current.val prev.next = current.next else: # Regular node current.val = current.next.val current.next = current.next.next def reverse(self): prev = None current = self.head while current is not None: savedNext = current.next # Reverse the link current.next = prev # Next iteration prev = current current = savedNext self.head = prev def detect_loop(self): slow = self.head fast = self.head while fast is not None and fast.next is not None: fast = fast.next if fast.next is not None: fast = fast.next slow = slow.next if fast == slow: break # fast & slow are pointing at k nodes away from LoopNode # Head is pointing at k nodes away from LoopNode current = self.head while current is not slow: current = current.next slow = slow.next return current def size(self, head=None): count = 0 if head is None: current = self.head else: current = head while current is not None: count += 1 current = current.next return count def size_recur_util(self, node): if node is None: return 0 return 1 + self.size_recur_util(node.next) def size_recur(self): return self.size_recur_util(self.head) def printLL(self): current = self.head while current: print current.val, current = current.next def printLLReversed_Util(self, node): if node is None: return self.printLLReversed_Util(node.next) print node.val def printLLReversed(self): return self.printLLReversed_Util(self.head) def swap(self, item, new_item): current = self.head while current.val != item: if current.next is None: return False current = current.next # We are at node to swap current.val = new_item def middle(self): slow = self.head fast = self.head while fast is not None and fast.next is not None: fast = fast.next if fast.next is not None: fast = fast.next slow = slow.next return slow def get_nth_from_last(self, n): slow = self.head fast = self.head while n > 0 and fast is not None: fast = fast.next n -= 1 while fast is not None: fast = fast.next slow = slow.next return slow.val if fast is not None else -1 def isPalindrom_Util(self, Left, Right): if Right is None: return True, Left # Left will be traversing reverse from back # Right will be traversing reverse from back isp, Left = self.isPalindrom_Util(Left, Right.next) if isp is False: return False, Left # Compare values of Right <-- with Left ---> isp1 = (Left.val == Right.val) # Move Left Left = Left.next return isp1, Left def isPalindrom(self): Left = self.head Right = self.head return self.isPalindrom_Util(Left, Right) """ ADD 2 numbers represented as reversed LinkedList https://leetcode.com/problems/add-two-numbers/description/ """ class Solution(object): def addTwoNumbersRecur(self, l1, l2, carry): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ # Base Case # Base Case if l1 is None and l2 is None: if carry: return ListNode(carry) else: return None #1) Constraint for root sumVal = carry if l1 is not None: sumVal += l1.val if l2 is not None: sumVal += l2.val newNode = ListNode(sumVal % 10) # 2) Same constraint for next Node (Recurssion) newNode.next = self.addTwoNumbersRecur(l1.next if l1 is not None else None, l2.next if l2 is not None else None, sumVal//10) return newNode def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ dummyHeadNode = ListNode(0) current = dummyHeadNode sumVal, carry = 0, 0 # Iterate through both lists while l1 or l2: sumVal = 0 if l1: sumVal += l1.val if l2: sumVal += l2.val if carry > 0: sumVal += carry carry = sumVal // 10 # Create a result node current.next = ListNode(sumVal % 10) current = current.next # Next if l1: l1 = l1.next if l2: l2 = l2.next # Edge case: Remaining carry! if carry > 0: current.next = ListNode(carry) return dummyHeadNode.next def removeNthFromEnd(self, head, n): dummyHead = ListNode(0, head) """ :type head: ListNode :type n: int :rtype: ListNode """ slow = fast = dummyHead for i in xrange(n): fast = fast.next while fast.next: slow = slow.next fast = fast.next # Slow is pointing to pre location of node to be deleted slow.next = slow.next.next return dummyHead.next def swapPairs(self, head): dummyHead = ListNode(0, head) pre,pre.next = dummyHead, head while pre.next and pre.next.next: a = pre.next b = a.next # Swap a, b links pre.next = b a.next = b.next b.next = a # Next iteration pre = a return dummyHead.next def findSize(self, head): ptr = head c = 0 while ptr: ptr = ptr.next c += 1 return c def sortedListToBST(self, head): size = self.findSize(head) def convertRecur(l, h): global head # Base condition if l > h: return None # if l == h: # # Single node, let's make a TreeNode out of this # node = TreeNode(l) # return node # Traversal, BST pre-order = sorted sequence, so building BST with pre-order from sorted LL mid = (l + h) // 2 # 1) L left = convertRecur(l, mid - 1) # 2) C node = TreeNode(head.val) node.left = left # We are in LCR traversal, so earlier built node is Left of node built Now! head = head.next # this node(head) is built in BST, keep traversing original LL # 3) R node.right = convertRecur(mid + 1, h) return node return convertRecur(0, size - 1) def copyRandomList(self, head): old = head # Dict to map {oldNodeAddress -> sameNewNodeAddress} d = {} while old: # Creating new Node and a dict[OldNodeAddress] = newNodeAddress d[old] = RandomListNode(old.val, None, None) old = old.next # Edge case: Add last node Null! d[None] = None print(d) old = head while old: # d[old] will give exact new node d[old].val = old.val d[old].next = d[old.next] d[old].random = d[old.random]i3 old = old.next return d[head] def addLL_Util_Reverse(node1, node2): # Base case # Return node values when both lists are empty if node1 is None and node2 is None: return None, 0 headRef, carry = addLL_Util_Reverse(node1.next, node2.next) sum_nodes = carry + node1.val + node2.val newNode = ListNode(sum_nodes % 10) carry = sum_nodes // 10 if headRef is None: headRef = newNode else: newNode.next = headRef headRef = newNode return headRef, carry def intersection(L1, L2): m = L1.size() n = L2.size() if m > n: fast = L1 slow = L2 else: fast = L2 slow = L1 # Now SKIP abs(len(1)-len(2) nodes from bigger list for i in xrange(abs(m-n)): fast = fast.next # Now both list are same nodes away from INTERSECTION while slow != fast: fast = fast.next slow = slow.next return slow def addLL(L1, L2): carry = 0 return addLL_Util(L1, L2, carry) def addLLReversed(L1, L2, sizeL1, sizeL2): skipNodes = abs(sizeL1 - sizeL2) while skipNodes > 0: L1 = L1.next skipNodes -= 1 HeadRef, carry = addLL_Util_Reverse(L1, L2) return HeadRef """ Reverses a LL and returns Head of new LL """ def reverse(head): prev = None current = head while current is not None: savedNext = current.next # Reverse the link current.next = prev # Next iteration prev = current current = savedNext return prev def printLL(head): while head: print head.val, head = head.next def main(): # myLL = LinkedList(1) # myLL.insert(2) # myLL.insert(3) # myLL.insert(4) # myLL.insert(5) # # reversed_head = reverse(myLL.head) # while reversed_head is not None: # print reversed_head.val # reversed_head = reversed_head.next print "Adding 2 numbers represented by LL...." L1 = LinkedList(3) L1.insert(1) L1.insert(5) L1.insert(7) L2 = LinkedList(5) L2.insert(9) L2.insert(2) s = Solution() result = s.addTwoNumbers(L1.head, L2.head) printLL(result) while result is not None: print result.val result = result.next result = s.removeNthFromEnd(L1.head, 2) printLL(result) """ myLL = LinkedList('k') myLL.insert('a') myLL.insert('y') myLL.insert('a') myLL.insert('k') # myLL.printLL() print"\nChecking palindrome" isp, Left = myLL.isPalindrom() print isp myLL = None myLL = LinkedList(1) myLL.printLL() print "\nChecking insertInSortedOrder" myLL.insertInSortedOrder(4) myLL.printLL() print "\nChecking insertAtPosition" myLL.insertAtPosition(5, 3) myLL.printLL() print "\nChecking remove" myLL.remove(2) myLL.printLL() print "\nChecking remove HEAD" myLL.remove(1) myLL.printLL() print "\nChecking remove NOT FOUND" myLL.remove(15) myLL.printLL() print "\nChecking remove NOT FOUND" myLL.remove_node(ListNode(1)) myLL.printLL() print "\nChecking remove" myLL.remove_node(ListNode(7)) myLL.printLL() print "\nreverse" myLL.reverse() myLL.printLL() print "\nsize" print myLL.size() print "\nsize recur" print myLL.size_recur() print "\nreverse print" print myLL.printLLReversed() print "\nswap" myLL.swap(11, 5) myLL.printLL() print "\nmiddle" print myLL.middle().val print "get nth from last" print myLL.get_nth_from_last(3) """ if __name__ == "__main__": main()
b766eddd7865f3735da5cc59e44c22225c8cf644
jigarshah2811/Python-Programming
/Algo-DP/Longest_SubString_Without_Repeat.py
1,555
4.03125
4
""" Longest Substring Without Repeating Characters https://leetcode.com/explore/interview/card/top-interview-questions-medium/103/array-and-strings/779/ https://www.geeksforgeeks.org/length-of-the-longest-substring-without-repeating-characters/ """ def longestUniqueSubStr(str): # HashMap {Char --> IndexLastSeen} d = dict() cur_len = 0 # To store the length of current substring max_len = 0 # To store the result # Start from the second character. First character is already # processed (cur_len and max_len are initialized as 1, and # visited[str[0]] is set for i in range(len(str)): # Char not seen or seen but not part of Current SubString # If the currentt character is not present in the already # processed substring or it is not part of the current NRCS, # then do cur_len++ if str[i] not in d or i - cur_len > d[str[i]]: cur_len += 1 else: # Char seen in current Substring # Also, when we are changing the NRCS, we should also # check whether length of the previous NRCS was greater # than max_len or not. max_len = max(cur_len, max_len) cur_len = i - d[str[i]] # update the index of current character d[str[i]] = i # Compare the length of last NRCS with max_len and update # max_len if needed max_len = max(cur_len, max_len) return max_len print(longestUniqueSubStr("GEEKSFORGEEKS")) print(longestUniqueSubStr("LEETCODE"))
56a53a69ddeb8f267a9ff221c3e91a7433af985a
jigarshah2811/Python-Programming
/8-DS-Design/HashMap.py
2,321
3.859375
4
""" https://leetcode.com/problems/design-hashmap/discuss/185347/Hash-with-Chaining-Python """ class ListNode: def __init__(self, key, val): self.pair = (key, val) self.next = None class HashMap: def __init__(self): """ Initialize DS here: A HashMap is List of 1000 nodes, Each Index in List can have chain (ListNodes) """ self.capacity = 1000 self.m = [None] * self.capacity def put(self, key, value): """ Key will always be in range (0...1million) and value can be any int :param key: int :param value: int :return: void """ index = key % self.capacity if self.m[index] is None: # No pair(key,val) at this index yet, this is the 1st node self.m[index] = ListNode(key, value) # NEW else: # Already pair(key, val) at this index, Use Chaining to see if pair exists cur = self.m[index] while cur.__next__ is not None: if cur.pair[0] == key: # this key exists cur.pair = (key, value) # UPDATE val return cur = cur.__next__ # key does not exists in chain. Add cur.next = ListNode(key, value) # NEW: Collision def get(self, key): """ Key will be at Index OR in case of collision of index, key will be part of chaining list. :param key: int :return: value int """ index = key % self.capacity cur = self.m[index] while cur: if cur.pair[0] == key: # Found key return cur.pair[1] else: cur = cur.__next__ # key not found return -1 def remove(self, key): return -1 def printMap(self): print((self.m)) myHashMap = HashMap() myHashMap.put(1, 1); myHashMap.put(2, 2); print(myHashMap.get(1)); # returns 1 print(myHashMap.get(3)); # returns -1 (not found) myHashMap.put(2, 1); # update the existing value print(myHashMap.get(2)); # returns 1 myHashMap.remove(2); # remove the mapping for 2 print(myHashMap.get(2)); # returns -1 (not found) myHashMap.printMap()
4a5fc85b209138408683797ef784cbd59dd978fe
jigarshah2811/Python-Programming
/LL_MergeSort.py
2,556
4.625
5
# Python3 program merge two sorted linked # in third linked list using recursive. # Node class class Node: def __init__(self, data): self.data = data self.next = None # Constructor to initialize the node object class LinkedList: # Function to initialize head def __init__(self): self.head = None # Method to print linked list def printList(self): temp = self.head while temp: print temp.data temp = temp.next # Function to add of node at the end. def append(self, new_data): new_node = Node(new_data) if self.head is None: self.head = new_node return last = self.head while last.next: last = last.next last.next = new_node def splitList(head): slow = fast = head while fast: fast = fast.next if fast is not None: fast = fast.next slow = slow.next # Now, Fast is at End and Slow is at Middle A = head B = slow slow.next = None return A, B def mergeSort(head): if head is None or head.next is None: return head # Split unsorted list into A and B A, B = splitList(head) # Indivudally sort A and B mergeSort(A) mergeSort(B) # Now we have 2 sorted lists, A & B, merge them return mergeLists(A, B) # Function to merge two sorted linked list. def mergeLists(A, B): tail = None if A is None: return B if B is None: return A if A.data < B.data: tail = A tail.next = mergeLists(A.next, B) else: tail = B tail.next = mergeLists(A, B.next) return tail # Driver Function if __name__ == '__main__': # Create linked list : # 10->20->30->40->50 list1 = LinkedList() list1.append(3) list1.append(5) list1.append(7) # Create linked list 2 : # 5->15->18->35->60 list2 = LinkedList() list2.append(1) list2.append(2) list2.append(4) list2.append(6) # Create linked list 3 list3 = LinkedList() # Merging linked list 1 and linked list 2 # in linked list 3 list3.head = mergeLists(list1.head, list2.head) print(" Merged Linked List is : ") list3.printList() print "Testing MergeSort" # Create linked list 4 : # 5->2->1->4->3 list3 = LinkedList() list3.append(5) list3.append(2) list3.append(1) list3.append(4) list3.append(3) sortedList = mergeSort(list3.head) sortedList.printList()
34860ea98e636d64ada5e34e3d025dcc898a23b1
jigarshah2811/Python-Programming
/Algo-Greedy/timePlanner.py
1,814
3.578125
4
class Solution(object): def planner(self, slotsA, slotsB, targetDuration): res = [] a, b = 0, 0 start, end = 0, 1 while a < len(slotsA) and b < len(slotsB): A = slotsA[a] B = slotsB[b] if self.overlaps(A, B): print(("Overlapping found: SlotA: {0}, SlotB: {1}".format(A, B))) res = self.findDuration(A, B, targetDuration) if len(res) != 0: return res # Move to find next overlap if B[start] <= A[start]: b += 1 else: a += 1 return res def overlaps(self, A, B): start, end = 0, 1 print(("Checking overlap: {0} and {1}".format(A, B))) # If any point B[start] or B[end] is in middle of A[start] --> A[end] then it's overlapping if A[start] <= B[start] <= A[end] or A[start] <= B[end] <= A[end]: return True return False def findDuration(self, A, B, targetDuration): start, end = 0, 1 print(("Checking duration {2} in overlap: {0} and {1}".format(A, B, targetDuration))) if B[end] >= A[start]: curDur = B[end] - A[start] if curDur >= targetDuration: # Bingo ! return [A[start], A[start]+targetDuration] elif A[end] >= B[start]: curDur = A[end] - B[start] if curDur >= targetDuration: # Bingo return [B[start], B[start]+targetDuration] return [] s = Solution() slotsA = [[10, 50], [60, 120], [140, 210]] slotsB = [[0, 15], [60, 70]] print(s.planner(slotsA, slotsB, 8)) slotsA = [[10, 50], [60, 120], [140, 210]] slotsB = [[0, 15], [60, 70]] print(s.planner(slotsA, slotsB, 12))
ea993d762ecccbaf00c838eecd5530604263057e
jigarshah2811/Python-Programming
/Algo-Backtracking-Recurssion/5_GraphColor.py
1,598
3.90625
4
class Solution: def graphColor(self, graph, V, numColors): def isSafe(curV, c): # Check if this color is not applied to any connection of V. for i in range(V): print(("Checking vertex: [0]".format(curV))) if graph[curV][i] and c == color[i]: # There is edge between curV and i, and that neighbour has same color return False return True def backtrack(curV): # 1) Base case: If all vertex are colored, then we found solution if curV == V: return True # 2) Breath ---> Possible moves are to select any from available colors for c in range(1, numColors+1): # 3) Check if it's safe to apply this color to vertex if isSafe(curV, c): # 4) Apply this color print(("vertex:[0] color:[1]".format(curV, c))) color[curV] = c # 5) Recursively apply available colors to next vertex if backtrack(curV+1): return True # 6) Backtrack: If we can't find solution recursively for all vertexes print(("Backtrack vertex:[0] color:[1]".format(curV, c))) color[curV] = 0 return False color = [0] * V backtrack(0) return color s = Solution() graph = [[0, 1, 1, 1], [1, 0, 1, 0], [1, 1, 0, 1], [1, 0, 1, 0]] print((s.graphColor(graph=graph, V=4, numColors=3)))
483184733d370d27c5b02dbaf2d578cac47f8701
jigarshah2811/Python-Programming
/7-DS-Heap/TopKFreq.py
1,699
3.78125
4
from typing import List import collections import heapq class Solution: """ DS: Freq Map Algorithm: Bucket Sort FreqMap {num: times} Bucket {times: [num1, num2, num3]} """ def topKFrequent(self, nums: List[str], k: int) -> List[str]: # Create Freq Map # {num: times} freqMap = collections.defaultdict(int) for num in nums: freqMap[num] += 1 print(freqMap) # Create FreqBucketMap # {times: [num1, num2, ...]} freqBucketMap = collections.defaultdict(list) for num, times in freqMap.items(): freqBucketMap[times].append(num) print(freqBucketMap) # Now freqMap buckets stores all freq, we are interested in high to low times topFreqList = [] for times in range(len(nums), -1, -1): # <----- Descending order of "frequency" listOfWords = freqBucketMap[times] # Same freq words should be in sorted order! sortedWords = sorted(listOfWords) topFreqList.extend(sortedWords) print(topFreqList) return topFreqList[:k] def topKWords(words, k=1): freqMap = collections.defaultdict(int) maxHeap = [] res = [] for word in words: freqMap[word] += 1 for word, freq in freqMap.items(): heapq.heappush(maxHeap, (-freq, word)) for i in range(k): (freq, word) = heapq.heappop(maxHeap) res.append(word) return res words = ["i","love","leetcode","i","love","coding"] res = topKWords(words, k=2) print(res) words = ["the","day","is","sunny","the","the","the","sunny","is","is"] res = topKWords(words, k=4) print(res)
f9e0bf6998f5ee9065ca8b27e56baa95907cb486
jigarshah2811/Python-Programming
/Advance-OOP-Threading/OOP/ClassObject.py
1,422
4.53125
5
""" This is valid, self takes up the arg! """ # class Robot: # def introduce(self): # print("My name is {}".format(self.name)) # # r1 = Robot() # r1.name = "Krups" # #r1.namee = "Krups" # Error: Because now self.name wouldn't be defined! # r1.introduce() # # r2 = Robot() # r2.name = "Pasi" # r2.introduce() """ OOP Class constructor """ class Robot: def __init__(self, name, color, weight): self.name, self.color, self.weight = name, color, weight def introduce(self): print("My name: {}, color: {}, weight: {}".format(self.name, self.color, self.weight)) r1 = Robot(name="Google", color="Pink", weight=10) r2 = Robot(name="Alexa", color="Purple", weight=60) r1.introduce() r2.introduce() class Person: def __init__(self, name, personality, isSitting=True): self.name, self.personality, self.isSitting = name, personality, isSitting def introduce(self): print("Person name: {}, personality: {}, isSitting: {}".format(self.name, self.personality, self.isSitting)) krups = Person(name="Krups", personality="Talkative", isSitting=False) pasi = Person(name="pasi", personality="Singing", isSitting=True) """ OOP: Relationship between objects """ krups.robot_owned = r1 # A class member can be defined "Run-Time"!. This will be self.robot_owned in "krups" object pasi.robot_owned = r2 krups.robot_owned.introduce() pasi.robot_owned.introduce()
082fb020db06e9d58f4ff9d06abe8fd3db745131
jigarshah2811/Python-Programming
/Algo-Backtracking-Recurssion/Recur_BackTracking_WordSearch_Matrix.py
1,733
3.734375
4
class Solution(object): def exist(self, board, word): ###### BACKTRACKING ########## # 1) Breath -->: Go through all cells in matrix for i in range(len(board)): for j in range(len(board[0])): # 2) isSafe --> Constraint: Word char match # 3) Depth ---> if self.DFS(board, word, i, j): # All word char matched from this cell return True return False def DFS(self, board, word, i, j): # Base case if len(word) == 0: # Everything from the word matched return True # 2) isSafe --> # OOB if i < 0 or j < 0 or i >= len(board) or j >= len(board[0]): # print "OOB {0}{1}".format(i,j) return False # Constraint: word char should match to this cell if board[i][j] != word[0]: # print "Don't match {0}{1}".format(i,j) return False # Most Imp DFS thing: Mark the cell visited to prevent visiting again!!! # 4) BackTracking # 4.1) Take a move tmp = board[i][j] board[i][j] = "#" # 4.2) See if recursively lead to solution res = self.DFS(board, word[1:], i, j + 1) or \ self.DFS(board, word[1:], i, j - 1) or \ self.DFS(board, word[1:], i - 1, j) or \ self.DFS(board, word[1:], i + 1, j) # 4.3) Backtrack board[i][j] = tmp return res board =[ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] s = Solution() print(s.exist(board, "ABCCED")) print(s.exist(board, "SEE")) print(s.exist(board, "ABCB")) board = [["a"]] print(s.exist(board, "a"))
30947d19e31e5d58137168d179d797d3f9c2a333
jigarshah2811/Python-Programming
/3-DS-Stack-Queue/IncreasingStack-LargestAreaRectangle.py
1,666
3.90625
4
def largestRect(hist): stack = list() maxArea = 0 # Go through the hist once i = 0 while i < len(hist): if (not stack) or (hist[i] >= hist[stack[-1]]): # Increasing sequence so keep adding indexes on stack stack.append(i) print(("Push index: {0}, currentEle: {1}, stackEle: {2}".format(i, hist[i], hist[stack[-1]]))) i += 1 else: top_of_stack = stack.pop() # Calc area #width = i - top_of_stack # MOST TRICKY to find the width width = abs(i - stack[-1] - 1) if stack else i height = hist[top_of_stack] area = height * width maxArea = max(maxArea, area) print(("Pop index: {0}, currentEle: {1}, stackEle: {2} MaxArea: {3}".format(top_of_stack, hist[i], hist[top_of_stack], maxArea))) # Remaining elements on stack print("Remaining...") while stack: top_of_stack = stack.pop() # Calc area width = abs(i - stack[-1] - 1) if stack else i height = hist[top_of_stack] area = height * width maxArea = max(maxArea, area) print(("Pop i: {0}, stackEle: {1}, MaxArea: {2}".format(top_of_stack, hist[top_of_stack], maxArea))) return maxArea hist = [2, 3, 4, 5, 3, 3, 1] #print ("Maximum rectangle area in histogram is: ", largestRect(hist)) hist = [2, 1, 2] #print ("Maximum rectangle area in histogram is: ", largestRect(hist)) hist = [5,4,1,2] #print ("Maximum rectangle area in histogram is: ", largestRect(hist)) hist = [4,2,0,3,2,5] print(("Maximum rectangle area in histogram is: ", largestRect(hist)))
f8290f38eb41af185b5ae229ea1fe60c9b887fc5
jigarshah2811/Python-Programming
/Pattern_BitManipulation_Sets/Bit_Manipulation.py
1,578
3.578125
4
class Solution(object): def countBits(self, value): count = 0 while value != 0: if value & 1: count = count + 1 value = value >> 1 return count def setBit(self, value, bitNum): value = value | (1 << bitNum) return value def resetBit(self, value, bitNum): value = value & ~(1 << bitNum) return value def flipBit(self, value, bitNum): if value & (1 << bitNum): result = self.resetBit(value, bitNum) else: result = self.setBit(value, bitNum) return result def findOddOccuringNumber(self, array): result = 0 for num in array: result = result ^ num return result def find2OddOccuringNumber(self, array): result = 0 for num in array: result = result ^ num return result def powerSet(self, array): powerSetSize = pow(2, len(array)) print(powerSetSize) powerSet = [] for counter in range(powerSetSize): subset = [] for bitPosition in range(len(array)): if counter & (1 << bitPosition): subset.append(array[bitPosition]) powerSet.append(subset) return powerSet s = Solution() print(s.countBits(5)) print(s.countBits(7)) print(s.countBits(8)) print(s.flipBit(5, 1)) print(s.findOddOccuringNumber([12, 12, 14, 90, 14, 14, 14])) """ https://www.geeksforgeeks.org/?p=588 """ QueSet = ['a', 'b', 'c'] print(s.powerSet(QueSet))
da82f9c03c227499e5f72a758513c8e71a1f43cd
jigarshah2811/Python-Programming
/Algo-Sorting-Searching/Array_BinarySearch.py
5,031
3.875
4
import collections import sys """ Regular Binday Search """ class Solution(object): def binsearch(self, nums, target): low, high = 0, len(nums)-1 while low < high: mid = (low + high) >> 1 if target == nums[mid]: # Check if target is HERE return mid # FOUND Target, Bingo elif target > nums[mid]: # Target is HIGHER? low = mid + 1 # Search on R -----> else: # Target is LOWER? high = mid - 1 # Search on <------- L return -1 def binsearch_nolen(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ low = 0 high = sys.maxsize while low <= high: mid = (low + (high - low)) >> 1 if target == nums[mid]: return mid elif target > nums[mid]: # Target must be on Right side low = mid + 1 else: # Target must be on left side high = mid return -1 """Tweaked Binday Search: If multiple values are same as target, return the lowest index instead of 1st hit in binary search """ def BinarySearch_LowestIndex(nums, target): low, high = 0, len(nums)-1 result = -1 # Not found by default while low < high: mid = (low + high) >> 1 if target == nums[mid]: # Trick: This can be one of the dup, we still want to find the first occurance result = mid high = mid - 1 # Keep searching on <------ L side elif target > nums[mid]: # Target is Higher, must be on R ---> side low = mid + 1 else: # Target is Lower, must be on <------ L side high = mid - 1 return result """ Follow Up: Can you write BS for Last Occurance? """ """ https://leetcode.com/problems/search-in-rotated-sorted-array Search in Rotated Sorted Array Example 1: Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4 Example 2: Input: nums = [4,5,6,7,0,1,2], target = 3 Output: -1 """ def BinarySearch_SortedRotatedArray(nums, target): low = 0 high = len(nums)-1 while low <= high: mid = (low + high) >> 1 if nums[mid] == target: return mid if nums[low] <= nums[mid]: # LEFT half is Sorted. Perform regular ops if nums[low] <= target <= nums[mid]: high = mid - 1 # <----- L Search Left Half else: low = mid + 1 # ----> R Search Right Half else: # RIGHT half is sorted. Perform regular ops but inverted if nums[mid] <= target <= nums[high]: low = mid + 1 else: high = mid - 1 return -1 def main(): """ a = [1, 3, 5, 6, 8, 10, 10, 10, 12] target = 10 result = BinarySearch(a, target) if result == -1: print "Value {0} Not found".format(target) else: print "Found {0} at location Index {1}".format(target, result) result = BinarySearch_LowestIndex(a, target) if result == -1: print "Value {0} Not found".format(target) else: print "Found {0} at location Index {1}".format(target, result) result = BinarySearch_HighestIndex(a, target) if result == -1: print "Value {0} Not found".format(target) else: print "Found {0} at location Index {1}".format(target, result) sumToFind = 14 low, high = FindPairWithSum(a, sumToFind, 0, len(a)-1) if low == -1 or high == -1: print "Sum {0} Not found".format(sumToFind) else: print "Sum {0} found at pair of index {1} and {2}".format(sumToFind, low, high) sumToFind = 16 for i in xrange(0, len(a)-1): low, high = FindPairWithSum(a, sumToFind-i, i, len(a)-1) if low != -1 and high != -1: print "Sum {0} found at index {1} {2}".format(sumToFind, low, high) index = BinarySearch_SortedRotatedArray([4, 5, 6, 7, 0, 1, 2, 3], 0) print "Index found: {0}".format(index) index = BinarySearch_SortedRotatedArray([4, 5, 6, 7, 0, 1, 2, 3], 7) print "Index found: {0}".format(index) index = BinarySearch_SortedRotatedArray([5 ,1, 3], 5) print "Index found: {0}".format(index) index = BinarySearch_SortedRotatedArray([5, 1, 3], 1) print "Index found: {0}".format(index) index = BinarySearch_SortedRotatedArray([5, 1, 3], 3) print "Index found: {0}".format(index) index = BinarySearch_SortedRotatedArray([5, 1, 3], 0) print "Index found: {0}".format(index) """ if __name__ == "__main__": s = Solution() nums = [-1,0,3,5,9,12] print(("Find 9, index: {0}".format(s.binsearch(nums, 9)))) nums = [5] print(("Find 5, index: {0}".format(s.binsearch(nums, 5))))
aef347e759278a90472b16dc638a64282aabb574
jigarshah2811/Python-Programming
/Stack_LargestRectangleInHistogram.py
3,616
3.640625
4
from STACK import Stack """ http://www.geeksforgeeks.org/largest-rectangle-under-histogram/ """ def LargestRectangleInHistogram(hist): s = Stack() i = 0 max_area = 0 # Scan through Histogram while i < len(hist): # Increasing ---> Current Hist > Prev Hist if s.isEmpty() or hist[i] >= hist[s.peek()]: s.push(i) # Decreased! ---> Current Hist < Prev Hist (Hisab lagavi do) else: # Pop hist till Decreasing stops while not s.isEmpty() and hist[s.peek()] > hist[i]: L = s.pop() height = hist[L] if s.isEmpty(): area = height * i else: area = height * (i - s.peek() - 1) max_area = max(max_area, area) s.push(i) i += 1 while not s.isEmpty(): L = s.pop() height = hist[L] area = height * (i - L - 1) max_area = max(max_area, area) return max_area """ Optimized version """ def LargestRectangleInHistogram_optimized(hist): s = Stack() max_area = 0 i = 0 # Scan through Histogram while i < len(hist): # Increasing ---> Current Hist > Prev Hist if s.isEmpty() or hist[i] >= hist[s.peek()]: s.push(i) i += 1 # Decreased! ---> Current Hist < Prev Hist (Hisab lagavi do) else: # Pop hist till Decreasing stops L = s.pop() # Calculate area if s.isEmpty(): current_area = hist[L] * i else: current_area = hist[L] * (i - s.peek() - 1) # Hisab for max area max_area = max(max_area, current_area) # Consider all remaining histogram while not s.isEmpty(): L = s.pop() # Calculate area if s.isEmpty(): current_area = hist[L] * i else: current_area = hist[L] * (i - s.peek() - 1) # Hisab for max area max_area = max(max_area, current_area) return max_area hist = [6, 2, 5, 4, 5, 1, 6] print LargestRectangleInHistogram(hist) print LargestRectangleInHistogram_optimized(hist) hist = [2, 1, 5, 6, 2, 3] print LargestRectangleInHistogram(hist) print LargestRectangleInHistogram_optimized(hist) """ Nearest Smaller Element Given an array, find the nearest smaller element G[i] for every element A[i] in the array such that the element has an index smaller than i. More formally, G[i] for an element A[i] = an element A[j] such that j is maximum possible AND j < i AND A[j] < A[i] Elements for which no smaller element exist, consider next smaller element as -1. Example: arr = [4, 5, 2, 10] result = [-1, 4, -1, 2] arr = [3, 2, 1] result = [-1, -1, -1] """ def Nearest_Smallest(arr): result = [-1] * len(arr) s = Stack() s.push(-1) # Scan through entire Array for index in xrange(len(arr)): # Nearest value is lesser ? Choose it if arr[index] > s.peek(): result[index] = s.peek() else: # Go till the prev nearest value that's lesser? Choose it while arr[index] > s.peek(): s.pop() result[index] = s.peek() # Get ready for next iteration s.push(arr[index]) return result arr = [4, 5, 2, 10] print Nearest_Smallest(arr) arr = [4, 5, 6, 1, 2] print Nearest_Smallest(arr) arr = [4, 2, 10, 6, 5] print Nearest_Smallest(arr) arr = [3, 2, 1] print Nearest_Smallest(arr) arr = [1, 3, 0, 2, 5] print Nearest_Smallest(arr)
67c3f537284076c7a52854c5d1dc7a58d99d908d
jigarshah2811/Python-Programming
/Algo-DP/DP_LCS.py
607
3.546875
4
""" http://www.geeksforgeeks.org/dynamic-programming-set-4-longest-common-subsequence/ """ def LCS(str1, str2): m = len(str1) n = len(str2) L = [[0]*50]*50 for i in range(len(str1)+1): for j in range(len(str2)+1): if i == 0 or j == 0: L[i][j] = 0 elif str1[i-1] == str2[j-1]: # MATCH L[i][j] = 1 + L[i-1][j-1] # = 1 + diagonal else: L[i][j] = max(L[i-1][j], L[i][j-1]) # No Match = max match from prior row or col print(L[m][n]) str1 = "ABCDGH" str2 = "AEDFHR" LCS(str1, str2)
8fe0bcd0540ab6b12b3db8f6fa0619f218f0d89b
jigarshah2811/Python-Programming
/Hash_Last2ShortestStrings.py
670
3.828125
4
k = 3 mydict = {} def insert(str): global k global mydict try: mydict[len(str)] = mydict[len(str)].append(str) except KeyError: mydict[len(str)] = [str] sortedKeys = sorted(mydict.iterkeys()) # mydict = sorted(mydict, key=lambda item: item[0], reverse=True) inserted = 0 for key in sortedKeys: if inserted > k: del mydict[key] else: inserted += 1 continue def lookup(k): global mydict for key, val in mydict.items(): print val insert("That is") insert("nothing") insert("Compare to") insert("What I have gone through") insert("This") lookup(3)
923c91352c1941344adada6d21014b06ce7add3d
jigarshah2811/Python-Programming
/8-DS-Design/DS_bloom_filter.py
960
3.71875
4
""" Space efficient probablistic DS for membership testing Google uses it before Map Reduce """ from random import seed, sample class BloomFilter(object): def __init__(self, iterable=(), population=56, probes=6): self.population = range(population) self.probes = probes self.data = set() for name in iterable: self.add(name) def add(self, name): seed(name) lucky = sample(self.population, self.probes) print(lucky) self.data.update(lucky) def __contains__(self, name): seed(name) lucky = sample(self.population, self.probes) return set(lucky).issubset(self.data) #return set(lucky) <= self.data if __name__ == "__main__": names = 'raymond rachel matthew ramon gayle dennis sharon' hettingers = BloomFilter(names, population=100, probes=10) for name in names.split(): hettingers.add(name) print('rachel' in hettingers) print('Jigar' in hettingers)
2949f87f4092c51a398b8a3081bb45a42b010432
jigarshah2811/Python-Programming
/Pattern-2-Pointers/2.MultiPassPattern-ProductExceptSelf.py
2,519
3.734375
4
from math import prod from typing import List """ Pattern: Multi-Pass L -----> & <------- R L = Prefix L Running Multiplier R = Suffix R Running Multiplier Result = Multiplier of (Prefix L * Suffix R) Next Q: Trapping Rain Water! """ class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: N = len(nums) L, R, res = [1]*N, [1]*N, [1]*N # L -----> Traverse front # Left Product at i is: Prefix product of i-1 * previous num for i in range(1, N): L[i] = L[i-1] * nums[i-1] # <---------R Traverse back # Right Product at i is: Prefix product until i+1 * previous num for i in range(N-2, -1, -1): R[i] = R[i+1] * nums[i+1] # L[i] has product of all numbers till i # R[i] has product of all numbers till i # Result is simply L[i] (prefix product of all L) * R[i] (prefix product of all R) for i in range(N): res[i] = L[i] * R[i] return res def productExceptSelfOptimized(self, nums: List[int]) -> List[int]: """ Optimized version O(1) space L ----> Result while R <------- """ N = len(nums) res = [1]*N # L -----> Traverse front # Left Product at i is: Prefix product of i-1 * previous num for i in range(1, N): res[i] = res[i-1] * nums[i-1] print(res) # <---------R Traverse back # Right Product at i is: Prefix product until i+1 * previous num rMax = 1 for i in range(N-1, -1, -1): # Result at i is: L prefix product till now (res[i]) * Right prefix product till now (rMax) res[i] = res[i] * rMax # Update max R prefix product to carry forward rMax = rMax * nums[i] print(res[i], rMax) return res def productExceptSum(nums): N = len(nums) # ----> L Prefix L = [1] * N for i in range(1, N): L[i] = L[i-1] * nums[i-1] print(f"Left: {L}") # <---- R Prefix RMul = 1 # Total res = [1] * N for i in range(N-1, -1, -1): # Res here is the LeftPrefix * RightPrefix res[i] = L[i] * RMul # RightPrefix is now ThisNum*LastRightPrefix RMul = nums[i] * RMul return res nums = [8, 10, 2] print(productExceptSum(nums)) # [20, 16, 80] nums = [2, 7, 3, 4] print(productExceptSum(nums)) # [84, 24, 56, 42] nums = [4, 5, 1, 8, 2] print(productExceptSum(nums)) # [80, 64, 320, 40, 160]
6bbd0b28467b15d9d3d5103b41375d6c79999f6c
brunda4/Trees-1
/solution41.py
1,036
3.59375
4
class Solution: prev=None #initializing the global variabe prev to hold the previous node def isValidBST(self, root: TreeNode) -> bool: return self.inorder(root) #caling the inorder function for root def inorder(self,root:TreeNode)->bool: if root==None: # if the root is Null node return True return True if (self.inorder(root.left)==False): #if the inorder of left subtree s false return false return False if(self.prev!=None and self.prev.val>=root.val): # if the previous node is not empty and its value is greater than current node value return False #return False self.prev=root #update the previous node return self.inorder(root.right) #return the boolean value after checking the right subtree
b510a87a4c15901bfb22b5568623d78be1a35d6d
EFulmer/sorts_of_sorts
/merge_sort.py
895
4.0625
4
# Standard merge sort, done in Python as an exercise. from math import floor from random import shuffle def merge_sort(ls): if len(ls) <= 1: return ls # in smaller arrays, it'd be better to do insertion sort to reduce overhead mid = int(floor(len(ls)/2)) left = merge_sort(ls[0:mid]) right = merge_sort(ls[mid:]) return merge(left, right) def merge(a, b): c = [] i = 0 j = 0 while i < len(a) and j < len(b): if a[i] <= b[j]: c.append(a[i]) i = i + 1 else: c.append(b[j]) j = j + 1 if i < len(a): c.extend(a[i:]) else: c.extend(b[j:]) return c def main(): print 'Test of merge sort:' lst = [x for x in range(10)] shuffle(lst) print 'Input:', lst lst = merge_sort(lst) print 'Output:', lst if __name__ == '__main__': main()
28a8e6ee2b125056cfe0c3056d6e3a92ba5e4a65
sabeeh99/Batch-2
/fathima_ashref.py
289
4.28125
4
# FathimaAshref-2-HelloWorldAnimation import time def animation(word): """this function takes the input and displays it character by character with a delay of 1 second""" for i in word: time.sleep(1) print(i, end="") animation("Hello World")
7fa5ac027e065348e292847aa7b03933fc57bef0
Andriy-Hladkiy/ITEA_Python_Basic
/topic_1/task_4.py
213
3.828125
4
# Напишите программу, которая сортирует заданный список из чисел list = ['topic_1', '23', '435', '143', 'topic_2', 'topic_1'] print(sorted(list, key = int))
56a57411d7f44b8a7c15b69fcbf11ac3001f3ab4
hanucane/dojo
/Bootcamp/bootcamp-python/python_algorithm/lambda.py
245
3.96875
4
def map(list, function): for i in range(len(list)): list[i] = function(list[i]) return list print( map([1,2,3,4], (lambda num: num*num) )) print( map([1,2,3,4], (lambda num: num*3) )) print( map([1,2,3,4], (lambda num: num%2) ))
1fda8b3fd2d9f8aa385c9f365ae983fde0bc711a
hanucane/dojo
/Bootcamp/bootcamp-algorithms/linked-lists/SLists.py
1,353
3.625
4
class Node: def __init__(self, value): self.value = value self.next = None self.prev = None class SList: def __init__(self, value): node = Node(value) self.head = node def printAllValues(self): runner = self.head while runner.next != None: print(id(runner), runner.value, id(runner.next)) runner = runner.next print(id(runner), runner.value, id(runner.next)) def addNode(self, value): node = Node(value) runner = self.head while runner.next != None: runner = runner.next runner.next = node def removeNode(self, value): runner = self.head prev = None if runner != None: if runner.value == value: self.head = runner.next runner = None return while runner != None: if runner.value == value: break prev = runner runner = runner.next if runner == None: return prev.next = runner.next runner = None slist = SList(5) slist.addNode(7) slist.addNode(3) slist.addNode(8) slist.printAllValues() slist.removeNode(7) slist.removeNode(5) slist.printAllValues() slist.addNode(10) slist.addNode(2) slist.printAllValues()
d2f96447565c188fcc5fb24a24254dc68a2f5b60
hanucane/dojo
/Online_Academy/python-intro/datatypes.py
763
4.3125
4
# 4 basic data types # print "hello world" # Strings # print 4 - 3 # Integers # print True, False # Booleans # print 4.2 # Floats # print type("hello world") # Identify data type # print type(1) # print type(True) # print type(4.2) # Variables name = "eric" # print name myFavoriteInt = 8 myBool = True myFloat = 4.2 # print myFavoriteInt # print myBool # print myFloat # Objects # list => array (referred to as list in Python) # len() shows the length of the variable / object myList = [ name, myFavoriteInt, myBool, myFloat, [myBool, myFavoriteInt, myFloat] ] print len(myList) # Dictionary myDictionary = { "name": "Eric", "title": "Entrepenuer", "hasCar": True, "favoriteNumber": 8 } print myDictionary["name"]
cdb6fb12e74cffd7dce421a4edd389d02d2b4523
haalogen/hash_table
/func.py
2,197
3.703125
4
"""Basic functionality of the project "Hash_Table".""" def float2hash(f): """Float value to hash (int)""" s = str(f) n_hash = 0 for ch in s: if ch.isdigit(): n_hash = (n_hash << 5) + n_hash + ord(ch) # print ch, n_hash return n_hash class HashTable(object): def __init__(self, q_probe=False , sz=101): self.size = sz self.slots = [None] * self.size # False <-> linear probing # True <-> quadratic probing self.quad_probe = q_probe def __repr__(self): return str(self.slots) def hash_function(self, key): return float2hash(key) % self.size def rehash(self, oldhash, iteration): n_hash = 0 if self.quad_probe: # do quadratic probing rehash n_hash = (oldhash + iteration**2) % self.size print 'rehash_qua:', n_hash else: # do linear probing rehash n_hash = (oldhash + iteration) % self.size print 'rehash_lin: ', n_hash # raw_input() return n_hash def put(self, key): collis_cnt = 0 hashvalue = self.hash_function(key) if self.slots[hashvalue] == None: self.slots[hashvalue] = key else: if self.slots[hashvalue] == key: pass # do nothing else: iter_cnt = 1 first_hash = hashvalue nextslot = self.rehash(first_hash, iter_cnt) # looking for our key or empty slot while self.slots[nextslot] != None and \ self.slots[nextslot] != key and iter_cnt <= self.size: iter_cnt += 1 nextslot = self.rehash(first_hash, iter_cnt) collis_cnt = iter_cnt if self.slots[nextslot] == None: self.slots[nextslot] = key # else <-> self.slots[nextslot] == key => do nothing return collis_cnt
eb392b54023303e56d23b76a464539b70f8ee6e8
shamim-ahmed/udemy-python-masterclass
/section-4/examples/guessinggame6.py
507
4.1875
4
#!/usr/bin/env python import random highest = 10 answer = random.randint(1, highest) is_done = False while not is_done: # obtain user input guess = int(input("Please enter a number between 1 and {}: ".format(highest))) if guess == answer: is_done = True print("Well done! The correct answer is {}".format(answer)) else: suggestion = "Please guess higher" if guess < answer else "Please guess lower" print(f"Sorry, your guess is incorrect. {suggestion}")
7a3191f98809ba4587415bae2f7f638446c5d8c6
shamim-ahmed/udemy-python-masterclass
/section-12/examples/condcomp1.py
1,472
3.8125
4
#!/usr/bin/env python menu = [ ["egg", "spam", "bacon"], ["egg", "sausage", "bacon"], ["egg", "spam"], ["egg", "bacon", "spam"], ["egg", "bacon", "sausage", "spam"], ["spam", "bacon", "sausage", "spam"], ["spam", "egg", "spam", "spam", "bacon", "spam"], ["spam", "egg", "sausage", "spam"], ["chicken", "chips"] ] for meal in menu: print(meal, "contains sausage" if "sausage" in meal else "contains bacon" if "bacon" in meal else "contins egg") print() items = set() for meal in menu: for item in meal: items.add(item) print(items) print() menu = [ ["egg", "spam", "bacon"], ["egg", "sausage", "bacon"], ["egg", "spam"], ["egg", "bacon", "spam"], ["egg", "bacon", "sausage", "spam"], ["spam", "bacon", "sausage", "spam"], ["spam", "egg", "spam", "spam", "bacon", "spam"], ["spam", "egg", "sausage", "spam"], ["chicken", "chips"] ] result1 = [] for meal in menu: if "spam" not in meal: result1.append(meal) else: print("A meal was skipped") print(result1) print() result2 = [meal for meal in menu if "spam" not in meal and "chicken" not in meal] print(result2) print() result3 = [meal for meal in menu if "spam" in meal or "egg" in meal if not "bacon" in meal and "sausage" in meal] print(result3) print() result4 = [meal for meal in menu if ("spam" in meal or "egg" in meal) and ("bacon" not in meal and "sausage" in meal)] print(result4) print()
3d1946247a3518c4bd2128786609946be2ae768c
shamim-ahmed/udemy-python-masterclass
/section-4/exercises/exercise11.py
638
4.21875
4
#!/usr/bin/env python3 def print_option_menu(options): print("Please choose your option from the list below:\n") for i, option in enumerate(options): print("{}. {}".format(i, option)) print() if __name__ == "__main__": options = ["Exit", "Learn Python", "Learn Java", "Go swimming", "Have dinner", "Go to bed"] print_option_menu(options) done = False while not done: choice = int(input()) if choice == 0: done = True elif 0 < choice < len(options): print("You have entered {}".format(choice)) else: print_option_menu(options)
f9610b35b3785f1cd0b5a7ae4f00e2cd9856034a
shamim-ahmed/udemy-python-masterclass
/section-4/examples/strings3.py
279
4.0625
4
#!/usr/bin/env python number = "9,223;372:036 854,775;807" separators = "" for c in number: if not c.isnumeric(): separators += c print(separators) values = "".join([c if c not in separators else " " for c in number]).split() print([int(val) for val in values])
75f04b946796c071f7913bf308f0bf1c40a4c441
shamim-ahmed/udemy-python-masterclass
/section-4/examples/conditions.py
135
4.15625
4
#!/usr/bin/env python3 age = int(input("Please enter your age: ")) if age >= 16 and age <= 65: print("Have a good day at work!")