blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
476b041ca6f300773a1342f16ba45511a00290b5
piecesofreg09/DSA
/Course_1/W4/6_closest_points/closest.py
4,374
3.5
4
#Uses python3 import sys import math #import random #import time def minimum_distance_naive(x, y): d_min = float('Inf') for i in range(len(x)): for j in range(i + 1, len(x)): t = (x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j]) d_min = min(t, d_min) return d_min def binary_left(x, low, high, mid_point, d): # high is exclusive if high - low == 1: return low mid = low + (high - low) // 2 if mid_point - x[mid] > d: return binary_left(x, mid, high, med, d) else: if mid == low or (mid_point - x[mid - 1]) > d: return mid else: return binary_left(x, low, mid, mid_point, d) def minimum_distance(x, y): #write your code here if len(x) == 1: return float('Inf') elif len(x) == 2: xd = x[0] - x[1] yd = y[0] - y[1] return xd * xd + yd * yd else: med = len(x) // 2 d1 = minimum_distance(x[:med], y[:med]) d2 = minimum_distance(x[med:], y[med:]) d = min(d1, d2) mid_point = (x[med - 1] + x[med]) / 2 i = med - 1 while i > -1 and (mid_point - x[i]) <= math.sqrt(d): i -= 1 j = med while j < len(x) and (x[j] - mid_point) <= math.sqrt(d): j += 1 #print(str(i) + ' ' + str(med) + ' ' + str(j)) temp2sort = list(zip(x[(i + 1):j], y[(i + 1):j])) temp2sort.sort(key=lambda cor: cor[1]) d_min_temp = float('Inf') if len(temp2sort) > 0: x_temp, y_temp = list(zip(*temp2sort)) for y_i in range(0, len(x_temp)): for y_i_seven in range(y_i + 1, min(y_i + 8, len(x_temp))): xd = x_temp[y_i] - x_temp[y_i_seven] yd = y_temp[y_i] - y_temp[y_i_seven] t = (xd) * (xd) + (yd) * (yd) d_min_temp = min(t, d_min_temp) return min(d, d_min_temp) if __name__ == '__main__': input = sys.stdin.read() data = list(map(int, input.split())) n = data[0] x = data[1::2] y = data[2::2] sorted_res = sorted(list(zip(x, y)), key=lambda x: (x[0], x[1])) x, y = zip(*sorted_res) x = list(x) y = list(y) print("{0:.15f}".format(math.sqrt(minimum_distance(x, y)))) ''' #x = [random.randrange(-100000, 900000) for i in range(n)] for rpt in range(50): x = [0] * n x = [random.randrange(-100, 100) for i in range(n)] y = [random.randrange(-100, 100) for i in range(n)] t1 = time.time() sorted_res = sorted(list(zip(x, y)), key=lambda x: (x[0], x[1])) x, y = zip(*sorted_res) x = list(x) y = list(y) #print(time.time() - t1) t2 = time.time() res1 = math.sqrt(minimum_distance(x, y)) #print("{0:.9f}".format(res1)) #print(time.time() - t2) t3 = time.time() res2 = math.sqrt(minimum_distance_naive(x, y)) #print("{0:.9f}".format(res2)) #print(time.time() - t3) if abs(res1 - res2) > 1e-6: print('Not Pass in case ' + str(i)) else: print('Pass') ''' # test for constant ''' for n in [1000, 2000, 3000, 5000, 8000, 10000, 20000, 40000, 80000, 100000]: t = [] sz = 5 for ttt in range(sz): x = [random.randrange(-1000000000, 1000000000) for i in range(n)] y = [random.randrange(-1000000000, 1000000000) for i in range(n)] t1 = time.time() sorted_res = sorted(list(zip(x, y)), key=lambda x: (x[0], x[1])) x, y = zip(*sorted_res) x = list(x) y = list(y) #print(time.time() - t1) t2 = time.time() print("{0:.9f}".format(math.sqrt(minimum_distance(x, y)))) t.append(time.time() - t2) print('constant is') print(sum(t) / sz / n / math.log(n) / math.log(n)) #t3 = time.time() #print("{0:.9f}".format(math.sqrt(minimum_distance_naive(x, y)))) #print(time.time() - t3) '''
ec8462176e244bddfbf830a9d3af69940eb7f5ec
kaskrex/pythonexercises
/Python Files/dog.py
99
3.65625
4
def dogcal (age): hum = age * 7 return hum age = int(input("Dog age?")) print(dogcal(age))
a9b00824405fbac7d0059a4a9bcc2fea6871340f
dimivas/tictactoe
/players/tictactoe_computer_naive.py
7,105
3.703125
4
""" The implementation of the Tic-Tac-Toe player component using a naive version of Q-Learning """ from __future__ import print_function import random from .abstract_tictactoe_player import AbstractTicTacToePlayer class TicTacToeComputerNaive(AbstractTicTacToePlayer): """ The implementation of the Tic-Tac-Toe player component using a naive version of Q-Learning """ INITIAL_STATE_VALUE = 0.5 COM_WIN_REWARD = 1.0 COM_LOSS_PENALTY = 0.0 DRAW_REWARD = 0.5 COM_PLAYER_ID = 1 OPPONENT_PLAYER_ID = 2 def __init__(self, epsilon=1.0, epsilon_decay_step=10e-5): """ Constructor @param epsilon: the epsilon parameter (randomness of the next move) of Q-Learning algorithm [0, 1] @param epsilon_decay_step: the decay factor for updating the epsilon parameter [0, 1] """ self.epsilon = epsilon self.epsilon_decay_step = epsilon_decay_step self.q_values = {} self.game_moves_history = [] self.player_id = None def __encode_state(self, game_state): """ Transforms the 2D list game state into an internal representation @param game_state: a 2D list with the game state given by the game engine @return: a (flatten) list with the internal representation of the game engine """ flatten_list = list(item for sublist in game_state for item in sublist) encoded_state = tuple(map(self.__map_player_id, flatten_list)) return encoded_state def __get_free_seats(self, game_state): """ Get the available (free) seats @param game_state: a 2D list with the game state @return: a list with the set of the available seats. Each seat is a tuple with the x and y values. """ free_seats = [] for i in range(len(game_state)): for j in range(len(game_state[i])): if not game_state[i][j]: free_seats.append((i, j)) return tuple(free_seats) def __get_next_greedy_move(self, game_state): """ Get the next move based on a greedy algorithm and the Q-Values @param game_state: a 2D list with the game state @return: a list with the x and y values of the selected seat """ best_move = None best_score = None for free_seat in self.__get_free_seats(game_state): next_game_state_score = self.__get_score(game_state, free_seat) if best_score is None: best_score = next_game_state_score best_move = free_seat continue if next_game_state_score > best_score: best_score = next_game_state_score best_move = free_seat return best_move def __get_next_random_move(self, game_state): """ Get the next move based on a random selection @param game_state: a 2D list with the game state @return: a list with the x and y values of the selected seat """ return random.choice(self.__get_free_seats(game_state)) def __get_score(self, game_state, move): """ Get the Q-Value of the move @param game_state: a 2D list with the game state @move: a list with the x and y values of the selected move @return: the Q-Value """ return self.q_values[self.__encode_state(game_state)][move][0] def __init_q_values(self, game_state): """ Initialize the Q-Values for the current game state and the next possible game states, based on the available seats @param game_state: a 2D list with the game state """ encoded_game_state = self.__encode_state(game_state) if encoded_game_state in self.q_values: return self.q_values[encoded_game_state] = {} for free_seat in self.__get_free_seats(game_state): self.q_values[encoded_game_state][free_seat] = (self.INITIAL_STATE_VALUE, 0) def __map_player_id(self, seat): """ Maps the symbol given by the game engine to an internal notation @param value: the value of the seat (symbol) @return: the mapped value """ internal_player_id = None if seat: if seat == self.player_id: internal_player_id = self.COM_PLAYER_ID else: internal_player_id = self.OPPONENT_PLAYER_ID return internal_player_id def __reset(self): """ Reset state of the object """ self.game_moves_history = [] self.player_id = None def __update_epsilon(self): """ Update epsilon parameter """ self.epsilon *= (1 - self.epsilon_decay_step) def __update_q_values(self, reward): """ Update Q-Values @param reward: the reward for all moves taken during the game """ for encoded_game_state, move in self.game_moves_history: value, times_passed = self.q_values[encoded_game_state][move] new_value = (value * times_passed + float(reward)) / (times_passed + 1) self.q_values[encoded_game_state][move] = (new_value, times_passed + 1) def end_of_game(self, winning_player_id): """ End of game. Update Q-Values and reset the game state @param winning_player_id: the winning player ID (symbol), given by the game engine """ reward = self.DRAW_REWARD if winning_player_id == self.player_id: reward = self.COM_WIN_REWARD elif winning_player_id: reward = self.COM_LOSS_PENALTY self.__update_q_values(reward) self.__reset() def get_next_move(self, game_state): """ Get the next move @param game_state: the current game state given by the game engine @return: a list with the x and y values of the selected seat """ next_move = None encoded_game_state = self.__encode_state(game_state) self.__init_q_values(game_state) if random.random() < self.epsilon: next_move = self.__get_next_random_move(game_state) self.__update_epsilon() else: next_move = self.__get_next_greedy_move(game_state) self.game_moves_history.append((encoded_game_state, next_move)) return next_move def get_q_values_from_other_com(self, other_player): """ Merges the learned Q-Values taken by an other instance of the player @param com_player: instance of the other player """ for game_state in other_player.q_values: if game_state not in self.q_values: self.q_values[game_state] = other_player.q_values[game_state] def set_player_id(self, player_id): """ Set the player's symbol in game @param player_id: the symbol used by the player """ self.player_id = player_id
897d10034ad4e41e4c183ca730d33144caeadb08
AggarwalAnshul/Dynamic-Programming
/InterviewBit/Strings/add-binary-strings.py
1,455
3.90625
4
""" Given two binary strings, return their sum (also a binary string). Example: a = "100" b = "11" Return a + b = “111”. [+]Temporal marker : Mon, 13:12 | Feb 17, 20 [+]Temporal marker untethered: Mon, 13:25 | Feb 17, 20 [+]Comments : EASY [+]Space Complexity : O(N) [+]Time Complexity : O(N) [+]Level : EASY [+]Tread Speed : PACED [+]LINK : https://www.interviewbit.com/problems/add-binary-strings [+] Supplement Sources : N/A """ def findSolution(one, two): if len(one) < len(two): return findSolution(two, one) # Equate the length of the string length_one = len(one) length_two = len(two) offset = length_one - length_two while offset > 0: two = "0" + two offset -= 1 flag = 0 ans = "" # add the numbers for i in range(length_one - 1, -1, -1): charOne = int(one[i]) charTwo = int(two[i]) add = charOne + charTwo + flag flag = 0 if add < 2: ans = str(add) + ans else: flag = 1 if add == 2: ans = "0" + ans else: ans = "1" + ans if flag == 1: return "1" + ans return ans if __name__ == "__main__": data = [["1111", "1"]] for x in data: print("data: " + str(x) + " >> " + str(print(findSolution(x[0], x[1]))))
3a11f2858cb592ee6905101eb150b4bb03a53564
nmortha/HacktoberFest2019
/src/sum/sum.py
300
4.1875
4
#!/usr/bin/env python num1=(input('Enter number1 to calculated sum of two munmbers: ')) num2=(input('Enter number2 to calculated sum of two munmbers: ')) print ('Enterted Numbers are : '+ num1 + " ,"+ num2) total=int(num1)+int(num2) print('Sum of 2 numbers '+ num1+ ','+ num2 + ' is :', total)
6d972eb7fa93e7e5a34edf81ffdf6c1c19de9492
f-fathurrahman/ffr-MetodeNumerik
/chapra_7th/ch04/chapra_example_4_4.py
708
3.859375
4
def f(x): return -0.1*x**4 - 0.15*x**3 - 0.5*x**2 - 0.25*x + 1.25 def df(x): return -0.4*x**3 - 0.45*x**2 - x - 0.25 x = 0.5 h = 0.5 #h = 0.25 true_val = df(x) print("true_val = ", true_val) print("h = ", h) # Forward diff approx_val = ( f(x+h) - f(x) )/h print("Using forward diff: ", approx_val) print("ε_t (in percent) = ", (true_val - approx_val)/true_val*100) # Backward diff approx_val = ( f(x) - f(x-h) )/h print("Using backward diff: ", approx_val) print("ε_t (in percent) = ", (true_val - approx_val)/true_val*100) # Centered diff approx_val = ( f(x+h) - f(x-h) )/(2*h) print("Using centered diff: ", approx_val) print("ε_t (in percent) = ", (true_val - approx_val)/true_val*100)
86aa1aab9ba6df46ccdf85dc30c58c19e980ca25
ThaiSonNguyenTl/NguyenThaiSon-Lab-c4e24
/lab3/calculate.py
272
3.78125
4
a = int(input("Enter a:")) b = int(input("Enter b:")) from calc import evaluate # print() # if ptoan == "+": # n = a + b # elif ptoan == "-": # n = a - b # elif ptoan == "*": # n =a*b # else: # n =a/b pt = input("pt: ") n = evaluate(a,b,pt ) print(n)
6c6571d242844e89b80cabb238833b36a4161d8f
GingerLee11/ATBS_ed2_projects
/collatz_sequence.py
793
4.34375
4
# -*- coding: utf-8 -*- """ Created on Sat Jun 19 12:21:15 2021 @author: Cleme """ #! python3 # collatz.py - Number is evaluated as odd or even and is then evaluated # down to one import sys # Define the collatz sequence def collatz(number): if number % 2 == 0: print(number // 2) return number // 2 elif number % 1 == 0: result = 3 * number + 1 print(result) return result else: print('Something went wrong, please type in a different number.') n = int(input('Please type in a number:\n')) try: while n != 1: n = collatz(n) except KeyboardInterrupt: print('Something went wrong. Please try again.') sys.exit()
643357c540c2ababe9acd4d6565269fbfcb19325
yangke928/connect-four-gameboard
/project/point.py
2,042
3.609375
4
'''Ke Yang cs5001 Project April 1st ''' class Point: '''Class Point Attributes: point_red, point_yellow Methods: add_point_red, add_point_yellow, add_point_yellow initialie_point_red, initialie_point_yellow ''' def __init__(self): ''' Constructor -- creates new instance of point Parameters: self -- the current object ''' self.point_red = 0 self.point_yellow = 0 def add_point_red(self): ''' Method -- red player add one point Parameters: self -- the current object ''' self.point_red += 1 def add_point_yellow(self): ''' Method -- yellow player add one point Parameters: self -- the current object ''' self.point_yellow += 1 def initialie_point_red(self, filename): ''' Method -- get the red player's point as an int in a file Parameters: self -- the current object filename -- the name of the red score file ''' try: with open (filename, "r") as infile: information = infile.read() if not information: self.point_red = 0 else: self.point_red = int(information) except OSError: self.point_red = 0 def initialie_point_yellow(self, filename): ''' Method -- get the red player's point as an int in a file Parameters: self -- the current object filename -- the name of the yellow score file ''' try: with open (filename, "r") as infile: information = infile.read() if not information: self.point_yellow = 0 else: self.point_yellow = int(information) except OSError: self.point_yellow = 0
83539941e3d6b2ce784c660d28427fc278a7b91f
Zain1298/Python-Matplotlib
/Python-Matplotlib/Piechart.py
306
3.578125
4
from matplotlib import pyplot as plt numbers = [15,35,25,12.5,12.5] subjects = ['English','Maths','Physics','Chemistry','Urdu'] cols = ['r','g','b','m','c'] plt.pie (numbers, labels=subjects, colors=cols, startangle=90, shadow=True,explode=(0,0.1,0,0,0),autopct='%0.1f%%') plt.title('Pie Plot') plt.show()
fadfd54e5684ffb9f2b545feea8fa8bc259f2c7b
greatjunekim/py
/조건 판정문 (만약에~라면)/WhatsMyGrade.py
127
3.609375
4
점수 = eval(input("점수를 입력")) if 점수 == 100: print("A+") if 점수 <= 90: print("A") elif: print("")
1f4f63fbd57e2a865f75f48e28f60588bde674fa
spiroxide/COMP-17100
/Flippers/Flippers.py
407
3.640625
4
from random import * def coinFlip(): return randint(1, 2) == 1 def flipper1(): heads = 0 for i in range(100): if coinFlip(): heads += 1 return heads def flipper2(): flips = 0 heads = 0 while heads < 50: flips += 1 if coinFlip(): heads += 1 return flips def main(): print(flipper1()) print(flipper2()) main()
b25ef2140bd3725b44cca58d9769fa0a98909fcb
ravalrupalj/BrainTeasers
/Edabit/Day 1.4.py
403
4.125
4
#Find the Index (Part 1) #Create a function that finds the index of a given item. #search([1, 5, 3], 5) ➞ 1 #search([9, 8, 3], 3) ➞ 2 #search([1, 2, 3], 4) ➞ -1 #If the item is not present, return -1. def search(lst, item): if item in lst: return lst.index(item) else: return -1 print(search([1, 5, 3], 5) ) print(search([9, 8, 3], 3) ) print(search([1, 2, 3], 4))
804f12562d380abaea2d1af8611fa8b5fbfa9d76
athitf56/CP3-Arthit-Sankok
/Lecture71_Arthit_S.py
593
3.796875
4
menulist = [] menuprice = [] def showBill(): Count = 0 print("---ThitShop---") for number in range(len(menulist)): print(menulist[number], menuprice[number]) Count += menuprice[number] print("Total =", Count, "Bath") while True : menuName = input("กรุณาใส่ชื่อเมนู : ") if(menuName.lower() == "exit" ): break else: menuPrice = int(input("กรุณาใส่ราคาเมนู : ")) menulist.append(menuName) menuprice.append(menuPrice) showBill()
1ba65e2ce177744d171d59335ad3bf84be476490
gheorghecr/Course-Work-Programming-Algorithms-and-Data-Structures-Module
/CourseWork/Exercise1And2/binaryTree_test.py
2,152
3.8125
4
import unittest import sys from binaryTree import BinaryTree #To complete the exercise I based my self on some tutorials and information such as: """Title: *args and **kwargs in python explained Author: Yasoob Date: 2013 Availability: https://pythontips.com/2013/08/04/args-and-kwargs-in-python-explained/ Title: Python Tutorial: Unit Testing Your Code with the unittest Module Author: Corey Schafer Date: 2017 Availability: https://www.youtube.com/watch?v=6tNS--WetLI&t=1986s Title: Binary search tree in Python with simple unit tests. Author: Chinmaya Patanaik Date: 2016 Availability: http://chinmayakrpatanaik.com/2016/06/01/Binary-Search-Tree-Python/ Title: unittest — Unit testing framework Author: Python Docs Date: n.d. Availability: https://docs.python.org/2/library/unittest.html Title: Working with the Python Super Function Author: PythonForBeginners Date: 2017 Availability: https://www.pythonforbeginners.com/super/working-python-super-function Title: Document that unittest.TestCase.__init__ is called once per test Author: Python Bug Tracker, Claudiu Popa Date: 2013 Availability: https://bugs.python.org/issue19950 """ class TestBinarySearchTree(unittest.TestCase): def __init__(self, *args, **kwargs): #init method is inialized for each time that a test is run super(TestBinarySearchTree, self).__init__(*args, **kwargs) self.word = "hey" self.binaryTree = BinaryTree(self.word) self.words = [ "this", "is", "my", "exercise"] for word in self.words: self.binaryTree.insert_value(word) def test_search(self): x, path = self.binaryTree.find_word("this") self.assertEqual(x, True) x, path = self.binaryTree.find_word("not") self.assertEqual(x, False) def test_delete(self): self.binaryTree.delete_node("is") x, path = self.binaryTree.find_word("is") self.assertFalse(x) def test_pre_order(self): print("Pre order Print") self.binaryTree.print_pre_order() if __name__ == '__main__': unittest.main()
74c0406fc6b11c2ce4cfc144e71d688c9b73718f
infiniteoverflow/Student-Information-Analysis
/screens/tk.py
291
3.78125
4
from tkinter import * root = Tk() root.geometry("500x500+0+0") startbutton = Button(root, text="Start",height=1,width=4) startbutton.place(relx=0.5, rely=0.5, anchor=CENTER) #Configure the row/col of our frame and root window to be resizable and fill all available space root.mainloop()
a0a1035464453e65ab385229220183141c50a7c4
Comvislab/Deep-Learning-Fundementals
/Simple Linear Regression/simplelinearregression.py
2,451
3.921875
4
#THIS CODE IS MODIFIED VERSION of # My STUDENT ISMET EMIR DEMIR(180315070) # # Objective : Gold Price Prediction Using Simple Linear Regression # CopyRight (C) : Ismet Emir Demir & Muhammed Cinsdikici # Date : 30 March 2021, 13:20 # Code Repo : ComVIS Lab # DataSet : https://evds2.tcmb.gov.tr/index.php?/evds/serieMarket/collapse_25/5849/DataGroup/turkish/bie_mkaltytl/ # (Dataset is taken from Turkiye Cumhuriyeti Merkez Bankasi) import numpy as np import pandas as pd import matplotlib.pyplot as plt def plt_line(w0, w1, points): abline_values = [w1 * i + w0 for i in points] # Plot the best fit line over the actual values plt.plot(x, abline_values, 'b') plt.title("Simple Linear Regression, w0:{} w1:{}".format(w0,w1)) plt.xlabel("Normalized Day numbers inputs") plt.ylabel("Normalized Gold Prices") data = pd.read_excel("EVDS.xlsx") # Take the Prices as "y" (Real gold prices) # Take the number of each day as "x" y = np.array(data['fiyat'].tolist()); x = np.array(range(1,len(y)+1)); # initialize w0 and w1 to random value. Lets take w0=0.43 w1=0.87 #derivative: 2.u.u' => (-2)*Sigma((y - w0 -w1x1)*x1) # wi = wi - etha*derivative w0=0.43 w1=0.87 #For lr(etha)=0.6 : If you normalize your inputs and outputs, # =0.0001 : If you not normalize then use very very very small lr=etha=0.6 epochs = 10000 n= len(y) # IF YOU NORMALIZE THE INPUT Learning Rate 0.6 is can be used # THEN summation is getting big example: gold price(240) the day (100) produces 24000 # and saturation arises. # Normalize with Z-Score: y= (y-np.mean(y))/np.std(y) # DON'T forget to Normalize your TEST PATTERNS with THESE y_mean,y_std & x_mean,x_std y_mean, y_std = np.mean(y), np.std(y) y= (y-y_mean)/y_std x_mean, x_std = np.mean(x), np.std(x) x= (x-x_mean)/x_std # IF YOU DON'T NORMALIZE THE INPUT AS WITH Z-SCORE's.. # YOU SHOULD TAKE LEARNING RATE very very very small number of 0.0001 or less than this. #w0,w1,RSS = linear_regression(x, y, w0=0.3, w1=0.47, epochs=1000, learning_rate=0.0001) #print(w0, w1, RSS) for epoch in range(1,epochs): y_predicted = w0 + w1*x; RSS = sum((y-y_predicted)**2) d_RSS_dw0 = (-2/n) * sum(y-y_predicted) d_RSS_dw1 = (-2/n) * sum((y-y_predicted)*x) w0 = w0 - (etha*d_RSS_dw0) w1 = w1 - (etha*d_RSS_dw1) print ("Epoch:{} w0:{} w1:{} Cost(RSS):{}".format(epoch,w0,w1,RSS)); plt.plot(x,y,"--") plt_line(w0,w1,x) plt.show()
8f6d1c31a07bdbf641125fa348da99a3777d473b
tamasdinh/data-structures
/Queue_stack.py
1,638
4.3125
4
# Implementing a Queue based on a stack structure #%% class Stack: def __init__(self): self.items = [] def is_empty(self): return len(self.items) == 0 def size(self): return len(self.items) def push(self, value): self.items.append(value) def pop(self): if self.is_empty(): return None else: return self.items.pop() class QueueS: def __init__(self): self.instore = Stack() self.outstore = Stack() def size(self): return self.outstore.size() + self.instore.size() def enqueue(self, value): """ Adding item to the end of the queue :param value: value to be added at end of queue :return: None - instore member is modified """ self.instore.push(value) def dequeue(self): """ Dequeuing elements. Here we use 2 stacks so that we can reverse the order of items\ in the second one for dequeuing. :return: dequeued item """ if not self.outstore.items: while self.instore.items: self.outstore.push(self.instore.pop()) return self.outstore.pop() #%% # TESTS # Setup q = QueueS() q.enqueue(1) q.enqueue(2) q.enqueue(3) # Test size print("Pass" if (q.size() == 3) else "Fail") # Test dequeue print("Pass" if (q.dequeue() == 1) else "Fail") # Test enqueue q.enqueue(4) print("Pass" if (q.dequeue() == 2) else "Fail") print("Pass" if (q.dequeue() == 3) else "Fail") print("Pass" if (q.dequeue() == 4) else "Fail") q.enqueue(5) print("Pass" if (q.size() == 1) else "Fail")
b5ea944432c7721b0185261283eb633d56ab2e3c
davidsram/written-examination-questions
/balance.py
224
3.84375
4
balance=int(input('balance')) payment=int(input('payment')) i=0 while (balance-payment)>0: i+=1 balance=balance-payment print(i,balance,payment) else: i=i+1 payment=balance print(i,balance,payment)
06c9137917c37dce85fd7cb6b4c8d8cfa287c260
dhnesh12/codechef-solutions
/02-CodeChef-Easy/1119--Walk on the Axis.py
95
3.640625
4
for _ in range(int(input())): N=int(input()) total=int(N+(N*(N+1))/2) print(total)
a24d6ac4c5b738538a9e9722220aff0723807179
VittorioYan/Leetcode-Python
/306.py
1,949
3.515625
4
from typing import List class Solution: def addStrings(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ num1, num2 = num1[::-1], num2[::-1] # 将输入字符串逆序 len1, len2 = len(num1), len(num2) # 获得字符串长度 res = '' # 初始化结果变量 carry = 0 # 初始化进位 for i in range(max(len1, len2)): # 开始遍历 n1 = ord(num1[i]) - ord('0') if i < len1 else 0 # 取第一个数的当前位 n2 = ord(num2[i]) - ord('0') if i < len2 else 0 # 取第二个数的当前位 s = n1 + n2 + carry # 当前位的计算结果 carry, r = s // 10, s % 10 # 获得余数和进位 res = str(r) + res # 把余数加到当前结果的最高位 if carry: # 如果算完还有进位 res = str(carry) + res # 加到结果最高位 return res def isAdditiveNumber(self, num: str) -> bool: n = len(num) def recursion(last_num: str, this_num: str, point: int) -> bool: nonlocal n, num if point == n: return True if last_num[0] == '0' and len(last_num) > 1: return False if this_num[0] == '0' and len(this_num) > 1: return False next_sum = self.addStrings(last_num, this_num) if len(next_sum) > n - point: return False if next_sum == num[point:point + len(next_sum)]: if recursion(this_num, next_sum, point + len(next_sum)): return True return False for i in range(1, n): for j in range(i + 1, n): if recursion(num[:i], num[i:j], j): return True return False a = Solution() in_para1 = "448122032" in_para2 = 9 resu = a.isAdditiveNumber(in_para1) print(resu)
b705ce921720d4bfecf2453964620155832be5ad
rayramsay/skills-object-orientation
/assessment.py
4,976
4.78125
5
""" Part 1: Discussion 1. What are the three main design advantages that object orientation can provide? Explain each concept. * Encapsulation: Data and its behaviors "live" close together, so it's easy to see what data can do/how it can be acted upon. * Abstraction: Details can be "hidden" from the user. For example, when we were using that graphics program, we knew which methods we could use with various shapes, like .setBackgroundColor(), but we didn't--and didn't need to-- know how those methods worked under the hood. * Polymorphism: Interchangeability of components. Classes that call the same methods should pass the same number of arguments. 2. What is a class? Classes are a way of storing data and its behaviors. The data structures we've encountered previously, like lists, tuples, etc., are specific types of classes; that's why they have their own methods. 3. What is an instance attribute? An instance attribute is an attribute that is specific to a particular instance, rather than shared with all instances of that class. 4. What is a method? A method is a function that is defined in the class or inherited from parent classes. These methods are called with dot notation, e.g., fido.speak(). 5. What is an instance in object orientation? An instance is a specific, individual occurrence of a class. For example, fido is an instance of the class Dog. 6. How is a class attribute different than an instance attribute? Give an example of when you might use each. A class attribute is shared among all instances of that class. For example, the class Dog can have color = 'brown' as a class attribute, so that dog instances don't need to have their color specified within them, as they can look up their class attribute. But if I want to make a particular dog black, I can give it an instance attribute of fido.color = 'black'. Instances look at themselves first, and if they don't have an instance attribute, they look up at their class to see if it's stored there. """ # Part 2: Classes and Init Methods # Part 3: Methods class Student(object): def __init__(self, first_name, last_name, address): """Initializes new student.""" self.first_name = first_name self.last_name = last_name self.address = address class Question(object): def __init__(self, question, correct_answer): """Initializes new question.""" self.question = question self.correct_answer = correct_answer def ask_and_evaluate(self): """Asks user the question and compares their response to the correct answer; returns a boolean.""" answer = raw_input("{} > ".format(self.question)) return answer.lower() == self.correct_answer.lower() # User's answer doesn't have to match the capitalization of correct # answer in order to be marked correct. class Exam(object): def __init__(self, name): """Initializes new exam with blank list of questions.""" self.name = name self.questions = [] def add_question(self, question, correct_answer): """Adds new question to the list of questions.""" self.questions.append(Question(question, correct_answer)) def administer(self): """Loops over exam's questions, returns score.""" score = 0 for question in self.questions: if question.ask_and_evaluate(): # if that returns True then score += 1 return score # Part 4: Create an actual exam! def take_test(exam, student): """Given an exam and a student, administers exam and records student's score.""" student.score = exam.administer() def example(): """Creates an exam, adds a few questions to it, creates a student, administers the test for that student.""" exam = Exam("exam") exam.add_question("Who received the first IBM PC delivered in New York " "City?", "Edie Windsor") exam.add_question("Who headed the team that wrote the software for the " "Apollo Guidance Computer?", "Margaret Hamilton") student = Student("Nicey", "Goodcoder", "123 Computer St") student.score = exam.administer() if student.score == len(exam.questions): print "Great job! Your score is {}.".format(student.score) else: print "Your score is {}.".format(student.score) # Part 5: Inheritance class Quiz(Exam): """It's like an exam, only pass/fail.""" def administer(self): score = super(Quiz, self).administer() return score / float(len(self.questions)) >= 0.5 # If you answer at least half of the questions correctly, you pass the # quiz. Length (i.e., number) of questions converted to a float due to # Python 2's counterintuitive implementation of the '/' operator.
49ee058afc3fd8c5c98cb7b641bbf2be032f3861
AugustLONG/Code
/CC150Python/crackingTheCodingInterview-masterPython全/crackingTheCodingInterview/cha10/solution1001.py
575
3.609375
4
""" 10.1 You have a basketball hoop and someone says that you can play 1 of 2 games. Game #1: You get one shot to make the hoop. Game #2: You get three shots and you have to make 2 of 3 shots. If p is the probability of making a particular shot, for which values of p should you pick one game or the other? Analyse: for each shots, they are independent, so C(2,3)*p*p*(1-p) + C(3,3)*p*p*p > p => 3*p(1-p) + p*p > 1 ==> 3*p - 2*p*p - 1 > 0 ==> 2*p*p - 3*p + 1 < 0 ==> (2p - 1)(p - 1) < 0 ==> p > 0.5 so if p > 0.5, you should pick game 2 """
9db6647800be1649cda1f84a1d117bb3568e0f6b
Akhilvijayanponmudy/pythondjangoluminar
/oops/ingeritance.py
198
3.75
4
class Parent: def phone(self): print("i have nokia 5310") class Child(Parent): pass c=Child() c.phone() #different types of inheritance #parent->child #suoer->sub #base->derived
6c2b2fa740be7d0f423e42017de413e609d5622d
austinschrader/Python-Game
/classexample.py
653
3.90625
4
class Room: """Making a room class for the game. Rooms has a width and height, doors, enemies, and chests. These will all be other classes. """ def __init__(self, width, height, doors, enemies, chests, character): self.width = width self.height = height self.doors = doors self.enemies = enemies self.chests = chests self.character = character class Character: def __init__(self, weapon, level, position, name): self.weapon = weapon self.level = level self.position = (x,y) self.name = name def position(self): self.x = ? self.y = ? def __repr__(self): return self.name
8ad898ea5186ebaa41adba6f8916c7d31d72e048
PedroGal1234/Unit4
/functionDemo.py
397
4
4
#Pedro Gallino #10/16/17 #functionDemo.py - learning fuctions def hw(): print ('Hellow,world!') def bigger(num1, num2): #prints which function is bigger if num1>num2: print(num1) else: print(num2) def slope(x1, y1, x2, y2): print((y2-y1)/(x2-x1)) #hw() #runs function #bigger(13,27) #test 1 #bigger(-10,-15) #test 2 #bigger('Smeds', 'Clay') slope(1,2,3,4,)
f4c6f6ac698877c51376925b1fe1d08b3ffefae4
trampolo/project-euler-python
/eu-1.py
499
4.28125
4
# Multiples of 3 and 5 # Problem 1 # If we list all the natural numbers below 10 that are multiples of 3 or 5, # we get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. multiples_3 = [x for x in range(3, 1000, 3)] multiples_5 = [x for x in range(5, 1000, 5)] multiples_3_5 = set(multiples_3) | set(multiples_5) sum_of_multiples_3_5 = 0 for n in multiples_3_5: sum_of_multiples_3_5 = sum_of_multiples_3_5 + n print(sum_of_multiples_3_5)
c23de213208c1c3707c0136a80092bb439722ef7
yeloblu/Python
/Basics/assign1.py
434
4.25
4
print("Assign 1 - Input Factorial"); #fact=1; x=input ("Enter a number :"); if (x==0): print("Factorial is : 1"); elif (x<0): print("Invalid number!"); else while(i>0): print(i*i-1); i=i-1; #elif(n>0): # while(n>0): # fact=fact*n; # n=n-1; # print("Fact of ",n,"=",fact); print("end of program");
d95152e227ad0b8e0f28711a280606ceb2716daa
sureshn98/python-assignment-3
/Q.6.py
207
4.0625
4
#new list with unique elements of current list list=['1','1','2','a','s','a','3','d'] def newlist(): j=[] for i in list: if i not in j: j.append(i) return j print(newlist())
6357aaab4df5c762d754a591a3688196f9ab1922
charleyjohnston/python-scripts
/write_numbers_to_text_file.py
8,029
3.96875
4
#write_numbers_to_text_file.py #Writes a range of numbers between and including two numbers inputted by the user to a text file, with one number per line. #Author: Charley Johnston #Date: December 3, 2018 #V2 - Added undo function from Tkinter import * import tempfile import base64 import zlib ################################################# def check_if_E2_bigger_than_E1(): global E1, E2 if ( (int (E1.get() ) <= int( E2.get() ) ) ): return True else: return False ################################################# def check_if_positive(get): if int(get) < 0: return False return True ################################################# def check_if_number(get): try: val = int(get) except ValueError: return False return True ################################################# def get_entries(): global min_number, max_number, label3_text, item_class, root #Blank entries if E1.get() == "" or E2.get() == "": #Both blank entries if E1.get() == "" and E2.get() == "": label3_text.set("Error: Please input at least one value.") #Just E2 has an entry elif E1.get() == "" and E2.get() != "": #Check if input is a number if check_if_number( str(E2.get()) ): #Check if input is positive if check_if_positive( str(E2.get()) ): label3_text.set("Min = Max = " + str( E2.get() ) + ", added to file.") min_number = int(E2.get()) max_number = min_number add_to_history(min_number, max_number) item_class = str(E3.get()) add_to_text_file() else: label3_text.set("Error: Please only input positive numbers.") else: label3_text.set("Error: Please only input numbers.") #Just E1 has an entry elif E1.get() != "" and E2.get() == "": #Check if input is a number if check_if_number(str(E1.get())): #Check if input is positive if check_if_positive( str(E1.get()) ): label3_text.set("Min = Max = " + str( E1.get() ) + ", added to file.") min_number = int(E1.get()) max_number = min_number add_to_history(min_number, max_number) item_class = str(E3.get()) add_to_text_file() else: label3_text.set("Error: Please only input positive numbers.") else: label3_text.set("Error: Please only input numbers.") #Both E1 and E2 have entries elif E1.get() != "" and E2.get() != "": #Check if inputs are numbers if check_if_number(str(E1.get())) and check_if_number(str(E2.get())): #Check if entries are positive numbers if check_if_positive( str(E1.get()) ) and check_if_positive( str(E2.get()) ): #Check that right entry is bigger than left entry if check_if_E2_bigger_than_E1(): label3_text.set("Min = " + str( E1.get() ) + " Max = " + str( E2.get() ) + ", added to file.") min_number = int(E1.get()) max_number = int(E2.get()) add_to_history(min_number, max_number) item_class = str(E3.get()) add_to_text_file() else: label3_text.set("Error: Right entry should be <= left entry") else: label3_text.set("Error: Please only input positive numbers.") else: label3_text.set("Error: Please only input numbers.") ################################################# def add_to_text_file(): global min_number, max_number, text_file_name, text_and_class_file_name, item_class #File with numbers and class try: with open(text_and_class_file_name, 'a') as the_file: for i in range(min_number, int(max_number) + 1): the_file.write(str(i) + "/" + str(item_class) + "/\n") except: with open(text_and_class_file_name, 'w') as the_file: for i in range(min_number, int(max_number) + 1): the_file.write(str(i) + "/" + str(item_class) + "/\n") ############################################################################# def add_to_history(min_value, max_value): global min_number_history, max_number_history min_number_history.append(min_value) max_number_history.append(max_value) ############################################################################# def find_str(s, char): index = 0 if char in s: c = char[0] for ch in s: if ch == c: if s[index:index+len(char)] == char: return index index += 1 return -1 ################################################# #~~~~~~~~~Finish~~~~~~~~~~~~# def undo_function(): global min_number_history, max_number_history values = [] try: min_value = min_number_history.pop() max_value = max_number_history.pop() for i in range(min_value, max_value + 1): values.append(i) f = open("frame_and_class_list.txt","r") lines = f.readlines() f.close() f = open("frame_and_class_list.txt","w") for line in lines: contains = 0 for i in range(len(values)): if find_str(line, str(values[i])) != -1: contains = 1 if contains == 0: f.write(line) f.close() except IndexError: label3_text.set("Error: There's nothing left to undo!") ################################################# ICON = zlib.decompress(base64.b64decode('eJxjYGAEQgEBBiDJwZDBy' 'sAgxsDAoAHEQCEGBQaIOAg4sDIgACMUj4JRMApGwQgF/ykEAFXxQRc=')) _, ICON_PATH = tempfile.mkstemp() with open(ICON_PATH, 'wb') as icon_file: icon_file.write(ICON) #Root root = Tk() root.iconbitmap(default=ICON_PATH) root.title('') #Labels label_min = Label(root, text='\nMin', borderwidth=10).grid(row=1,column=1) label_max = Label(root, text='\nMax', borderwidth=10).grid(row=1,column=3) label1 = Label(root, text='Enter your range of numbers to\n write them to the text file.', borderwidth=10).grid(row=1,column=2) label2 = Label(root, text='<----------- from to ----------->', borderwidth=10).grid(row=2,column=2) label4 = Label(root, text='Item class', borderwidth=10).grid(row=3,column=2) label3_text = StringVar() label3 = Label(root, textvariable=label3_text, borderwidth=10).grid(row=5,column=2) label3_text.set('Press "Enter" to write to the file!') #Entries E1 = Entry(root, borderwidth=5 ) E1.grid(row=2,column=1, padx=10, pady=5) E2 = Entry(root, borderwidth=5 ) E2.grid(row=2,column=3, padx=10, pady=5) E3 = Entry(root, borderwidth=5 ) E3.grid(row=4,column=2, padx=10, pady=5) #Button submit = Button(root, text ="Enter", command = get_entries).grid(row=6,column=2, padx=10, pady=10) undo_button = Button(root, text ="Undo", command = undo_function).grid(row=6,column=3, padx=10, pady=10) #Prevents resize of window root.grid_columnconfigure(2, minsize=250) min_number = 0 max_number = 0 #History for undo min_number_history = [] max_number_history = [] item_class_history = [] item_class = "" text_file_name = "frame_list.txt" text_and_class_file_name = "frame_and_class_list.txt" root.mainloop()
452de579bbb9ce2c4beb3a744c34eed42cee9fda
JorgeMGuimaraes/uff-chronos
/src/chronos/Entidade.py
1,470
4.03125
4
class Entidade(): """ Guarda informacoes gerais sobre o aluno. """ def __init__(self, id: int): ''' Guarda informacoes gerais sobre o aluno. ''' self.id = id self.nota_ponderada = 0 self.carga_horaria_total = 0 return def set_nota_ponderada(self, nota: int, carga: int)-> None: ''' Incrementa a soma dos produtos 'nota'*'carga horaria'. Parameters ---------- nota : int A nota atribuida a entidade. carga : int A carga horaria atribuida a cada curso. ''' self.nota_ponderada += nota * carga return def set_carga_horaria_total(self, carga:int)-> None: ''' Incrementa a carga horaria total da entidade. Parameters ---------- carga : int A carga horaria atribuida a cada curso. ''' self.carga_horaria_total += carga def get_cr(self)-> None: ''' Retorna o CR de cada entidade de acordo com os criterios da universidade ''' if self.carga_horaria_total == 0: return 0 return int(self.nota_ponderada / self.carga_horaria_total) def get_output_cr(self)-> int: ''' Retorna string formatada com o CR e o id da entidade, como *.ToString() ''' return '{0}\t- {1}'.format(self.id, self.get_cr())
2ef56889c27d4e1b8df3cc5e451ab42a8cc18434
ototonari/Anna
/remove.py
732
3.71875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # DIR内の、引数の文字列に一致したファイルを削除する import sys, os, re, traceback from time import sleep from datetime import datetime, timedelta, time def remove(filename, directory): # target dir DIR = directory or "./file/" fileList = os.listdir(DIR) pattern = re.compile(r'({})'.format(filename)) for file in fileList: m = pattern.search(file) if m: os.remove("{dir}{file}".format(dir=DIR, file=m.string)) def removeAll(directory): directory = directory or "./file/" fileList = os.listdir(directory) for file in fileList: os.remove("{dir}{file}".format(dir=directory, file=file))
61e6dd6432050d2b5c7f2109481419497c169dde
JunnanZ/production-network
/stochastic_k.py
5,287
3.5
4
# Code for the paper "Equilibrium in a Model of Production Networks" by Meng # Yu and Junnan Zhang # # File name: stochastic_k.py # # Compute the equilibrium prices as a fixed point of T specified in equation # (3) and (6) in the paper. Two methods are used: one is successive # evaluations of T and the other is Algorithm 1 in the paper. # # The code is based on the code by John Stachurski for the paper "Span of # Control, Transaction Costs and the Structure of Production Chains". # # For example usages, see 'plots.py'. # # Author: Junnan Zhang # # Date: Nov 18, 2018 import numpy as np from scipy.optimize import fminbound from scipy.optimize import minimize import matplotlib.pyplot as plt from scipy.stats import poisson from scipy.stats import geom class RP: def __init__(self, n=500, delta=1.01, g=lambda k: 0.1 * k, c=lambda x: np.exp(3 * x) - 1, dist='discreet', kmax=30, method='L-BFGS-B'): self.n = n self.delta = delta self.g = g self.c = c self.grid = np.linspace(0, 1, num=n) self.dist = dist if dist == 'discreet': self.solve_min = self.solve_min_dis else: self.solve_min = self.solve_min_st self.kmax = kmax self.method = method def set_prices(self): self.p = self.compute_prices() self.p_func = lambda x: np.interp(x, self.grid, self.p) def set_prices2(self): self.p = self.compute_prices2() self.p_func = lambda x: np.interp(x, self.grid, self.p) def solve_min_dis(self, p, s, s2=None): """ Solve for minimum and minimizers when at stage s, given p. The parameter p should be supplied as a function. """ current_function_min = np.inf delta, g, c, kmax = self.delta, self.g, self.c, self.kmax if s2 is None: s2 = s for k in range(1, kmax+1): def Tp(ell): return (delta * k * p((s - ell)/k) + c(ell) + g(k - 1)) ell_star_eval_at_k = fminbound(Tp, s-s2, s) function_value = Tp(ell_star_eval_at_k) if function_value < current_function_min: current_function_min = function_value k_star = k ell_star = ell_star_eval_at_k # else: # break # if k_star == kmax: # print("Warning: kmax reached.") return current_function_min, k_star, ell_star def solve_min_st(self, p, s, s2=None): """ Same as the previous function but in the stochastic case. """ delta, g, c, kmax = self.delta, self.g, self.c, self.kmax dist, E, method = self.dist, self.E, self.method if s2 is None: s2 = s def fun(x): # x[0]: s-t; x[1]: param return E(lambda k: delta * k * p((s - x[0])/k) + c(x[0]) + g(k - 1), x[1]) if dist == 'poisson': bnds = ((s-s2, s), (0, kmax)) x0 = 0 elif dist == 'geom': bnds = ((s-s2, s), (1e-6, 1)) x0 = 1 res = minimize(fun, (s, x0), method=method, bounds=bnds) return res.fun, res.x[1], res.x[0] def apply_T(self, current_p): n = self.n solve_min = self.solve_min def p(x): return np.interp(x, self.grid, current_p) new_p = np.empty(n) for i, s in enumerate(self.grid): current_function_min, param_star, ell_star = solve_min(p, s) new_p[i] = current_function_min return new_p def E(self, f, param, n=100): dist = self.dist if dist == 'poisson': def h(k): return f(k) * poisson.pmf(k, param, loc=1) elif dist == 'geom': def h(k): return f(k) * geom.pmf(k, param) else: print("Distribution error.") return sum(map(h, np.arange(1, n+1))) def compute_prices(self, tol=1e-3, verbose=False): """ Iterate with T. The initial condition is p = c. """ c = self.c current_p = c(self.grid) # Initial condition is c error = tol + 1 n = 0 while error > tol: new_p = self.apply_T(current_p) error = np.max(np.abs(current_p - new_p)) if verbose is True: print(error) current_p = new_p n += 1 print(n) return new_p def compute_prices2(self): """ Compute the price vector using the algorithm specified in the paper. """ grid, n, c, kmax = self.grid, self.n, self.c, self.kmax solve_min = self.solve_min new_p = np.zeros(n) new_p[1] = c(grid[1]) for i in range(2, n): def interp_p(x): return np.interp(x, grid[:i], new_p[:i]) p_min, param_star, ell_star = solve_min(interp_p, grid[i], grid[i-1]) # print(p_min, param_star, ell_star) if param_star >= kmax: raise ValueError("kmax reached") new_p[i] = p_min return new_p def plot_prices(self, plottype='-', label=None): plt.plot(self.grid, self.p, plottype, label=label)
bb7cf0837caa179a8fcba045ca678cc662ff0fe9
D1egoS4nchez/Ejercicios
/Ejercicios/ejercicio30.py
384
3.921875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def suma_while(): x = 1 suma = 0 while x<=10: valor = int(input("Ingrese el numero que va a sumar: \n")) suma = suma + valor x = x + 1 promedio = suma // 10 print("La suma de los 10 valores que ingreso es: \n", suma) print("\t") print("El promedio es de: \t", promedio) suma_while()
124ac95e766e57766ac9123d36c5ef5433f6d44a
1050669722/LeetCode-Answers
/Python/problem0461.py
800
3.578125
4
# -*- coding: utf-8 -*- """ Created on Thu Jul 11 16:43:48 2019 @author: ASUS """ class Solution: def hammingDistance(self, x: int, y: int) -> int: X, Y = [], [] while x: tmp = x%2 X.append(tmp) x //= 2 while y: tmp = y%2 Y.append(tmp) y //= 2 lendiff = len(X) - len(Y) if lendiff > 0: for _ in range(lendiff): Y.append(0) elif lendiff < 0: for _ in range(abs(lendiff)): X.append(0) X.reverse() Y.reverse() count = 0 for k in range(len(X)): if X[k] != Y[k]: count += 1 return count solu = Solution() x, y = 1, 4 print(solu.hammingDistance(x, y))
9e1912941af02bfa1259bf1034f51c65b7622eef
gierulum/PYTHON_LESSONS
/FUN_IMP.py
252
4.0625
4
import sys my_name = input("Whats u name?") print ("My name is " + my_name) my_list = [1,2,3,4,5,6] for x in range(1,4): print(x) def print_list(list_name): var_list_name = list_name for a in var_list_name: print (a) print_list(my_list)
259b1dd8bbaccfdd292156e587bf6f532ec6acf8
atheenaantonyt9689/Python-Problems
/DAY3/robot_simulator.py
1,521
4.09375
4
EAST = 1 NORTH = 2 WEST = 3 SOUTH = 4 class Robot: def __init__ (self,direction=NORTH,x=0,y=0): self.direction=direction self.x=x self.y=y self.coordinates=(self.x,self.y) def move(self,instructions): for i in instructions: if self.direction == "R": Robot.turn_right(self) elif self.direction == "L": Robot.turn_left(self) elif self.direction =="A": Robot.advance(self) def turn_right(self): if self.direction == NORTH: self.direction = EAST elif self.direction == EAST: self.direction = SOUTH elif self.direction == SOUTH: self.direction = WEST elif self.direction == WEST: self.direction = NORTH def turn_left(self): if self.direction == NORTH: self.direction = WEST elif self.direction == WEST: self.direction = SOUTH elif self.direction == SOUTH: self.direction = EAST elif self.direction == EAST: self.direction = NORTH def advance(self): if self.direction == NORTH: self.x = self.x + 1 if self.direction == SOUTH: self.x = self.x -1 if self.direction == EAST: self.y =self.y+1 if self.direction == WEST: self.y =self.y -1 robot= Robot(EAST,1,1) robot.move("RAALAL")
9a0d6a487f6483f3c3b637d29d3547fd743d2992
mirszhao/python-base
/basefile/oop.py
1,496
3.84375
4
#coding:utf-8 __author__ = 'Administrator' class Student(object): def __init__(self,name,score): self.name = name self.score = score def print_score(self): print('%s %s'%(self.name,self.score)) def get_grade(self): if self.score >= 90: return 'A' elif self.score >= 60: return 'B' else: return 'C' bart = Student('Sean ',33) mirs = Student('mirs ',90) bart.print_score() print bart.get_grade() mirs.print_score() mirs.score =30 #此时可以任意修改 print mirs.get_grade() #在创建实例的时候,把一些我们认为必须绑定的属性强制填写进去。通过定 #义一个特殊的__init__ 方法,在创建实例的时候,就把name , score 等属性绑上去: #访问限制 属性前 双 下划线 class User(object): def __init__(self,name): self.__name = name def print_name(self): print "name is %s" %self.__name def get_name(self): return self.__name user = User("Tom") user.print_name() #print user.__name 不可以访问 print user.get_name() #通过get和 set方法 可以对参数做检查 # 其实是可以访问的 print user._User__name #但是强烈不建议你这样做 #总的来说就是,Python 本身没有任何机制阻止你干坏事,一切全靠自觉。 #继承和多态
845a92a140b20540cd4bde8a52bd232a954cfa62
Fitrah1812/Tugas3Kelompok
/Greedy/Tugas3-Maze-Greedy.py
2,648
3.640625
4
import math from time import time goal_x=5 goal_y=0 maze=[ ['#','#','#','#','#','G','#','#'], ['#','#','#','#',' ',' ',' ','#'], [' ',' ',' ',' ',' ','#',' ',' '], [' ','#','#','#','#','#','#',' '], [' ','S',' ',' ',' ',' ',' ',' '] ] maze_width=8 maze_height=5 class Node: def __init__(self,x,y,cost,actions): self.x=x self.y=y self.cost=cost self.heuristic=self.euclidean_distance() self.actions=actions def euclidean_distance(self): return math.sqrt(math.pow(self.x-goal_x,2)+math.pow(self.y-goal_y,2)) action=['LEFT','RIGHT','UP','DOWN'] ctr_x=[-1,1,0,0] ctr_y=[0,0,-1,1] fringe=list() init_x=1 init_y=4 initial_state=Node(init_x,init_y,0,list()) fringe.append(initial_state) count_expansion=1 closed = list() while len(fringe) > 0: node_now=fringe.pop(0) if(node_now.x == goal_x and node_now.y == goal_y): waktu = time() print("Ditemukan setelah melakukan ekspansi sebanyak",count_expansion,"node") print("dengan",len(node_now.actions), "langkah:",node_now.actions) waktu1 = time()-waktu print("Waktunya adalah ", waktu1) break is_closed=False for i in closed: if i[0]==node_now.x and i[1]==node_now.y: is_closed=True if not is_closed: closed.append((node_now.x,node_now.y)) zero_x=node_now.x zero_y=node_now.y for i in range(len(action)): #coba semua aksi new_x=zero_x+ctr_x[i] #calon posisi x yang baru new_y=zero_y+ctr_y[i] #calon posisi y yang baru if(new_x >= 0 and new_x < maze_width and new_y >= 0 and new_y < maze_height and maze[new_y][new_x]!='#'): #validasi perpindahan posisi successor_in_fringe=False for k in fringe: if k.x == new_x and k.y == new_y: successor_in_fringe=True break successor_in_closed=False for k in closed: if k[0] == new_x and k[1] == new_y: successor_in_fringe=True break if not successor_in_fringe and not successor_in_closed: copy_actions=node_now.actions.copy() copy_actions.append(action[i]) new_node=Node(new_x,new_y,node_now.cost+1,copy_actions) fringe.append(new_node) fringe.sort(key=lambda x: x.heuristic) count_expansion+=1
870e9fc73a49fff86281badf208e854e3fd966ab
z778107203/pengzihao1999.github.io
/python/pythonday1/python_07_if3.py
171
3.53125
4
holiday_name = "圣诞节" if holiday_name == "情人节": print("haha") elif holiday_name == "圣诞节": print("kaka") else: print("每天都是节日啊")
19c16c440ceb8fdc79087ab3c925c5f5f3553bd3
tomasmika/Computational-Science-course-UvA
/Assignment4/CA4.zip/plot.py
2,995
3.71875
4
# Name: Tomas Bosschieter en Sven de Ronde # UvAnetID: 12195073 en 12409308 # Description: This program makes the plots from the data made by experiment.py # How to run: python3 plot.py <code> # - code : 0 plots the density experiment, 1 the p_den, 2 # the p_veg, both if omitted # # IMPORATANT: It might be the case that one plot is behind the other plot. # To fix: just remove the first one to see the second. import numpy as np import sys COLOR = 'orange' # The color of the line in the errorbar plot ECOLOR = 'b' # The color of the error bars LINEWIDTH = 2 def make_density_plot(data, N): import matplotlib.pyplot as plt average = np.average(data, axis=1) error = np.std(data, axis=1) fig, ax = plt.subplots() fig.suptitle("Percentage burned") markers, caps, bars = ax.errorbar([i / N for i in range(N + 1)], average, error, color=COLOR, ecolor=ECOLOR) [bar.set_alpha(0.5) for bar in bars] markers.set_linewidth(LINEWIDTH) plt.xlabel("density") plt.ylabel("percentage burned") plt.show() def make_pden_plot(data, N): import matplotlib.pyplot as plt average = np.average(data, axis=1) error = np.std(data, axis=1) fig, ax = plt.subplots() fig.suptitle("Percentage burned") markers, caps, bars = ax.errorbar([1.2 * i / N - .7 for i in range(N + 1)], average, error, color=COLOR, ecolor=ECOLOR) [bar.set_alpha(0.5) for bar in bars] markers.set_linewidth(LINEWIDTH) plt.xlabel("p_den") plt.ylabel("percentage burned") plt.show() def make_pveg_plot(data, N): import matplotlib.pyplot as plt average = np.average(data, axis=1) error = np.std(data, axis=1) fig, ax = plt.subplots() fig.suptitle("Percentage burned") markers, caps, bars = ax.errorbar([1.2 * i / N - .6 for i in range(N + 1)], average, error, color=COLOR, ecolor=ECOLOR) [bar.set_alpha(0.5) for bar in bars] markers.set_linewidth(LINEWIDTH) plt.xlabel("p_veg") plt.ylabel("percentage burned") plt.show() if __name__ == "__main__": code = -1 try: if sys.argv[1]: code = int(sys.argv[1]) except Exception: print("If you enter an argument, it has to be 0 or 1.") # code 0 means plot this oneone if code == 0 or code == -1: densitydata = np.loadtxt('densitydata') N = len(densitydata) - 1 make_density_plot(densitydata, N) # code 1 means plot this oneone if code == 1 or code == -1: pdendata = np.loadtxt('pdendata') N = len(pdendata) - 1 make_pden_plot(pdendata, N) # code 2 means plot this oneone if code == 2 or code == -1: pvegdata = np.loadtxt('pvegdata') N = len(pvegdata) - 1 make_pveg_plot(pvegdata, N)
7aa67ca1b08c2e2a4a6df42c014c923f77c80aa1
allenai/robustnav
/allenact_plugins/ithor_plugin/ithor_util.py
975
3.53125
4
import math def vertical_to_horizontal_fov( vertical_fov_in_degrees: float, height: float, width: float ): assert 0 < vertical_fov_in_degrees < 180 aspect_ratio = width / height vertical_fov_in_rads = (math.pi / 180) * vertical_fov_in_degrees return ( (180 / math.pi) * math.atan(math.tan(vertical_fov_in_rads * 0.5) * aspect_ratio) * 2 ) def horizontal_to_vertical_fov( horizontal_fov_in_degrees: float, height: float, width: float ): return vertical_to_horizontal_fov( vertical_fov_in_degrees=horizontal_fov_in_degrees, height=width, width=height, ) def round_to_factor(num: float, base: int) -> int: """Rounds floating point number to the nearest integer multiple of the given base. E.g., for floating number 90.1 and integer base 45, the result is 90. # Attributes num : floating point number to be rounded. base: integer base """ return round(num / base) * base
07397eadd2299bf5cbb38fde390fbe529db0343f
sooryaprakash31/ProgrammingBasics
/OOPS/Polymorphism/Python/method_overloading.py
952
4.28125
4
''' Polymorphism: - Polymorphism - Many forms - It allows an entity such as a variable, a function, or an object to have more than one form. Method Overloading: - Performing different operations using the same method name. - Python does not support method overloading as it does not uses arguments as the method signature If there are multiple methods with the same name, it will throw an error ''' # Method overloading in python can be achieved by the following method. # But this is not a good approach. def sum(a=None,b=None,c=None): s = 0 #if c is None, then only a and b are passed if c==None: s=a+b #if c is not None, then a,b and c are passed else: s=a+b+c return s #executes sum() for two arguments print("Sum of 1 and 2 is",sum(1,2)) #executes sum() for three arguments print("Sum of 1,2 and 3 is",sum(1,2,3)) ''' Output: Sum of 1 and 2 is 3 Sum of 1,2 and 3 is 6 '''
3ade6966f7dcaab81d3b88d8acc35d693368a67c
campjake/algorithms
/Viterbi.py
2,457
3.6875
4
''' The Viterbi algorithm is a dynamic programming algorithm for finding the most likely sequence of hidden states (the Viterbi path) that results in a sequence of observed events. INPUT - The observation space O = {o_1, o_2, ..., o_N} - the state space S = {s_1, s_2, ..., s_K} - an array of initial probabilities PI = (pi_1, pi_2, ..., pi_K) such that pi_i stores the probability that x_1 == s_i - a sequence of observations Y = (y_1, y_2, ..., y_T) such that y_t == i if the observation at time t is o_i - transition matrix A of size K * K such that A_{ij} stores the transition probability of transiting from state s_i to state s_j - emission matrix B of size K * N such that B_{ij} stores the probability of observing o_j from state s_i OUTPUT - The most likely hidden state sequence X = (x_1, x_2, ..., x_T) The complexity of this algorithm is O(T * |S| ^ 2) ''' def viterbi(obs, states, start_p, trans_p, emit_p): V = [{}] for st in states: V[0][st] = {"prob": start_p[st] * emit_p[st][obs[0]], "prev": None} # Run Viterbi when t > 0 for t in range(1, len(obs)): V.append({}) for st in states: max_tr_prob = max(V[t - 1][prev_st]["prob"] * trans_p[prev_st][st] for prev_st in states) for prev_st in states: if V[t - 1][prev_st]["prob"] * trans_p[prev_st][st] == max_tr_prob: max_prob = max_tr_prob * emit_p[st][obs[t]] V[t][st] = {"prob": max_prob, "prev": prev_st} break for line in dptable(V): print(line) opt = [] # The highest probability max_prob = max( value["prob"] for value in V[-1].values() ) previous = None # Get most probable state and its backtrack for st, data in V[-1].items(): if data["prob"] == max_prob: opt.append(st) previous = st break # Follow the backtrack till the first observation for t in range(len(V) - 1, 0, -1): opt.insert(0, V[t][previous]["prev"]) previous = V[t][previous]["prev"] print('The steps of states are {' + ' -> '.join(opt) + '} with highest probability of %s' % max_prob) def dptable(V): # Print a table of steps from dictionary yield " ".join( ("%10d" % i) for i in range(len(V)) ) for state in V[0]: yield "%-7s: " % state + " ".join("%-10s" % ("%f" % v[state]["prob"]) for v in V)
9bbb39ffff1f92d4ac3530f0029a9bd995e6f859
feiyanshiren/myAcm
/leetcode/t000766.py
1,985
3.828125
4
# 766. 托普利茨矩阵 # 如果一个矩阵的每一方向由左上到右下的对角线上具有相同元素,那么这个矩阵是托普利茨矩阵。 # 给定一个 M x N 的矩阵,当且仅当它是托普利茨矩阵时返回 True。 # 示例 1: # 输入: # matrix = [ # [1,2,3,4], # [5,1,2,3], # [9,5,1,2] # ] # 输出: True # 解释: # 在上述矩阵中, 其对角线为: # "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]"。 # 各条对角线上的所有元素均相同, 因此答案是True。 # 示例 2: # 输入: # matrix = [ # [1,2], # [2,2] # ] # 输出: False # 解释: # 对角线"[1, 2]"上的元素不同。 # 说明: # matrix 是一个包含整数的二维数组。 # matrix 的行数和列数均在 [1, 20]范围内。 # matrix[i][j] 包含的整数在 [0, 99]范围内。 # 进阶: # 如果矩阵存储在磁盘上,并且磁盘内存是有限的,因此一次最多只能将一行矩阵加载到内存中,该怎么办? # 如果矩阵太大以至于只能一次将部分行加载到内存中,该怎么办? # 解: # 按提议,横竖计算 # ``` from typing import List class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: l1 = len(matrix) l2 = len(matrix[0]) for i in range(l1): i1 = i j1 = 0 a = matrix[i1][j1] i1 += 1 j1 += 1 while i1 < l1 and j1 < l2: if a != matrix[i1][j1]: return False i1 += 1 j1 += 1 for i in range(1, l2): i1 = 0 j1 = i a = matrix[i1][j1] i1 += 1 j1 += 1 while i1 < l1 and j1 < l2: if a != matrix[i1][j1]: return False i1 += 1 j1 += 1 return True
a4bd50b4ac26814d745411ca815aa8115c058d0c
bettymakes/python_the_hard_way
/exercise_03/ex3.py
2,343
4.5
4
# Prints the string below to terminal print "I will now count my chickens:" # Prints the string "Hens" followed by the number 30 # 30 = (30/6) + 25 print "Hens", 25 + 30 / 6 # Prints the string "Roosters" followed by the number 97 # 97 = ((25*3) % 4) - 100 # NOTE % is the modulus operator. This returns the remainder (ex 6%2=0, 7%2=1) print "Roosters", 100 - 25 * 3 % 4 # Prints the string below to terminal print "Now I will count the eggs:" # Prints 7 to the terminal # 4%2=[0], 1/4=[0] # 3 + 2 + 1 - 5 + [0] - [0] + 6 # NOTE 1/4 is 0 and not 0.25 because 1 & 4 are whole numbers, not floats print 3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0 # Prints the string below to terminal print "Is it true that 3 + 2 < 5 - 7?" # Prints false to the screen # 5 < -2 is false # NOTE the < and > operators check whether something is truthy or falsey print 3 + 2 < 5 - 7 # Prints the string below followed by the number 5 print "What is 3 + 2?", 3 + 2 # Prints the string below followed by the number -2 print "What is 5 - 7?", 5 - 7 # Prints the string below to terminal print "Oh, that's why it's False." # Prints the string below to terminal print "How about some more." # Prints the string below followed by 'true' print "Is it greater?", 5 > -2 # Prints the string below followed by 'true' print "Is it greater or equal?", 5 >= -2 # Prints the string below followed by 'false' print "Is it less or equal?", 5 <= -2 # ================================ # ========= STUDY DRILLS ========= # ================================ #1 Above each line, use the # to write a comment to yourself explaining what the line does. ### DONE! #2 Remember in Exercise 0 when you started Python? Start Python this way again and using the math operators, use Python as a calculator. ### DONE :) #3 Find something you need to calculate and write a new .py file that does it. ### See calculator.py file #4 Notice the math seems "wrong"? There are no fractions, only whole numbers. You need to use a "floating point" number, which is a number with a decimal point, as in 10.5, or 0.89, or even 3.0. ### Noted. #5 Rewrite ex3.py to use floating point numbers so it's more accurate. 20.0 is floating point. ### Only rewrote line 20 because that's the only statement that would be affected by floating points. ### Rewrote calculator.py as well :).
e3a7d0d86c46c6175e4a309b892c92a1845b7c5e
Kieran-W-97/Miscellaneous_Problems
/nonogram_solve_main.py
400
3.515625
4
""" AUTHOR: KIERAN WACHSMUTH, 30th Jun 2020 Main script for solving a Nonogram. """ import numpy as np #import matplotlib.pyplot as plt from useful_fns import load_obj from permutator import permutate # x = load_obj('nonogram_x') y = load_obj('nonogram_y') dim_x = len(x) dim_y = len(y) # Generate all solutions for each column 'x': sol_dict = {} for i in range(dim_x): sol_dict[i] = permutate(dim_x,x[i])
c27415f61954fbb8f8a0ffa801ce8566f1394d1f
robinsharma1911/ATM
/ATM_code.py
2,138
4.0625
4
#accounts dict contains:- #keys as account no's of two persons and value[0] as pins and value[1] as balance accounts = {822466:[1234,20000],822456:[2345,30000]} #main function after authentication def main_function(account_number, accounts): while True: amt = accounts[account_number][1] #save balance of current user in amt variable #check balance def check_balance(account_number, amt): print('account number:-',account_number,'\ntotal balance:-',amt) #withdraw balance def withdraw(account_number, amt): withdraw_amt = int(input('\nenter amount for withdraw:-')) amt=amt-withdraw_amt print('\nafter withdraw remaining balance:-',amt) accounts[account_number][1] =amt #update dict balance at run time print(accounts) print( #choose options '\nchoose option' '\n 1)check balance' '\n 2)withdraw' '\n 3)exit\n' ) select = int(input('choice:-')) if select == 1: check_balance(account_number, amt) elif select == 2: withdraw(account_number, amt) elif select == 3: exit() else: print('\nwrong choice try again') #function to authenticate user account number and pin.. def authentication(): account_number = int(input('enter account number:-')) #___take input from user for account no. and pin.... pin = int(input('enter pin:-')) for acc, pins in accounts.items(): if account_number == acc: if pin == pins[0]: amt = pins[1] main_function(account_number,accounts) #call main_function after successful authenticate a person... else: print('wrong credentials') authentication() #program starts here... authentication()
de8347a2d7fc26aa61f763d26a09ebb9edd6baa1
KamalAres/Infytq
/Infytq/Day8/Exer-40.py
230
3.84375
4
#PF-Exer-40 #This verification is based on string match. num1=20 num2=30 div = lambda num1,num2:num1+num2 if(div(num1,num2)%10)==0: #write your logic here print("Divisible by 10") else: print("Not Divisible by 10")
1cf3ef3ea86a74420d90dd94e6f1a1722052b8a0
robgoyal/CodingChallenges
/HackerRank/Algorithms/Implementation/31-to-40/fairRations.py
1,059
3.984375
4
# Name: fairRations.py # Author: Robin Goyal # Last-Modified: December 5, 2017 # Purpose: Calculate the number of loaves to distribute so everyone has even loaves def fairRations(N, B): ''' N -> int: number of subjects in bread line B -> list: number of loaves for each subject return -> int: number of loaves distributed Each subject must have an even number of loaves but distributing a loaf of bread to subject i in array means you must distribute a loaf to subject i+1 or subject i-1 ''' loaves = 0 for i in range(N - 1): # Provide loaf to subject i and i + 1 if subject i has odd number if B[i] % 2 != 0: B[i] += 1 B[i + 1] += 1 loaves += 2 # Check if final subject has an even number of loaves if B[N - 1] % 2 == 0: return loaves return "NO" def main(): N = int(input().strip()) B = [int(B_temp) for B_temp in input().strip().split(' ')] result = fairRations(N, B) print(result) if __name__ == "__main__": main()
e3ffdc9519620627b87f1742954e00653fa52578
sudhir512kj/just-test
/find_fractions_bw_0_to_1.py
1,018
3.84375
4
# def printfractions(n): # for i in range(1, n): # for j in range(i + 1, n + 1): # # If the numerator and # # denominator are coprime # if __gcd(i, j) == 1: # a = str(i) # b = str(j) # print(a + '/' + b, end=", ") # def __gcd(a, b): # if b == 0: # return a # else: # return __gcd(b, a % b) # # Driver code # if __name__ == '__main__': # n = 5 # printfractions(n) # # This code is contributed by virusbuddah_ def printFractions(n): Fractions_set = set() res = [] for i in range(n,0,-1): for j in range(1,i+1): if j/i not in Fractions_set: Fractions_set.add(j/i) res.append("{}/{}".format(j,i)) else: res.remove("{}/{}".format(j+1,i+1)) res.append("{}/{}".format(j,i)) res = sorted(key= lambda i,j: res[i].split("/")[0]/ res[i].split("/")[1] < res[j].split("/")[0]/ res[j].split("/")[1]) return res print(printFractions(3))
bba8dfad6c31ed40c931bd39245eaeec7669302f
orazaro/udacity
/cs101/reachability.py
1,087
4.15625
4
#!/usr/bin/python #Reachability #Single Gold Star #Define a procedure, reachable(graph, node), that takes as input a graph and a #starting node, and returns a list of all the nodes in the graph that can be #reached by following zero or more edges starting from node. The input graph is #represented as a Dictionary where each node in the graph is a key in the #Dictionary, and the value associated with a key is a list of the nodes that the #key node is connected to. The nodes in the returned list may appear in any #order, but should not contain any duplicates. def walk(graph, node, rlist): if node not in rlist: rlist.append(node) for e in graph[node]: walk(graph, e, rlist) def reachable(graph, node): rlist = [] walk(graph, node, rlist) return rlist #For example, graph = {'a': ['b', 'c'], 'b': ['a', 'c'], 'c': ['b', 'd'], 'd': ['a'], 'e': ['a']} print reachable(graph, 'a') #>>> ['a', 'c', 'd', 'b'] print reachable(graph, 'd') #>>> ['d', 'a', 'c', 'b'] print reachable(graph, 'e') #>>> ['e', 'a', 'c', 'd', 'b']
b116bfd419b2cac66b8e78ab0821b39f93ff9794
paeoigner/Functional-Python-Programs
/SpeechRecognitionAsk.py
500
3.5625
4
def ask(): import speech_recognition as sr r = sr.Recognizer() count = 4 while count > 0: print("Please speak now") with sr.Microphone() as source: audio = r.listen(source) print("Processing audio") try: return r.recognize(audio) # recognize speech using Google Speech Recognition except LookupError: # speech is unintelligible print("Could not understand audio") count -= 1 print("{} attempts remaining".format(count)) return "Audio could not be decyphered"
81ae43652e02f95a4942224f4fe8c3d5c9f72084
shao918516/spider
/docs/s12306/test/map_filter_reduce_test(1).py
258
3.640625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Terry' # filter li = [1, 2, 3, 4, 5] li_new = filter(lambda x: x%2 == 0, li) print(list(li_new)) # li_new = [] # for i in li: # if i % 2 ==0 : # li_new.append(i) # # print(li_new)
a1be4ab30ad76ea5a8d037a2096b73d4a77077cd
maddymb/PythonBasics
/basics/whileloop.py
249
3.71875
4
i = 0 # while(i< 45): # print(i) # i = i+1 # while(True): # print(i) # if (i==10): # break # i = i+1 while(True): if i < 5: i = i+1 continue print(i) if (i==10): break i = i+1
a3199ffdf27987fade5dbfd25e76951667063380
zhanganxia/other_code
/笔记/selfstudy/04-函数/studentmangement3.py
2,489
3.875
4
#encoding=utf-8 #用来保存学生的所有信息 stuInfos = [] #获取一个学生的信息 #全局变量 newName = "" newSex = "" newPhone = "" def getInfo(): global newName global newSex global newPhone #3.1 提示并获取学生的姓名 newName = input("请输入新学生的名字:") #3.2 提示并获取学生的性别 newSex = input("请输入新学生的性别:(男/女)") #3.3 提示并获取学生的手机号码 newPhone = input("请输入新学生的手机号码:") #通过列表的方式把数据整合成一个整体,然后返回 #return [newName,newSex,newPhone] #通过元组的方式把数据整合成一个整体,然后返回 #return (newName,newSex,newPhone) #打印提示信息 def printMenu(): print("="*30) print("学生管理系统v1.0") print("1.添加学生信息") print("2.删除学生信息") print("3.修改学生信息") print("4.查询学生信息") print("5.显示所有学生信息") print("6.退出系统") print("="*30) #添加一个学生的信息 def addStuInfo(): getInfo() #result = getInfo() newInfo = {} newInfo['name'] = newName newInfo['sex'] = newSex newInfo['phone'] = newPhone stuInfos.append(newInfo) #修改一个学生的信息 def upStuInfo(): #3.1 提示并获取需要修改的学生序号 stuId = int(input("请输入要修改的学生序号:")) getInfo() #3.3 获取要修改的学生信息 stuInfos[stuId-1]['name'] = newName stuInfos[stuId-1]['sex'] = newSex stuInfos[stuId-1]['phone'] = newPhone def main(): while True: #1.打印功能提示 printMenu() #2.获取功能的选择 key = input("请输入功能对于的数字:") #3.根据用户的选择,进行相应的操作 if key == "1": #添加学生信息 addStuInfo() elif key == "3": #修改学生的信息 upStuInfo() elif key == "5": print("="*30) print("学生的信息如下:") print("="*30) print("序号 姓名 性别 手机号码") i = 1 for tempInfo in stuInfos: print("%d %s %s %s"%(i,tempInfo['name'],tempInfo['sex'],tempInfo['phone'])) i+=1 #print(stuInfos) #调用主函数 main()
f06fe107a35f0c80c736ee7b889a04e59f267c24
dayitachaudhuri/Basic_Python_Problems
/31_insertion sort.py
258
3.65625
4
fruits = ['red' ,'blue', 'pink', 'magenda', 'green','olive'] n=len(fruits) for i in range(n): j=i-1 key = fruits[i] while j >=0 and fruits[j] > key: fruits[j+1]=fruits[j] j -= 1 else: fruits[j+1]=key print(fruits)
07a1bc601f91288255686d274e3a81c97d5d0557
jegadeesh2001/Lab-Main
/Sem4/Python/Basics-1/2.py
296
3.875
4
website = ["www.zframez.com", "www.wikipedia.org", "www.asp.net", "www.abcd.in"] # total = int(input('Enter the number of websites ')) # # for i in range(0,total): # str = input('Enter the website ') # # website.append(str) for web in website: str = web.split('.') print(str[2])
22b17f36a01b5068a998ccd61ee8672400cf795d
andrestbr/html_engine
/create_html_element.py
1,436
3.953125
4
'''Creates an html element. Args: element (str): element name to be created, i.e. <div> content_list (str): the content of the element <div>'content'</div> attribute (str) (optional): for creating an element with an attribute <div style='text-align:right'>'content'</div> attribute_value (str) (optional): value for the attribute Returns: html element ''' def create_html_element(element, content_list, attribute=False): # convert the content (a list of elements) in a string list = '' for e in content_list: list = list + e # build the html element and store it in a variable html_element = '<' + element + '>' + list + '</' + element + '>' # if an attribute and a value are given, build the html element with an attribute (style='text-align:right') and store it in a variable if attribute: attribute_length = len(attribute) attribute_number = 1 attributes = 'style="' for k, v in attribute.items(): attributes = attributes + k + ':' + v if attribute_number == attribute_length: attributes = attributes + '"' else: attributes = attributes + ';' attribute_number = attribute_number + 1 html_element = '<' + element + ' ' + attributes + '>' + list + '</' + element + '>' return html_element
1fed2b362226b94a18b96e1fcd96ea3ad5ca7fe7
rmitio/CursoEmVideo
/Desafio047.py
234
3.890625
4
#DESAFIO047 Crie um programa que mostre na tela todos os números pares que estão no intervalo entre 1 e 50. #for c in range(0, 51, 2): # print(c) for c in range(1, 51): if c % 2 == 0: print('{}'.format(c), end=' ')
ad1f85c147cb84a4740a7de5179ad889cd30e4a8
RownH/MyPy
/py_fluent/leetCode/257.py
1,406
4.28125
4
''' 给定一个二叉树,返回所有从根节点到叶子节点的路径。 说明: 叶子节点是指没有子节点的节点。 示例: 输入: 1 / \ 2 3 \ 5 输出: ["1->2->5", "1->3"] 解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/binary-tree-paths 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def binaryTreePaths(self, root): """ :type root: TreeNode :rtype: List[str] """ paths=[] def constructPath(root,path): if root: #如果存在根 path+=str(root.val); #添加致末尾 if not root.left and not root.right: paths.append(path); #如果为叶节点 else: path+='->'; #如果存在叶节点 constructPath(root.left,path); constructPath(root.right,path); constructPath(root,''); return paths;
922ca8ebaaa3d278e2a64732390208b1ff685361
melvingiovanniperez/pythonprojects
/spiral.py
196
3.703125
4
from turtle import * def spiral(): for x in range(10, 50): forward(x) left(90) def spira(angle): for x in range (10,50): forward(x) left(angle)
70e02d7de4981df52b7c895c6b1ed25d62d84c95
EduMeurer999/Algoritmos-Seg-
/15.py
131
3.703125
4
tempF = float(input('Informe temperatura em °F: ')) tempC = ((tempF-32)*5)/9 print("Temperatura em °C: ", round(tempC, 4), "°C")
c6e53cf87d7dec6b3b18378a64cf12ca175bf08e
jenerational/Python_NYU-CS-1114
/Lab09/Lab09-1a-e.py
1,133
3.671875
4
def main(): print("a. Count:") lst = [0, 32, 'a', '0', '4', 15, 'q', '0'] item = '0' print(count(lst, item)) print("b. Powers of 2:") n = int(input("Please enter an integer.")) print(powersOfTwo(n)) print("c. Find Min Index:") lst = [56, 24, 58, 10, 33, 95] print(findMinIndex(lst)) print("d. Circular Shift List 1:") lst = [1, 2, 3, 4, 5, 6, 7, 8] k = 3 print(circularShiftList1(lst, k)) print("e. Circular Shift List 2:") print(circularShiftList2(lst, k)) def count(lst, item): lstCount = 0 for x in lst: if item == x: lstCount += 1 return lstCount def powersOfTwo(n): L = [] for x in range(1, n+1): L.append(2**x) return L def findMinIndex(lst): min = lst[0] for x in lst: if x < min: min = x return lst.index(min) def circularShiftList1(lst, k): L = [] for x in lst[len(lst)-k:]: L.append(x) for x in lst[:len(lst)-k]: L.append(x) return L def circularShiftList2(lst, k): L = lst[len(lst)-k:] + lst[:len(lst)-k] return L main()
350f49f6c2bfb455bb5a5e210c1e516ff66a2300
rkdvnfma90/Algorithm
/Python/Shortest_path/02_min_heap.py
942
3.6875
4
""" 개선된 다익스트라 알고리즘을 사용하기에 앞서 필요한 최소힙의 사용법을 알아본다. 파이썬같은 경우 heapq 라이브러리는 기본적으로 최소 힙으로 되어있다. Java도 마찬가지로 최소 힙으로 되어있고, C++ 같은 경우는 최대 힙으로 되어 있다. 만약 파이썬에서 최대힙을 사용하고 싶다면 우선순위에 음수 부호를 붙여서 넣었다가 꺼낼때 다시 음수 부호를 붙여 원래의 수로 돌린다. """ import heapq # 오름차순 힙정렬(Heap sort) def heap_sort(iterable): h = [] result = [] # 모든 원소를 차례대로 힙에 삽입 for val in iterable: heapq.heappush(h, val) # 힙에 삽입된 원소를 차례대로 꺼내어 담는다. for i in range(len(h)): result.append(heapq.heappop(h)) return result result = heap_sort([1,3,5,7,9,2,4,6,8,10]) print(result)
118ba7903c6e50eb95a335c90e50b6f9d2999da3
FlynnHillier/World-Population-Calculator
/Population Calculator V2.py
2,174
3.984375
4
print("Welcome to Kalanz's Population Calculator!\n") #change base values here baseyear = 2017 basepopulation = 7550262101 annualprcntchange = 1.2 print("Current Statistics set to the base year "+(str(baseyear))+", a base popualtion of "+(str(basepopulation))+", and an annual population percentage change of "+(str(annualprcntchange))+"%.") print("type 'kill' at anytime to end program.") #Question, gathers the desired year from input, doesn't allow invalid inputs def question(): loop = "on" while loop == "on": year=input("\nPlease Enter Desired Year For Info: ") if year == "kill": loop="off" return year elif year.isdigit() == False: loop = "on" print("please enter valid year.") else: year = (int(year)) if (year<(baseyear)) == True: print("please enter year past "+(str(baseyear))+".") loop = "on" elif (len((str(year)))==4)== False: print("please enter a year no greater than 4 digits long.") loop = "on" else: return year loop = "off" def stats(): #Generates Estimated Population yeardiff = ((year)-(baseyear)) pop = (basepopulation) for i in range (yeardiff): pop+= ((pop)/100*(annualprcntchange)) estpop=(int(pop)) #Finds change in population since base year popchange = ((estpop)-(basepopulation)) #generates length of surrounding line for box when printed line = "" for i in range (30+(len(str((estpop))))): line+="-" #prints all data print("") print(line) print("Year: "+(str(year))) print("Estimated Population: {:,}".format(estpop)) print("Population change since "+(str(baseyear))+": {:,}".format (popchange)) print(line) print("") #runs program loop = "on" while loop == "on": year = question() if year =="kill": print("\nEnd Of Program") loop ="off" else: stats()
7528a9bc3626c7007745ab79add73a2f1cb139ea
martin-costa/incremental-cycle-detection
/Python Graphs/BFGT11.py
3,912
3.640625
4
from graphs import * import math # O(min{m^1/2, n^2/3} * m) algorithm from BFGT 2011, for sparse graphs class BFGT11: def __init__(self, n, m): # stores the number of nodes and edges to be added self.n, self.m = n, m slef.delta = min(m**(1/2), n**(2/3)) # stores the level and index of the nodes self.k, self.i = [1]*self.n, range(-self.n, 0, 1) # sets of outgoing and incoming edges for each node self.outward, self.inward = [], [] for i in range(self.n): self.outward.append(set()) self.inward.append(set()) self.index = -n # used during the insertion of an edge self.B, self.F = [], [] self.arcs = 0 self.marked_nodes = set() # stores the edge while its being inserted self.v, self.w = 0, 0 def insert(self, v, w): self.v, self.w = v, w # STEP 1 (test order) if self.k[v] < self.k[w] or (self.k[v] == self.k[w] and self.i[v] < self.i[w]): return True # STEP 2 (search backward) self.B, self.F = [], [] self.arcs = 0 s = self.Bvisit(v) # return false if a cycle is detected if s == "stop": return False skip_step3 = False if s == "continue": if self.k[w] == self.k[v]: skip_step3 = True else: self.k[w] = self.k[v] self.inward[w] = set() # STEP 3 (forward search) if s == "abort" or not skip_step3: r = self.Fvisit(w) # return false if a cycle is detected if r == "stop": return False # STEP 4 (re-index) L = B + F while(len(L) > 0): self.index = self.index - 1 self.i[L.pop()] = self.index # STEP 5 (insert edge) self.outward[v].add((v, w)) if self.k[v] == self.k[w]: self.inward[w].add((v,w)) # mutually recursive functions for backward search def Bvisit(self, y): self.marked_nodes.add(y) for (x,y) in self.inward[y]: s = self.Btraverse(x,y) # a cycle has been found, stop the algorithm if s == "stop": return s # search aborted, go to step 3 elif s == "abort": return s self.B.append(y) return "continue" def Btraverse(self, x, y): # if a cycle has been found, stop the algorithm if x == self.w: return "stop" self.arcs = self.arcs + 1 # if delta edges have been traversed and w not yet found, abort search if self.arcs >= self.delta: self.k[w] = self.k[v] + 1 slef.inward[w] = [] self.B = [] self.marked_nodes = set() return "abort" if x not in self.marked_nodes: s = self.Bvisit(x) # a cycle has been found, stop the algorithm if s == "stop": return s # search aborted, go to step 3 elif s == "abort": return s return "continue" # mutually recursive functions for forward search def Fvisit(x): for (x,y) in self.outward[x]: s = self.Ftraverse(x,y) # a cycle has been found, stop the algorithm if s == "stop": return s self.F = [x] + self.F # !!!!!COMPLEXITY VERY WRONG def Ftraverse(x,y): # if a cycle has been found, stop the algorithm if y == self.v or y in self.B: return "stop" if self.k[y] < self.k[w]: self.k[y] = self.k[w] self.inward[y] = set() s = self.Fvisit(y) # a cycle has been found, stop the algorithm if s == "stop": return s # now k(y) >= k(w) if self.k[y] == self.k[w]: self.inward[y].add((x,y)) return "continue"
2349a6c727fb538b776d67238099dfc1815b16d2
Gary2018X/data_processing_primer
/E4-1.py
371
3.609375
4
# -*- coding: utf-8 -*- # author:Gary import numpy as np storages = [24, 3, 4, 23, 10, 123] print(storages) # 1. 调用array方法生成ndarray # np.array(list数据类型) np_storages = np.array(storages) print(np_storages, type(np_storages)) # 2. 调用arange方法生成ndarray # np.arange(X)生成0至X-1个整数的一元数组 # np.arange(4) # 生成[0,1,2,3]
b3c21a31df07f42f3ebee513e6b9c4f77e2f4e70
alejopijuan/Python-Projects
/Distance Conversion/smoots.py
529
3.9375
4
def conversion(data): x = data smoots = x / 5.583 return round(smoots,1) def main(): while True: y = float(input("please enter bridge lentgh in feet:")) if y >= 0: print(conversion(y)) elif y < 0: print("error number must be positive") z = input( "do you want to continue ? y/n:") if z == "y": continue else: break if __name__ == "__main__": main()
7090d875ee568146727a3c60185c70325313569b
chymoltaji/Algorithms
/MoveZeros.py
371
4.21875
4
#Given an array nums, write a function to move all zeroes to the end of it # while maintaining the relative order of the non-zero elements. array1 = [0,1,0,3,12] array2 = [1,7,0,0,8,0,10,12,0,4] def move_zeros(array): for i in array: if i == 0: array.remove(0) array.append(0) print(array) move_zeros(array1) move_zeros(array2)
3cb105cbe124891734a96d8c3e1683addecdd0b5
Bruno-morozini/Aulas_DIO_Phyton
/Coursera_Phyton/LISTA_04/Exercicio_03 .py
160
3.890625
4
x = int(input("Digite um numero para descobrir se o numero é divisivel por 5 : ")) teste = x % 5 if teste == 0: print("Buzz") else: print(x)
019eb14a799b2d3156ee235081dd7f13fb336466
JonMer1198/developer
/secondorderdiff.py
1,075
3.640625
4
from math import * def solver (a,b,c): print("This is a solution to the second order homogenous differential equation ay'' + by' + cy = 0 where the answer has:") #Case 1: if b**2 - (4.0*a*c)==0: print("repeated roots") r1= (-b/(2.0*a)) r2= (-b/(2.0*a)) r1=str(r1) r2=str(r2) return([r1,r2]) #Case 2: elif b**2 - (4.0*a*c)< 0: print("imaginary roots") re= (-b/(2.0*a)) im= (((4.0*a*c)-b**2)**0.5)/(2.0*a) r1= re r2= im r1=str(r1) r2=str(r2) return([r1,r2]) #Case 3: else: print("real roots") r1= (-b/(2.0*a)) + ((b**2 - (4.0*a*c))**0.5)/(2.0*a) r2= (-b/(2.0*a)) - ((b**2 - (4.0*a*c))**0.5)/(2.0*a) r1=str(r1) r2=str(r2) return([r1,r2]) def main (): a=1 b=(-4) c=5 r=solver(a,b,c) if b**2 - (4.0*a*c) ==0: GeneralSolution= ("A*exp("+r[0]+"x) + Bx*exp("+r[1]+"x)") elif b**2 - (4.0*a*c)< 0: GeneralSolution= ("A*exp(("+r[0]+ "-" "" "i"+r[1]+")x) + B*exp(("+r[0]+ "+" "" "i"+r[1]+")x)") else: GeneralSolution= ("A*exp("+r[0]+"x) + B*exp("+r[1]+"x)") print(GeneralSolution) main()
60c306aa373f8de0a8652a163a54a5c22d3bc79b
C4DLabOrg/ca-training
/elseif.py
373
4.375
4
''' Introducing the if - else statements ''' ''' a = 4 b = 5 if a == b: #print 'the numbers match' else: #print 'the numbers do not match' using elif statements in python ''' marks = 45 marks2 = 45 if marks > marks2: print 'marks is greater than marks2' elif marks < marks2: print 'marks is lesser than marks2' else: print 'These marks are just the same'
9d9b663881913e0e4754748748b304b59838937a
EthanDills/Sudoku-Verifier
/find_duplicate.py
1,260
3.953125
4
''' for given array A of size n, determine whether there are any duplicate values in the array ''' # Input array A = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Compute ( determine existence of duplicate ) ## could stop at any point # let int k=0 s.t. A[k] is compared to every value in A[k+1...n-1], # and when A[k] doesn't equal any value in A[k+1...n-1] # k advances by 1 until k equals n-1. ## k = 0 j = k+1 while(k < len(A)-1): # compare duplicates after A[k] (nothing after A[n-1], so only have to stop at A[n-2]) while(j < len(A) and A[k] != A[j]): # compare each value between A[k+1] to A[n-1] j += 1 # print("A[" + k.__str__() + "] doesn't equal A[" + j.__str__() + "]") if(j <= len(A)-1): # if j doesn't equal n-1, then we found a duplicate print("A[" + k.__str__() + "] equals A[" + j.__str__() + "]") break else: for i in range(k, j): # for visualization of how the max # of comparisons is (n^2 - 2)/2 print(A[i], end=" ") print() k += 1 j = k+1 # Output whether there are duplicates or not if(k == len(A)-1): # if k reaches n-1, then we found no duplicates print('no duplicates found') else: print('at least one duplicate in the array')
53dc36ab6468bd5ec9d593ce56a81e8c7a3e9188
keer2345/DataAnalysisWithPython
/Foundations-of-Computational-Agents/code/ch01/utilities.py
1,220
4.09375
4
import random def argmax(gen): """gen is a generator of (element,value) pairs, where value is a real. argmax returns an element with maximal value. If there are multiple elements with the max value, one is returned at random. """ maxv = float('-Infinity') maxvals = [] for (e, v) in gen: if v > maxv: maxvals, maxv = [e], v elif v == maxv: maxvals.append(e) return random.choice(maxvals) def filip(prob): """return ture with probalility prob""" return random.random() < prob def dict_union(d1, d2): """returns a dictionary that contains the keys of d1 and d2. The value for each key that is in d2 is the value from d2, otherwise it is the value from d1. This does not have side effects. """ d = dict(d1) # copy d1 d.update(d2) return d def test(): """test part of utilites""" assert argmax(enumerate([1, 6, 55, 3, 55, 23])) in [2, 4] assert dict_union({ 1: 4, 2: 5, 3: 4 }, { 5: 7, 2: 9 }) == { 1: 4, 2: 9, 3: 4, 5: 7 } print("Passed unit test in utilities") if __name__ == '__main__': test()
a9d5fb016e798b766c6a160b35536b824df65632
iAnafem/Python_programming
/1.12.5.py
162
3.796875
4
a, b, c = (int(input()) for i in range(3)) _list = [a, b, c] print(_list.pop(_list.index(max(_list)))) print(_list.pop(_list.index(min(_list)))) print(_list[0])
8a231aa17e56a56261c1d55eb4c5486e830d766c
mcmerle30/GolfApplication
/hole.py
1,223
3.875
4
class Hole: """ Hole object derived from data in the golfCoursesInput.csv Instance variables: hole_id a unique id for this hole (to be used as a primary key when stored in the database) course_id the id of the golf course where this hole is played hole_num the number of the hole (1-18) par the par value for this hole (3,4, or 5) """ # Please provide your definition here from Project 1-A # __init__ def __init__(self, hole_id, course_id, h_num, par): self.__hole_id = hole_id self.__course_id = course_id self.__hole_num = h_num self.__par = par # get_hole_id def get_hole_id(self): return self.__hole_id # get_course_id def get_course_id(self): return self.__course_id # get_hole_num def get_hole_num(self): return self.__hole_num # get_par def get_par(self): return self.__par # __str__ def __str__(self): csv_str = "{0},{1},{2},{3}".format(self.__hole_id, self.__course_id, self.__hole_num, self.__par) return csv_str
d042bbf5de9d9a9e8f881d435c005633f41467d3
richzw/CodeHome
/Python/qsort.py
160
3.609375
4
def qsort(l): if len(l) <= 1: return l else: qsort([x for x in l[1:] if x<l[0]]) + [l[0]] + qsort([x for x in l[1:] if x>=l[0]])
af18398c668c799ba0cb62a20d0694f829cd48f7
baloooo/coding_practice
/generate_all_parentheses.py
4,604
4
4
""" Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses of length 2*n. For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()()" Make sure the returned list of strings are sorted. Idea: As I understand, the idea is that we will add left brackets whenever possible. For a right bracket, we will add it only if the remaining number of right brackets is greater than the left one. If we had used all the left and right parentheses, we will add the new combination to the result. We can be sure that there will not be any duplicate constructed string. So to speak the basic principle here is, add left brackets whenever you can and add right whenever valid(i.e #f opening braces >= #f closing) """ class Solution(): def __init__(self): self.cur_paran_combination = [] self.balanced_paran = [] def gen_paran_latest(self, open_paran_count, close_paran_count): """ Time: O(n*catlan(n)) = O(4^n / n^(3/2)) Space: O(n*C(2n, n)/(n+1)) Detail analysis: https://leetcode.com/articles/generate-parentheses/ Idea: https://discuss.leetcode.com/topic/4485/concise-recursive-c-solution/33 open_paran_count: No. of remaining open paranthesis. '(' close_paran_count: No. of remaining closed paranthesis. ')' """ if open_paran_count == 0 and close_paran_count == 0: self.parans.append(''.join(self.cur_paran)) else: if open_paran_count > 0: self.cur_paran.append('(') self.gen_paran(open_paran_count-1, close_paran_count) self.cur_paran.pop() if open_paran_count < close_paran_count: """ Since a close paran will only come when there is already a open paran in place, which would mean the count of remaining open parans should always be less than closed parans so as to satisfy the condition that they are well formed parans. """ self.cur_paran.append(')') self.gen_paran(open_paran_count, close_paran_count-1) self.cur_paran.pop() def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ self.parans = [] self.cur_paran = [] self.gen_paran(n,n) return self.parans def gen_balanced_paran_simplified(self, n): if n<1: return [] def gen_paran(left_paran_stock, right_paran_stock): if left_paran_stock == 0 and right_paran_stock == 0: self.balanced_paran.append(''.join(self.cur_paran_combination)) if left_paran_stock != 0: self.cur_paran_combination.append('(') gen_paran(left_paran_stock-1, right_paran_stock+1) self.cur_paran_combination.pop() if right_paran_stock != 0: self.cur_paran_combination.append(')') gen_paran(left_paran_stock, right_paran_stock-1) self.cur_paran_combination.pop() gen_paran(3, 0) return self.balanced_paran def gen_balanced_paran(self, n): def gen_paran(left_paran_stock, right_paran_stock): if left_paran_stock == 0 and right_paran_stock == 0: # add balanced condn self.balanced_paran.append(''.join(self.cur_paran_combination)) # self.cur_paran_combination.pop() else: # conditions for keeping paran balanced # don't make left paran if no right paran left to cover it up if left_paran_stock != 0 and right_paran_stock != 0: self.cur_paran_combination.append('(') gen_paran(left_paran_stock-1, right_paran_stock) self.cur_paran_combination.pop() # right paran should be always greater than left param to finally cover all left param added if right_paran_stock != 0 and right_paran_stock > left_paran_stock: self.cur_paran_combination.append(')') gen_paran(left_paran_stock, right_paran_stock-1) self.cur_paran_combination.pop() if n < 1: return [] # since first paran cannot be closing paran to be balanced paran combination self.cur_paran_combination.append('(') gen_paran(n-1, n) return self.balanced_paran if __name__ == '__main__': sol = Solution() n = 0 n = 3 print sol.gen_balanced_paran(n) # print sol.gen_balanced_paran_simplified(n)
df07222b035fee2b7d36d436deec9a4d1f7042f8
arthurguerra/cursoemvideo-python
/exercises/CursoemVideo/aula23.py
744
4.03125
4
try: # onde geralmente ocorre o erro a = int(input('Numerador: ')) b = int(input('Denominador: ')) r = a / b except (ValueError, TypeError): print(f'Tivemos um problema com os tipos de dados que você digitou.') except ZeroDivisionError: print('Não é possível dividir um número por zero!') except KeyboardInterrupt: print('O usuário terminou o programa!') except Exception as erro: print(f'O erro encontrado foi {erro.__cause__}') else: # quando não houver erro print(f'O resultado é {r:.2f}') finally: # finaliza o 'try', dando erro ou não. print(' << Volte sempre! Muito Obrigado >>') ''' except Exception as erro: # tratamento de erro print(f'O problema encontrado foi {erro.__class__}') '''
7321adcb9f408490ef7596fe006a29922287510c
AtindaKevin/BootCamp
/flow control/if.py
1,018
4.0625
4
name=input("Enter your name \n") Class=input("Enter your class \n") ClassTeacher=input("Enter class teacher \n") maths=int(input("Enter maths Mark \n")) eng=int(input("Enter Eng Mark \n")) kisw=int(input("Enter kisw Mark \n")) sci=int(input("Enter sci Mark \n")) sst=int(input("Enter sst Mark \n")) average=(maths+eng+kisw+sci+sst)/5 if(average>=80): print("Grade: A") elif(average>=75): print("Grade: A-") elif(average>=70): print("Grade: B+") elif(average>=65): print("Grade: B") elif(average>=60): print("Grade: B-") elif(average>=55): print("Grade: C+") elif(average>=50): print("Grade: C") elif(average>=45): print("Grade: C-") elif(average>=40): print("Grade: D+") elif(average>=35): print("Grade: D") elif(average>=30): print("Grade: D-") else: print("Grade: F") print("NAME: ", name, "CLASS:", Class,"CLASS TEACHER", ClassTeacher, ) print("MATHS:", maths,"ENGLISH:", eng,"KISWAHILI: ", kisw,"SCIENCE: ", sci,"SOCIAL STUDIES", sst ) print("AVERAGE", average)
cea3fc8c87a5830dc310a9cf7c39f64c9af27dd3
SR2k/leetcode
/4/543.二叉树的直径.py
1,264
3.5
4
# # @lc app=leetcode.cn id=543 lang=python3 # # [543] 二叉树的直径 # # https://leetcode-cn.com/problems/diameter-of-binary-tree/description/ # # algorithms # Easy (56.63%) # Likes: 988 # Dislikes: 0 # Total Accepted: 203.6K # Total Submissions: 359.4K # Testcase Example: '[1,2,3,4,5]' # # 给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。 # # # # 示例 : # 给定二叉树 # # ⁠ 1 # ⁠ / \ # ⁠ 2 3 # ⁠ / \ # ⁠ 4 5 # # # 返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。 # # # # 注意:两结点之间的路径长度是以它们之间边的数目表示。 # # from commons.Tree import TreeNode # @lc code=start class Solution: def diameterOfBinaryTree(self, root: TreeNode) -> int: result = 0 def helper(node: TreeNode): if not node: return 0 l, r = helper(node.left), helper(node.right) nonlocal result result = max(l + r + 1, result) return max(l, r) + 1 helper(root) return result - 1 # @lc code=end
cd48c39e1acc00d146710ef097c2702df3e603df
stabradi/euler
/sam/euler_7.py
377
3.75
4
primes = [2, 3, 5, 7] def is_prime(num, primes): for p in primes: if not (n % p): return False return True prime_count = 4 n = 7 while True: n += 1 if is_prime(n , primes): #print "prime: {}".format(n) primes.append(n) prime_count += 1 if prime_count > 10000: print primes[-1] break
b08662340a6f8fbf4f7ac1b5276e748d57336668
daniel-reich/ubiquitous-fiesta
/jwiJNMiCW6P5d2XXA_7.py
124
3.609375
4
def does_rhyme(txt1, txt2): if txt1[len(txt1)-2].lower()==txt2[len(txt2)-2].lower(): return True else: return False
00a5795c39029a6e97fc77302fa61e5a4d6be3c1
rabiaasif/Python
/BSTree.py
4,699
3.734375
4
#!/bin/python class BSTree: ''' Note: keys appear at most one time in this tree ''' def __init__(self): self._tree=BSTreeNull() def delete(self, key): self._tree=self._tree.delete(key) def insert(self, key): self._tree=self._tree.insert(key) def is_empty(self): return(self._tree.is_empty()) def print_inorder(self): self._tree.print_inorder() def print_preorder(self): self._tree.print_preorder() def print_postorder(self): self._tree.print_postorder() def get_max(self): return self._tree.get_max() def get_min(self): return self._tree.get_min() def find(self, key): ''' return whether key is in this tree ''' return self._tree.find(key) def range(self, lower, upper): ''' return a list of all keys in self between lower (inclusive) and upper (exclusive)''' if lower<upper: return self._tree.range(lower, upper) else: return [] def height(self): return self._tree.height() def __str__(self): return str(self._tree) class BSTreeNode: def __init__(self, key): self._left=BSTreeNull() self._right=BSTreeNull() self._key=key def height(self): left = self._left.height() right = self._right.height() bigger = max(left,right) return bigger + 1 def delete(self, key): if key<self._key: self._left=self._left.delete(key) return self if key>self._key: self._right=self._right.delete(key) return self # key == self._key if self._left.is_null() and self._right.is_null(): return self._left # any BSTreeNull will do if self._left.is_null(): return self._right if self._right.is_null(): return self._left m=self._left.get_max() self._key=m._key self._left=self._left.delete(self._key) return self def print_postorder(self): self._left.print_postorder() self._right.print_postorder() print(str(self._key)+ " " ) return def print_preorder(self): print(str(self._key)+ " " ) self._left.print_preorder() self._right.print_preorder() return def print_inorder(self): self._left.print_inorder() print(str(self._key)+ " " ) self._right.print_inorder() return def get_min(self): m=self._left.get_min() if m.is_null(): return self else: return m def get_max(self): m=self._right.get_max() if m.is_null(): return self else: return m def is_null(self): return False def insert(self, key): ''' insert key in my subtree if not already there, return the root of my subtree ''' if key<self._key: self._left=self._left.insert(key) elif key>self._key: self._right=self._right.insert(key) else: pass return self def find(self, key): ''' return whether key is in this subtree ''' if key<self._key: return self._left.find(key) elif self._key<key: return self._right.find(key) else: # self._key=key return True def range(self, lower, upper): ''' return a list of all keys in this subtree between lower (inclusive) and upper (exclusive)''' if self._key<=lower: left=[] else: left=self._left.range(lower, upper) if lower<=self._key and self._key<upper: middle=[self._key] else: middle=[] if upper<self._key: right=[] else: right=self._right.range(lower, upper) return left+middle+right def __str__(self): return str(self._left)+" "+str(self._key)+" "+str(self._right) def is_empty(self): return False class BSTreeNull: def __init__(self): pass def height(self): return 0 def delete(self, key): return self def is_empty(self): return True def is_null(self): return True def get_max(self): return self def get_min(self): return self def print_inorder(self): return def print_preorder(self): return def print_postorder(self): return def insert(self, key): ''' insert key in my subtree if not already there, return the root of my subtree ''' return BSTreeNode(key) def find(self, key): return False def range(self, lower, upper): ''' return a list of all keys in this subtree between lower (inclusive) and upper (exclusive)''' return [] def __str__(self): return "" if __name__ == '__main__': t=BSTree() print(t.is_empty()) t=BSTree() for v in [65, 2, 99, 22, 132, 5, 22, 6]: t.insert(v) print("after t.insert("+str(v)+") str(t)="+str(t)) for v in [22, 44, 65, 22,7,2, 1, 99, 102, 132, 5, 6, 22, 159]: print("t.find(",v,")=",t.find(v)) # 2 5 6 22 65 99 132 for (lower, upper) in [(-5, 200), (-5, 100), (3, 200), (6, 99), (22, 22), (22, 23), (15, 7)]: print("t.range(",lower,",",upper,")=", t.range(lower, upper)) for v in [22, 44, 65, 7,2, 22, 99, 102, 132, 5, 6]: t.delete(v) print("after t.delete(",v,") str(t)="+str(t))
4e6def2c9bbc328a98440cf20710cb05cb82f121
goelhardik/programming
/leetcode/implement_queue_using_stacks/sol.py
1,049
4.03125
4
""" Implemented stack using the python list. Used standard stack operations only. For the size of the stack, len operation is used. It means the same thing effectively. """ class Queue(object): def __init__(self): """ initialize your data structure here. """ self.s1 = [] self.s2 = [] def push(self, x): """ :type x: int :rtype: nothing """ self.s1.append(x) def pop(self): """ :rtype: nothing """ if (len(self.s2) > 0): self.s2.pop() else: while (len(self.s1) > 0): self.s2.append(self.s1.pop()) self.s2.pop() def peek(self): """ :rtype: int """ if (len(self.s1) > 0): return self.s1[0] else: return self.s2[len(self.s2) - 1] def empty(self): """ :rtype: bool """ if (len(self.s2) == 0 and len(self.s1) == 0): return True return False
7f080b48e2512963087e2437daaabf7a54cff021
pecholi/jobeasy-python-course
/lesson_5/homework_5_1.py
1,326
4.1875
4
# FOR LOOPS EXERCISES # Enter your name, save it in name variable and create function print_name_three_times which return value is equal to # your name three times name_1 = 'Jimmy' def print_name_three_times(name): if name == name_1: return name*3 # pass # Modify your previous program so that it will enter your name (save it in variable name_2) and a number # (save in variable number) and then display their name that number of times. Each time add your name to result # variable name_2 = 'Jimmy' number_1 = 10 def print_name_number_times(number, name): if name == name_2: count = 0 result = '' while count < number: result = result + name count += 1 return result #pass # Enter a random string, which include only digits. Write function sum_digits which find a sum of digits in this string # and save it in string_number_1 = '4324376375383723296' def sum_digits(string): sum0 = 0 for char in string: if char.isdigit(): sum0 += int(char) return sum0 #pass # Create function which sum up all even numbers between 2 and 100 (include 100) def sum_even_numbers(): sum1 = 0 count = 0 for i in range(2, 102, 2): if i % 2 == 0: sum1 += i return sum1 #pass
1d6b8ddc5c4e6e6ca196ac420edbdbf62c726707
aford4074/HackerRank
/python/regex/intro.py
618
4.03125
4
''' Introduction to Regex Module Sample Input 4 4.0O0 -1.00 +4.54 SomeRandomStuff Sample Output False True True False ''' def verify(): inputs = ['4.0O0', '-1.00', '+4.54', 'SomeRandomStuff', '+-4.0', '', '4.-0', '+.2'] answers = [False, True, True, False, False, False, False, True] for i, a in zip(inputs, answers): print(i, a, is_float(i)) import re def is_float(float_str): try: float(float_str) except ValueError: return False return bool(re.match(r'(\+|\-)?[0-9]*[.][0-9]+$', float_str)) n = int(input()) for _ in range(n): print(is_float(input()))
3f82d06bce690a1cd6a2b9e174b247c817ec1c64
EdwaRen/Competitve-Programming
/Leetcode/395.longest-substring-with-at-least-k-repeating-characters.py
1,918
3.71875
4
import collections class Solution(object): def longestSubstring(self, s, k): # Two pointer solution """ We iterate 1-26 to still be O(n) but also enforcing times to change the left pointer Otherwise, we would not know when to increase/decrease each two pointer bound """ max_len = 0 # This loop enforces the amount of unique elements in a substring T, only 26 possibilities thus O(n) for i in range(1, 26): # Set variables for two pointer process at every iteration unique = 0 left = 0 right = 0 # Record occurances in two_pointer subset in a hashmap cur_map = collections.defaultdict(int) # Record number of unique elements with greater than k occurances greater_than_k = 0 # Two pointers while right < len(s): # Expand right bounds when we are under our unique-limit if unique <= i: if cur_map[s[right]] == 0: unique +=1 cur_map[s[right]] +=1 if cur_map[s[right]] == k: greater_than_k +=1 right +=1 # Otherwise, expand left bounds else: cur_map[s[left]] -=1 if cur_map[s[left]] == 0: unique -=1 if cur_map[s[left]] == k -1: greater_than_k -=1 left+=1 # Conditions necessary to consider new max if unique == greater_than_k and unique == i: max_len = max(max_len, right - left) return max_len z = Solution() s = "dcababbcabab" k = 2 print(z.longestSubstring(s, k))
995ff158ba3f0eed8cc016ea198eae3f9e0c2c36
Ljubica17/xo4
/xo4_fcn.py
3,681
3.75
4
def create_board(): return ['-', '-', '-', '-', '-', '-', '-', '-', '-'] def prepare_board_for_display(board): return 'Koordinate su \n 1|2|3 \n 4|5|6 \n 7|8|9\n' + "--------------\n" +\ board[0] + '|' + board[1] + '|' + board[2] + "\n" + \ board[3] + '|' + board[4] + '|' + board[5] + "\n" +\ board[6] + '|' + board[7] + '|' + board[8] + "\n" def read_position(board): valid = False position = '0' while not valid: position = input("Odabrati poziciju od 1 do 9:") while position not in ['1', '2', '3', '4', '5', '6', '7', '8', '9']: position = input("Odabrati poziciju od 1 do 9:") position = int(position) - 1 if board[position] == '-': valid = True return position def play_turn(player, board, position): board[position] = player return board def switch_player(player): if player == 'x': player = 'o' elif player == 'o': player = 'x' return player def winner_by_rows(board): winner = None row_1 = board[0] == board[1] == board[2] != '-' row_2 = board[3] == board[4] == board[5] != '-' row_3 = board[6] == board[7] == board[8] != '-' if row_1: winner = board[0] if row_2: winner = board[3] if row_3: winner = board[6] return winner def winner_by_columns(board): winner = None column_1 = board[0] == board[3] == board[6] != '-' column_2 = board[1] == board[4] == board[7] != '-' column_3 = board[2] == board[5] == board[8] != '-' if column_1: winner = board[0] if column_2: winner = board[1] if column_3: winner = board[2] return winner def winner_by_diagonals(board): winner = None diagonal_1 = board[0] == board[4] == board[8] != '-' diagonal_2 = board[2] == board[4] == board[6] != '-' if diagonal_1: winner = board[0] if diagonal_2: winner = board[2] return winner def get_winner(board): winner = None if winner_by_rows(board) is not None: winner = winner_by_rows(board) elif winner_by_columns(board) is not None: winner = winner_by_columns(board) elif winner_by_diagonals(board) is not None: winner = winner_by_diagonals(board) return winner def has_winner(board): if get_winner(board) is not None: return True return False def is_a_tie(board): if '-' not in board: return True return False def is_game_on(board): if has_winner(board): return False if is_a_tie(board): return False return True def main(): while True: player = 'x' board = create_board() print(prepare_board_for_display(board)) while is_game_on(board): print("Na redu je: " + player) position = read_position(board) board = play_turn(player, board, position) print(prepare_board_for_display(board)) if has_winner(board): print("Pobedio je: " + player) if is_a_tie(board): print("Nereseno je.\n") player = switch_player(player) continue_game = input('Da li zelite da nastavite igru(Y,N):') while continue_game not in ['Y', 'y', 'n', 'N']: continue_game = input('Pogresan unos! Da li zelite da nastavite igru(Y,N):') if continue_game == 'N' or continue_game == 'n': break
82c1507ea124f1b7bd2b53c86eafb092f829f09e
chvyqnne/nims-and-stone
/nims-stone.py
2,938
4.09375
4
# constant variables max_stones_global = 5 total_stones_global = 100 def game(total_stones, max_stones): """ This is an interactive two-player game called Nims and Stone. Each player can draw between 1 and a maximum number of stones from global max_stones, calling on the validity_check function to check if the move is allowed. The game will keep on going until the last stone is drawn, declaring the winner. :param total_stones: total amount of stones the players have to draw from precondition: must be an integer :param max_stones: maximum number of stones the players can draw each turn precondition: must be an integer :return: the winner of the game according to the last stone taken (player 1 or player 2) """ pile = total_stones print("There are", total_stones, "stones.") print("You can take a maximum of", max_stones, "stones each turn.") while pile > 0: # player one's turn player = 1 while player == 1 and pile > 0: player_one_move = int(input("Player 1: What's your move? ")) # checks if move is valid if 0 < player_one_move <= max_stones: potential_remaining = pile - player_one_move # logical conditions for game to continue or end # potential_remaining subtracts from pile if player move is valid given remaining stones if potential_remaining == 0: print("Player 1 wins!") elif potential_remaining < 0: print("Sorry, try again. You can't have a negative number of stones.") continue elif potential_remaining > 0: player = 2 pile -= player_one_move print("Total stones left:", pile) else: print("Sorry, try again.") player = 1 # player two's turn while player == 2 and pile > 0: player_two_move = int(input("Player 2: What's your move? ")) # checks if move is valid if 0 < player_two_move <= max_stones: potential_remaining = pile - player_two_move # conditions for game to continue or end # potential_remaining subtracts from pile if player move is valid given remaining stones if potential_remaining == 0: print("Player 2 wins!") elif potential_remaining < 0: print("Sorry, try again. You can't have a negative number of stones.") continue elif potential_remaining > 0: player = 1 pile -= player_two_move print("Total stones left:", pile) else: print("Sorry, try again.") player = 2 game(total_stones_global, max_stones_global)
e00148f901d20f83aa0460834b51ab4bbcbc20d9
janash/oop_design_pattern
/iterator.py
950
4.09375
4
""" Iterator class in Python. """ class Iterator(object): def __init__(self, start, end, step): self.start = start self.end = end self.step = step def __iter__(self): # any pre init self.current = self.start # you have to return iter object return self def __next__(self): """ return the next data in order """ # stopping if self.current >= self.end: raise StopIteration tmp = self.current self.current += self.step return tmp class Molecule(): def __init__(self, atoms: list): self.atoms = atoms # ...lots of other stuff... def __iter__(self): return iter(self.atoms) #--------------------------------------------------------- iterator = Iterator(1, 10, 1) for i in iterator: print(i) molecule = Molecule(['C', 'C', 'H', 'O']) for atom in molecule: print(atom)
1403102c9f8ba9e79c840efbe10c505341998680
AbiramiRavichandran/DataStructures
/Tree/SortedArrayToBalancedBST.py
1,294
3.765625
4
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def sortedArrayToBst(elements, start, end): if start > end: return None mid = (start + end) // 2 root = Node(elements[mid]) root.left = sortedArrayToBst(elements, start, mid-1) root.right = sortedArrayToBst(elements, mid + 1, end) return root def get_height(root): if not root: return 0 lheight = get_height(root.left) rheight = get_height(root.right) if lheight > rheight: return lheight + 1 else: return rheight + 1 def isBalanced(root): if root is None: return True lh = get_height(root.left) rh = get_height(root.right) if abs(lh - rh) <= 1 and isBalanced(root.right) and isBalanced(root.left): return True return False def inorder_traversal(root): nodes = [] if root.left: nodes += inorder_traversal(root.left) nodes.append(root.data) if root.right: nodes += inorder_traversal(root.right) return nodes if __name__ == "__main__": elements = [1,2,3,4,5,6,7,8] root = sortedArrayToBst(elements,0,len(elements)-1) print(inorder_traversal(root)) print(get_height(root)) print(isBalanced(root))
f732303a24769232425c90c7881f70bb156a3f9c
PangXing/leetcode
/common/BlackRandom.py
524
3.5
4
# coding:utf-8 import random class Solution(object): def __init__(self, N, blacklist): self._N = N self._blacklist = blacklist def pick(self): random_num = random.randint(0, self._N-1) while random_num in self._blacklist: if random_num == 0: random_num = self._N - 1 else: random_num -= 1 return random_num if __name__ == '__main__': solution = Solution(2, []) print solution.pick() print solution.pick()
900ae29821766f3e169c0fed5e16b839aba5fad8
Maguilarbagaria/DailyCodingProblem
/Problems/PROBLEM 4 #STRIPE#HARD.py
739
3.921875
4
#This problem was asked by Stripe. #Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. #For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3. def who_is_left(arr): k =[] for i in arr: if i >= 0: k.append(i) a = min(k) b = max(k) q = 0 for t in range(a, b+1): if t in k: q += 1 else: return(t) if q == len(k): return(t+1) lista = [3,4,-1,1] listb = [1,2,0] print(who_is_left(lista))
2cddb0c06c8077d1c70dd5dcf76f7b085a9e0309
jaleonro/Classic-algorithms
/bucketSort.py
736
3.765625
4
import math def quickSort(array, p, r): if p<r: q=partition(array,p,r) quickSort(array,p,q-1) quickSort(array,q+1,r) def partition(array,p,r): x=array[r] i=p-1 for j in range(p,r): if array[j]>=x: i=i+1 temp=array[i] array[i]=array[j] array[j]=temp temp2=array[i+1] array[i+1]=array[r] array[r]=temp2 return i+1 def bucketSort(A): C=[] n=len(A) B=[[] for _ in range(n)] for i in range(0,n): B[(math.floor((A[i])*n))].append(A[i]) for i in range(0, n): quickSort(B[i],0,(len(B[i]))-1) for i in range(0, n): C+=B[i] return C
4a07f2914de177c42a3ae77cffb88098c69aa01b
gaurav-kc/En_dec
/file_encode_types.py
2,268
3.71875
4
# this file is to handle various file encoding and decoding schemes as per the value of mode # in the pipeline, create an object of class file_encode_mode and call encodeFile or decodeFile with mode value # Also, while creating the object for class file_encode_mode, there params need to be given # 1. flags -> for code to get access to any flags # 2. args -> for code to get access to args # 3. self -> (reference to self) which is required to call any function which is present in the caller class class file_enocde_mode: def __init__(self, flags, args, caller): self.flags = flags self.args = args self.caller = caller def encodeFile(self, mode, filepath): # filepath is a path object blob = None if mode == 0: enmode = default_mode(self.flags, self.args) blob = enmode.encodeFile(filepath, self.caller) # add new modes here if blob is None: print("Some error occured while encoding with mode ",mode) exit(0) return blob def decodeFile(self, mode, fileblob, filepath, fileHeader): retfileblob = None if mode == 0: decmode = default_mode(self.flags, self.args) retfileblob = decmode.decodeFile(fileblob, filepath, fileHeader, self.caller) # add new modes here if fileblob is None: print("Some error occured while decoding in mode ",mode) exit(0) return retfileblob class default_mode(): def __init__(self, flags, args): self.flags = flags self.args = args def encodeFile(self, filepath, caller): # function takes a filepath (path object) as args. Here, we can encode a particular file as per format to compress it # or make it robust or for any other purpose with open(filepath,"rb") as temp_file: f = temp_file.read() blob = bytearray(f) # by default does nothing return blob def decodeFile(self, fileblob, filepath, fileHeader, caller): # this function is called when a fileblob has to be decoded. The filename is to get the format and decode blob accordingly. # by default does nothing return fileblob
2de9a8e68a3caefb2f75be342bcaaebb85a90479
YashSaxena75/GME
/calcu.py
1,793
3.53125
4
import sys import re #import os import time w="So u wish to continue...." class color: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[93m' WARNING = '\033[92m' FAIL = '\033[91m' # Formatting BOLD = '\033[1m' UNDERLINE = '\033[4m' # End colored text END = '\033[0m' c='' #r=None #d=None while c!='\q': r=None d=None print("\n") f=input("Enter ur first number here:") if f==re.sub('[a-zA-Z,.:@()" "!#$^&=?<>{}`~;:]','',f): print("Number is correct....") r=1 else: print(color.FAIL+"Error...."+color.END) s=input("Enter the second number here:") if s==re.sub('[a-zA-Z,.:@()" "!#$^&=?<>{}`~;:]','',s): print("Number is correct...") d=1 else: print(color.FAIL+"Error...."+color.END) if r==1 and d==1: print(color.OKGREEN+" ---------MENU---------"+color.END) print(""" 1.Addition 2.Subtraction 3.Divison 4.Multiplication """) ch=int(input("Enter ur choice here:")) if ch==1: print("Addition of two numbers is:",float(f)+float(s)) elif ch==2: print("Difference of two numbers is:",float(f)-float(s)) elif ch==3: try: print("Division of two numbers is:",float(f)/float(s)) except: print(color.FAIL+"Divide by zero Error..."+color.END) elif ch==4: print("Multiplication of two numbers is:",float(f)*float(s)) c=input("want to perfrom some more calculations then enter c and if not then enter \q here:") if c=='c': for t in w: sys.stdout.write(t) sys.stdout.flush() time.sleep(0.05) else: print("Thanks for using me!") else: c="\q" print("GOOD-BYE!")
69ac7c89e71758ce6ae30dcc1c6033e2a54ad3e0
aritraaaa/Competitive_Programming
/Number_Theory/EulerTotientFunc.py
694
3.703125
4
''' Author: @amitrajitbose Problem : https://www.hackerearth.com/practice/math/number-theory/totient-function/practice-problems/algorithm/euler-totient-function/ ''' def SieveOfEratosthenes(n): prime = [True for i in range(n+1)] p=2 while(p * p <= n): # If prime[p] is not changed, then it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p * 2, n+1, p): prime[i] = False p+=1 prime[1]=False return prime N=int(input()) prime=SieveOfEratosthenes(N+1) ans=N for i in range(2,N+1): if(prime[i] and N%i==0): ans=ans*(1-(1/i)) print(int(ans))
933ef0a7be213c9a7bb36f447d2a0c916a1ccd9c
f-fathurrahman/ffr-MetodeNumerik
/chapra_7th/ch06/chapra_example_6_1_with_func.py
655
3.609375
4
# Simple fixed-point iteration # f(x) = exp(-x) - x # The equation is transformed to # x = exp(-x) = g(x) # # x_{i+1} = exp(-x_{i}) import numpy as np def f(x): return np.exp(-x) - x def g(x): return np.exp(-x) def root_fixed_point(g, x0, NiterMax=100, TOL=1e-10): # Initial guess x = x0 for i in range(1,NiterMax+1): xnew = g(x) Δx = np.abs(xnew - x) print("%3d %18.10f %13.5e" % (i, xnew, Δx)) # we are not using relative error here if Δx < TOL: x = xnew break x = xnew return x xroot = root_fixed_point(g, 0.0) print("At root: f(x) = ", f(xroot))