blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
1c80f06edf2685be2307b28843a24f612cd5fbc0
AndreeaGherghe/Home-assignments
/task2.py
313
4.03125
4
myName=input("Hello! What is your name?") userNumber = input("Tell me your favourite number between 1 and 100 and I will tell you a joke") if userNumber == "50": print("Who's there? Doctor. Doctor who? You've seen that TV show?") else: print("Who's there? Yah. Yah who? No, I prefer google.")
f416784019ea3f5626472160d7c4eed5e1048a90
florinrm/ASC-Lab-Tutorial
/Lab2/threads.py
1,341
3.546875
4
from threading import Thread from math import ceil lst = [] NO_THREADS = 8 # varianta 1 - extindem clasa Thread si suprascriem metoda run class MyThread(Thread): def __init__(self, index): Thread.__init__(self) self.index = index def run(self): start = self.index * ceil(len(lst) / NO_THREADS) end = min(len(lst), ((self.index + 1) * ceil(len(lst) / NO_THREADS))) for i in range(start, end): lst[i] += 1 def increment(index): start = index * ceil(len(lst) / NO_THREADS) end = min(len(lst), ((index + 1) * ceil(len(lst) / NO_THREADS))) for i in range(start, end): lst[i] += 1 def main(): global lst # varianta 1 print('Varianta 1') lst = [x for x in range(1, 21)] print(lst) threads = [] for i in range(0, NO_THREADS): threads.append(MyThread(i)) threads[-1].start() for t in threads: t.join() print(lst) # varianta 2 print('Varianta 2') lst = [x for x in range(1, 21)] print(lst) threads = [] for i in range(0, NO_THREADS): threads.append(Thread(target=increment(i))) threads[-1].start() for t in threads: t.join() print(lst) if __name__ == '__main__': main()
3e35c29bf046b03689362f16db474c3e0b48c2e2
prade7970/PirplePython
/secondassignment_purple_functions.py
927
3.78125
4
""" Pirple Assignment 1 - Variables """ # Describe a song song_name = 'Feliz Navidad' #name song_year= 1988 #year released song_duration_sec= 180 #duration of the song song_composer = 'Anonymous' #Composed song_copyright_owner= 'Public License' #Copyright owners song_spotify_enabled = False #Availability on Spotify song_played_number=10 #Number of Times song played song_genre='Christmas Carol' #Genre of the song song_favorited_number=20 def GetSongName(song_name): return song_name def GetSongGenre(song_genre): return song_genre def CheckIfSongOnSpotify(song_spotify_enabled): if (song_spotify_enabled==True): return "you can listen to this on spotify" else: return "Sorry!" print("Song Name is " + GetSongName(song_name) + '\n' + "Song Genre is " + GetSongGenre(song_genre) + '\n' + "Spotify Availability :" + CheckIfSongOnSpotify(song_spotify_enabled) )
49578056f606280dfa2218085d5e3d2432dac621
sqayum/StudyGroups
/StudyGroupNotes/Extra/dashboards.py
2,103
3.65625
4
##################################################### ### Creating Dashboards with Python - Plotly Dash ### ##################################################### # Import libraries import dash import dash_core_components as dcc import dash_html_components as html import pandas as pd import plotly.graph_objs as go from dash.dependencies import Input, Output from dash.exceptions import PreventUpdate import dash_bootstrap_components as dbc # Load data at the start of the file. df = pd.read_csv('weight-height.csv') # Create an app. app = dash.Dash(__name__, external_stylesheets=[dbc.themes.SOLAR]) app.title = 'My App' # Setup a simple html `div`. my_heading = html.H1('This is an <h1> text!') # Creating a graph. graph = dcc.Graph(id='graph') # Creating a dropdown. menu_items = [ dict(label='Height', value='Height'), dict(label='Weight', value='Weight') ] dropdown_menu = dcc.Dropdown( id='dropdown', options=menu_items, value=None ) # Creating a Graph / Dropdown Div graph_div = html.Div( children=[graph, dropdown_menu], style={ 'margin-top': '100px', 'margin-bottom': '100px', 'margin-right': '15%', 'margin-left': '15%' } ) # Set the layout of the app. app.layout = html.Div( id='main_div', children=[my_heading, graph_div], style={'width': '90%', 'margin': 'auto', 'padding': '30px'} ) # Callback @app.callback(Output('graph', 'figure'), Input('dropdown', 'value')) def update_figure(string): """ Input: string from dropdown which updates the paramaters of the graph. Output: graph_object. """ # By default, the `Input` is None. if not string: raise PreventUpdate traces = [] traces.append( go.Histogram(x=df[string][df.Gender=='Male'], name='Male') ) traces.append( go.Histogram(x=df[string][df.Gender=='Female'], name='Female') ) return dict( data=traces, layout=go.Layout( title=f'{string} Distribution') ) # Run the app. if __name__ == '__main__': app.run_server(debug=True)
1436c8914706df65471ce088070a3c86d52330bb
sandromelobrazil/Python_for_Pentesters
/MODULE_1_code/global-class-instance-vars.py
1,012
4.09375
4
#!/usr/bin/python # This sample code is part of the SecurityTube Python Scripting Expert course and certification # Website : http://securitytube-training.com # Author: Vivek Ramachandran # global variable i = 100 class PortScan : # class variable default_ports = [ 21, 22, 80, 443, 8080] def __init__ (self, range) : # ports_to_scan is an instance variable self.ports_to_scan = range def GetPorts(self) : return self.ports_to_scan class MyPortScan (PortScan) : def GetPorts(self) : self.ports_to_scan = [1,2,3] return self.ports_to_scan print "Global variable: " +str(i) print "Default Ports " + str( PortScan.default_ports ) PortScan.default_ports.append(200) print "Default Ports " + str( PortScan.default_ports ) newScan = PortScan([ 100, 200, 30 ]) print "New Ports to scan: " + str( newScan.GetPorts() ) print "Default ports in newScan : " + str (newScan.default_ports) newMyPortScan = MyPortScan([100]) print "Override Parent Method proof " + str(newMyPortScan.GetPorts())
002f20b1610e8a43814d00d6d1b6845b59e6f729
Aya-Mahmoud-99/MinMax
/human_vs_ human.py
537
4.03125
4
from TicTacToe import Game state=[] state.append(3) state.append([]) state.append([]) state.append([]) for i in range(3): for j in range(3): state[3].append((i,j)) end=False game=Game() while not end: a=input("Enter an action please in format of 0,1 where 0 is row 1 is column") action=tuple(int(x) for x in a.split(",")) print(action) print(state) state=game.get_successor(state,action) print(action) print(state) end,winner=game.is_terminal(state) print(winner)
aa95f7dcbc3455ff4c7c8318d00b8f3dcc69bed5
dinomoon/TIL_old
/Algorithm/Codewar/8kyu/12. Convert number to reversed array of digits.py
700
4.03125
4
#각각의 숫자를 리스트에 추가하는데..단,, 거꾸로... # ex) n =1234 => result = [4,3,2,1] #내 풀이 def digitize(n): result = [] a = str(n) for i in range(len(a)): result.insert(0, int(a[i])) return result print(digitize(1234)) #사람들 풀이 def digitize(n): return map(int, str(n)[::-1]) ##### map...? => map(function, iterables) iterable: 반복가능한 ##### def myfunc(n): ##### return len(n) ##### ##### x = map(myfunc, ('apple', 'banana', 'cherry')) => [5,6,6] ### def digitize(n): return [int(x) for x in str(n)[::-1]] #### seq[start:end:step] ##### range(10)[::2] => [0,2,4,6,8] ##### range(10)[::-1] => [9,8,7,6,5,4,3,2,1,0]
322bbd3116e0889f9c0bc0eaaf6fdcad7ce9bf8f
amitmakhija/python
/comparator_example.py
655
4.25
4
''' This function takes a list of integers and sorts the list as per the number of factors of that element. It uses comparator operator present in sort or sorted function in the form of key ''' from functools import cmp_to_key def find_factors(n): count = 0 for i in range(1,n+1): if n % i == 0: count+=1 #print(i) return count #print(find_factors(i)) def comparator(x,y): if find_factors(x) < find_factors(y): return -1 elif find_factors(x) > find_factors(y): return 1 else: return 0 lst = [2,4,6,3,8,36,49,60,128,25] lst.sort(key = cmp_to_key(comparator)) print(lst)
fc7d7946c1c94a119b3a9618055e3376abd02450
sohanghanti/LearningPython
/practiceExercise/take 2 inputs from user and interchane the values.py
214
4.09375
4
str1 = str(input("Enter first value: ")) str2 = str(input("Enter second value: ")) print("Before interchanging the value: ", str1, str2) str1, str2 = str2, str1 print("After interchanging the value: ", str1, str2)
00882d357b1f790fd450a3b82d44efb1069eb8fe
VidhyaPakath/Application_English_Thesaurus
/run_english_app.py
1,150
3.875
4
import json from difflib import get_close_matches data = json.load(open("data.json")) def definition(input_word): input_word = input_word.lower() # converting the words to lower case as dictionary has all words so if input_word in data: return data[input_word] elif len(get_close_matches(input_word, data.keys())) > 0: # to get the approx close word possible, # output of this method is a list and if the len is > 0, the first word would be most close match matching_word = get_close_matches(input_word, data.keys())[0] confirm = "Did you mean {} instead?" print(confirm.format(matching_word)) yn = input("Enter Y is yes or N if no: ") if yn == 'Y': return data[matching_word] elif yn == 'N': return "The word does not exist" else: return "Invalid input" else: return "The word does not exist" # for mismatch words word = input("Enter the word: ") output = definition(word) for out in output: if type(output) == list: print(out) else: print(output)
0c6810ea42b765c70d9aa2ca622f587ad4caefc2
harhoyz/Repo_Belajar_Class
/minggu2.py
2,341
4.4375
4
#Looping #Algoritma pengulangan supaya code kita lebih efisien dalam menjalankan perintah yang berulang #Contoh code yang tidak efisien (speed, memory, maintainance) #print("Halo") #print("Halo") #print("Halo") #print("Halo") #print("Halo") # Jenis Looping # 1. While Loop # 2. For Loop #1. While Loop # angka = 1 # angka awal adalah 1 # while angka <6 : #selama angka kurang dari 6, maka jalankan perintah di bawah # print (f"halo ke - {angka}") #tampil halo # angka +=1 #angka setiap putaran di tambahkan 1 #2. For Loop #belajar membuat list # contoh_list = [1, 2, 3, 4, 5] # contoh_list2 = ['a', 'b', 'c', 4, 5] # print(contoh_list) # print(contoh_list2) # list_item = list (range(1,11,2)) #membuat list 1 sampai 11 dengan step 2 # print(list_item) #Belajar Menggunakan For Loop # list_item = list (range(1,11,2)) #membuat list 1 sampai 11 dengan step 2 # print (list_item) # for item in range(1,11,2) : # print(item) # for i in range (1,6) : # print("halo") # for item in range (0,5) : #pengulangan 0 sampai 5 : 0,1,2,3,4 # print ("halo") # for i in range (5) : # print("halo") # for pengulangan in range (0,5): # pengulangan perintah sebanyak range 0 sampai 5 : 0, 1, 2, 3, 4 (lima kali) # print(f'Pengulangan ke - {pengulangan}') # print("halo") # for i in range (1,11) : # print (f'Nomor urut ke - {i}') # j=1 # while j < 11 : # print (f'nomor urut ke -{j}') # j +=1 # for i in range (0,21,2) : # print (f'Nomor urut ke - {i}') # j=0 # while j < 21 : # print (f'nomor urut ke - {j}') # j +=2 #LOOP DRAWING #teks = '' # for i in range (0,5) : # teks += ' * ' # #print (teks) # print (teks) # teks2 = '' # for i in range (0,5) : # teks += ' * \n' # \n itu untuk enter # print(teks2) # teks = '' #variabel dengan nama teks yang isisnya string # for item in range (0,5) : #pengulangan perintah sebanyak jumlah item di range 0 -5 # perintah looping AWAL # for item in range (0,5) : #pengulangan perintah sebanyak jumlah item di range 0 -5 # perintah looping AKHIR # teks +=' *' # perintah A # teks += '\n' # perintah B # print (teks) # teks = "" # for item in range (0,5) : # teks += ' * ' # print (teks) teks = '' for i in range(0,5): for j in range(0,i+1): teks +=(' * ') teks += '\n' print(teks)
09b05dfba129f8d032828e921c6d52dbdd9b68b3
AnvilOfDoom/PythonKursus2019
/5 gang/Opgave 6.py
1,258
3.78125
4
"""Opgave 6 - funktioner fra standardbiblioteket Stort set alt i standard bibliotet er faktisk funktioner (også nogle gange kaldt metoder eller methods på engelsk), som så virker på forskellige datatyper. Prøv f.eks. at gå ind på denne side fra den officielle python documentation https://docs.python.org/3.7/library/stdtypes.html#string-methods Der er defineret de metoder som virker på strings - hvis du scroller lidt ned. Læs documentation for følgende funktioner og lav nogle små program stumper som bruger disse funktioner: strip isdigit join (hvor du skal bruge # som adskille tegn). Hvad skal input være? """ #strip print(" aaabbbccc ".strip()) #fjerner white space rundt om indholdet i den string, funktionen anvendes på. print(" aaabbbccc ".strip("a ")) #fjerner det/de angivne symboler fra venstre og højre, stopper når den # rammer et tegn, der ikke er inkluderet i input. print('www.example.com'.strip('cmowz.')) #isdigit - input skal være en string der består af tal og kun tal print("test".isdigit()) print("123".isdigit()) print("12.3".isdigit()) print("".isdigit()) print("#123".isdigit()) #join - input skal være en liste af strings print("#".join(["This", "is", "a", "test"]))
81f484d5d8e297b24c94611902b6dc7d60adb4b0
ralevn/Python_scripts
/PyCharm_projects_2020/OOP/Abstract_magic_methods/vehicle.py
1,512
3.90625
4
class Vehicle(): def __init__(self, fuel_quantity, fuel_consumption): self.fuel_quantity = fuel_quantity self.fuel_consumption = fuel_consumption @staticmethod def air_condition(): pass def drive(self, distance): pass def refuel(self, litters): pass class Car(Vehicle): def air_condition(self): return 0.9 def drive(self, distance): if distance * (self.fuel_consumption + self.air_condition()) < self.fuel_quantity: self.fuel_quantity -= distance * (self.fuel_consumption + self.air_condition()) return self.fuel_quantity else: return self.fuel_quantity def refuel(self, litters): self.fuel_quantity += litters return self.fuel_quantity class Truck(Vehicle): def air_condition(self): return 1.6 def drive(self, distance): if distance * (self.fuel_consumption + self.air_condition()) < self.fuel_quantity: self.fuel_quantity -= distance * (self.fuel_consumption + self.air_condition()) return self.fuel_quantity else: return self.fuel_quantity def refuel(self, litters): self.fuel_quantity += litters * 0.95 car = Car(20, 5) car.drive(3) print(car.fuel_quantity) car.refuel(10) print(car.fuel_quantity) print() truck = Truck(100, 15) truck.drive(5) print(truck.fuel_quantity) truck.refuel(50) print(truck.fuel_quantity)
09aad4b6eb3597e5c462be7e21ba0238a4949f96
noamalka228/PythonExercise
/Atm.py
6,584
3.734375
4
import socket import random import sqlite3 con = sqlite3.connect('mydb.db') cur = con.cursor() # python interpreter 3.8 class Atm: # constructor. responsible for maintaining the session def __init__(self): data_to_bank="" self.my_socket = socket.socket() # creating new socket # setting the server address as loopback because the server/client is on my computer and not remote one. # connecting the socket to the server (Bank) on port 1729 self.my_socket.connect(('127.0.0.1', 1729)) while True: try: # sending the code the the server code=input("Welcome to Noam's Bank!\nLogin = 1 Create new account = 2: ") if code=='1': self.my_socket.send(bytes((code).encode())) break elif code=='2': # creating new account self.my_socket.send(bytes((code).encode())) while True: # generating a random 6 digit number and checks if its available account_number = random.randint(100000, 999999) result = cur.execute("SELECT account_number FROM Bank WHERE account_number=?", (account_number,)).fetchone() if result: # if not available, generate again continue break self.my_socket.send(bytes((str(account_number)).encode())) # sending the account number to the server print("Your account number is: %d" % account_number) name = input("Enter the account owner name: ") self.my_socket.send(bytes((name).encode())) # sending the account name to the server while True: # asking for a PIN code. if its not 4 digits long, ask for another one pin = input("Enter PIN code (must be 4 digits only): ") if len(pin) != 4: print("Incorrect PIN!\n") else: try: # checking if the PIN is consisted of digits only check = int(pin) if check < 0: print("Incorrect PIN!\n") else: break except: print("Incorrect PIN!\n") self.my_socket.send(bytes((pin).encode())) # sending the pin code to the server while True: # asking for a starting balance: it has to be positive number! balance = input("Enter the amount of money you would like to deposit: ") try: if int(balance) <= 0: print("Error! Must deposit positive amount!") else: break except: print("Incorrect amount!\n") self.my_socket.send(bytes((balance).encode())) # sending the starting balance to the server print("New bank account has been created successfully!") else: print("Wrong input! Please try again") except: print("Wrong input! Please try again") # broke the while, and now logging in to any account based on credentials while True: acc = input("Enter your account number: ") pin = input("Enter your PIN: ") # sending the credentials to the bank self.my_socket.send(bytes((acc).encode())) self.my_socket.send(bytes((pin).encode())) from_bank = self.my_socket.recv(1024).decode() # receiving answer from the bank if from_bank == "True": # if account exists # as long as we dont press 4 (exit), keep getting input from user after every action while str(data_to_bank) != "4": from_bank = self.my_socket.recv(1024).decode() print(from_bank) data_to_bank = input("") self.my_socket.send(bytes((data_to_bank).encode())) # sending the code of the action to the bank if data_to_bank=='1': # deposit amount=self.check_amount(1) self.my_socket.send(bytes(str(amount).encode())) # sending the amount to the bank if amount!=-1: # if its valid amount, print the respond from the bank (Success message) print(self.my_socket.recv(1024).decode()) elif data_to_bank=='2': # withdraw amount = self.check_amount(2) self.my_socket.send(bytes(str(amount).encode())) # sending the amount to the bank if amount != -1: # if its valid amount, print the respond from the bank (Success message) print(self.my_socket.recv(1024).decode()) elif data_to_bank=='3': # check balance print(self.my_socket.recv(1024).decode()) elif data_to_bank!='4': # any other input (except from 4) is wrong input print("Incorrect code entered! Please try again") break #getting here if 4 is pressed, ending the While else: # if doesnt exists, check again for credentials print("Incorrect credentials! Please try again") self.my_socket.close() # ending the session # checking the amount the user entered as an input to check if its a positive number def check_amount(self, flag): try: # for deposit if flag==1: amount = int(input("Enter amount to deposit in your account: ")) else: # for withdraw amount = int(input("Enter amount to withdraw from your account: ")) if amount <= 0: print("Error! Must deposit positive amount!") else: return amount except: print("Incorrect amount!\n") # if the amount is not a number return -1 # return -1 if the amount is not a positive number def main(): atm=Atm() main()
c95938185b52157110894dfa80c787722c06b07f
mihokrusic/adventOfCode2020
/utility/inputs.py
268
3.59375
4
def read(file_name): input = [] with open("inputs/" + file_name, "r") as f: for line in f: input.append(line) return input def read_str(file_name): with open("inputs/" + file_name, "r") as f: data = f.read() return data
b57372429569cb39bb5cd02ec3842ab35ab2ca44
VisusAdAstra/Eternity
/functions/common.py
3,220
4.59375
5
import exceptions.exceptions as exceptions def factorial(argument: int) -> int: """Returns the product of all non-negative integers less than or equal to some non-negative integer. Args: argument (int): Non-negative integer used as input to factorial function Returns: int: Product of all non-negative integers less than or equal to 'argument' Raises: InputError: If 'argument' is not a non-negative integer """ # Ensure that input is an integer. if int(argument) != argument: raise exceptions.InputError(argument, "Input to factorial must be a positive integer.") argument = int(argument) # Ensure that input is non-negative. if argument < 0: raise exceptions.InputError(argument, "Input to factorial must be a positive integer.") # Calculate factorial using repeated multiplication. result = 1 for i in range(1, argument + 1): result *= i return result def is_even(argument: int) -> bool: """Returns true is input is even and false otherwise. Args: argument (int): Value to be checked Returns: bool: True if 'argument' is even and false otherwise Raises: InputError: If 'argument' is not an integer """ # Ensure that argument is an integer. if not isinstance(argument, int): raise exceptions.InputError(argument, "Parity of non-integers is undefined.") return not (argument & 1) def is_odd(argument: int) -> bool: """Returns true is input is odd and false otherwise. Args: argument (int): Value to be checked Returns: bool: True if 'argument' is odd and false otherwise Raises: InputError: If 'argument' is not an integer """ # Ensure that argument is an integer. if not isinstance(argument, int): raise exceptions.InputError(argument, "Parity of non-integers is undefined.") return argument & 1 def is_positive(argument: float) -> bool: """Returns true is input is positive and false otherwise. Args: argument (float): Value to be checked Returns: bool: True if 'argument' is positive and false otherwise """ return argument > 0 def is_negative(argument: float) -> bool: """Returns true is input is negative and false otherwise. Args: argument (float): Value to be checked Returns: bool: True if 'argument' is negative and false otherwise """ return argument < 0 def inverse(argument: float) -> float: """Returns inverse of input. Args: argument (float): Non-zero input to inverse function Returns: float: Inverse of 'argument'. Raises: InputError: If 'argument' is equal to 0 """ # Ensure that input is not equal to 0. if argument == 0: raise exceptions.InputError(argument, "Inverse of 0 is undefined.") # Calculate inverse of argument. return 1 / argument def abs(argument: float) -> float: """Returns absolute value of input. Args: argument (float): Input to function Returns: float: Absolute value of 'argument'. """ return -argument if argument < 0 else argument
68f039b8eaa39ba827078858a5f286b4e7fe9418
hkwarner/project4
/BST_Test.py
20,950
3.75
4
import unittest from Binary_Search_Tree import Binary_Search_Tree class BSTTester (unittest.TestCase): def setUp(self): self.__bst = Binary_Search_Tree() # empty def test_empty_bst(self): self.assertEqual('[ ]', str(self.__bst)) def test_empty_bst_height(self): self.assertEqual(0, self.__bst.get_height()) def test_empty_bst_removal(self): # exception with self.assertRaises (ValueError): self.assertEqual('[ ]', self.__bst.remove_element(1),'Raise ValueError') def test_empty_bst_pre_order(self): self.assertEqual('[ ]', self.__bst.pre_order()) def test_empty_bst_post_order(self): self.assertEqual('[ ]', self.__bst.post_order()) def test_empty_bst_breadth_first(self): self.assertEqual('[ ]', self.__bst.breadth_first()) # insertion - check height; printing order def test_insert_one(self): self.__bst.insert_element(1) self.assertEqual('[ 1 ]', str(self.__bst)) def test_insert_one_height(self): self.__bst.insert_element(1) self.assertEqual(1, self.__bst.get_height()) def test_pre_order_one(self): self.__bst.insert_element(1) self.assertEqual('[ 1 ]', self.__bst.pre_order()) def test_post_order_one(self): self.__bst.insert_element(1) self.assertEqual('[ 1 ]', self.__bst.post_order()) def test_breadth_first_one(self): self.__bst.insert_element(1) self.assertEqual('[ 1 ]', self.__bst.breadth_first()) def test_insert_three(self): self.__bst.insert_element(2) self.__bst.insert_element(1) self.__bst.insert_element(3) self.assertEqual('[ 1, 2, 3 ]', str(self.__bst)) def test_insert_three_height(self): self.__bst.insert_element(2) self.__bst.insert_element(1) self.__bst.insert_element(3) self.assertEqual(2, self.__bst.get_height()) def test_insert_three_pre_order(self): self.__bst.insert_element(2) self.__bst.insert_element(1) self.__bst.insert_element(3) self.assertEqual('[ 2, 1, 3 ]', self.__bst.pre_order()) def test_insert_three_post_order(self): self.__bst.insert_element(2) self.__bst.insert_element(1) self.__bst.insert_element(3) self.assertEqual('[ 1, 3, 2 ]', self.__bst.post_order()) def test_insert_three_breadth_first(self): self.__bst.insert_element(2) self.__bst.insert_element(1) self.__bst.insert_element(3) self.assertEqual('[ 2, 1, 3 ]', self.__bst.breadth_first()) def test_insert_four(self): self.__bst.insert_element(4) self.__bst.insert_element(2) self.__bst.insert_element(6) self.__bst.insert_element(3) self.assertEqual('[ 2, 3, 4, 6 ]', str(self.__bst)) def test_insert_four_height(self): self.__bst.insert_element(4) self.__bst.insert_element(2) self.__bst.insert_element(6) self.__bst.insert_element(3) self.assertEqual(3, self.__bst.get_height()) def test_insert_four_pre_order(self): self.__bst.insert_element(4) self.__bst.insert_element(2) self.__bst.insert_element(6) self.__bst.insert_element(3) self.assertEqual('[ 4, 2, 3, 6 ]', self.__bst.pre_order()) def test_insert_four_post_order(self): self.__bst.insert_element(4) self.__bst.insert_element(2) self.__bst.insert_element(6) self.__bst.insert_element(3) self.assertEqual('[ 3, 2, 6, 4 ]', self.__bst.post_order()) def test_insert_four_breadth_first(self): self.__bst.insert_element(4) self.__bst.insert_element(2) self.__bst.insert_element(6) self.__bst.insert_element(3) self.assertEqual('[ 4, 2, 6, 3 ]', self.__bst.breadth_first()) ### def test_insert_five(self): self.__bst.insert_element(4) self.__bst.insert_element(2) self.__bst.insert_element(6) self.__bst.insert_element(3) self.__bst.insert_element(5) self.assertEqual('[ 2, 3, 4, 5, 6 ]', str(self.__bst)) def test_insert_five_height(self): self.__bst.insert_element(4) self.__bst.insert_element(2) self.__bst.insert_element(6) self.__bst.insert_element(3) self.__bst.insert_element(5) self.assertEqual(3, self.__bst.get_height()) def test_insert_five_pre_order(self): self.__bst.insert_element(4) self.__bst.insert_element(2) self.__bst.insert_element(6) self.__bst.insert_element(3) self.__bst.insert_element(5) self.assertEqual('[ 4, 2, 3, 6, 5 ]', self.__bst.pre_order()) def test_insert_five_post_order(self): self.__bst.insert_element(4) self.__bst.insert_element(2) self.__bst.insert_element(6) self.__bst.insert_element(3) self.__bst.insert_element(5) self.assertEqual('[ 3, 2, 5, 6, 4 ]', self.__bst.post_order()) def test_insert_five_breadth_first(self): self.__bst.insert_element(4) self.__bst.insert_element(2) self.__bst.insert_element(6) self.__bst.insert_element(3) self.__bst.insert_element(5) self.assertEqual('[ 4, 2, 6, 3, 5 ]', self.__bst.breadth_first()) ### def test_insert_eight(self): self.__bst.insert_element(4) self.__bst.insert_element(2) self.__bst.insert_element(6) self.__bst.insert_element(1) self.__bst.insert_element(3) self.__bst.insert_element(5) self.__bst.insert_element(7) self.__bst.insert_element(8) self.assertEqual('[ 1, 2, 3, 4, 5, 6, 7, 8 ]', str(self.__bst)) def test_insert_eight_height(self): self.__bst.insert_element(4) self.__bst.insert_element(2) self.__bst.insert_element(6) self.__bst.insert_element(1) self.__bst.insert_element(3) self.__bst.insert_element(5) self.__bst.insert_element(7) self.__bst.insert_element(8) self.assertEqual(4, self.__bst.get_height()) def test_insert_eight_pre_order(self): self.__bst.insert_element(4) self.__bst.insert_element(2) self.__bst.insert_element(6) self.__bst.insert_element(1) self.__bst.insert_element(3) self.__bst.insert_element(5) self.__bst.insert_element(7) self.__bst.insert_element(8) self.assertEqual('[ 4, 2, 1, 3, 6, 5, 7, 8 ]', self.__bst.pre_order()) def test_insert_eight_post_order(self): self.__bst.insert_element(4) self.__bst.insert_element(2) self.__bst.insert_element(6) self.__bst.insert_element(1) self.__bst.insert_element(3) self.__bst.insert_element(5) self.__bst.insert_element(7) self.__bst.insert_element(8) self.assertEqual('[ 1, 3, 2, 5, 8, 7, 6, 4 ]', self.__bst.post_order()) def test_insert_eight_breadth_first(self): self.__bst.insert_element(4) self.__bst.insert_element(2) self.__bst.insert_element(6) self.__bst.insert_element(1) self.__bst.insert_element(3) self.__bst.insert_element(5) self.__bst.insert_element(7) self.__bst.insert_element(8) self.assertEqual('[ 4, 2, 6, 1, 3, 5, 7, 8 ]', self.__bst.breadth_first()) # removal def test_remove_one(self): self.__bst.insert_element(1) self.__bst.remove_element(1) self.assertEqual('[ ]', str(self.__bst)) def test_remove_one_height(self): self.__bst.insert_element(1) self.__bst.remove_element(1) self.assertEqual(0, self.__bst.get_height()) def test_romove_one_pre_order(self): self.__bst.insert_element(1) self.__bst.remove_element(1) self.assertEqual('[ ]', self.__bst.pre_order()) def test_remove_one_post_order(self): self.__bst.insert_element(1) self.__bst.remove_element(1) self.assertEqual('[ ]', self.__bst.post_order()) def test_remove_one_breadth_first(self): self.__bst.insert_element(1) self.__bst.remove_element(1) self.assertEqual('[ ]', self.__bst.breadth_first()) # insert two remove right leaf def test_remove_leaf_with_two_right(self): self.__bst.insert_element(1) self.__bst.insert_element(2) self.__bst.remove_element(2) self.assertEqual('[ 1 ]', str(self.__bst)) def test_remove_leaf_with_two_height_right(self): self.__bst.insert_element(1) self.__bst.insert_element(2) self.__bst.remove_element(2) self.assertEqual(1, self.__bst.get_height()) def test_romove_leaf_with_two_pre_order_right(self): self.__bst.insert_element(1) self.__bst.insert_element(2) self.__bst.remove_element(2) self.assertEqual('[ 1 ]', self.__bst.pre_order()) def test_romove_leaf_with_two_post_order_right(self): self.__bst.insert_element(1) self.__bst.insert_element(2) self.__bst.remove_element(2) self.assertEqual('[ 1 ]', self.__bst.post_order()) def test_romove_leaf_with_two_breadth_first_right(self): self.__bst.insert_element(1) self.__bst.insert_element(2) self.__bst.remove_element(2) self.assertEqual('[ 1 ]', self.__bst.breadth_first()) # insert two remove root def test_remove_root_with_two_right(self): self.__bst.insert_element(1) self.__bst.insert_element(2) self.__bst.remove_element(1) self.assertEqual('[ 2 ]', str(self.__bst)) def test_remove_root_with_two_height_right(self): #### self.__bst.insert_element(1) self.__bst.insert_element(2) self.__bst.remove_element(1) self.assertEqual(1, self.__bst.get_height()) def test_remove_root_with_two_pre_order_right(self): self.__bst.insert_element(1) self.__bst.insert_element(2) self.__bst.remove_element(1) self.assertEqual('[ 2 ]', self.__bst.pre_order()) def test_remove_root_with_two_pre_order_right(self): self.__bst.insert_element(1) self.__bst.insert_element(2) self.__bst.remove_element(1) self.assertEqual('[ 2 ]', self.__bst.post_order()) def test_remove_root_with_two_breadth_first_right(self): self.__bst.insert_element(1) self.__bst.insert_element(2) self.__bst.remove_element(1) self.assertEqual('[ 2 ]', self.__bst.breadth_first()) # insert two remove left leaf def test_remove_leaf_with_two_left(self): self.__bst.insert_element(1) self.__bst.insert_element(0) self.__bst.remove_element(0) self.assertEqual('[ 1 ]', str(self.__bst)) def test_remove_leaf_with_two_height_left(self): self.__bst.insert_element(1) self.__bst.insert_element(0) self.__bst.remove_element(0) self.assertEqual(1, self.__bst.get_height()) def test_romove_leaf_with_two_pre_order_left(self): self.__bst.insert_element(1) self.__bst.insert_element(0) self.__bst.remove_element(0) self.assertEqual('[ 1 ]', self.__bst.pre_order()) def test_romove_leaf_with_two_post_order_left(self): self.__bst.insert_element(1) self.__bst.insert_element(0) self.__bst.remove_element(0) self.assertEqual('[ 1 ]', self.__bst.post_order()) def test_romove_leaf_with_two_breadth_first_left(self): self.__bst.insert_element(1) self.__bst.insert_element(0) self.__bst.remove_element(0) self.assertEqual('[ 1 ]', self.__bst.breadth_first()) # insert two on left remove root def test_remove_root_with_two_left(self): self.__bst.insert_element(1) self.__bst.insert_element(0) self.__bst.remove_element(1) self.assertEqual('[ 0 ]', str(self.__bst)) def test_remove_root_with_two_height_left(self): self.__bst.insert_element(1) self.__bst.insert_element(0) self.__bst.remove_element(1) self.assertEqual(1, self.__bst.get_height()) def test_remove_root_with_two_pre_order_left(self): self.__bst.insert_element(1) self.__bst.insert_element(0) self.__bst.remove_element(1) self.assertEqual('[ 0 ]', self.__bst.pre_order()) def test_remove_root_with_two_pre_order_left(self): self.__bst.insert_element(1) self.__bst.insert_element(0) self.__bst.remove_element(1) self.assertEqual('[ 0 ]', self.__bst.post_order()) def test_remove_root_with_two_breadth_first_left(self): self.__bst.insert_element(1) self.__bst.insert_element(0) self.__bst.remove_element(1) self.assertEqual('[ 0 ]', self.__bst.breadth_first()) # remove node with two children def test_remove_root_with_three(self): self.__bst.insert_element(2) self.__bst.insert_element(1) self.__bst.insert_element(3) self.__bst.remove_element(2) self.assertEqual('[ 1, 3 ]', str(self.__bst)) def test_remove_root_with_three_height(self): self.__bst.insert_element(2) self.__bst.insert_element(1) self.__bst.insert_element(3) self.__bst.remove_element(2) self.assertEqual(2, self.__bst.get_height()) def test_remove_root_with_three_pre_order(self): self.__bst.insert_element(2) self.__bst.insert_element(1) self.__bst.insert_element(3) self.__bst.remove_element(2) self.assertEqual('[ 3, 1 ]', self.__bst.pre_order()) def test_remove_root_with_three_post_order(self): self.__bst.insert_element(2) self.__bst.insert_element(1) self.__bst.insert_element(3) self.__bst.remove_element(2) self.assertEqual('[ 1, 3 ]', self.__bst.post_order()) def test_remove_root_with_three_breadth_first(self): self.__bst.insert_element(2) self.__bst.insert_element(1) self.__bst.insert_element(3) self.__bst.remove_element(2) self.assertEqual('[ 3, 1 ]', self.__bst.breadth_first()) # remove node with only left child def test_remove_node_with_left_child(self): self.__bst.insert_element(4) self.__bst.insert_element(2) self.__bst.insert_element(6) self.__bst.insert_element(3) self.__bst.insert_element(1) self.__bst.insert_element(5) self.__bst.insert_element(8) self.__bst.insert_element(7) self.__bst.insert_element(6.5) self.__bst.remove_element(7) self.assertEqual('[ 1, 2, 3, 4, 5, 6, 6.5, 8 ]', str(self.__bst)) def test_remove_node_with_left_child_height(self): self.__bst.insert_element(4) self.__bst.insert_element(2) self.__bst.insert_element(6) self.__bst.insert_element(3) self.__bst.insert_element(1) self.__bst.insert_element(5) self.__bst.insert_element(8) self.__bst.insert_element(7) self.__bst.insert_element(6.5) self.__bst.remove_element(7) self.assertEqual(4, self.__bst.get_height()) def test_remove_node_with_left_child_pre_order(self): self.__bst.insert_element(4) self.__bst.insert_element(2) self.__bst.insert_element(6) self.__bst.insert_element(1) self.__bst.insert_element(3) self.__bst.insert_element(5) self.__bst.insert_element(8) self.__bst.insert_element(7) self.__bst.insert_element(6.5) self.__bst.remove_element(7) self.assertEqual('[ 4, 2, 1, 3, 6, 5, 8, 6.5 ]', self.__bst.pre_order()) def test_remove_node_with_left_child_post_order(self): self.__bst.insert_element(4) self.__bst.insert_element(2) self.__bst.insert_element(6) self.__bst.insert_element(1) self.__bst.insert_element(5) self.__bst.insert_element(3) self.__bst.insert_element(8) self.__bst.insert_element(7) self.__bst.insert_element(6.5) self.__bst.remove_element(7) self.assertEqual('[ 1, 3, 2, 5, 6.5, 8, 6, 4 ]', self.__bst.post_order()) def test_remove_node_with_left_child_breadth_first(self): self.__bst.insert_element(4) self.__bst.insert_element(2) self.__bst.insert_element(6) self.__bst.insert_element(1) self.__bst.insert_element(3) self.__bst.insert_element(5) self.__bst.insert_element(8) self.__bst.insert_element(7) self.__bst.insert_element(6.5) self.__bst.remove_element(7) self.assertEqual('[ 4, 2, 6, 1, 3, 5, 8, 6.5 ]', self.__bst.breadth_first()) # remove node with only right child def test_remove_node_with_right_child(self): self.__bst.insert_element(4) self.__bst.insert_element(2) self.__bst.insert_element(6) self.__bst.insert_element(1) self.__bst.insert_element(3) self.__bst.insert_element(8) self.__bst.insert_element(7) self.__bst.insert_element(10) self.__bst.insert_element(9) self.__bst.remove_element(8) self.assertEqual('[ 1, 2, 3, 4, 6, 7, 9, 10 ]', str(self.__bst)) def test_remove_node_with_right_child_height(self): self.__bst.insert_element(4) self.__bst.insert_element(2) self.__bst.insert_element(6) self.__bst.insert_element(1) self.__bst.insert_element(3) self.__bst.insert_element(8) self.__bst.insert_element(7) self.__bst.insert_element(10) self.__bst.insert_element(9) self.__bst.remove_element(8) self.assertEqual(4, self.__bst.get_height()) def test_remove_node_with_right_child_pre_order(self): self.__bst.insert_element(4) self.__bst.insert_element(2) self.__bst.insert_element(6) self.__bst.insert_element(1) self.__bst.insert_element(3) self.__bst.insert_element(8) self.__bst.insert_element(7) self.__bst.insert_element(10) self.__bst.insert_element(9) self.__bst.remove_element(8) self.assertEqual('[ 4, 2, 1, 3, 6, 9, 7, 10 ]', self.__bst.pre_order()) def test_remove_node_with_right_child_post_order(self): self.__bst.insert_element(4) self.__bst.insert_element(2) self.__bst.insert_element(6) self.__bst.insert_element(1) self.__bst.insert_element(3) self.__bst.insert_element(8) self.__bst.insert_element(7) self.__bst.insert_element(10) self.__bst.insert_element(9) self.__bst.remove_element(8) self.assertEqual('[ 1, 3, 2, 7, 10, 9, 6, 4 ]', self.__bst.post_order()) def test_remove_node_with_right_child_breadth_first(self): self.__bst.insert_element(4) self.__bst.insert_element(2) self.__bst.insert_element(6) self.__bst.insert_element(1) self.__bst.insert_element(3) self.__bst.insert_element(8) self.__bst.insert_element(7) self.__bst.insert_element(10) self.__bst.insert_element(9) self.__bst.remove_element(8) self.assertEqual('[ 4, 2, 6, 1, 3, 9, 7, 10 ]', self.__bst.breadth_first()) # exceptions def test_insert_same_value(self): with self.assertRaises(ValueError): self.__bst.insert_element(5) self.__bst.insert_element(3) self.__bst.insert_element(4) self.__bst.insert_element(5) def test_remove_non_existing_value(self): with self.assertRaises(ValueError): self.__bst.insert_element(5) self.__bst.insert_element(3) self.__bst.insert_element(4) self.__bst.remove_element(6) def test_remove_value_exceeding_volume(self): with self.assertRaises(ValueError): for i in range (4): self.__bst.insert_element(4+i) self.__bst.insert_element(3-i) for i in range(8): self.__bst.remove_element(i) self.__bst.remove_element(0) # special margin cases def test_add_four_remove_four_print(self): self.__bst.insert_element(2) self.__bst.insert_element(1) self.__bst.insert_element(3) self.__bst.insert_element(4) self.__bst.remove_element(2) self.__bst.remove_element(1) self.__bst.remove_element(3) self.__bst.remove_element(4) self.assertEqual('[ ]', str(self.__bst)) def test_add_eight_remove_eight_print(self): for i in range (4): self.__bst.insert_element(4+i) self.__bst.insert_element(3-i) for i in range (8): self.__bst.remove_element(i) self.assertEqual('[ ]', str(self.__bst)) if __name__ == '__main__': unittest.main()
223fc17c0c6462cf5cf8188553ca1f2be11663af
Demedro/Luch_DZ
/DZ_4_2.py
224
4
4
mon = int(input("введите номер месяца: ")) d = ["зима","зима","весна","весна","весна","лето","лето","лето","осень","осень","осень","зима"] print(d[mon])
7b519065193c3312707a5446bc138568e61e786a
edisontrent1337/python_robolab
/beers.py
320
3.6875
4
#!/usr/bin/env python3 def orderBeer(age, beersHad): if age < 16: print(f'Get outta here. You are only {age} y.o.') elif beersHad > 5: print(f'Go home! You are drunk, you had {beersHad} beers dude.') else: beersHad += 1 print(f'Here is your beer. Enjoy!') return beersHad
8b8fbea56feebd86fe597400d746eb99221e1f74
ww-tech/primrose
/primrose/base/transformer_sequence.py
1,223
3.859375
4
"""a simple container for a list of transformers Author(s): Carl Anderson (carl.anderson@weightwatchers.com) """ from primrose.base.transformer import AbstractTransformer class TransformerSequence: """A container for list of transformers""" def __init__(self, sequence=[]): """init a transformer sequence Args: sequence (list of transformers): list of transformers Returns: nothing. Transformers in sequence are added to the internal list """ self.sequence = [] for s in sequence: self.add(s) def add(self, transformer): """add a transformer to the sequence Returns: nothing. Side effect is to add transformer to the list Raises: Exception if transformer is not a transformer """ if not isinstance(transformer, AbstractTransformer): raise Exception("Transformer needs to extend AbstractTransformer") self.sequence.append(transformer) def transformers(self): """generate: yield each transformer Yields: yields a transformer from the list """ for transformer in self.sequence: yield transformer
514ee3c7af125f8c2f5d1f358ee9b16c6ec410a2
csenn/alg-practice
/sort/heap_sort.py
2,668
3.9375
4
# Loop backwards through the array # In first for loop, num will be len(array) # largest will be the current index # left will be its child, right will be the other child # there will not be left or right if the node is # on the bottom of the binary tree # if left < num and right < num is really asking if the nodes even exists # nodes in the lowest or second to lowest layer may not have children # Find the largest out of the 3 in the triangle def swap(arr, i, j): temp = arr[i] arr[i] = arr[j] arr[j] = temp def heap_sort(arr): # This function forces the node at the index to # be larger then its two children, and will work # its way down through the tree to put that node in # its correct location. def heapify(num, node_idx): largest = node_idx left = 2 * node_idx + 1 right = 2 * node_idx + 2 if left < num and arr[left] > arr[largest]: largest = left if right < num and arr[right] > arr[largest]: largest = right if largest != node_idx: swap(arr, node_idx, largest) # this recursive call will push a the top node down # to where it needs to be heapify(num, largest) arr_len = len(arr) # Create a max heap for idx in range(arr_len, -1, -1): heapify(arr_len, idx) # Sort the max heap # The max number will be at the very top # So place that number at the last position in the array # Then do another heapify, which will get the max number # to the top again for idx in range(arr_len-1, 0, -1): swap(arr, idx, 0) heapify(idx, 0) return arr # a = [4, 10, 3, 5, 1] a = [4,2,6,98,32,1,2,5,45,6,1, 5, 18,9, 16, 18, 67, 21, 18, 23, 78] # a = [4,2,6,98,32,1,2,5,45,6,1, 5] 15# 04 7 # 02 06 3 # 98 32 01 02 1 # 05 45 06 01 05 34 # 1 # 2 # 3 # 4 # level nodes # 0 1 1 # 1 2 3 # 2 4 7 # 3 8 15 # 4 16 31 # 5 32 63 def fix_num(num): if num < 10: return ' ' + str(num) else: return str(num) def get_spaces(num): text = '' for idx in range(0, num): text += ' ' return text def print_heap(heap): num = len(heap) level = 0 nodes = 0 node_levels = [] while True: nodes += pow(2, level) node_levels.append(nodes) if nodes > num: break level += 1 curr_index = 0 nodes = 0 for curr_level in range(0, level + 1): nodes += pow(2, curr_level) text = '' for idx in range(curr_index, nodes): if idx < num: buff = get_spaces(node_levels[level-curr_level]) text += buff + fix_num(heap[idx]) + buff curr_index += 1 print text if __name__ == 'main': heap_sort(a) print_heap(a) print a
a206eafd6129916f9be40b9bbd65743316ee0f97
shuvava/python_algorithms
/sort/merge_sort.py
2,856
3.65625
4
#!/usr/bin/env python # encoding: utf-8 # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # Copyright (c) 2017-2022 Vladimir Shurygin. All rights reserved. # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ '''Merge sort Complexity: O(n*ln(n)) require double size of memory Algorithm: 1. Split array on a half (merge_sort) recursively till 1 elements array 2. merge two pre sorted sub array (merge) (on the deepest level array contents just one element) ''' import operator def msort(x): '''Implementation of merge sort: Thomas H. Cormen Algorithms Unlocked (2013) page 54 ''' if len(x) < 2: return x result = [] mid = int(len(x) / 2) y = msort(x[:mid]) z = msort(x[mid:]) i = 0 j = 0 while i < len(y) and j < len(z): if y[i] > z[j]: result.append(z[j]) j += 1 else: result.append(y[i]) i += 1 result += y[i:] result += z[j:] return result class MergeSorted: def __init__(self): self.inversions = 0 def __call__(self, l, key=None, reverse=False): self.inversions = 0 if key is None: self.key = lambda x: x else: self.key = key if reverse: self.compare = operator.gt else: self.compare = operator.lt dest = list(l) working = [0] * len(l) self.inversions = self._merge_sort(dest, working, 0, len(dest)) return dest def _merge_sort(self, dest, working, low, high): if low < high - 1: mid = (low + high) // 2 x = self._merge_sort(dest, working, low, mid) y = self._merge_sort(dest, working, mid, high) z = self._merge(dest, working, low, mid, high) return (x + y + z) else: return 0 def _merge(self, dest, working, low, mid, high): i = 0 j = 0 inversions = 0 while (low + i < mid) and (mid + j < high): if self.compare(self.key(dest[low + i]), self.key(dest[mid + j])): working[low + i + j] = dest[low + i] i += 1 else: working[low + i + j] = dest[mid + j] inversions += (mid - (low + i)) j += 1 while low + i < mid: working[low + i + j] = dest[low + i] i += 1 while mid + j < high: working[low + i + j] = dest[mid + j] j += 1 for k in range(low, high): dest[k] = working[k] return inversions msorted = MergeSorted() if __name__ == '__main__': arr = [2, 1, 3, 1, 2] res = msort(arr.copy()) res2 = msorted(arr.copy()) origin = sorted(arr) print(f'origin={origin} res={res} res2={res2}')
148b4b523d2fffed63340c6899aad3317a4b6f80
gtang31/algorithms
/search/traverse.py
5,986
4.0625
4
""" Prints a list of keys that represents the order in which each node was visited in a tree. '#' represents an empty node. If a list[list[int]] is returned, this is highlight the number of nodes at a particular level. Implementation of different traversal methods: 1.) Pre-Order 2.) In-Order 3.) Post-Order 4.) ZigZag 5.) Level-Order """ from llist.queue import Queue from tree.binarytree import BinaryTree, Node as TreeNode from tree.bstree import BinarySearchTree from tree.heap import Heap __author__ = 'Gary Tang' class Traversal(object): def zig_zag(self, root): """ zigzag level order traversal of its nodes' values. IE, from left to right, then right to left for the next level and alternate between. :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] output, stack, temp = [[root.value]], [(root, 0)], [] while stack: node, level = stack.pop() if node and (level%2 == 0): # push right child node onto temp stack first temp.append((node.right, level+1)) temp.append((node.left, level+1)) elif node and (level%2 == 1): # push left child node onto temp stack first temp.append((node.left, level+1)) temp.append((node.right, level+1)) if not stack and temp: stack = temp output.append([node[0].value for node in temp if node[0] is not None]) temp = [] output.pop() # remove the leaf children return output def in_order(self, root): """ In-order traversal's order is: left child, parent, right child type root: TreeNode rtype: List[int] """ traversal = [] def dfs(node): """DFS helper function""" if node is None: return dfs(node.left) traversal.append(node.value) dfs(node.right) dfs(root) return traversal def pre_order(self, root): """ Pre-order traversal's order is: parent, left child, right child type root: TreeNode rtype: List[int] """ traversal = [] def dfs(node): """DFS helper function""" if node is None: return traversal.append(node.value) dfs(node.left) dfs(node.right) dfs(root) return traversal def post_order(self, root): """ Post-order traversal's order is: left child, right child, parent type root: TreeNode rtype: List[int] """ traversal = [] def dfs(node): """DFS helper function""" if node is None: return dfs(node.left) dfs(node.right) traversal.append(node.value) dfs(root) return traversal def level_order(self, node, level=0): """ Use BFS to display level order traversal: parent, left child, right child type node: TreeNode rtype: List[List[int]] """ traversal = [] if not node: return traversal q = Queue() q.enqueue((node, level)) while not q.is_empty(): node, level = q.dequeue() if node is not None: # index in traversal list represents the level in the binary tree if len(traversal)-1 < level: traversal.append([node.value]) else: traversal[level].append(node.value) q.enqueue((node.left, level+1)) q.enqueue((node.right, level+1)) return traversal # test cases # BST bst = BinarySearchTree([4, 8, 1, 2, 5, 6, 0]) assert(Traversal().level_order(bst.root) == [[4], [1, 6], [0, 2, 5, 8]]) bst = BinarySearchTree([4, 8, 1, 2, 5, 6, 0]) assert(Traversal().in_order(bst.root) == [0, 1, 2, 4, 5, 6, 8]) bst = BinarySearchTree([]) assert(Traversal().level_order(bst.root) == []) # Binary Trees t = BinaryTree([1, 2, 3, 4, 5]) assert(Traversal().in_order(t.root) == [4, 2, 5, 1, 3]) t = BinaryTree([3, 9, 20, None, None, 15, 7]) assert(Traversal().zig_zag(t.root) == [[3],[20,9],[15,7]]) t = BinaryTree([1,2,3,4,5,6,7,8,9,10,11]) assert(Traversal().zig_zag(t.root) == [[1], [3,2], [4,5,6,7], [11,10,9,8]]) t = BinaryTree([]) assert(Traversal().zig_zag(t.root) == []) t = BinaryTree([1, 2, 3, 4, 5]) assert(Traversal().pre_order(t.root) == [1, 2, 4, 5, 3]) t = BinaryTree([1, 2, 3, 4, 5]) assert(Traversal().post_order(t.root) == [4, 5, 2, 3, 1]) t = BinaryTree([1, 2, 3, 4, 5, 6, None, None, 7, 8]) assert(Traversal().level_order(t.root) == [[1], [2, 3], [4, 5 ,6], [7, 8]]) # Heaps min_heap = Heap([5,3,6,7,1,9]) t = BinaryTree(min_heap._heap_list[1:]) assert(Traversal().level_order(t.root) == [[1], [3, 6], [7, 5, 9]]) min_heap.insert(4) t = BinaryTree(min_heap._heap_list[1:]) assert(Traversal().level_order(t.root) == [[1], [3, 4], [7, 5, 9, 6]]) assert(min_heap.extract() == 1) t = BinaryTree(min_heap._heap_list[1:]) assert(Traversal().level_order(t.root) == [[3], [5, 4], [7, 6, 9]]) max_heap = Heap([5,3,6,7,1,9], 'max') t = BinaryTree(max_heap._heap_list[1:]) assert(Traversal().level_order(t.root) == [[9], [6, 7], [3, 1, 5]]) max_heap.insert(4) t = BinaryTree(max_heap._heap_list[1:]) assert(Traversal().level_order(t.root) == [[9], [6, 7], [3, 1, 5, 4]]) assert(max_heap.extract() == 9) t = BinaryTree(max_heap._heap_list[1:]) # print(Traversal().level_order(t.root)) assert(Traversal().level_order(t.root) == [[7], [6, 5], [3, 1, 4]]) assert(max_heap.extract() == 7) assert(max_heap.extract() == 6) t = BinaryTree(max_heap._heap_list[1:]) assert(Traversal().level_order(t.root) == [[5], [4, 1], [3]]) h=Heap([6,4,5]) assert(h.extract() == 4) assert(h.extract() == 5) assert(h.extract() == 6)
825963884af8bdd63faff2e9f7c7c3c7da096881
ikikenik/Kerstpuzzel-2020
/egyptian_fraction.py
1,302
4.03125
4
# Python3 program to print a fraction # in Egyptian Form using Greedy # Algorithm # import math package to use # ceiling function import math import decimal from decimal import Decimal # define a function egyptianFraction # which receive parameter nr as # numerator and dr as denominator def egyptianFraction(nr, dr): # enable large number support decimal.getcontext().prec = 100000000 nr = Decimal(nr) dr = Decimal(dr) print(f"The Egyptian Fraction Representation of {nr}/{dr} is") # empty list ef to store # denominator ef = [] # while loop runs until # fraction becomes 0 i.e, # numerator becomes 0 while nr != 0: x = Decimal(0) # taking ceiling x = math.ceil(dr / nr) # storing value in ef list ef.append(x) # updating new nr and dr nr = Decimal(x * nr - dr) dr = Decimal(dr * x) # printing the values for i in range(len(ef)): if i != len(ef) - 1: print(f" 1/{ef[i]} +", end="") else: print(f" 1/{ef[i]}") # calling the function alist = [[121, 48], [1749257, 652080]] for nr, dr in alist: egyptianFraction(nr, dr) # This code is contributed # by Anubhav Raj Singh
4ae5804d28c38f89f28b356190321217832aeeae
domonic/CS490_DomonicNeal
/LessonPlan1.py
1,623
4.40625
4
'''Input the string “Python” as a list of characters from console, delete at least 2 characters, reverse the resultant string and print it.''' '''variables''' user_string = input("Please enter a string: ") string_list = [] result_string = " " '''loop through the input string from the user and add each letter to a list''' for char in user_string: string_list.append(char) '''delete 2 of the characters from the string''' del string_list[1:3] '''take the characters from the string_list variable and turn them back into a string''' result_string = ''.join(map(str, string_list)) '''reverse string''' print((result_string[::-1])) print() print() '''Take two numbers from user and perform arithmetic operations on them.''' '''get user integer input''' user_num1 = int(input("Please enter an integer: ")) user_num2 = int(input("Please enter another integer: ")) '''operation performance on user integers''' summation = user_num1 + user_num2 difference = user_num1 - user_num2 product = user_num1 * user_num2 division = user_num1 / user_num2 '''output results''' print(summation) print(difference) print(product) print(division) print() print() ''' Write a program that accepts a sentence and replace each occurrence of ‘python’ with ‘pythons’ without using regex''' '''variables''' pythons_string = input("Please enter a string:") '''iterate through string to find occurrences of the word python and replace with pythons''' new_pythons_string = pythons_string.replace("python", "pythons") '''print new resultant string''' print("Result String: ", new_pythons_string)
d942010f5ad6745aa52cf51239bdd2b3ce91e2a0
chenjb04/fucking-algorithm
/剑指offer/7、斐波那契数列.py
865
3.78125
4
""" 写一个函数,输入 n ,求斐波那契(Fibonacci)数列的第 n 项。斐波那契数列的定义如下: F(0) = 0,   F(1) = 1 F(N) = F(N - 1) + F(N - 2), 其中 N > 1. 斐波那契数列由 0 和 1 开始,之后的斐波那契数就是由之前的两数相加而得出。 答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。   示例 1: 输入:n = 2 输出:1 示例 2: 输入:n = 5 输出:5   提示: 0 <= n <= 100 """ """ 递归 会超时 """ def fib(n: int) -> int: if n < 2: return n return (fib(n-1) + fib(n-2)) % 1000000007 """ 动态规划 """ def fib1(n: int) -> int: dp = {} dp[0] = 0 dp[1] = 1 if n >=2 : for i in range(2, n+1): dp[i] = dp[i-1] + dp[i-2] return dp[n] % 1000000007 if __name__ == '__main__': n = 5 print(fib(n)) print(fib1(n))
9a9180f30238ddef0f8126dddedc0fcceea6f8fb
DmitryVlaznev/leetcode
/1689-partitioning-into-minimum-number-of-deci-binary-numbers.py
838
3.796875
4
# 1689. Partitioning Into Minimum Number Of Deci-Binary Numbers # Medium # A decimal number is called deci-binary if each of its digits is either # 0 or 1 without any leading zeros. For example, 101 and 1100 are # deci-binary, while 112 and 3001 are not. # Given a string n that represents a positive decimal integer, return # the minimum number of positive deci-binary numbers needed so that they # sum up to n. # Example 1: # Input: n = "32" # Output: 3 # Explanation: 10 + 11 + 11 = 32 # Example 2: # Input: n = "82734" # Output: 8 # Example 3: # Input: n = "27346209830709182346" # Output: 9 # Constraints: # 1 <= n.length <= 10^5 # n consists of only digits. # n does not contain any leading zeros and represents a positive integer. class Solution: def minPartitions(self, n: str) -> int: return max(n.split(""))
6a37677ec1e4d5084d946f80b84c064d7d74161a
zs930831/Practice
/Ml/TensorflowDemo/tf简单的逻辑回归.py
1,574
3.578125
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data",one_hot=True) #参数定义 learning_rate = 0.01 training_epoch = 25 batch_size = 100 display_step=1 x=tf.placeholder(tf.float32,[None,784]) y=tf.placeholder(tf.float32,[None,10]) #变量定义 W=tf.Variable(tf.zeros([784,10])) b=tf.Variable(tf.zeros([10])) #计算预测值 pred = tf.nn.softmax(tf.matmul(x,W)+b) #计算损失值 使用相对熵计算损失值 cost=tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred),reduction_indices=1)) #定义优化器 optimizer=tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) #初始化所有变量值 init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) for epoch in range(training_epoch): avg_cost = 0. total_batch = int(mnist.train.num_examples/batch_size) for i in range(total_batch): batch_xs,batch_ys=mnist.train.next_batch(batch_size) _,c=sess.run([optimizer,cost],feed_dict={x:batch_xs,y:batch_ys}) avg_cost+=c/total_batch if (epoch+1)%display_step==0: print ("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost)) print ("Optimization Finished!") # Test model correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) # Calculate accuracy for 3000 examples accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print ("Accuracy:", accuracy.eval({x: mnist.test.images[:3000], y: mnist.test.labels[:3000]}))
93704b7c549e2f176dd64ae51a415655a0d9dcbf
angelahe/NLPPython
/S02_reg_expr.py
1,532
4.21875
4
# regular expressions part 1 # pattern identifier # \d digits # \w alphanumeric # \s white space # \D non digit # \W non-alphanumeric # \S non-whitespace # \d{3} 3 digits # pattern quantities # + occurs one or more times # {3} occurs exactly 3 times # {2,4} occurs 2 to 4 times # {3,} occurs 3 or more times # * occurs zero or more times # ? occurs once or none # example pattern code # file_\d\d matches file_25 # \w-\w\w\w matches A-b_1 # a\sb\sc matches a b c # \D\D\D matches ABC # \W\W\W\W\W matches *-+=) # \S\S\S\S matches Yoyo # Version \w-\w+ # \D{3} will match with abc # \d{2,4} will match with 123 # \w{3,} will match anycharacters123 # A*B*C will match AAACC # ? plurals? will match plural (once or none) import re text = 'the phone number is 403-555-1234. all soon.' found = '403-555-1234' in text print (f'{found}') pattern = 'phone' # find first instance my_match = re.search(pattern, text) # if found, beginning index and end index in the string print(f'found at index: {my_match.span()}') my_match.start() my_match.end() text2 = 'my phone is a new phone' match = re.search(pattern, text) all_matches = re.findall('phone', text2) print(f'number of matches is {len(all_matches)}') for match in re.finditer('phone', text2): print(match.span()) pattern_phone = r'\d\d\d-\d\d\d-\d\d\d\d' # could also be... pattern_phone2 = r'\d{3}-\d{3}-\d{4}' phone_number = re.search(pattern_phone, text) print(f'phone number found is: {phone_number.group()} beginning at index {phone_number.start()}')
4ef6297d51154d53cb6f97debbb7b80f62340abe
Neelima1234534-tech/Task4
/Task4.6.py
135
3.765625
4
def calculateSum (a,b): s = int(a) + int(b) return s num1 = "10" num2 = "20" sum = calculateSum (num1, num2) print "Sum = ", sum
0b4c934884d74d52181699471377b67d480ee301
Ronnapon/python-example
/b-controlflow5.py
320
3.890625
4
successful = True for number in range(5): if successful: print("you correct") break else: print("Bye") print("*" * 5) # nested Loop for a in range(1): for b in range(1, 13): c = 2 * b print(f"2 * {b} = {c}") for k in "Python": print(k) for j in [1, 2, 3]: print(j)
605f3a06f501d01df9cac8399e06a464764380ca
RunarVestmann/inngangur-i-almenna-forritun
/vika3/verkefni/dice_rolls.py
304
3.890625
4
import random number = int(input("Enter how many times: ")) dice_dict = {} for i in range(number): roll = random.randint(1, 6) if roll in dice_dict: dice_dict[roll] += 1 else: dice_dict[roll] = 1 for key in dice_dict: print(f"{key} came up {dice_dict[key]} times")
3b743762f341068e6fc1eba89c1daddcca50ec1c
amaranand/python
/unpacking_arguments.py
207
3.578125
4
def calculate_area(length, width, length2, width2): area = length * width print (area) area2 = length2 * width2 print (area2) square1 = [20, 30, 50, 70] calculate_area(*square1)
11b1360f24044e3dfe38aeea30e25b91921ce7f4
mareaokim/hello-world
/03_7번points.py
854
4.4375
4
import math def main(): print("This program calculates the distance between two points.") print() x1 = float(input("Enter the x for the first points : ")) y1 = float(input("Enter the y for the first points : ")) print() x2 = float(input("Enter the x for the second points : ")) y2 = float(input("Enter the y for the second points : ")) distance = math.sqrt((x2 - x1) **2 + (y2 - y1) ** 2) print() print("The distance between the points is" , distance) main() >>>>>>>> This program calculates the distance between two points. Enter the x for the first points : 9 Enter the y for the first points : 5.6 Enter the x for the second points : 222.3 Enter the y for the second points : 36 The distance between the points is 215.4554478308683 Press any key to continue . . .
3681c8d089a9213b0357bbea1cc9fbefe059869c
hangongzi/leetcode
/arr/longest_word.py
872
3.78125
4
from typing import List class Solution: def longestWord(self, words: List[str]) -> str: def isCombanded(set_words: set, word: str)->bool: if not word: return True # 回溯法 for i in range(len(set_words)): if set_words[i] in word and isCombanded(set_words, word.replace(set_words[i], '')): return True return False words.sort(key=lambda x: -len(x)) ans = [] for i in range(len(words)): if ans and len(ans[-1])>len(words[i]): break if isCombanded(words[i+1:], words[i]): ans.append(words[i]) if not ans: return "" ans.sort() return ans[0] print(Solution().longestWord(["bbbbb","bbbbbb","bb","bb","bbb","bbbbb","bbbbbbbb","bbb","bbbbbbb"]))
75ab0c5bed1dc998aec3bce9421e50600fd248c0
tishyk/python_lessons
/hello_my_weight.py
843
4.4375
4
print (""" . .""") a = input(" = ") b = input(" = ") c = b/(a**2) if c>=18 and c<=25: print(" ") elif c>=25 and c<=30: print(" ") elif c>=30 and c<=35: print("1 ") elif c>=35 and c<=40: print("2 ") elif c>40: print("3 ") elif c<18: print(" ") else: print(" -. , ")
79b011cc2283541ee94d64681e2d398f2a205bfc
budaLi/jianzi
/tutle数字.py
605
3.8125
4
# @Time : 2020/6/24 20:39 # @Author : Libuda # @FileName: tutle数字.py # @Software: PyCharm # import turtle as t # t.hideturtle() # t.setup() # t.penup() # t.pencolor('red') # t.write('2',font=("Times", 33, "normal")) # t.fd(40) # t.pencolor('blue') # t.write('6',font=("Times", 33, "normal")) # t.fd(40) # t.pencolor('yellow') # t.write('0',font=("Times", 33, "normal")) # t.done() def main(m): lis = [0,1,1] tem = 0 while tem<=m: tem = lis[-2]+lis[-1] if tem>m: continue else: lis.append(tem) return lis res = main(100) print(res)
440b59dc75447620e82e1f494dca0d80a940b66e
Marcfeitosa/listadeexercicios
/ex106.py
1,129
4.09375
4
""" Desafio 106 Faça um mini-sistema que utilize o Interactive help do Python. O usuário vai digitar o comando e o manual vai aparecer. Quando o usuário digitar a palavra 'FIM', o programa se encerrerará. OBS: use cores. Cada bloco de mensagem deve vir numa cor diferente. """ from time import sleep def ajuda(comando): titulo(f"Acessando o manual do comando '{comando}'", cor='azul') print(cores['branco']) help(comando) print(cores['limpa']) sleep(2) def titulo(msg, cor='limpa'): tam = len(msg) + 4 print(cores[cor], end='') print('~' * tam) print(f' {msg}') print('~' * tam) print(cores['limpa'], end='') sleep(1) cores = { 'limpa': '\033[m', 'vermelho': '\033[1;31m', 'verde': '\033[1;32m', 'amarelo': '\033[1;33m', 'azul': '\033[1;34m', 'roxo': '\033[1;35m', 'ciano': '\033[1;36m', 'branco': '\033[30m' } while True: titulo('SISTEMA DE AJUDA PyHELP', cor='verde') comando = input('Função ou Biblioteca > ').strip().lower() if comando == 'fim': break ajuda(comando) titulo('Até logo!', cor='amarelo')
4261a2dbc44dc4b3b83c732eaf7a86e4b3f60c2a
tabspacecoder/dailycodes
/dll-lab-2.py
11,448
3.859375
4
class node: def __init__(self, data): self.element = data self.next = None self.prev = None class DLList: def __init__(self): self.head = None self.tail = self.head self.sz = 0 def insertLast(self, u): # @start-editable@ newNode = node(u) if self.sz == 0: self.head = newNode self.tail = newNode self.sz = self.sz + 1 return else: self.tail.next = newNode newNode.prev = self.tail self.tail = newNode self.sz = self.sz + 1 return # @end-editable@ def insertFirst(self, u): # @start-editable@ newNode = node(u) if self.sz == 0: self.head = newNode self.tail = newNode self.sz = self.sz + 1 return else: self.head.prev = newNode newNode.next = self.head self.head = newNode self.sz = self.sz + 1 return # @end-editable@ def findNode(self, u): # @start-editable@ temp = self.head while (temp.next != None): if (temp.element == u): return temp temp = temp.next return None # @end-editable@ def insertAfter(self, u, v): # @start-editable@ present = self.findNode(v) newNode = node(u) if (present == None): print("Node not found") return elif present == self.tail: present.next = newNode newNode.prev = present self.tail = newNode self.sz += 1 return else: temp = present nextNode = temp.next temp.next = newNode newNode.prev = temp newNode.next = nextNode nextNode.prev = newNode self.sz += 1 return # @end-editable@ def insertBefore(self, u, v): # @start-editable@ newNode = node(u) present = self.findNode(v) if (present == None): print("Node not found") return elif present == self.head: present.prev = newNode newNode.next = present self.head = newNode self.sz += 1 return else: temp = present prevNode = temp.prev temp.prev = newNode newNode.next = temp newNode.prev = prevNode prevNode.next = newNode self.sz += 1 return # @end-editable@ def deleteFirst(self): # @start-editable@ if self.sz == 0: return else: temp = self.head self.head = self.head.next self.head.prev = None self.sz -= 1 return # @end-editable@ def deleteLast(self): # @start-editable@ if self.sz == 0: return else: temp = self.tail self.tail = self.tail.prev self.tail.next = None self.sz -= 1 return # @end-editable@ def deleteAfter(self, u): # @start-editable@ present = self.findNode(u) if (present == None): print("Node not found") return else: temp = present if (temp == self.tail): print("Node not found") return elif temp == self.tail.prev: toDelNode = temp.next temp.next = None toDelNode.prev = None self.tail = temp self.sz -= 1 return else: toDelNode = temp.next temp.next = toDelNode.next toDelNode.next.prev = temp self.sz -= 1 return # @end-editable@ def deleteBefore(self, u): # @start-editable@ present = self.findNode(u) if (present == None): print("Node not found") return else: temp = present if (temp == self.head): print("Node not found") return elif temp == self.head.next: toDelNode = temp.prev toDelNode.next = None temp.prev = None self.head = temp return else: toDelNode = temp.prev temp.prev = toDelNode.prev toDelNode.prev.next = temp self.sz -= 1 return # @end-editable@ def size(self): return self.sz def isEmpty(self): return self.sz == 0 def printList(self): if (self.isEmpty()): print("Linked List Empty Exception") else: count = 0 tnode = self.head while tnode != None: count = count + 1 print(tnode.element, end=" ") tnode = tnode.next if (tnode == self.head): break if (count > self.size()): break print(" ") tnode = self.tail count = 0 while tnode != None: count = count + 1 print(tnode.element, end=" ") tnode = tnode.prev if (tnode == self.tail): break if (count > self.size()): break print(" ") return # swap the nodes containing u and v def swap(self, u, v): # @start-editable@ findU = self.findNode(u) findV = self.findNode(v) if (findU == None and findV == None): print("Node not Found") return elif findU == None or findV == None: print("Node not Found") return elif (findU == self.tail and findV == self.head) or (findV == self.tail and findU == self.head): if (findU == self.tail and findV == self.head): Uprev = findU.prev Vnext = findV.next Uprev.next = findV Vnext.prev = findU findV.next = None findV.prev = Uprev findU.prev = None findU.next = Vnext self.tail = findV self.head = findU return elif (findV == self.tail and findU == self.head): Vprev = findV.prev Unext = findU.next Vprev.next = findU Unext.prev = findV findU.next = None findU.prev = Vprev findV.prev = None findV.next = Unext self.tail = findU self.head = findV return elif findU == self.head or findU == self.tail: if findU == self.head: Unext = findU.next Vprev = findV.prev Vnext = findV.next Unext.prev = findV findV.next = Unext Vprev.next = findU Vnext.prev = findU findU.next = Vnext findU.prev = Vprev findV.prev = None self.head = findV return else: Uprev = findU.prev Vprev = findV.prev Vnext = findV.next Uprev.next = findV findV.prev = Uprev Vprev.next = findU Vnext.prev = findU findU.next = Vnext findU.prev = Vprev findV.next = None self.tail = findV return elif findV == self.head or findV == self.tail: if findV == self.head: Vnext = findV.next Uprev = findU.prev Unext = findU.next Vnext.prev = findU findU.next = Vnext Uprev.next = findV Unext.prev = findV findV.next = Unext findV.prev = Uprev findU.prev = None self.head = findU return else: Vprev = findV.prev Uprev = findU.prev Unext = findU.next Vprev.next = findU findU.prev = Vprev Uprev.next = findV Unext.prev = findV findV.next = Unext findV.prev = Uprev findU.next = None self.tail = findU return else: Upos = findU Vpos = findV tempU = Upos tempV = Vpos Upos.next.prev = Vpos Upos.prev.next = Vpos Vpos.next = tempU.next Vpos.prev = tempU.Prev tempV.next.prev = Upos tempV.prev.next = Upos Upos.next = tempV.next Upos.prev = tempV.prev return # @end-editable@ def testDLL(): dll = DLList() inputs = int(input()) while inputs > 0: command = input() operation = command.split() if (operation[0] == "S"): print(dll.size()) elif (operation[0] == "I"): print(dll.isEmpty()) elif (operation[0] == "IF"): dll.insertFirst(int(operation[1])) dll.printList() elif (operation[0] == "IL"): dll.insertLast(int(operation[1])) dll.printList() elif (operation[0] == "DF"): dll.deleteFirst() dll.printList() elif (operation[0] == "DL"): dll.deleteLast() dll.printList() elif (operation[0] == 'FIND'): key = dll.findNode(int(operation[1])) if (key != None): print(key.element) else: print("Data not Found") elif (operation[0] == "IA"): dll.insertAfter(int(operation[1]), int(operation[2])) dll.printList() elif (operation[0] == "IB"): dll.insertBefore(int(operation[1]), int(operation[2])) dll.printList() elif (operation[0] == "DA"): dll.deleteAfter(int(operation[1])) dll.printList() elif (operation[0] == "DB"): dll.deleteBefore(int(operation[1])) dll.printList() elif (operation[0] == 'SW'): dll.swap(int(operation[1]), int(operation[2])) dll.printList() """elif(operation[0]=="F"): print(dll.getHead()) elif(operation[0]=='L'): print(dll.getLastNode()) """ inputs -= 1 def main(): testDLL() if __name__ == '__main__': main()
800e5e9e40693c041861fd2a16c2bdd5f3e3ac73
NiranjanRaaj/Python
/factorial.py
79
3.53125
4
a=int(input()) f=1 if (a<=20)==True: for i in range (1,a+1): f=f*i print(f)
f03c7ccf2b1d7138f869c05ed2177b7ad3d0db03
Seandor/python-web-data
/week6/parsejson.py
329
3.671875
4
import json import urllib request_url = raw_input('Enter location: ') print 'Retrieving ', request_url jsondata = urllib.urlopen(request_url).read() info = json.loads(jsondata) print info sumresult = 0 for comment in info['comments']: count = comment['count'] sumresult += int(count) print 'The sum of Number is: ', sumresult
72c066e9513cf06f5dabc253ad7db4e1a9b15f50
arunachalamev/PythonProgramming
/Algorithms/LeetCode/L0788rotatedDigits.py
1,508
3.734375
4
# X is a good number if after rotating each digit individually by 180 degrees, # we get a valid number that is different from X. Each digit must be rotated - # we cannot choose to leave it alone. # A number is valid if each digit remains a digit after rotation. # 0, 1, and 8 rotate to themselves; 2 and 5 rotate to each other; 6 and 9 rotate to each other, # and the rest of the numbers do not rotate to any other number and become invalid. # Now given a positive number N, how many numbers X from 1 to N are good? def rotatedDigits(N): myDict = {'1':'1','2':'5','5':'2','6':'9','8':'8','9':'6','0':'0'} count = 0 for i in range(1,N+1): temp = str(i) result = '' flag = 1 for ch in temp: if ch not in myDict: flag = 0 break else: result = result + myDict[ch] if flag == 1 and int(result) != i: count = count + 1 return count print (rotatedDigits(10)) #4 # There are four good numbers in the range [1, 10] : 2, 5, 6, 9. # Note that 1 and 10 are not good numbers, since they remain unchanged after rotating. def rotatedDigits2(N): ans = 0 # For each x in [1, N], check whether it's good for x in range(1, N+1): S = str(x) # Each x has only rotateable digits, and one of them # rotates to a different digit ans += (all(d not in '347' for d in S) and any(d in '2569' for d in S)) return ans
1892fad4aa5526bc8c5e46c3a0d7b53928a20ef2
DevStarSJ/algorithmExercise
/baekjoon/14584.py
632
3.765625
4
input_str = str(input()) num_words = int(input()) words = [] for _ in range(num_words): words.append(str(input())) def shift_sentence(sentence, num_shift): asciis = [ord(x) + num_shift for x in sentence] asciis = map(lambda x: x if x <= 122 else x-26, asciis) new_sentence = ''.join([chr(x) for x in asciis]) return new_sentence def find_sentence(s1): for i in range(26): sentence = shift_sentence(s1,i) #print(i,sentence) for w in words: if w in sentence: #print("FIND") print(sentence) return find_sentence(input_str)
5f5074bffce737cfc2a3e4e06e6bec56b5319d4f
janvsz/CheckiO
/Escher/Wild dogs.py
1,377
3.609375
4
from itertools import combinations from math import sqrt, hypot def wild_dogs(coords): def same_line(p1, p2, p3): x1, y1 = p1 x2, y2 = p2 x3, y3 = p3 return abs((x1 - x2) * (y1 - y3)) == abs((x1 - x3) * (y1 - y2)) def distance(group): x0, y0 = group[0] x1, y1 = group[1] # the line passing through p0 and p1 : a*x + b*y == c a = y1 - y0 b = x0 - x1 c = b * y0 + a * x0 # distance from (0, 0) to the line return abs(c) / hypot(a, b) # make group of point on same line. groups = [] for p1, p2 in combinations(coords, 2): groups.append([p for p in coords if same_line(p1, p2, p)]) # return nearest distance with max dogs. return round(min((-len(g), distance(g)) for g in groups)[1], 2) if __name__ == '__main__': print("Example:") print(wild_dogs([(7, 122), (8, 139), (9, 156), (10, 173), (11, 190), (-100, 1)])) #These "asserts" using only for self-checking and not necessary for auto-testing assert wild_dogs([(7, 122), (8, 139), (9, 156), (10, 173), (11, 190), (-100, 1)]) == 0.18 assert wild_dogs([(6, -0.5), (3, -5), (1, -20)]) == 3.63 assert wild_dogs([(10, 10), (13, 13), (21, 18)]) == 0 print("Coding complete? Click 'Check' to earn cool rewards!")
a5bd7c9e58cc74701f50bbaffae396c78148996c
garygriswold/BibleDB
/py/JesusFilmImporter.py
2,276
3.640625
4
# This is a command line program that accesses the Jesus Film API, and # populates the tables JesusFilm and Video with data of the API. # # It first finds all country codes in the World using the Region table # so that it can lookup in the API for all countries. # Next, it finds all of the sil codes (3 char lang codes) that is used in the # Bible App. So, that it will extract data only for those languages. # Next, it pulls the language code data from the JesusFilm Api for all # country codes and selecting languages. # # 28672 Mar 20 12:37 Versions.db It contains only Video table # 143360 Mar 20 13:36 Versions.db # Jesus Film is 114,688 # Jan 11, 2019, rewrite in python import io #import urllib2 import json from urllib.request import urlopen from Config import * from SqliteUtility import * out = io.open("sql/jesus_film.sql", mode="w", encoding="utf-8") out.write(u"DROP TABLE IF EXISTS JesusFilm;\n") out.write(u"CREATE TABLE JesusFilm (\n") out.write(u" country TEXT NOT NULL,\n") out.write(u" iso3 TEXT NOT NULL,\n") out.write(u" languageId TEXT NOT NULL,\n") out.write(u" population INT NOT NULL,\n") out.write(u" PRIMARY KEY(country, iso3, languageId));\n") config = Config() db = SqliteUtility(config) sql = "SELECT iso2 FROM Countries ORDER BY iso2" countries = db.selectList(sql, ()) print(countries) for country in countries: #response = urlopen("http://www.google.com/") #html = response.read() #print(html) url = "https://api.arclight.org/v2/media-countries/" + country + "?expand=mediaLanguages&metadataLanguageTags=en" url += "&apiKey=585c557d846f52.04339341" results = None try: response = urlopen(url) html = response.read() results = json.loads(html) #response = json.loads(answer.read()) except Exception as err: print("Could not process", country, str(err)) embedded = results["_embedded"] print("EMBEDDED", embedded) sys.exit() # if embedded != None: # jfpLangs = embedded["mediaLanguages"] # for lang in jfpLangs: # iso3 = lang["iso3"] # languageId = lang["languageId"] # population = lang["counts"]["countrySpeakerCount"]["value"] # sql = "INSERT INTO JesusFilm (country, iso3, languageId, population) VALUES ('%s','%s','%s',%s);\n" # out.write(sql % (country, iso3, languageId, population)) out.close() db.close()
5201c5bc441e513d2cbdeb0a099d36ac4695f748
johnriv1/Computer_Science_1_Fall_2015
/HW 9/hw9_part2.py
1,477
3.640625
4
"""Author: John Rivera Purpose: Find id's from one file that match up to user inputted restaurant, then get the reviews corresponding to the id's from another file. """ import json import textwrap r = open('reviews.json') f = open('businesses.json') business_name = raw_input("Enter a business name => ") print business_name id_set = set() business_found = True for line in f: business = json.loads(line) if business['name'] == business_name: id_set.add(business['business_id']) if len(id_set) == 0: business_found = False if business_found == False: print "This business is not found" else: review_list = [] for line in r: review = json.loads(line) if review['business_id'] in id_set: review_list.append(review['text']) if review_list == []: print "No reviews for this business is found" else: review_output = '' for i in range(len(review_list)): review_output += "\nReview %s:" %(i + 1) text = "%s" %(review_list[i]) text = text.split('\n\n') for line in text: textw = textwrap.wrap(line, 70) for line in textw: review_output += '\n' + ' ' + line review_output += '\n\n' print review_output.strip('\n') print print
b3299bd8154ad8e2edb314211865c28cf137bfa4
moheed/python
/languageFeatures/geneartorMyenumerate.py
459
4.28125
4
print("Hello World!") #Write a function my_enumerate that works like enumerate. def my_enumerate(item): #Note: generators dont need to raise StopIteration #they dont need to write __next__() and __iter__() #methods it=iter(item) i=0 while True: try: yield (i,next(it)) i+=1 except StopIteration: break x=[1,2,3,4,5] for i,item in my_enumerate(x): print(i, item)
2f3a4ca58486664bfe0325e3bb40c296d79d728e
ErickTocasca/Scripts-Miner-a-
/SCRIPTS SEGURIDAD Y SALUD MINERA/agente_quimico.py
5,429
3.625
4
print("Bienvenido este es un script para hallar el limite maximo tolerable") while True: try: print("1. Particulas Inhalables 100 micrometros") print("2. Particulas Torácica 25 micrometros") print("3. Particulas Respirables 10 micrometros") print("4. Limite de tolerancia") print("5. Verificador de Caudal") print("6. Salir") a = int(input("Digite una opción: ")) if a == 1: h = float(input("Digite el número de horas que trabaja el usuario: ")) m = float(input("Digite el número de minutos que trabaja el usuario: ")) t = float(input("Digite el Valor Limite Tolerable(TLV-TWA): ")) n = float(input("Digite el número de días que trabaja el usuario: ")) q = float(input("NIOSH 0500: Digite el flujo de succión: ")) v = float(input("NIOSH 0500: Digite el Volumen: ")) m1 = (m*1)/60 #minutos pasados a horas ht = m1+h #horas totales al día hs = ht*n #horas totales a la semana df = round(ht/((v/q)/60)) #Tiempo de duración del filtro l = [] for i in range(df): mo = float(input(f"{i+1}. Masa Inicial: ")) mf = float(input(f"{i+1}. Masa Final: ")) cn = (mf-mo)/v l.append(cn) twa = round(sum(l)*10**6/df,2) print(f"TWA = {twa} mg/m3") fcd = (8/ht)*((24-ht)/16) fcs = (40/hs)*((168-hs)/128) tlvd = t * fcd tlvs = t * fcs print(f"TLVdiario = {round(tlvd,2)} \nTLVsemanal = {round(tlvs,2)}") print("\n") print("¿Quiere calcular los Limites de Confianza: IRAM 80021?") b = int(input("Oprima 1 si quiere calcular y 2 si no: ")) if b == 1: k = float(input("Nivel de confianza: ")) cv = 0.05 s = cv * twa LCi = twa - k*s LCs = twa + k*s if LCs <= t: print(f"{LCs} CUMPLE") else: print(f"{LCs} NO CUMPLE") elif b == 2: break elif a == 2: print("Hola, todavia estamos en proceso") print("\n") elif a == 3: h = float(input("Digite el número de horas que trabaja el usuario: ")) m = float(input("Digite el número de minutos que trabaja el usuario: ")) t = float(input("Digite el Valor Limite Tolerable(TLV-TWA): ")) n = float(input("Digite el número de días que trabaja el usuario: ")) q = float(input("NIOSH 0600: Digite el flujo de succión: ")) v = float(input("NIOSH 0600: Digite el Volumen: ")) m1 = (m*1)/60 #minutos pasados a horas ht = m1+h #horas totales al día hs = ht*n #horas totales a la semana df = round(ht/((v/q)/60)) #Tiempo de duración del filtro l = [] for i in range(df): mo = float(input(f"{i+1}. Masa Inicial: ")) mf = float(input(f"{i+1}. Masa Final: ")) cn = (mf-mo)/v l.append(cn) twa = round(sum(l)*10**6/df,2) print(f"TWA = {twa} mg/m3") fcd = (8/ht)*((24-ht)/16) fcs = (40/hs)*((168-hs)/128) tlvd = t * fcd tlvs = t * fcs print(f"TLVdiario = {round(tlvd,2)} \nTLVsemanal = {round(tlvs,2)}") print("\n") print("¿Quiere calcular los Limites de Confianza: IRAM 80021?") b = int(input("Oprima 1 si quiere calcular y 2 si no: ")) if b == 1: k = float(input("Nivel de confianza: ")) cv = 0.045 s = cv * twa LCi = twa - k*s LCs = twa + k*s if LCs <= t: print(f"{LCs} CUMPLE") else: print(f"{LCs} NO CUMPLE") elif b == 2: break elif a == 4: n = int(input("Digite el número de agentes quimicos: ")) l = [] for i in range(n): m = float(input(f"{i+1}. Medido: ")) t = float(input(f"{i+1}. TLV: ")) d = m/t l.append(d) if sum(l) < 1: print(sum(l), "Cumple con el Limite Tolerable") else: print(sum(l), "No cumple con el Limite Tolerable") print("\n") elif a == 5: n = 10 la = [] lf = [] for i in range(n): m = float(input(f"{i+1}. Antes: ")) la.append(m) for j in range(n): t = float(input(f"{j+1}. Despues: ")) lf.append(t) qpa = sum(la)/n qpd = sum(lf)/n if (qpa - qpd) < 0.05: print(f"{qpa} - {qpd} es aceptable") else: print("No es aceptable") print("\n") elif a == 6: print("Fue un gusto ayudarte") break except: print("No has introducido algun argumento") print("Tienes que introducir un número del 1 al 6")
a957300250027c53824aad30039cedcc97dd01cc
huntercollegehighschool/srs1pythonbasicsf21-eaindra-naing
/part4.py
1,196
4.625
5
""" Reminder: The triangle inequality theorem states that the sum of the lengths of any two sides of a triangle must be greater than the length of the third side. The function possibletriangle will take 3 integer arguments(NOT as a list), each representing a side length of a triangle. Define possible triangle so that it returns the Boolean value True if the 3 sides make a possible triangle, and False if the 3 sides cannot be the sides of a triangle. Two examples of what this function should do (not necessarily what will appear on the console): possibletriangle(7, 5, 2) --> False #the result returned is the Boolean value False(not the string "False") possibletriangle(8, 12, 13) --> True #the result returned is the Boolean value True(not the string "True") """ def possibletriangle(side1, side2, side3): #side1, side2, and side3 will all be integers if side1 + side2 > side3 and side2 + side3 > side1 and side1 + side3 >side2: return True return False """" if program == 4: side1 = int(input("Side 1: ")) side2 = int(input("Side 2: ")) side3 = int(input("Side 3: ")) print(possibletriangle(side1, side2, side3)) """
f6a19769bfa950cea12eaed04c700f991038c7fb
nsayara/learn-python-from-scratch
/Challenges/Challenge 1.py
291
3.703125
4
#!/usr/bin/python a = int(raw_input("Enter First Number ")) b = int(raw_input("Enter Second Number ")) c=a+b print c # Question : Design an application that can take input and calculate additional_tests # Shorten the code ! #www.priyankgada.com #www.youtube.com/priyankgada
b4b8018fdc83c0e0b2a459ced9a7055247a1bb6c
Ucodek/Python-dersleri-IEEE-AGU
/1.hafta/DataTypes/example.py
742
3.8125
4
""" 85-100 A 70-84 B 60-69 C 50-60 D 0-50 F """ grade = 38 print("You got an ", end="") if grade >= 85: print("A") print("Congrulations") elif grade >=70: print("B") elif grade >= 60: print("C") elif grade >= 50: print("D") else: print("F") print("Work harder") """ Are there more than 1 maximum """ ls = [3, 6, 9, 15, 5, 7, 9, 12, 15] maxVal = max(ls) maxValCnt = ls.count(maxVal) if maxValCnt > 1: print(f"There are {maxValCnt} times {maxVal}") else: print("There are only one {maxVal}") class A: def __init__(self, a): self.a = a l = [A(3), A(5), A(8)] def f(x): return abs(x.a) arr = [int(i) if i!='0' else 1 for i in input().split()] l.sort(key = lambda x:x.a)
959ef898245a4233614dccbcf48d0db261d3e983
Paulyoufu/pythonTurtle
/shape.py
741
3.796875
4
import turtle bob = turtle.Turtle() #画四方形 def square(t,length): for i in range(4): t.lt(90) t.fd(length) square(bob,200) #画多边形 def polygon(t,length,n): for i in range(n): t.lt(360/n) t.fd(length) polygon(bob,50,30) #画圆形 def circle(t,r): for i in range(1000): t.lt(360 / 1000) t.fd(3.14*2*r/1000) circle(bob,100) #画圆形二 def arc(t,r,angle): if angle ==0: x = 0 elif angle ==360: x = 360 for i in range(int(x)): t.fd(3.14 * 2 * r / x) t.lt(1) else: x = 360/angle for i in range(int(x)): t.fd(3.14 * 2 * r / x) t.lt(angle) arc(bob,50,360)
d87f87dd20fb5918ab415046fa1d8a031b1cc8e1
JasonKYi/stone-weierstrass
/python/bernstein.py
984
3.65625
4
import numpy as np from setup import user_input def bernstein_poly(f, n): from math import factorial choose = lambda n, k: factorial(n) // (factorial(k) * factorial(n - k)) return lambda x: sum([f(k / n) * choose(n, k) * x**k * (1 - x)**(n - k) for k in range(n + 1)]) def approx_plot(is_seq = False): import matplotlib.pyplot as plt f, n, f_str = user_input() x_vals = np.linspace(0, 1, 100) if is_seq == False: approx_y_vals = np.vectorize(bernstein_poly(f, n))(x_vals) label_str = "{}-th Bernstein Approx." .format(n) plt.plot(x_vals, approx_y_vals, label = label_str) else: for i in range(1, n + 1): approx_y_vals = np.vectorize(bernstein_poly(f, i))(x_vals) label_str = "{}-th Bernstein Approx." .format(i) plt.plot(x_vals, approx_y_vals, label = label_str) plt.plot(x_vals, f(x_vals), label = f_str) plt.legend(loc = "best"); plt.show() approx_plot(is_seq = True)
8e200d32a6a542f04e5fea9f876d7c01264785b7
mattjp/leetcode
/practice/easy/2248-Intersection_of_Arrays.py
227
3.625
4
class Solution: def intersection(self, nums: List[List[int]]) -> List[int]: ans = set(nums[0]) for num in nums[1:]: ans = ans.intersection(set(num)) return sorted(list(ans))
2ff1cc02de46d6c4548190d743640654a16546e9
WilliamC07/SoftDevP0
/data/db_manager.py
8,766
4.03125
4
# db_manager is to be used to facilitate database operations. import sqlite3 DB_FILE = "spew.db" # add_login takes a username and password and stores it in the users table # returns an empty string is successful, or an appropriate error message def add_login(input_name, input_password): db = sqlite3.connect(DB_FILE) # open file c = db.cursor() # facilitate db ops message = "" c.execute("SELECT * FROM users WHERE user_name = ?;" , (input_name,)) # query rows where the username and input_name match if c.fetchone() is None: # if the username does not already exist in the database c.execute("INSERT INTO users(user_name, user_password) VALUES(?, ?);" , (input_name, input_password)) # stores the input login credentials in the users table else: message = "Username exists!" # error message for when the input_name is found in the users table db.commit() # save changes db.close() # close database return message # verify_login takes a name and password and checks if they exist in any row of the users table # returns an empty string if the login credentials are found, or an error message if they are not def verify_login(input_name, input_password): db = sqlite3.connect(DB_FILE) # open file c = db.cursor() # facilitate db ops message = "" c.execute("SELECT * FROM users WHERE user_name = ? AND user_password = ?;" , (input_name, input_password)) # query rows where the input name and password match if c.fetchone() is None: # if login credentials are not found in the users table message = "Login credentials not found!" db.commit() # save changes db.close() # close database return message # get_usernames_with_blogs is used to list the users that have made blogs # returns a list of the usernames that have created blogs def get_usernames_with_blogs(): db = sqlite3.connect(DB_FILE) # open file c = db.cursor() # facilitate db ops usernames = [] #list of all usernames c.execute("SELECT blog_author FROM blogs;") # query every blog author in the blogs table for tuple in c.fetchall(): # iterate through the rows that are returned usernames.append(tuple[0]) # add username from tuple to list of usernames db.commit() # save changes db.close() # close database return list(set(usernames)) # return list without duplicate usernames # get_blog_id_from_title takes an author and a blog title to find the blog id # returns the id of the blog if it's found, or None if it is not found def get_blog_id_from_title(username, blog_title): db = sqlite3.connect(DB_FILE) # open file c = db.cursor() # facilitate db ops id = None # initialized at none to fix bugs with viewing entries c.execute("SELECT blog_id FROM blogs WHERE blog_author = ? AND blog_name = ?;" , (username, blog_title)) # query blog_id from rows where the inputs match for row in c.fetchall(): # rows that are queried id = row[0] # id changed from None to the queried id db.commit() # save changes db.close() # close database return id # get_blogs_for_username takes a username to compare to authors in the blogs table # returns a list of every blog they have created, or an empty list if they have not created a blog def get_blogs_for_username(username): #get names of blogs for a username db = sqlite3.connect(DB_FILE) # open file c = db.cursor() # facilitate db ops blogs = [] # initialized empty list of blogs c.execute("SELECT blog_name FROM blogs WHERE blog_author = ? ORDER BY blog_last_update DESC;" , (username,)) # query blog_names from rows where the username matches the author for tuple in c.fetchall(): # iterates through rows that match the query blogs.append(tuple[0]) # add blog name from tuple to list db.commit() # save changes db.close() # close database return blogs # create_blog_for_username takes a username and title and creates a new blog in the blogs table # returns an empty string if successful, or an appropriate error message def create_blog_for_username(username, blog_title): db = sqlite3.connect(DB_FILE) # open file c = db.cursor() # facilitate db ops message = "" c.execute("SELECT * FROM blogs WHERE blog_name = ? AND blog_author = ?;" , (blog_title, username)) # query rows where the name and author match if c.fetchone() is None: # if there are no rows that match the query c.execute("INSERT INTO blogs(blog_name, blog_author) VALUES (?, ?);" , (blog_title, username)) # insert the new blog information into the table else: message = "Blog already exists!" db.commit() # save changes db.close() # close database return message # get_entries_for_blog takes a blog id and returns the entries for that blog # returns a list of tuples with the title and the content of each entry in the blog def get_entries_for_blog(blog_id): db = sqlite3.connect(DB_FILE) # open file c = db.cursor() # facilitate db ops entries = [] # initialize list of entries c.execute("SELECT * FROM entries WHERE entry_blog = ? ORDER BY entry_last_update DESC;" , (blog_id,)) # query rows in entries table where the blog id matches for tuple in c.fetchall(): # query uses ORDER BY to return the list of tuples ordered from most recently updated entries.append(tuple[2:4]) # append tuple containing the title and content db.commit() # save changes db.close() # close database return entries # is_owner takes a username and blog and checks if that user is the author of the blog # returns an True if the user is the owner, or False if they are not def is_owner(username, blog_id): #return boolean is a user is owner of a blog db = sqlite3.connect(DB_FILE) # open file c = db.cursor() # facilitate db ops ownership = False # initialize boolean to False c.execute("SELECT * FROM blogs WHERE blog_id = ? AND blog_author = ?;" , (blog_id, username)) # query rows where the id and author match if c.fetchone() is not None: # if there is such row ownership = True # the user is the author of the blog db.commit() # save changes db.close() # close database return ownership # add_entry takes a title, content, and blog and stores that information in the entries table # returns an empty string if successful, or an appropriate error message def add_entry(entry_title, entry_content, blog_id): db = sqlite3.connect(DB_FILE) # open file c = db.cursor() # facilitate db ops message = "" c.execute("SELECT * FROM entries WHERE entry_blog = ? AND entry_title = ?;" , (blog_id, entry_title)) # query rows where the information matches if c.fetchone() is None: # if there is no such row c.execute("INSERT INTO entries(entry_title, entry_content, entry_blog) VALUES (?, ?, ?);" , (entry_title, entry_content, blog_id)) # insert the information in the entries table else: message = "Entry title already exists in this blog!" db.commit() # save changes db.close() # close database return message # get_entry_id takes the title of an entry and the id of the blog to which it belongs # returns the id of the entry if the entry is found, otherwise it will return None def get_entry_id(entry_title, blog_id): db = sqlite3.connect(DB_FILE) # open file c = db.cursor() # facilitate db ops id = None # initialized at none to fix bugs with viewing entries c.execute("SELECT entry_id FROM entries WHERE entry_title = ? AND entry_blog = ?;" , (entry_title, blog_id)) # query entry_ids for rows where the input_title and blog_id are found for row in c.fetchall(): # rows that are returned id = row[0] # id changed from None to the queried id db.commit() # save changes db.close() # close database return id # remove_entry will remove an entry from the entries table given the id # returns an empty string if successful, or an appropriate error message def remove_entry(entry_id): db = sqlite3.connect(DB_FILE) # open file c = db.cursor() # facilitate db ops c.execute("SELECT * FROM entries WHERE entry_id = ?;" , (entry_id,)) # query rows in entries table where the id matches the input message = "" if c.fetchone() is not None: # if there is a row with the id c.execute("DELETE FROM entries WHERE entry_id = ?;" , (entry_id,)) # the row is deleted from the table else: message = "Entry does not exist!" # error message when the id is not found db.commit() # save changes db.close() # close database return message
f07d3c437d664b9ad4c365c6425a6eeab0373953
heerapatil/filehandlingAss
/assignment6.py
289
4.25
4
#6. Write a Python program to read a file line by line store it into a variable. def file(fname): with open (fname, "r") as f: data=f.readlines() print(data) file('text.txt') '''output: ['hello people\n', 'hi\n', 'how\n', 'are\n', 'you\n'] '''
0e6712fc84e3e86586c55b03960559d58bbb44f7
User9000/100python
/ex89.py
230
3.546875
4
#Get countries greater than 2,000,000. import sqlite3 conn = sqlite3.connect("database.db") c = conn.cursor() c.execute("SELECT country FROM countries WHERE area > '2000000' ") for i in c.fetchall(): print(i[0])
2ff52bfb86253e1d52aa1b826e74d873b503b0a7
kksinghal/mini-keras
/keras/activations/linear.py
834
3.828125
4
import numpy as np """ Linear activation function class """ class linear: """ Activate: Activate output of neuron using identity function ---------- Parameters: Z: n*m dimensional numpy matrix n = number of units in layer, m = number of datapoints Z = WX + b Returns: A: n*m dimensional numpy matrix n = number of units in layer, m = number of datapoints A = linear activated output of neuron """ def activate(self, Z): return Z """ Derivative: ------------ Returns derivative with respect to the Z=WX+b Parameters: A: n*m dimensional numpy matrix n = number of units in layer, m = number of datapoints Activations of units in layers """ def derivative(self, A): return np.ones(A.shape)
022f18682a2a8ca28611246be17622a4dcbb7a31
jornbh/Courses
/Algdat/Oving5/Boolean.py
445
3.578125
4
from sys import stdin import binascii def main(): basis = stdin.readline().split() strings ={} for i in basis: length = len(i) if length not in basis: strings[length]=[] strings[length].append(i) for i in strings: pass strings = [i.rstrip() for i in stdin] string = "aaaaaaaaaa" ints = [i-97 for i in string.encode("utf-8")] print(type(string.encode("utf-8"))) print(ints)
056a0e515f2ed38e1a7fa9119b09150985ef05e4
alejp1998/python_course
/Classes and objects/classes.py
1,419
3.9375
4
class Line: def __init__(self,coor1,coor2): self.coor1 = coor1 self.coor2 = coor2 def distance(self): xdist = abs( self.coor1(0) - self.coor2(0) ) ydist= abs( self.coor1(1) - self.coor2(1) ) distance = (xdist**2 + ydist**2)**0.5 return distance def slope(self): return ( self.coor2(1) - self.coor1(1) )/( self.coor2(0) - self.coor1(0) ) class Cylinder: def __init__(self,height=1,radius=1): self.height = height self.radius = radius def volume(self): return 3.141592*self.height*self.radius**2 def surface_area(self): return 2*3.141592*self.radius*self.height class Account: def __init__(self,owner,balance=0): self.owner = owner self.balance = balance def deposit(self,money): self.balance += money print("{}$ added to {}'s account".format(money,self.owner)) print('Your balance is {}'.format(self.balance)) def withdraw(self,money): if self.balance >= money: self.balance -= money print("{}$ extracted from {}'s account".format(money,self.owner)) print('Your balance is {}'.format(self.balance)) else: print('Not enough money. You can withdraw up to {}$'.format(self.balance)) newaccount = Account('Alex') newaccount.deposit(100) newaccount.withdraw(50) newaccount.withdraw(60)
eca16e854a768c764db4fcef0a8f9b1100138ee2
OrinaOisera/Jetbrainsprograms
/stackclass.py
330
3.90625
4
class Stack(): def __init__(self): self.item= [] def push (self, el): self.item.append(el) def pop(self): self.item.pop(-1) def peek(self): return self.item[-1] #check if the stack is empty and return True or False def is_empty(self): return len(self.item) == 0
2113bb87907213318bce76ffde5be08eaaafc6bc
gbaghdasaryan94/Kapan
/Garnik/Python 3/Strings/7.py
245
4.4375
4
# 7. Write a Python program to remove the characters which have odd index values of a given string. string = input("Please enter a string: ") result = [] for i in range(0, len(string), 2): result.append(string[i]) print(''.join(result))
e048ce2dcb603461a783cfcf8aca3ef6fdc6ba63
DefCon-007/UtiloBot-New
/utilobot/helper.py
1,016
3.578125
4
import requests def make_request(method, url, session=None, args={}): """ Make a HTTP request and returns response if it was successful :param method: :param url: :param session: :param args: Dict of request arguments like data, params, headers etc :return: response, session """ assert method and url, "Cannot create request without method and url" if not session: session = requests.Session() response = session.request(method=method, url=url, **args) if response.status_code == 200: return response, session else: print("Got invalid response, status-{}, \nresponse-{}".format(response.status_code, response.text)) return None, session def add_document_to_firestore(collectionName, docId, data): from google.cloud import firestore db = firestore.Client() doc_ref = db.collection(collectionName).document(docId) doc_ref.set(data)
956d73ee317c6d6017c6551a25b1d7c04697f80c
subramaniam-kamaraj/codekata_full
/array/find_least_occerance.py
400
3.640625
4
''' Given a number N and array of N integers, find the number which occurs the least number of times. Input Size : |N| <= 1000000 Sample Testcase : INPUT 5 3 3 4 4 7 OUTPUT 7 ''' #import collections as cs n=int(input()) lis=list(map(int,input().split())) #gets_indexes = lambda lis, xs: [i for (y, i) in zip(xs, range(len(xs))) if lis == y] #print(get_indexes) #a=cs.Counter(lis) #print(a.values())
211bb6ad515d09f0d4747c8291dc78a742329665
RuiWu-yes/leetcode
/Python/Algorithms/Sort/经典排序算法/493 H_翻转对.py
2,142
3.546875
4
# -*- coding: utf-8 -*- # @Author : ruiwu # @Email : ryanwoo@zju.edu.cn # @Title : 493 翻转对 # @Content : 给定一个数组 nums ,如果 i < j 且 nums[i] > 2*nums[j] 我们就将 (i, j) 称作一个重要翻转对。 # 你需要返回给定数组中的重要翻转对的数量。 from typing import List import bisect class Solution: def reversePairs1(self, nums: List[int]) -> int: # 二分查找 tb, res = [], 0 for n in reversed(nums): res += bisect.bisect_left(tb, n) n2 = 2 * n idx = bisect.bisect_left(tb, n2) tb.insert(idx, n2) return res def reversePairs2(self, nums: List[int]) -> int: # 归并排序 + 归并的同时统计 return self.mergeSort(nums, 0, len(nums) - 1) def mergeSort(self, nums, l, r): if l >= r: return 0 mid = l + ((r - l) >> 1) left = self.mergeSort(nums, l, mid) right = self.mergeSort(nums, mid + 1, r) return self.merge(nums, l, mid, r) + left + right def merge(self, nums, l, mid, r): ans = 0 cache = [0] * (r - l + 1) i, t, c = l, l, 0 for j in range(mid + 1, r + 1): # i这个指针指的一直都是刚刚大于2倍nums[j]的元素,因为j所在的nums[mid+1, r]有序 # 所以我们可以记录上一次的i,这样i最多也只从l到mid遍历一次 while i <= mid and (nums[i] + 1) >> 1 <= nums[j]: i += 1 while t <= mid and nums[t] < nums[j]: cache[c] = nums[t] c += 1 t += 1 cache[c] = nums[j] c += 1 ans += mid - i + 1 while t <= mid: cache[c] = nums[t] c += 1 t += 1 nums[l:r + 1] = cache return ans if __name__ == '__main__': # case1 res = 2 nums1 = [1, 3, 2, 3, 1] # case2 res = 1 nums2 = [2, 4, 3, 5, 1] sol = Solution() res1 = sol.reversePairs(nums1) res2 = sol.reversePairs(nums2) print('case1:', res1) print('case2:', res2)
1394f00ba2322efc4f923808c75fe930683fdf15
bozi6/hello-world
/python_tuts/sort_list/multiple_sort.py
775
3.703125
4
#!/usr/bin/env python3 from operator import attrgetter from typing import NamedTuple def multi_sort(data, specs): for key, reverse in reversed(specs): data.sort(key=attrgetter(key), reverse=reverse) return data class Student(NamedTuple): id: int name: str grade: str age: int s1 = Student(1, 'Patrick', 'A', 21) s2 = Student(2, 'Lucia', 'B', 19) s3 = Student(3, 'Robert', 'C', 19) s4 = Student(4, 'Monika', 'A', 22) s5 = Student(5, 'Thomas', 'D', 20) s6 = Student(6, 'Petra', 'B', 18) s6 = Student(7, 'Sofia', 'A', 18) s7 = Student(8, 'Harold', 'E', 22) s8 = Student(9, 'Arnold', 'B', 23) students = [s1, s2, s3, s4, s5, s6, s7, s8] multi_sort(students, (('grade', False), ('age', True))) for student in students: print(student)
bd5715fc14f0b356f0a3b92235af1171e477c3c0
ThinkRedstone/Stronghold2016
/Raspberry Pi/RaspberrySide/AngleHelper.py
1,351
3.984375
4
from math import asin, degrees, radians, acos, sqrt class AngleHelper(object): ''' A class that handles the angle to U calculating. ''' def __init__(self, UWidth, UHeight, centerUWidth, knownDistance): ''' This method initialising the variables for the AngleHelper instance. :param UWidth: The real life width of the U. :param centerUWidth: The U width as it looks in the camera when it is in the center (in pixels). :param knownDistance: The distance which the centerUWidth wast taken from. :return: None ''' self.UWIDTH = UWidth self.UHEIGHT = UHeight self.cameraUWidth = centerUWidth self.CUWKnownDistance = knownDistance def getAngle(self, DFC, CUW, FL, CUH): ''' This method returns the angle of the object from the tower. The angle that is calculated in this method is described in AngleDraw. :param DFC: The distance of the robot from the camera in real life. :param CUW: The current U width as it looks in the camera (in pixels). :param FL: The Focal length. :param CUH: The current U height as it looks in the camera (in pixels). :return: The angle of the object from the tower, in degrees. ''' return 331600000 # Not implemented, meanwhile 331600000
11c9ecce54992beee574944a64dc881ded488889
brian09088/basic-python
/A6-107201522-3.py
918
3.515625
4
""" Assignment 6-3 Name: 蘇柏瑜 Student Number: 107201522 Course 2020-CE1001 """ final=[] while True: up, north, south, east, west, down = 1, 2, 5, 3, 4, 6 n= int(input()) if n==0: break else: for i in range(n): dir=input() if dir == "east": east, up, west, down = up, west, down, east elif dir == "west": east, down, west, up = down, west, up, east elif dir == "north": up, south, down, north = south, down, north, up elif dir == "south": up, north, down, south = north, down, south, up final+=('Up:',up,'North:',north,'East:',east,'South:',south,'West:',west,'Down',down) continue long=len(final) for k in range(long): final[k]=str(final[k]) for p in range(long//12): print(" ".join(final[12*p:12*(p+1)]))
fe49197c4d2c6eebd8860ddd168b12510811a24d
devikamadasamy/beginner
/even_factorisation.py
99
3.8125
4
n=int(input()) for i in range(2,n): if n%i==0 and i%2==0: print(i,end=" ") if n%2==0: print(n)
27f0369d540acfa917f598319802cc444b5841d0
TechMainul-dev/Python
/Harvard_py/02.name.py
123
4.0625
4
name = ("World: ") #input("World: ") print("Hello, " + name) # formate - 1 print(f"Hello, {name}") # formate - 2
bae1a56a53bc24955df66fbe73f88f4f778f6b02
heecheol1508/algorithm-problem
/_swea/d2/미로.py
973
3.53125
4
def miro(x, y): visit[x][y] = True for i in range(4): ix = x + near[i][0] iy = y + near[i][1] if 0 <= ix < row and 0 <= iy < row: if board[ix][iy] == '3': return 1 elif board[ix][iy] == '0' and visit[ix][iy] == False: temp = miro(ix, iy) if temp == 1: return 1 if x == si and y == sj: return 0 TC = int(input()) for tc in range(1, TC+1): row = int(input()) board = [list(input()) for r in range(row)] visit = [[False]*row for r in range(row)] si = sj = 0 sflag = False for i in range(row): for j in range(row): if board[i][j] == '2': si = i sj = j sflag = True break if sflag == True: break near = [(-1, 0), (0, -1), (1, 0), (0, 1)] result = miro(si, sj) print('#{} {}'.format(tc, result))
bb3da6dbee9f04584d5fe4edf8a8bb3495171ece
IRIS-UNICAMP/Cobrinhas
/exemplo.py
352
3.578125
4
conjunto = set() for x in range(0, 620, 20): for y in range(0, 620, 20): quadrado = (x, y) conjunto.add(quadrado) nova_comida = random.choices(conjunto) """ #### 0 -> 600, 20 em 20 (x) 0 -> 600, 20 em 20, (y) conjunto = set() excluir valores que façam parte da cobra for i in range(0, 620, 20): print(i) #### """ # 32
706764fa90fa6cf8086146ca9c95beaac03ee419
NiCrook/Edabit_Exercises
/First_Ten/04.py
305
4
4
# https://edabit.com/challenge/aWLTzrRsrw7RakYrN # Write a function that takes the base and height of a triangle and return its area. # area = (base * height) / 2 def area_finder(base: float, height: float) -> float: area = (base * height) / 2 return area print(area_finder(10.0, 10.0))
05544f05b9754102e522fac94fe86abac70fef09
hellspite/nexivemanifesto
/parsexl.py
5,983
3.5
4
import openpyxl """ Funzione per il caricamento del file excel e la selezione del foglio di calcolo INPUT nome del file OUTPUT False se il file è sconosciuto oppure restituisce il foglio di calcolo """ def load_excel(file_name): try: wb = openpyxl.load_workbook(file_name) except FileNotFoundError: print("File non trovato") return False return wb """ Funzione per selezionare il foglio di calcolo dal documento excel """ def select_sheet(wb): ws = None while ws is None: sheet_num = int(input("Seleziona il numero del foglio di calcolo: ")) wb.active = (sheet_num - 1) ws = wb.active if ws is None: print("Foglio di calcolo inesistente, provare di nuovo") else: if check_sheet(ws) is False: print(f'Hai selezionato il foglio: {ws.title}') print("Foglio di calcolo non valido, provare di nuovo") ws = None else: correct = None while correct != 's' and correct != 'n': correct = input('Hai selezionato il foglio: ' + ws.title + ' è corretto? (s/n) ') correct.lower() if correct == 'n': ws = None return ws """ Funzione per creare un nuovo foglio excel che verrà poi caricato sul sito Nexive """ def create_empty_sheet(): wb = openpyxl.Workbook() ws = wb.active ws['A1'] = "TITOLO" ws['B1'] = "COGNOME_RAGSOC" ws['C1'] = "NOME" ws['D1'] = "INFOUTILIXCONSEGNA" ws['E1'] = "VIA" ws['F1'] = "PIANOINTERNO" ws['G1'] = "CAP" ws['H1'] = "FRAZIONE" ws['I1'] = "COMUNE" ws['J1'] = "PROVINCIA" ws['K1'] = "IMPORTO_CONTRASSEGNO" ws['L1'] = "MODALITACONTRASSEGNO" ws['M1'] = "COLLI" ws['N1'] = "TAGLIA" ws['O1'] = "CELLULARE" ws['P1'] = "TELEFONO" ws['Q1'] = "EMAIL" ws['R1'] = "RIFERIMENTO_CLIENTE" ws['S1'] = "CENTRO_COSTO" ws['T1'] = "MITTENTE" ws['U1'] = "MITTENTE_NOME" ws['V1'] = "MITTENTE_VIA" ws['W1'] = "MITTENTE_CAP" ws['X1'] = "MITTENTE_COMUNE" ws['Y1'] = "MITTENTE_PROVINCIA" ws['Z1'] = "IMPORTOASSICURATA" ws['AA1'] = "PRODOTTO" ws['AB1'] = "SERVIZIO_RESI_EASY" return wb """ Funzione per contare le righe effettive da processare """ def count_rows(worksheet): col_a = worksheet['A'] row_num: int = 0 for i in col_a: if i.value is not None: row_num += 1 return row_num """ Funzione che si occupa dell'elaborazione del contenuto """ def parse_content(quantity, content): content = content.lower() content = content.replace('maglietta io rompo black', 'B') content = content.replace('maglietta io rompo orange', 'O') content = content.replace('femmina', 'F') content = content.replace('maschio', 'M') content = content.upper() if quantity > 1: content = content + " " content = content * quantity content = content.rstrip() return content """ Funzione per passare i dati dal primo foglio excel a quello definitivo per la spedizione Nexive """ def parse_xl(ws_in, wb_out): file_in = ws_in file_out = wb_out.active rows = count_rows(file_in) + 1 # Numero d'ordine for i in range(3, rows): file_out['A' + str(i - 1)] = file_in['A' + str(i)].value # Email for i in range(3, rows): file_out['Q' + str(i - 1)] = file_in['D' + str(i)].value # Nome for i in range(3, rows): file_out['B' + str(i - 1)] = file_in['E' + str(i)].value # Indirizzo for i in range(3, rows): file_out['E' + str(i - 1)] = file_in['F' + str(i)].value # Presso for i in range(3, rows): file_out['C' + str(i - 1)] = file_in['G' + str(i)].value # Città for i in range(3, rows): file_out['I' + str(i - 1)] = file_in['H' + str(i)].value # CAP for i in range(3, rows): cap = file_in['I' + str(i)].value if cap is not None: cap = int(cap) cap = str(cap) cap_len = len(cap) if cap_len < 5: for c in range(cap_len, 5): cap = '0' + cap else: cap = None file_out['G' + str(i - 1)] = cap # Provincia for i in range(3, rows): file_out['J' + str(i - 1)] = file_in['J' + str(i)].value # Telefono for i in range(3, rows): file_out['P' + str(i - 1)] = file_in['K' + str(i)].value # Taglia for i in range(3, rows): file_out['N' + str(i - 1)] = 'S' # Contenuto for i in range(3, rows): quantity = int(file_in['B' + str(i)].value) shirt = file_in['C' + str(i)].value shirt = parse_content(quantity, shirt) file_out['D' + str(i - 1)] = shirt return wb_out """ Funzione per verificare ordine su righe multiple """ def check_rows(wb): wb = wb ws = wb.active rows = count_rows(ws) prev_order = 0 double_list = [] for i, row in enumerate(ws.iter_rows(min_row=2, max_row=rows, min_col=1, max_col=4)): if row[0].value == prev_order: double_list.append((i - 1, i)) prev_order = row[0].value if len(double_list) > 0: to_delete = [] for o, d in double_list: o_index = o + 2 d_index = d + 2 ws['D' + str(o_index)] = ws['D' + str(o_index)].value + ' ' + ws['D' + str(d_index)].value to_delete.append(d_index) counter = 0 for d in to_delete: ws.delete_rows(d - counter) counter += 1 return wb """ Funzione per verificare validità foglio di calcolo """ def check_sheet(sheet): if sheet is None: return False if sheet.title[:6].lower() == 'ordini': return True elif sheet.title[:6].lower() == 'ordine': return True else: return False
eddd04ef32ad5ca453850c88d5d2b33228e10c6e
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/anagram/60586ca28c254c87b308d7b107995034.py
277
3.625
4
def detect_anagrams(word, candidates): word = word.lower() canon = sorted(word) # Who says a word can't be its own anagram? That's ridiculous. I'm doing this under protest. return [cand for cand in candidates if sorted(cand.lower()) == canon and cand.lower() != word]
654b38dbe0c5205965a68e0153ea847a87757518
mahendra49/task-capital
/app.py
1,089
3.59375
4
from flask import Flask, request from processCountries import processData import json app = Flask(__name__) capitals = processData() @app.route('/') def hello(): return ("Hello DataGrokr.! The API is https://sample-python-app-task.herokuapp.com/capital?country=India") """ This API will give the capital of the given country The format is "https://sample-python-app-task.herokuapp.com/capital?country=%%%" Replace the %%% in above url with the country name Response is in the json with keys error and message if error is true then either country name is not provided or incorrect country name """ @app.route('/capital' , methods=['GET']) def getCapital(): if request.args.get('country','') == "": return json.dumps({ 'error':True , 'message':"No country name provided"}) if request.args.get('country','') in capitals: return json.dumps({ 'error':False , 'capital':capitals[request.args.get('country')]}) else: return json.dumps({ 'error':True ,'message':"Invalid country name"}) if __name__ == '__main__': app.run()
e9636fbf591355f3bd69f8c6434284158bce21b0
kulkarnidk/datastructurePrograms
/UnOrdered_List.py
3,141
4.0625
4
import array class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None self.last_node = None def insert(self, data): """data:takes data as input if node is not present then creates a node if present then adds the node to the next of the current node """ if self.last_node is None: self.head = Node(data) self.last_node = self.head else: self.last_node.next = Node(data) self.last_node = self.last_node.next def print(self): """ this method will print the data in the node by traversing from head :return:not return anything """ current = self.head while current is not None: print(current.data, end=" ") current = current.next def search(self, element): """ :param element:element to be search from the list be passed here :return:if data present will returns true if not present returns false """ current = self.head while current != None: if current.data == element: return True current = current.next return False def delete(self, element): """ :param element:deleting a perticular element from node :return:not return anything """ current = self.head while current != None: if self.head.data == element: self.head = self.head.next break if current.data == element: self.last_node.next = current.next break self.last_node = current current = current.next def poll_first(self): """ :return:it will return first element of the list """ self.last_node = self.head self.head = self.head.next return self.last_node.data def size_of_node(self): """ :return:it will return size of the node """ current=self.head size=0 while current: size=size+1 current=current.next return size if __name__=='__main__': arr = [] ll = LinkedList() fo = open("UnOrdered.txt","r") arr = fo.read() words = arr.strip().split(' ') fo.close() print("File Output: ") # inserting_into_list for i in words: ll.insert(i) ll.print() print() print("enter element to search in linked list") element = input() var = ll.search(element) if var: print("element found and removed from list") ll.delete(element) else: print("element not found") print(element, " is added to list") ll.insert(element) ll.print() node_size=ll.size_of_node() array = [] for i in range(node_size): array.append(ll.poll_first()) print() print(array) fo = open("UnOrdered.txt", "w") for i in array: fo.write(i+" ") fo.close()
d330be57de3187cc44f3c8bca0c4dfc4df26421e
ashumeow/TextCaptchaBreaker
/DayPattern.py
1,700
3.859375
4
''' TextCaptchaBreaker. Created on Nov 11, 2010 @author: Sajid Anwar ''' import re days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] def solve(question): tokens = re.sub(r'[^\w\d\s]', '', question).lower().split(' ') # Weekend: # 'Which day from Sunday, Thursday, Tuesday or Monday is part of the weekend?' - sunday # 'Which day from Friday, Saturday, Tuesday, Wednesday or Monday is part of the weekend?' - saturday if 'weekend' in tokens: for i in range(len(tokens)): # Go through each token and return that which is a weekend day. if tokens[i] == 'saturday' or tokens[i] == 'sunday': return tokens[i] return None # Which day is today: # 'What day is today, if yesterday was Wednesday?' - thursday # 'Tomorrow is Tuesday. If this is true, what day is today?' - monday elif 'today' in tokens: offset = None day = None for i in range(len(tokens)): # Go through each token and find whether we are looking for # after yesterday or before tomorrow and save that day. if tokens[i] == 'yesterday': offset = 1 # Add 1 to yesterday to get today. elif tokens[i] == 'tomorrow': offset = -1 # Subtract 1 from tomorrow to get today. elif tokens[i] in days: day = tokens[i] if day is None or offset is None: return None return days[(days.index(day) + offset) % 7] else: return None
6368c550a7bdc4ca0d54e4d9b190ba7578564f04
ballib/SC-T-111-PROG
/verkefni_fyrir_prof/progs/practice_exam/sales.py
1,045
3.9375
4
def open_file(file): try: sales_list = [] with open(file, "r") as data: for line in data.readlines(): sale = [] for num in line.split(): if num.isdigit(): sale.append(int(num)) if sale: sales_list.append(sale) return sales_list except FileNotFoundError: print("File not found!") def calc_average(sales_list): average_sales = [] for sales in sales_list: total_value = 0 for sale in sales: total_value += sale average_sales.append(total_value / len(sales)) return average_sales def print_sales(average_sales): count = 1 print("Average sales:") for sale in average_sales: print("Department no. {}: {:.1f}".format(count, sale)) count += 1 def main(): file_name = input("Enter file name: ") data = open_file(file_name) average_sale = calc_average(data) print_sales(average_sale) main()
a2ef09ec3806e57e7a44178115cfa6717be3fa76
grs7/database
/main.py
1,994
4.0625
4
from prettytable import PrettyTable #print table at position t def printTable(t): #remember that the first line of each table are field titles ptable = PrettyTable( myList[t][0] ) for j in myList[t]: ptable.add_row(j) ptable.del_row(0) print(tablenames[t]) print(ptable) def showMenu(): print("OPTIONS:") print("1.ADD TABLE") print("2.PRINT TABLE") print("3.EDIT TABLE") print("4.EXIT") myList = list() #table counter t=0 #line counter l=0 #use this table to store table names #also usefull for indexes tablenames =list() print("Welcome to your database") showMenu() menu_answer=input("Select one of the above options: ") while(menu_answer != "4"): if(menu_answer == "1"): #ADD NEW TABLE t = len(tablenames) l=0 a= input("Give a name to your table: ") tablenames.append(a) #creates table myList.append(list()) myList[t].append(list()) #dummy variable a="" while ( a != "STOP" ) : a = input("Enter field name or STOP for exit: ") if ( a != "STOP"): myList[t][l].append(a) a = input("Add instance?(y/n): ") while(a == "y") : l=l+1 myList[t].append(list()) for j in myList[t][0]: myList[t][l].append(input(j+": ")) a = input("Add instance?(y/n): ") printTable(t) elif(menu_answer =="2"): #PRINT TABLE ptable = PrettyTable(tablenames) print(ptable) a = input("Type table name to print: ") found = False for j in tablenames: if j == a : found=True if(found == True): t = tablenames.index(a) printTable(t) else: print("There is not such table, try again") else: print("Wrong input, try again") showMenu() menu_answer=input("Select one of the above options: ")
05ef1fc13f0c0cdba75656a471c2b840e7a92938
rgap/rgap-bin-utils
/rgap_png2pdf_dir.py
2,281
3.546875
4
#!/usr/bin/env python3 """Crops margins of PDFs in a directory This script makes use of "ImageMagick" library http://www.imagemagick.org/script/index.php On Mac OS X: brew install imagemagick It allows converting every pdf file in a specific directoty. Usage: rgap_png2pdf_dir.py (--c|<input_dir>) <output_dir> [--suffix] rgap_png2pdf_dir.py (--c|<input_dir>) [--suffix] rgap_png2pdf_dir.py -h Arguments: input_dir input directory containing images output_dir output directory containing images --c to make input_dir the current directory Options: --suffix to add a suffixes "_conv.png" """ import os def main(args): input_dir = args["<input_dir>"] output_dir = args["<output_dir>"] current_directory = args["--c"] suffix = args["--suffix"] # In case the current directory is the one used if current_directory: input_dir = os.getcwd() if not output_dir: output_dir = input_dir # If the output directory doesn't exist then create it if not os.path.exists(output_dir): os.makedirs(output_dir) print(("input_dir = %s\noutput_dir = %s\n") % (input_dir, output_dir)) for input_filename in os.listdir(input_dir): output_filename = input_filename name_suffix = ".pdf" # Add suffix if necessary if suffix: name_suffix = "_conv.pdf" if name_suffix in input_filename: continue output_filename = os.path.splitext(input_filename)[0] + name_suffix # Check if it's a png is_image = input_filename.lower().endswith(".png") if is_image: input_file = os.path.join(input_dir, input_filename) output_file = os.path.join(output_dir, output_filename) command = ("convert -density 400 '%s' '%s'") % (input_file, output_file) # Run command try: os.system(command) except: print("error on convert") raise # print(output_file) else: continue if __name__ == "__main__": # This will only be executed when this module is run direcly from docopt import docopt main(docopt(__doc__))
d2a8038b5c7f9c9ac81c302aa4dd65495faa0be6
engineernaman/eJPTx-prep-tools
/python/portscanner.py
581
3.515625
4
import socket target = input("Enter the victim IP : ") portrange = input("Enter the port range to scan (Format is 1 - 100): ") lowport = int(portrange.split('-')[0]) highport = int(portrange.split('-')[1]) print("Initiating the scan on {} from port {} to {}...".format(target, lowport, highport)) for port in range(lowport, highport): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) status = s.connect_ex((target, port)) if status == 0: print("---PORT {} is open.---".format(port)) else: print("***PORT {} is closed.***".format(port)) s.close()
e6aaf7aeb7422b0d2e7954a7ab781bc4c27c6c5e
Ketan14a/Basic-Algorithms-for-Sorting-and-Searching
/binary search.py
745
3.8125
4
data = [] flag=0 n = int(input("Enter the number of elements:")) print("Enter %s numbers:" % str(n)) for i in range(n): data.append(int(input())) sv = int(input("Enter the search value:")) data.sort() print(data) def Bsearch(data,low,high): mid = int((low+high)/2) if(sv == data[mid]): print("gone at flag") flag=1; elif(sv > data[mid]): #data=data[mid:] print("sv > d[mid]") Bsearch(data,mid+1,high) else: print("sv < d[mid]") Bsearch(data,low,mid) result = Bsearch(data,0,n-1) if(flag == 1): print("%s found in the list " % str(sv)) else: print("%s not found in the list" % str(sv))
b127debd10f27c9fb4d73ce3a69e4f52e752f2db
snehal2841/DivisibilityTestPrograms
/Python/TestFor5.py
466
4.34375
4
def test_for_5(quotient): """Divisibility test to check if the quotient is a multiple of 5, without using the modulo operator. This can be done, by checking if the final digit is either 0 or 5""" last_digit = int(str(quotient)[-1]) if last_digit in [0, 5]: return True else: return False # Test to check that the function behaves properly for i in range(100): print("{} divisible by 5 {}".format(i, test_for_5(i)))
7b247d2c6defa2d2ab8125645e7acd68ce8a52af
a973826287/algorithm013
/Week_01/leetcode_189.py
597
3.578125
4
# # @lc app=leetcode.cn id=189 lang=python3 # # [189] 旋转数组 # # @lc code=start class Solution: def rotate(self, nums: List[int], k: int) -> None: """ Do not return anything, modify nums in-place instead. """ k = k % len(nums) if n < 2: pass else: def reverse(nums, t, s): while t < s: nums[t], nums[s] = nums[s], nums[t] t += 1 s -= 1 reverse(nums, 0, n-1) reverse(nums, 0, k-1) reverse(nums, k, n-1)
54a5a9775ed0d576fc2d6d5c64f1aa71c0885222
charliecjung/TextGameAdventure
/main.py
1,073
3.8125
4
print("Hello, World") print("Get ready for adventure!") location = "Siebel Center" blah = 10 number_of_lives = 3 name = input("What is your name?\n") print("Hello, " + name + "!") print("You are trying to survive the zombie apocalypse.") response = input("Do you run or hide?") if response == "run": print("You get tired and the zombies get you.") print("Game Over") elif response == "hide": print("You find refuge but you have no supplies") weapons_or_foods = input("Do you search for weapons or foods?") if weapons_or_foods == "weapons": print("You find a baseball bat") refuge_or_continue = input("Do you want to take refuge or keep searching?") if refuge_or_continue == "refuge": #story continues elif refuge_or_continue == "keep searching": #story continues elif weapons_or_food == "food": print("You go to the kitche nand find a person.") work_together = input("Do you want to work together?") #story continues else: print("That was not a valid response")
76eafb0a116d1fc5cfc1099453ee516f76c5e75f
elenakhas/methods-for-nlp-labs
/Strings&Comprehensions.Python/Lab1_NLPMethods.py
3,423
4.03125
4
def hello_world(): print("Hello World") def print_tick_tack_toe1(): a = " | | " b = "- - - - - - - -" print(a, b, sep = '\n') print(a, b, sep = '\n') print(a) def print_tick_tack_toe2(): a = " | | \n" b = "- - - - - - - -\n" print((a + b)*2, a, sep = '\n') def print_tick_tack_toe3(): a = "|".join(" "*4 for i in range(3)) b = "-".join(" " for i in range(8)) # alternation of two lines lines = [a if i%2 == 0 else b for i in range (5)] result = "\n".join(lines) print (result, sep = "\n") #print_tick_tack_toe3() def snow_white (num_chants, max_sing): first = "heigh" second = "ho" last = "it's off to work we go" verse = [first if i%2 ==0 else second for i in range (num_chants)] song = "\n".join(verse) + "\n" + last + "\n" while (max_sing != 0): max_sing -= 1 print (song, sep = "\n", end = "\n") #snow_white(5, 2) #parameters - number of repetitions def printing_challenge(num_rep): # define the line with 3 squares (consists of 2 lines) line_one = " | | " line_two = "--+--+--" between_line = "H" between_row = "="*8 between_row_line = "+" #if it is not the first line, add H in the beginning #concatenate the lines if the number of repetitions >1 (or 0?) for i in range (num_rep): line1 = line_one line2 = line_two between = between_row if (i != 0): line1 = between_line + line1 line2 = between_line + line2 between = between_row_line + between odd = line_one + line1 * num_rep + '\n' even = line_two + line2 * num_rep + '\n' between2 = between_row + between * num_rep + '\n' # repeat it twice, add the 5th line print(((odd+even)*2 + odd + between2) * num_rep) #repeat the whole thing number times #printing_challenge(3) def print_two(a, b): print("Arguments: {0} and {1}".format(a, b)) #print_two() # NO - no Arguments #print_two(4, 1) #YES #print_two(41) #NO missing argument #print_two(a=4, 1) #NO, should declare both #print_two(4, 1, 1) #NO, can take only 2 #print_two(b=4, 1) #NO, b defined twice #print_two(4, a=1) #NO, a defined twice #print_two(a=4, b=1) #YES #print_two(b=1, a=4) #YES #print_two(1, a=1) #NO, multiple values for a #print_two(4, 1, b=1) #NO, too many args #print_two(a=5, c=1) #NO, unexpected argument #print_two(None, b=1) #YES def keyword_args(a, b=1, c='X', d=None): print("a:", a) print("b:", b) print("c:", c) print("d:", d) #keyword_args(5) #YES #keyword_args(a=5) #YES #keyword_args(5, 8) #YES, b=8 ##keyword_args(5, 2, c=4) #YES #keyword_args(5, 0, 1) #YES #keyword_args(5,2, d=8, c=4) YES #keyword_args(5,2, 0, 1, "") No, too many #keyword_args(c=7, 1) #NO positional argument follows keyword argument #keyword_args(c=7, a=1) YES #keyword_args(5, 2, [], 5) YES #keyword_args(1, 7, e=6) NO, unexpected argument e #keyword_args(1, c=7) YES #keyword_args(5, 2, b=4) NO, b has multiple values #keyword_args(d=a, b=d, a=b, c=d) NO, names are not defined #keyword_args(d=5, c='', b=None, a='Cat') YES def variadic(*args, **kwargs): print("Positionsl:", args) print("Keyword", kwargs) #variadic (2, 3, 5, 7) YES #variadic (1, 1, n=1) YES #variadic (n=1, 2, 3) positional arguments follow keyword #variadic () YES #variadic (cs="Computer Science", pd = "Product design")
b43970a9e33cdb8ba9187056117e89e3ab0b4e70
drvinceknight/stationary
/stationary/entropy_rate_.py
2,226
3.5
4
""" Entropy Rate """ from collections import defaultdict, Callable from numpy import log def entropy_rate(edges, stationary, states=None): """ Computes the entropy rate given the edges of the process and the stationary distribution. Parameters ---------- edges: list of tuples or function The transitions of the process, either a list of (source, target, transition_probability), or an edge_function that takes two parameters, the source and target states, to the transition transition probability. If using an edge_function you must supply the states of the process. q_d: float, 1 parameter that specifies which divergence function to use states: list, None States for use with the edge_func stationary: dictionary Precomputed stationary distribution Returns ------- float, entropy rate of the process """ e = defaultdict(float) if isinstance(edges, list): for a,b,v in edges: e[a] -= stationary[a] * v * log(v) return sum(e.values()) elif isinstance(edges, Callable): if not states: raise ValueError, "Keyword argument `states` required with edge_func" for a in states: for b in states: v = edges(a,b) e[a] -= stationary[a] * v * log(v) return sum(e.values()) #def entropy_rate_func(N, edge_func, stationary): #""" #Computes entropy rate for a process with a large transition matrix, defined #by a transition function (edge_func) rather than a list of weighted edges. #Use when the number of states or the transition matrix is prohibitively #large, e.g. for the Wright-Fisher process. #Parameters #---------- #N: int #Population size / simplex divisor #edge_func, function #Yields the transition probabilities between two states, edge_func(a,b) #stationary: dictionary #Precomputed stationary distribution #""" #e = defaultdict(float) #for a in simplex_generator(N): #for b in simplex_generator(N): #v = edge_func(a,b) #e[a] -= stationary[a] * v * log(v) #return sum(e.values())
03be89d4a6f1b7dfd7c4a201f3c287c6995ac46f
gabrielvtan/Byte_Academy_Foundation
/Week1/week1.day4/01-function-design/function_design.py
2,223
4.21875
4
## Day 4 Exercise 1 Function Design #### Write the following functions. Pick descriptive names for the functions and their parameters. # A function that returns True if a number is divisible by 7 and False if it does not. def func1(x): return x % 7 == 0 y=func1(8) print(y) # A function that returns True if a string is 10 characters or longer and False if it does not. def func2(x): return len(x) >= 10 y = func2('thisismorethan10') print(y) # A function that returns the first letter of a string def func3(x): return x[:1] y = func3('string') print(y) # A function that takes an integer and returns a list with that many elements, where every element is zero. def func4(x): return [ 0 for i in range(x) ] y = func4(7) print(y) # A function that takes a list as input and prints out the contents of each element on a numbered line, like: ##print_list(['a', 'bee', 'cee', None]) #1. a #2. bee #3. cee #4. 'None' def func5(x): for i in range(len(x)): print (i, x[i]) y = func5(['a','b','c','d','e']) # A function that takes a string as input and returns a list of two character segments of the string like: #segment('Carter Adams') #returns #['Ca', 'rt', 'et', ' A', 'da', 'ms'] def func6(x,y): return[y[i:i+x] for i in range(0,len(y),x)] z = func6(2,'Carter Adams') print(z) # A function that when given an integer prints out that many dash charactes between two +'s, so dashprint(5) would print '+-----+' # make sure the print ends in a new line. # * This function should print, and not have any return value. def func7(x): print('+{}+\n'.format('-'*x)) y = func7(7) # A function that takes a string, and then uses that string as the prompt text for an input. Repeat the prompt as long as the input is not an integer. # Return the integer (as an integer) when it is one. def func8(x): x = input("Give me an integer: ") if not x.isdigit(): return(func8(x)) else: return(x) # A function that takes two integers, one that represents a width and one that represents a height, and returns a new two dimensional array, # where each element is None def func9(w,h): return[None, None]
5bba8cfe510db4e099c18f3ff1f8b085819b1f42
ceuity/algorithm
/leetcode/238.py
1,020
3.796875
4
# -*- coding: utf-8 -*- """ Created on Mon Jan 18 23:12:45 2021 """ import math from typing import List """ first try Timeout class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: ans = [] for _ in range(len(nums)): target = nums.pop(0) ans.append(math.prod(nums)) nums.append(target) return ans """ class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: left_prod = [] right_prod = [] ans = [] p = 1 for i in range(len(nums)): left_prod.append(p) p *= nums[i] p = 1 for i in reversed(range(len(nums))): right_prod.append(p) p *= nums[i] right_prod = right_prod[::-1] for i in range(len(nums)): ans.append(left_prod[i] * right_prod[i]) return ans nums = [4,5,1,8,2] ret = Solution() print(ret.productExceptSelf(nums))
49a830b0ff590f5ebec7cc8a02273472d5d0a941
kg55555/pypractice
/Part 1/Chapter 5/exercise_5.11.py
233
4.03125
4
ordinal_numbers = list(range(1,10)) for num in ordinal_numbers: if num == 1: print(f"{num}st") elif num == 2: print(f"{num}nd") elif num == 3: print(f"{num}rd") else: print(f"{num}th")
9eef925b02060c7678cdbd70fffb053ad5f4dae8
hekangyong/Python
/pythonHKY/0607_test_11.9.2.py
127
3.5625
4
import turtle t = turtle.Pen() t.reset() for x in range(1,9): t.color("red", "yellow") t.forward(100) t.left(45)
aaa5f850266e0729cb00b32211666a9ff4e8672f
f-fathurrahman/ffr-MetodeNumerik
/chapra_7th/ch17/chapra_example_17_6.py
850
3.578125
4
import numpy as np import matplotlib.pyplot as plt def fit_multilinear_2(x1, x2, y): N = len(x1) assert N == len(x2) assert N == len(y) # Build the matrix for linear system A = np.zeros((3,3)) # A[0,0] = N A[0,1] = np.sum(x1) A[0,2] = np.sum(x2) # A[1,0] = A[0,1] A[1,1] = np.sum(x1**2) A[1,2] = np.sum(x1*x2) # A[2,0] = A[0,2] A[2,1] = A[1,2] A[2,2] = np.sum(x2**2) # # The RHS vector # b = np.zeros(3) b[0] = np.sum(y) b[1] = np.sum(x1*y) b[2] = np.sum(x2*y) # # Solve the linear system # xsol = np.linalg.solve(A,b) return xsol[0], xsol[1], xsol[2] data = np.loadtxt("table_17_5.dat") x1 = data[:,0] x2 = data[:,1] y = data[:,2] a0, a1, a2 = fit_multilinear_2(x1, x2, y) print("a0 = ", a0) print("a1 = ", a1) print("a2 = ", a2)
444e82380ad2f06c819e604f2cd041559d02acdd
yflyzhang/redditmodel
/code_tests/hawkes_tree/Node.py
413
3.515625
4
class Node: def __init__(self, id, parent): self.id = id self.parent = parent self.children = [] #list of Node objects self.children_ids = set() #set of ids only def add_child(self, child_id): if child_id not in self.children_ids: self.children.append(Node(child_id, self.id)) def add_children(self, children_ids): for child_id in children_ids: self.add_child(child_id)
1a779df76f5712c76caf586db918c117278f2ce2
Aasthaengg/IBMdataset
/Python_codes/p03192/s029307225.py
126
3.53125
4
s=input() ans=0 if s[0]=='2': ans+=1 if s[1]=='2': ans+=1 if s[2]=='2': ans+=1 if s[3]=='2': ans+=1 print(ans)
0d64ea5a00318738375107a66cf12fcb4610e570
remotephone/pythoncrashcourse
/ch09/09_06-tryityourself3.py
6,116
4.125
4
from string import capwords class Restaurant(): # 3 arguments, self, r_n, and c_t def __init__(self, restaurant_name, cuisine_type): """ Create a restaurant with a name and food type.""" # Each instance types restaurant name = the argument we give to restaurant # name. Same for cuisine_type. self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type self.number_served = 0 # each instance gets this method available to it. the method prints both args # in a sentence. The self tells all characteristics associated with self (the class) # are available to it. def describe_restaurant(self): print("Welcome to " + capwords(self.restaurant_name) + " where we make " + self.cuisine_type + " food and served " + str(self.number_served) + " people.") # Each instance also gets this method. It only uses the r_n arg. def open_restaurant(self): print(capwords(self.restaurant_name) + " is now open!") def set_number_served(self, set_served): self.number_served += set_served def increment_number_served(self, more_served): self.number_served += more_served # This is a subclass of restaurant, it imports Restaurant and customizes it. # we can make a restaurant and have flavors. class IceCreamStand(Restaurant): """Represents an Ice Cream Stand Restaurant.""" def __init__(self, restaurant_name, cuisine_type): """Initialize attributes of the parent class.""" super().__init__(restaurant_name, cuisine_type) self.flavors = ['vanilla', 'chocolate', 'honey'] def flavor_list(self): print(self.flavors) # Call class with required arguements bobs = IceCreamStand('bob\'s', 'ice cream') # Listt flavors which we defined as defaults in the subclass. bobs.flavor_list() # Primary class here .It has some arguments assigned to it at run time and login_attempts # at 0. class User(): def __init__(self, first_name, last_name, zip, age): """ Create a user an accept f & l name, zip, age""" self.first_name = first_name self.last_name = last_name self.zip = zip self.age = age self.login_attempts = 0 # describe fucntion that stringifies and prints stuff. def describe_user(self): print("You are " + self.first_name.title() + " " + self.last_name.title() + " and you are " + str(self.age) + " years old and live in " + str(self.zip) + " zip code.") # Add to login attempts one by one. def increment_login_attempts(self): self.login_attempts += 1 # reset login_attempts to 0. def reset_login_attempts(self): self.login_attempts = 0 # Subclass of User. All we do is call privileges class. class Admin(User): """This is a special user with special rights.""" def __init__(self, first_name, last_name, zip, age): """Initialize attributes of the parent class.""" super().__init__(first_name, last_name, zip, age) self.privs = Privileges() # we assign some privs to the default class. show_privs just prints them. class Privileges(): """This is a special user with special rights.""" def __init__(self): """Initialize attributes of the parent class.""" self.privs = ['read', 'write', 'delete'] def show_privs(self): print(self.privs) bob = Admin('bob', 'bobberson', '11111', 99) bob.privs.show_privs() class Car(): """A simple attempt to represent a car.""" def __init__(self, make, model, year): """Initialize attributes to describe a car.""" self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): """Return a neatly formatted descriptive name.""" long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): """Print a statement showing the car's mileage.""" print("This car has a " + str(self.odometer_reading) + " miles on it.") def update_odometer(self, mileage): """Set the odometer reading to the given value. Reject change if it tries to roll it back.""" if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!") def increment_odometer(self, miles): """Add the given amount to the odometer reading.""" if miles + self.odometer_reading >= self.odometer_reading: self.odometer_reading += miles else: print("You can't roll back the mileage!") class Battery(): """A simple attempt to model a battery for an electric car.""" def __init__(self, battery_size=70): """Inititalize the battery's attributes""" self.battery_size = battery_size def describe_battery(self): """Print a statement describingg the battery size.""" print("This car has a " + str(self.battery_size) + "-kWh battery.") def get_range(self): """Print a statement about the range this battery provides.""" if self.battery_size == 70: range = 240 elif self.battery_size == 85: range = 270 message = "This car can go approximately " + str(range) message += " miles on a full charge." print(message) def upgrade_battery(self): if self.battery_size != 85: self.battery_size = 85 class ElectricCar(Car): """Represents aspects of a car, specific to electric vehicles.""" def __init__(self, make, model, year): """Initialize attributes of the parent class.""" super().__init__(make, model, year) self.battery = Battery() my_tesla = ElectricCar('tesla', 'model s', 2016) print(my_tesla.get_descriptive_name()) my_tesla.battery.describe_battery() my_tesla.battery.get_range() my_tesla.battery.upgrade_battery() my_tesla.battery.describe_battery() my_tesla.battery.get_range()
77bdc77b1a3997db5eab280161ddb39aebdc792e
InnovativeCoder/Innovative-Hacktober
/Data Structures and Algorithms/scraper/search.py
202
3.6875
4
from db import * def search(key): #key = input("Keyword : ") cmd = "SELECT url from links where txt like '%" + key + "%';" print (cmd) rows = db(cmd) for row in rows: print(row[0]) return rows
41fdbf94163074613bfd243a48093eeceb1fe1e2
Arteom27/Math-Modeling_8_class
/lec_1.py
875
4.25
4
print() print(4) print(3*4) #умножение print(4+3) #сложение print(12/4) #деление print(4-3) #вычитание print(4**3) #возведение в степень print(7//2) #челая часть от деления print(7%2) #остаток часть от деления s=3+4 #Объект/имя s ссылается назначение 3+4 print(s) s=5 #новая ссылка print(s) type #команда определения типа данных type(3) print(type(3)) print(type('Молодец')) a='Молодец' print(a) print(type([1,2])) a='Good' b='Bad' print(a+b) #сложение строк a=[1,3,5] #создание списка print(a[2]) #вывод на экран нулевого элемента списка b=[8,9,10] c=a+b #сложение списков print(c) c=a-b print(c)
898adaf85aa420e9075cbe02ea25914d4ecc2776
Aasthaj01/DSA-questions
/Tree/lca.py
3,718
3.859375
4
# lca is lowest common ancestor # i.e if 2 nodes haves 2 common ancestors then the function will return that common ancestor which is on lower level than other. # There can be 2 methods for the same: O(n) solution where tree is traversed 3 times and n+extra space time complexity # Other approach is traversing tree once and looking for the node that is common for the input nodes If root doesn’t match with any of the keys, we recur for left and right subtree. The node which has one key present in its left subtree and the other key present in right subtree is the LCA. If both keys lie in left subtree, then left subtree has LCA also, otherwise LCA lies in right subtree- O(h) time complexity solution class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None def lca(root, v1, v2): if root is None: return root if ((v1 < root.value) and (v2 < root.value)): root = lca(root.left,v1,v2) elif ((v1 > root.value) and (v2 > root.value)): root = lca(root.right,v1,v2) elif ((v1 < root.value) and (v2 > root.value)): return root return root def lowest_common_ancestor(node, n1, n2): if node is None: return if node.value == n1 or node.value == n2: return node.value left_lca = lowest_common_ancestor(node.left, n1, n2) right_lca =lowest_common_ancestor(node.right, n1, n2) if left_lca and right_lca: return node.value if left_lca is not None: return left_lca else: return right_lca def construct_tree(arr, node, i, n): if i<n: temp = Node(arr[i]) node = temp node.left = construct_tree(arr, node.left, 2*i+1, n) node.right = construct_tree(arr, node.right, 2*i+2, n) return node arr = list(map(int, input("Enter the nodes:").split())) n = len(arr) root = None root = construct_tree(arr, root, 0, n) t = int(input("Enter number of test cases:")) arr = [] arr2 = [] for i in range(0, t): n1, n2 = list(map(int, input().split())) ans = lowest_common_ancestor(root, n1, n2) ans2 = lca(root, n1, n2) arr.append(ans) arr2.append(ans2) print(arr) print(arr2) # ----------------------------------------------------------------------------------- # Method 2 - Naive solution class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None def findPath(node, path, k): if node is None: return False path.append(node.value) if node.value == k : return True if ((node.left != None and findPath(node.left, path, k)) or (rnode.right!= None and findPath(node.right, path, k))): return True path.pop() return False def findLCA(node, n1, n2): path1 = [] path2 = [] if not findPath(node, path1, n1) or not findPath(node, path2, n2)): return -1 i = 0 while(i < len(path1) and i < len(path2)): if path1[i] != path2[i]: break i += 1 return path1[i-1] def construct_tree(arr, node, i, n): if i<n: temp = Node(arr[i]) node = temp node.left = construct_tree(arr, node.left, 2*i+1, n) node.right = construct_tree(arr, node.right, 2*i+2, n) return node arr = list(map(int, input("Enter the nodes:").split())) n = len(arr) root = None root = construct_tree(arr, root, 0, n) t = int(input("Enter number of test cases:")) arr = [] for i in range(0, t): n1, n2 = list(map(int, input().split())) ans = findLCA(root,n1, n2) arr.append(ans) print(arr)
da89469f9ca112a71f7c5100a79c25ffc92ccdba
Martoxdlol/programacion
/algo1/ej1/vectores.py
595
3.828125
4
def norma(x, y, z): """Recibe un vector en R3 y devuelve su norma""" return (x**2 + y**2 + z**2) ** 0.5 def diferencia(x1, y1, z1, x2, y2, z2): """Recibe las coordenadas de dos vectores en R3 y devuelve su diferencia""" dif_x = x1 - x2 dif_y = y1 - y2 dif_z = z1 - z2 return dif_x, dif_y, dif_z def producto_vectorial(x1, y1, z1, x2, y2, z2): """Recibe las coordenadas de dos vectores en R3 y devuelve el producto vectorial""" productoX = y1*z2 - z1*y2 productoY = z1*x2 - x1*z2 productoZ = x1*y2 - y1*x2 return productoX, productoY, productoZ