blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
87ba541139b64b02e41df0d2a668c1a2dce5495b
riteshbisht/dsprograms
/arrays/rearrangement/problem2.py
980
4.21875
4
""" Write a program to reverse an array or string Given an array (or string), the task is to reverse the array/string. Examples : Input : arr[] = {1, 2, 3} Output : arr[] = {3, 2, 1} Input : arr[] = {4, 5, 1, 2} Output : arr[] = {2, 1, 5, 4} """ def reverse_whole_string(k): start = 0 end = len(k) new_tring = "" final, first, second = '', '', '' while(start < end): first += k[end-1] second = k[start] + second end -= 1 start = start + 1 final = first + second print(final) def reverse_string_but_keep_words_intact(k): new_string ='' temp ='' # get string till sencond last word. for index, i in enumerate(k): temp += i if i == ' ': new_string = temp + new_string temp ='' #for final word new_string = temp + ' ' + new_string print(new_string) if __name__ == '__main__': k = "this is ritesh bisht" reverse_whole_string(k)
a9bd908e67ca130617cb6c7fa37a0f39ee5f8c33
RafikFarhad/Bioinformatics_Codes
/solutions/ba1c.py
526
3.609375
4
def Reverse(Dna): tt = { 'A' : 'T', 'T' : 'A', 'G' : 'C', 'C' : 'G', } ans = '' for a in Dna: ans += tt[a] return ans[::-1] def main(infile, outfile): # Read the input, but do something non-trivial instead of count the lines in the file inp = lines = [line.rstrip('\n') for line in infile] print(inp) output = str(Reverse(inp[0])) # For debugging, print something to console print(output) # Write the output. outfile.write(output)
58318f29ce62fb824dd12e7b2b0a954b1f13b8a6
julian-chan/league-trivia
/flask_api/scripts/ExtractItemData.py
1,844
4.03125
4
""" This script is used to extract and create a new JSON file containing the key data fields that are needed for League Trivia from the item.json data downloaded from Data Dragon. This is because item.json contains a lot of data that isn't needed for League Trivia, so we only keep the data fields that the game needs in order to improve performance and the conciseness of the data the game works with. Pass in the path to the item JSON file as a command line argument. """ import os import json import sys def extract_key_item_data(item_data): """ This method takes a dictionary of item ids to their respective properties, extracts the key data fields for each item, and returns a dictionary of item ids to their respective extracted data. """ extracted_item_data = {} for item_id in item_data: key_data = {} key_data["id"] = item_id key_data["name"] = item_data[item_id]["name"] key_data["image"] = item_data[item_id]["image"]["full"] key_data["gold"] = item_data[item_id]["gold"]["total"] key_data["tags"] = item_data[item_id]["tags"] extracted_item_data[item_id] = key_data return extracted_item_data if __name__ == "__main__": # Ensure there is only 1 command line argument assert len(sys.argv) == 2, "There should be 1 argument for the path to the item JSON file" # Ensure that the command line argument is a valid file input_file = sys.argv[1] assert os.path.isfile(input_file), "Could not find the specified file" with open(input_file, encoding="utf8") as item_file: item_data = json.load(item_file)["data"] # Extract the key data points for each item and write it to a new JSON file extracted_item_data = extract_key_item_data(item_data) with open("items.json", "w") as json_file: json.dump(extracted_item_data, json_file)
b2ef6e37a895908e809f0c2177eae44931bf7141
vsrkrishnan/python-exercises
/the-game-of-snap/snap.py
1,978
3.921875
4
import itertools import random match_conditions = {1: "Suite", 2: "Face value", 3: "Both"} suites = ('Hearts', 'Spades', 'Diamonds', 'Clubs') values = ('Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King') print "\nWelcome to Snapster!!" print "=====================" for key, value in match_conditions.items(): print "{}: {}".format(key, value) condition = int(input("\nChoose a condition (1-3): ")) print "\nYou have chosen '{}' as your match condition\n".format(match_conditions[condition]) num_packs = int(input("Choose number of packs: ")) print "\nYou have chosen to use {} packs\n".format(num_packs) cards = [card for card in list(itertools.product(suites, values)) for _ in range(num_packs)] scores = {"player1": 0, "player2": 0} def check_card(cards_in_play, condition): if len(cards_in_play) < 2: return if condition < 3: if cards_in_play[-1][condition - 1] == cards_in_play[-2][condition - 1]: print "Snap!!" return True else: if ":".join(cards_in_play[-1]) == ":".join(cards_in_play[-2]): print "Snap!!" return True return False cards_in_play = [] while len(cards) > 0: current_player = "player1" p1card = random.choice(cards) print "Player 1 draws {}".format(p1card) cards_in_play.append(p1card) cards.remove(p1card) if check_card(cards_in_play, condition): scores[current_player] += len(cards_in_play) cards_in_play = [] current_player = "player2" p2card = random.choice(cards) print "Player 2 draws {}".format(p2card) cards_in_play.append(p2card) cards.remove(p2card) if check_card(cards_in_play, condition): scores[current_player] += len(cards_in_play) cards_in_play = [] print "\nScores: ", scores if scores['player1'] > scores['player2']: print "\nPlayer 1 WINS!!" else: print "\nPlayer 2 WINS!!"
128e483c5bafbcac95584b21a960ca829274321b
Chiafl/Wallbreakers-Cohort-3
/Solutions/Week 5/longest-univalue-path.py
1,080
3.84375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def longestUnivaluePath(self, root: TreeNode) -> int: self.ans = 1 self.helper(root) return self.ans-1 def helper(self, root): if not root: return 0 # if not root.left and not root.right: # return left = 0 right = 0 if root.left and root.val == root.left.val: left = 1+self.helper(root.left) elif root.left: left = 0*self.helper(root.left) if root.right and root.val == root.right.val: right = 1+self.helper(root.right) elif root.right: right = 0*self.helper(root.right) if root.left and root.left.val == root.val and root.right and root.right.val == root.val: self.ans = max(self.ans, left+right+1) else: self.ans = max(self.ans, max(left, right)+1) return max(left, right)
323d64b2cd937ab44ba6450a603b8387563e1b55
RamiroAlvaro/desafios
/maximum_subarray.py
1,941
4.125
4
""" Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [−2, 1, −3, 4, −1, 2, 1, −5, 4], the contiguous subarray [4, −1, 2, 1] has the largest sum = 6. """ def max_subarray_quadratic(list_): if not list_: return list_, 0 stop = len(list_) sum_ = list_[0] result = [sum_] start = 1 for index_start, _ in enumerate(list_): for index_stop in range(start, stop + 1): if sum_ < sum(list_[index_start:index_stop]): sum_ = sum(list_[index_start:index_stop]) result = list_[index_start:index_stop] start += 1 return result, sum_ assert max_subarray_quadratic([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == ([4, -1, 2, 1], 6) assert max_subarray_quadratic([10, -1, -3, -4, -1, 2, 1, -5, 4]) == ([10], 10) assert max_subarray_quadratic([1, -1, -3, -4, -1, 2, 1, -5, 9]) == ([9], 9) assert max_subarray_quadratic([]) == ([], 0) assert max_subarray_quadratic([11]) == ([11], 11) assert max_subarray_quadratic([1, 2, 3, 4]) == ([1, 2, 3, 4], 10) assert max_subarray_quadratic([-1, -2, -3, -4]) == ([-1], -1) assert max_subarray_quadratic([-1, -2, 3, -3, -4]) == ([3], 3) def max_subarray_linear(list_): if not list_: return 0 result = list_[0] sum_ = list_[0] stop = len(list_) for index in range(1, stop): sum_ = max(list_[index], sum_ + list_[index]) result = max(result, sum_) return result assert max_subarray_linear([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == 6 assert max_subarray_linear([10, -1, -3, -4, -1, 2, 1, -5, 4]) == 10 assert max_subarray_linear([1, -1, -3, -4, -1, 2, 1, -5, 9]) == 9 assert max_subarray_linear([]) == 0 assert max_subarray_linear([11]) == 11 assert max_subarray_linear([1, 2, 3, 4]) == 10 assert max_subarray_linear([-1, -2, -3, -4]) == -1 assert max_subarray_linear([-1, -2, 3, -3, -4]) == 3
932095dd38103ba872f14b3577cc253eeff80177
osnipezzini/PythonExercicios
/ex067.py
524
4.09375
4
''' Faça um programa que mostre a tabuada de vários números, um de cada vez, para cada valor digitado pelo usuário. O programa será interrompido quando o número solicitado for negativo. ''' tabuada = cont = 0 while True: cont = 0 numero = int(input('Digite um número que lhe mostrarei a tabuada: ')) if numero < 0: print('Número negativos não são aceitos ! ') break while cont <= 10: tabuada = numero * cont print(f'{numero} X {cont} = {tabuada}') cont += 1
f913ad25130197a143c0743aab785e249e3d6f3b
OtavioAMota/Maratona_Programacao
/Beginner/Salary with Bonus.py
156
3.640625
4
Name = str(input()) Salary = float(input()) Total_sell = float(input()) Total_Salary = Salary + (Total_sell*0.15) print("TOTAL = R$ %.2f" % Total_Salary)
61887c76a3886ad7e328b37a1b4c1cc72ad35d5b
xshi0001/base_function
/mouse_simulation_test.py
1,694
3.5
4
# -*-coding=utf-8-*- __author__ = 'Rocky' import pyautogui as pg import pyautogui, time def get_pos(): cur_x, cur_y = pg.position() print cur_x, cur_y def basic_api(): x, y = pg.size() print x, y ''' pg.moveTo(300,300,2) pg.moveTo(300,400,2) pg.moveTo(500,400,2) pg.moveTo(500,300,2) pg.moveTo(300,300,2) #pg.moveTo(300,500,2) ''' # pg.click(100,100) word = [u'你好', u'睡了吗'] pos = [452, 321] pg.moveTo(pos[0], pos[1]) pg.click() pg.typewrite(word[0]) def example(): screenWidth, screenHeight = pg.size() currentMouseX, currentMouseY = pg.position() pg.moveTo(500, 550) pg.click() pg.moveRel(None, 10) # move mouse 10 pixels down pg.doubleClick() # pg.moveTo(500, 500, duration=2, tween=pyautogui.tweens.easeInOutQuad) # use tweening/easing function to move mouse over 2 seconds. pg.typewrite('Hello world!', interval=0.25) # type with quarter-second pause in between each key pg.press('esc') pg.keyDown('shift') pg.press(['left', 'left', 'left', 'left', 'left', 'left']) pg.keyUp('shift') pg.hotkey('ctrl', 'c') delta_y = 50 def draw_rect(): time.sleep(5) distance = 200 while distance > 0: pyautogui.dragRel(distance, 0, duration=0.5) # move right distance -= 5 pyautogui.dragRel(0, distance, duration=0.5) # move down pyautogui.dragRel(-distance, 0, duration=0.5) # move left distance -= 5 pyautogui.dragRel(0, -distance, duration=0.5) # move up def message_test(): pg.alert('This displays some text with an OK button') # basic_api() #example() #draw_rect() message_test()
e62f11aba739f45933a76d0bfb2a5616707c6302
jeremiahduclanj/peanut
/tettt.py
678
3.765625
4
#group members: George, Jeramiah, Kunsh, Yidam import turtle as trtl painter = trtl.Turtle() #ask user for the equation, slope, and y-intercept (POSITIVE NUMBERS ONLY) eq = int(input("Input Equation in y = mx + b form: ")) slope = int(input("What is the slope?: ")) yint = int(input("What is the y-intercept?: ")) def make_graph (): painter.speed(0) Painter.setposition(-200,-200) Painter.pensize(5) painter.forward(400) Painter.penup() Painter.setposition(-200,-200) Painter.left(90) Painter.pendown() Painter.forward(400) Painter.setposition(-200,-200) make_graph() wn = trtl.Screen() wn.mainloop()
268724098e09bb2da44406bbb3107ac1ad4e9dd3
NileshProgrammer/Python-Project
/Next_Prime_Number.py
611
4.09375
4
import math list = [ ] n = int(input("Please enter the number to find the prime factor:")) def prime_factor(n): while n % 2 == 0: n = n / 2 list.append(2) for i in range(3,int(math.sqrt(n))+1,2): while n % i == 0: list.append(i) n = n /i if n > 2 : list.append(n) prime_factor(n) print(list) n = len(list) i = 0 while i in range(0,n): if ( i > n): break else: print(list[i]) if input('Do you want to continue Y or N ?') == 'Y': i = i + 1 continue else: break
27150fcba619ba3a4b11b0edd6ac29a364218b3a
Bravo555/advent-of-code
/03/03.py
1,145
3.5
4
from functools import reduce with open('input.txt') as f: data = list(map(str.strip, f.readlines())) data = [seq.split(',') for seq in data] # assume central port as (0, 0) def visited_coords(move, origin): length = int(move[1:]) unit = { 'U': (0, 1), 'D': (0, -1), 'L': (-1, 0), 'R': (1, 0), }[move[:1]] return [(origin[0] + unit[0] * length, origin[1] + unit[1] * length) for length in range(1, length + 1)] def trace(sequence): visited = [] origin = (0, 0) for line in sequence: visited_in_move = visited_coords(line, origin) origin = visited_in_move[-1] visited += visited_in_move return visited def manhattan_distance_from_origin(point): return abs(point[0]) + abs(point[1]) traces = list(map(trace, data)) intersections = set(traces[0]).intersection(set(traces[1])) print(min([traces[0].index(intersection) + traces[1].index(intersection) + 2 for intersection in intersections])) solution = reduce((lambda x, y: x if manhattan_distance_from_origin( x) < manhattan_distance_from_origin(y) else y), intersections)
6cd6697a08a953d03c0f52f3afd31549ae22fbb6
iamakhildabral/Python
/CommonCode/reverse word with delimiter.py
267
3.609375
4
user_input = "My name, I dont wanna tell" d = user_input.split(" ")[::-1] for each in d: f = each.split(",") i = len(f) for x in f: if i>1: print(",") print(f) i=0
1311f8997479924d64bf24c5f0ad6c43878df3b4
anonymous-iclr-3518/code-for-submission
/ethicml/data/load.py
1,769
3.59375
4
"""Load Data from .csv files.""" from pathlib import Path from typing import List, Optional import pandas as pd from ethicml.utility import DataTuple from .dataset import Dataset __all__ = ["load_data", "create_data_obj"] def load_data(dataset: Dataset, ordered: bool = False) -> DataTuple: """Load dataset from its CSV file. This function only exists for backwards compatibility. Use dataset.load() instead. Args: dataset: dataset object ordered: if True, return features such that discrete come first, then continuous Returns: DataTuple with dataframes of features, labels and sensitive attributes """ return dataset.load(ordered=ordered) def create_data_obj( filepath: Path, s_column: str, y_column: str, additional_to_drop: Optional[List[str]] = None ) -> Dataset: """Create a `ConfigurableDataset` from the given file. Args: filepath: path to a CSV file s_column: column that represents sensitive attributes y_column: column that contains lables additional_to_drop: other columns that should be dropped Returns: Dataset object """ if additional_to_drop is None: additional_to_drop = [] dataframe: pd.DataFrame = pd.read_csv(filepath) columns: List[str] = [str(x) for x in dataframe.columns.to_numpy().tolist()] columns.remove(s_column) columns.remove(y_column) for additional in additional_to_drop: columns.remove(additional) return Dataset( name=filepath.name, num_samples=len(dataframe), features=columns, cont_features=[], sens_attr_spec=s_column, class_label_spec=y_column, filename_or_path=filepath, discrete_only=False, )
bc45317d8d72de0d031d90072a587005379b224d
hushaoqi/LeetCode
/155.py
1,770
4.1875
4
class MinStack: def __init__(self): """ initialize your data structure here. """ self._data = [] self._minData = [] def push(self, x: int) -> None: """Add element x to the top of stack""" self._data.append(x) # new item stored at end of list if len(self._minData) == 0: # maintain the MinStack self._minData.append(x) else: if x < self._minData[-1]: self._minData.append(x) else: self._minData.append(self._minData[-1]) def pop(self) -> None: """Remove and return the element from the top of the stack Raise Empty exception if the stack is empty """ if len(self._data) == 0: raise Exception("Stack is empty") self._data.pop() # remove last item from list self._minData.pop() def top(self) -> int: """Return (but not remove) the element at the top of the stack Raise Empty exception if the stack is empty """ if len(self._data) == 0: raise Exception("Stack is empty") return self._data[-1] # the last item in the list def getMin(self) -> int: if len(self._minData) == 0: raise Exception("Stack is empty") return self._minData[-1] # Your MinStack object will be instantiated and called as such: # obj = MinStack() # obj.push(x) # obj.pop() # param_3 = obj.top() # param_4 = obj.getMin() if __name__ == '__main__': minStack = MinStack() minStack.push(-2) minStack.push(0) minStack.push(-3) print(minStack.getMin()) #--> 返回 - 3. minStack.pop() print(minStack.top()) #--> 返回0. print(minStack.getMin()) #--> 返回 - 2.
5e895d88bdd03c7f93febba64bfc0f48249be1af
Leekailklk/untitled_dingtalk
/Cocacola.py
300
3.671875
4
class CocaCola: formula=['coffeine','sugar','water','soda'] def drink(self): print('energy') coke_for_me=CocaCola() coke_for_you=CocaCola() print(CocaCola.formula) coke_for_me.drink() print(coke_for_you.formula) for element in coke_for_me.formula: print(element) print("\N{Cat}")
bdfe13adbb3b1d57212bf4f7bb864a40c43d6320
Yet-sun/python_mylab
/Lab_projects/lab4/Lab4_04.py
380
4
4
''' 需求:编写一个递归函数,实现Fabonacci数列 ''' def Fabonacci(n: int) -> int: if n == 1 or n == 2:#Fabonacci函数中,n=1和n=2是特殊值 return 1 else: return Fabonacci(n - 2) + Fabonacci(n - 1) def main(): n = int(input("请输入一个整数:")) print("Fabonacci函数的结果为:" + str(Fabonacci(n))) main()
675d653e3ced442f10418b7e6fb070870ccb00dc
sumit2798/GFG
/Stack/parenthesis_checker.py
881
3.765625
4
#Python 3 ''' Function Arguments : @param : a (auxilary array), top1 and top2 are declared as two tops of stack. # initialized value of tops of the two stacks top1 = -1 top2 = 101 @return : Accordingly. ''' # pop element from 1st stack def pop1(a): global top1 if top1 == -1: return -1 else: val = a[top1] top1-=1 return val # pop element from 2nd stack def pop2(a): global top2 if top2 == 101: # size of array is 101, so if stack is empty. return -1 else: val = a[top2] top2+=1 return val # push element to second stack def push2(a,x): global top1 global top2 if top1 < top2-1: top2-=1 a[top2] = x # push element to first stack def push1(a,x): global top1 global top2 if top1 < top2-1: top1+=1 a[top1] = x
fa79f40600fe70e07f0c128800140530dab8b8f5
MoKamalian/CSCI2202
/Solutions for lab 1-B nd assing1 nd test/Lab 7/vehulstEquation.py
689
3.8125
4
# Create an initial value for both equations, Verhulst and Alternate. V = 0.01 A = 0.01 # Set the value of r r = 3 # Print the output header line to the screen print("Verhulst1\t\tVerhulst2\t\tDifference") # Recalculate where each algorithm deviates. Perform 50 such recalculations. for i in range(50): # Find the difference between the algorithms. difference = abs(V - A) # Print the values to the screen. print("{:6.20f}\t{:6.20f}\t{:6.20f}".format(V, A, difference)) # Calculate p(n+1) = p(n) + r * p(n) * (1 - p(n)) V = V + r * V * (1 - V) # Calculate p(n+1) = (1 + r) * p(n) - r * p(n)^2 A = (1 + r) * A - r * A**2
556b8870d477d0f738f36f0f03d51429321937b5
Erivaldojelson/Calculadora
/day1.py
140
3.8125
4
>>> print("Hello; world!") Hello; world! >>> exit() >>> if 5 > 2: print("Five is greter than two!") Five is greter than two! >>>
8b2fee8d92c74d593e045a07f35df15dd6241c88
harris-ippp/hw-6-aeskenazi
/e1.py
1,862
3.5625
4
#!/usr/bin/env python import requests from bs4 import BeautifulSoup as bs addr = "http://historical.elections.virginia.gov/elections/search/year_from:1924/year_to:2016/office_id:1/stage:General" resp = requests.get(addr) #download url html = resp.content #look at the html content of that url soup = bs(html, "html.parser") #use beautiful soup to scrape the html content rows = soup.find_all("tr", "election_item") #find all tags with class "election_item" Year = [] #create empty list for Years for row in rows: Year.append(row.contents[1].text) #search rows and append all the years (in index 1) to the Year list IDelection = [] #create empty list of IDelection for i in range(len(rows)): IDelection.append(rows[i]["id"][-5:]) #put the election IDs (the last 5 numbers) into the IDelection list #print(Year, IDelection) with open('IDelection','w') as IDelection_file: #write an ID election file with open('Year','w') as Year_file: #write a year file for number in IDelection: IDelection_file.write(number[0] + ' ' + number[4]) #add election IDs to IDelection file for line in Year: Year_file.write(line[0] + ' ' + line[3]) #add years to Year file print(number, line) #this prints all the election IDs but then prints the same year (1924) over and over again next to them #I have tried adjusting the indents and moving the loops around but it still is not working #I also tried making one with statement that included IDelection and Year and got an error that said I needed an integer, not a string ''' with open('IDelection' , 'Year' , 'w') as IDelection_Year_file: for row in IDelection_Year_file: IDelection_Year_file.write(number[0] + ' ' + number[9]) Year_file.write(line[0] + ' ' + line[3]) print(number, line) '''
e6f543ee4573a4daf27e6e208dee0bbe7db056a6
yuko29/DHT22-dashboard
/test.py
644
3.640625
4
import sqlite3 sqliteConnection = sqlite3.connect('data.db') cursor = sqliteConnection.cursor() sql = "select Time, Temperature, Humidity from DHT22 limit 10" print(sql) cursor = cursor.execute(sql) data = { 'Header': [], 'Time':[], 'Temperature': [], 'Humidity': [] } header = list(map(lambda x: x[0], cursor.description)) for row in cursor: data['Time'].append(row[0]) data['Temperature'].append(row[1]) data['Humidity'].append(row[2]) data["Header"] = header cursor.close() sqliteConnection.close() print(data['Header']) print(data['Time']) print(data['Temperature']) print(data['Humidity'])
c96fe471e6409ce502f5d2f4ca56f6e59f9d13dc
pythonbtes/nandini
/btes/simple_calculator.py
2,072
3.828125
4
from tkinter import * window=Tk() window.title("simple calculator") window.configure(background="#17A589") window.geometry("370x150") window.resizable(0,0) expression="" def display(num): global expression # concatenation of string expression = expression + str(num) # update the expression by using set method equation.set(expression) equation = StringVar() value = Entry(window,text=equation) value.grid(columnspan=5,ipadx=120) button1=Button(window, text=' 1 ', height=1, width=10) button1.grid(row=2, column=0,command=display(1)) button2=Button(window, text=' 2 ', height=1, width=10) button2.grid(row=2, column=1,command=display(2)) button3 = Button(window, text=' 3 ', height=1, width=10) button3.grid(row=2, column=2) button4 = Button(window, text=' 4 ',height=1, width=10) button4.grid(row=3, column=0) button5 = Button(window, text=' 5 ', height=1, width=10) button5.grid(row=3, column=1) button6=Button(window, text= ' 6 ', height=1, width=10) button6.grid(row=3,column=2) button7=Button(window ,text= ' 7 ', height=1,width=10) button7.grid(row=4,column=0) button8=Button(window,text= ' 8 ',height=1,width=10) button8.grid(row=4,column=1) button9=Button(window ,text= ' 9 ', height=1,width=10) button9.grid(row=4,column=2) button0=Button(window,text= ' 0 ',height=1,width=10) button0.grid(row=5,column=0) button_clear=Button(window ,text= ' clear ', height=1,width=10) button_clear.grid(row=5,column=1) button_equal=Button(window,text= ' = ',height=1,width=10) button_equal.grid(row=5,column=2) button_plus=Button(window,text=" + ",height=1, width=10) button_plus.grid(row=2,column=3) button_minus=Button(window,text=" - ",height=1, width=10) button_minus.grid(row=3,column=3) button_divide=Button(window,text=" /",height=1, width=10) button_divide.grid(row=4,column=3) button_multiply=Button(window,text=" * ",height=1, width=10) button_multiply.grid(row=5,column=3 ) window.mainloop()
779944a0d9c5e15201a52ecf6200904fb581a368
AnkitAvi11/Data-Structures-And-Algorithms
/Data Structures/Queues/QueueList.py
1,447
4.46875
4
# class node to create a node for the queue linked list class Node : def __init__(self, val) : self.val = val self.next = None class Queue : # contructor of the queue class def __init__(self) : self.front = None self.rear = None # method to insert an element into the queue def insert(self, val) : new_node = Node(val) # if the front and rear pointer are null by default if self.rear is None and self.front is None : self.rear = new_node self.front = new_node # when there is already one more nodes or elements in the queue else : self.rear.next = new_node self.rear = new_node def traverse(self) : ptr = self.front if ptr is None : print('Queue is empty') return else : while ptr is not None : print(ptr.val, end = " ") ptr = ptr.next def delete(self) : ptr = self.front if ptr is None : print("queue is empty") return else : print(ptr.val) self.front = ptr.next del ptr if __name__ == '__main__' : queue = Queue() queue.insert(1) queue.insert(2) queue.insert(3) queue.delete() queue.delete() queue.delete() queue.delete() queue.traverse()
d3b13a5f10b5e20a8a726f42f6d372fede665021
Suraj-sati/programming-using-python
/remove_empty_tuples_in_list.py
206
4.03125
4
l=[] s=int(input("enter the size of list :")) for i in range(0,s): m=input("enter the element in list:") l.append(m) t=list(filter(None,l)) print ("list after removing empty elements :",t)
cd8b91ef3bf1ab9c87ebf93b5922b3a57982037a
gerrymandr/exhausting_splits
/hack3.py
8,318
3.609375
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat Nov 4 10:56:22 2017 @author: christy """ import networkx as nx import csv import sys import numpy as np import matplotlib.pyplot as plt plt.interactive(False) #using csv def create_graph(index,file): G=nx.Graph() f = open(file) reader = csv.reader(f) counter=0 for edge in reader: a=int(edge[0]) b=int(edge[1]) c=int(edge[2]) d=int(edge[3]) if index==0: G.add_edge(a,b,label=counter) elif index==1: G.add_edge(c,d,label=counter) counter=counter+1 f.close() return G #using txt (with spaces) def create_graph_txt(index,file): G=nx.Graph() f = open(file) lines=f.readlines() counter=0 for edge in lines: edge=edge.split() a=int(edge[0]) b=int(edge[1]) c=int(edge[2]) d=int(edge[3]) if index==0: G.add_edge(a,b,label=counter) elif index==1: G.add_edge(c,d,label=counter) counter=counter+1 f.close() return G #using csv #edge map is the crosswalk between blue and black(primal paths) def create_edge_map(index,m_primal,file): edge_map=-1*np.ones((m_primal,m_primal),dtype=np.int) f = open(file) reader = csv.reader(f) counter=0 for edge in reader: a=int(edge[0]) b=int(edge[1]) c=int(edge[2]) d=int(edge[3]) if index==0: edge_map[c,d]=a edge_map[d,c]=a elif index==1: edge_map[c,d]=b edge_map[d,c]=b f.close() return edge_map #using txt def create_edge_map_txt(index,m_primal,file): edge_map=-1*np.ones((m_primal,m_primal),dtype=np.int) f = open(file) lines=f.readlines() counter=0 for edge in lines: edge=edge.split() a=int(edge[0]) b=int(edge[1]) c=int(edge[2]) d=int(edge[3]) if index==0: edge_map[c,d]=a edge_map[d,c]=a elif index==1: edge_map[c,d]=b edge_map[d,c]=b f.close() return edge_map def get_population_data(m,file): population_data=np.zeros(m) f = open(file) reader = csv.reader(f) counter=0 for node in reader: pop=int(node[0]) population_data[counter]=pop counter=counter+1 return population_data def compute_population_score(m,k,population_ideal,population_data,districting): district_populations=np.zeros(k) for index in range(m): district_populations[int(districting[index])]+=population_data[index] pop_score=sum((district_populations-population_ideal)**2) return pop_score def compute_compactness_score(m,k,area_data,perimeter_data,districting,conflicted_edges): #ToDo compactness = np.array([0.0,0.0]) for district in districting: area = np.array([0.0,0.0]) for i in range(0,m): area[district[i]] = area_data[i] for edge in conflicted_edges return compactness def get_area_data(m,file): area_data=np.zeros(m) f = open(file) reader = csv.reader(f) counter=0 for node in reader: area=int(node[0]) area_data[counter]=area counter=counter+1 return area_data def get_perimeter_data(m_primal,file): perimeter_data=np.zeros((m_primal,m_primal)) f = open(file) reader = csv.reader(f) for edge in reader: a=int(edge[0]) b=int(edge[1]) p=int(edge[2]) perimeter_data[a][b]=p perimeter_data[b][a]=p return perimeter_data if __name__ == '__main__': k=2 example_file="simple2_graph_edge_map.csv" G_dual=create_graph(0,example_file) #adjacency map (blue map) G_primal=create_graph(1,example_file) #primal = drawing paths (black map) nx.draw(G_dual) plt.draw() plt.show(block=True) nx.draw(G_primal) plt.draw() plt.show(block=True) # example_file="squares_graph_edge_map.txt" # G_dual=create_graph_txt(0,example_file) # G_primal=create_graph_txt(1,example_file) m=len(G_dual.nodes()) # number of dual nodes (or the number of precincts) m_primal=len(G_primal.nodes()) #number of nodes in the path graph #m_primal=40 #for squares_graph example pop_ideal=m/float(k) # edge_map_0=create_edge_map(0,m_primal,example_file) # edge_map_1=create_edge_map(1,m_primal,example_file) edge_map_0=create_edge_map(0,m_primal,example_file) edge_map_1=create_edge_map(1,m_primal,example_file) #population_data=get_population_data(m,r"C:\DATA\Exhaust\exhausting_splits-master\exhausting_splits-master\simple_graph_population.csv") #area_data=get_area_data(m,"C:\DATA\Exhaust\exhausting_splits-master\exhausting_splits-master\simple_graph_area.csv") #perimeter_data=get_perimeter_data(m_primal,r"C:\DATA\Exhaust\exhausting_splits-master\exhausting_splits-master\simple_graph_perimeter.csv") #population_total=sum(population_data) #population_ideal=population_total/float(k) #simple boundary nodes # boundary_nodes_primal=[0,1,2,3,4] #making a list of nodes - if shape changes, this needs to be hard-coded in - we need to know how many #simple2 boundary nodes boundary_nodes_primal=[9,15,10,11,13,14,9,5,4,17,16,2,9] districtings=[] districtings_conflicted_edges=[] conflicted_edges=np.zeros((m_primal,m_primal)) for node1 in boundary_nodes_primal: for node2 in boundary_nodes_primal: if node1<node2: #print('here a') #print(node1) #print(node2) simple_paths=list(nx.all_simple_paths(G_primal,node1,node2)) for simple_path in simple_paths: #print('here b') #print(simple_path) G2=G_dual.copy() #copy the adjacency map so we can delete edges from it districting=np.zeros(m) for index in range(len(simple_path)-1): edge=(simple_path[index],simple_path[index+1]) #print(edge) edge2=(edge_map_0[edge[0],edge[1]],edge_map_1[edge[0],edge[1]]) #print(edge2) G2.remove_edge(edge2[0],edge2[1]) conflicted_edges[edge2[0],edge2[1]]=1 conflicted_edges[edge2[1],edge2[0]]=1 G2_districts=list(nx.connected_components(G2)) #returns a graph generator - a list of two graphs: dist 0 and dist 1 for index in range(2): for node in G2_districts[index]: districting[node]=index districtings.append(districting) districtings_conflicted_edges.append(conflicted_edges) print('districting:') print(districting) print G2_districts[0] # distgraph = nx.Graph(list(G2_districts[0])) # distgraph2 = nx.Graph(list(G2_districts[1])) # nx.draw(distgraph) # plt.draw() # plt.show(block=True) # nx.draw(distgraph2) # plt.draw() # plt.show(block=True) #create metagraph G_metagraph=nx.Graph() for i in range(len(districtings)): print "here" for j in range(len(districtings)): print "here2" districting1=districtings[i] print districting1 districting2=districtings[j] print districting2 if sum(abs(districting1-districting2))==1: G_metagraph.add_edge(i,j) nx.draw(G_metagraph) plt.draw() plt.show(block=True) print "done" # evaluate score for each districting # num_districtings=len(districtings) # scores=np.zeros((num_districtings,2)) # for districting in districtings: # conflicted_edge=districtings_conflicted_edges[index] # scores[index][0]=compute_population_score(m,k,population_ideal,population_data,districting) # scores[index][1]=compute_compactness_score(m,k,area_data,perimeter_data,districting,conflicted_edges) # index+=1 #
507da2f51cec77c87b07248a5bb7485e713a1d90
L200180039/praktikum-ASD
/MODUL - 1/14.py
315
3.796875
4
#14 def formatRupiah(a) : a = list(str(a)) b = len(a) if b % 3 == 0 : b = int(b/3) - 1 else : b = int(b/3) n = 0 for i in range(b) : x = -3*(i+1) a.insert(int(x)+n,".") n = n - 1 a = "".join(a) print("Rp "+a)
674c8c05dc66322924c290c52b2d6bb09c95b76f
Peixinho20/Python
/python/mundo2/a14/d62.py
670
3.921875
4
#Até a aula 14 ''' Melhore o desafio 61 perguntando para o usuário se ele quer mostrar mais alguns termos. O programa encerra quando ele disse que quer mostrar 0 termos. ''' a1 = int(input('Primeiro termo: ')) r = int(input('Razão: ')) termo = a1 cont = 1 total = 0 mais = 10 while mais != 0: total = total + mais # sem essa linha o programa não mostra a PA while cont <= total: print('{}'.format(termo), end='') print(' -> ' if cont < 10 else ' ', end='') termo += r cont += 1 print('\nPausa...') mais = int(input('\nQuantos termos quer mostrar a mais? ')) print('Progressão finalizada com {} termos'.format(total))
edc67b4ddf0b6ff2f3da3aa536e1ef2379e764b6
akshatakulkarni98/ProblemSolving
/DataStructures/MSFT/add_two_num_stored_rev.py
1,050
3.734375
4
# https://leetcode.com/problems/add-two-numbers/ # TC:O(N) # SC:O(N) # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: if not l1: return l2 if not l2: return l1 curr1=l1 curr2=l2 result=ListNode() traverse=result carry=0 while curr1 or curr2: x=curr1.val if curr1 else 0 y=curr2.val if curr2 else 0 temp_sum=x+y+carry new_node = ListNode(temp_sum%10) carry=temp_sum//10 traverse.next=new_node traverse=new_node if curr1: curr1=curr1.next if curr2: curr2=curr2.next if carry: traverse.next=ListNode(carry) return result.next
0c82160da861b9c3942862d706c04526fc26c1d2
chesneynyame/CLI-Application
/mini-project-csv-file-dict-2.1.1 CSV input.py
45,342
3.671875
4
# # WK1 # In this week we'll be building out the foundation of your app, in particular, the UI aspect. # This will make use of your ability to print to the screen, clear the screen, accept user input, and create a basic `list` data structure. # Try to make good use of functions for repetitive tasks. # ## Goals # As a user I want to: # - create a Courier and add it to a list # - view all products # - _STRETCH_ update or delete a Courier # ## Spec # A `Courier` should just be a `string` containing its name, i.e: `"Coke Zero"` # A list of `products` should be a list of `strings`, i.e: `["Coke Zero"]` # ## Pseudo Code # - START APP # LOAD COURIERS AND PRODUCTS FROM TXT # FILESHOW LIST OF OPTIONS TO USER AND ACCEPT NUMERICAL INPUT # IF USER ENTERS 0 THEN SAVE APP STATE TO TXT FILES AND EXIT APP # - SHOW LIST OF OPTIONS TO USER AND ACCEPT NUMERICAL INPUT # - IF USER ENTERS `0` THEN EXIT APP # - IF USER ENTERS `1` THEN SHOW `PRODUCT` MENU - list # - IF USER ENTERS `0` RETURN TO MAIN MENU # - IF USER ENTERS `1` PRINT OUT `PRODUCTS` TO SCREEN - print list # - IF USER ENTER `2` CREATE NEW `PRODUCT` # - ASK USER FOR THE `NAME` OF THE `PRODUCT` # - APPEND THIS TO THE LIST OF `PRODUCTS` - append # - _STRETCH_ IF USER ENTERS `3` UPDATE `PRODUCT` # - ASK USER TO SELECT A `PRODUCT` TO UPDATE # - ASK USER FOR NEW `NAME` OF `PRODUCT` # - REPLACE `PRODUCT` AT SELECTED `IDX` WITH NEW `NAME` # - _STRETCH_ IF USER ENTERS `4` DELETE `PRODUCT` # - ASK USER TO SELECT A `PRODUCT` TO DELETE # - REMOVE THIS ITEM FROM THE `PRODUCT` LIST # IF USER ENTERS `2` THEN SHOW `COURIER` MENU # - IF USER ENTERS `0` RETURN TO MAIN MENU # - IF USER ENTERS `1` PRINT OUT `COURIERS` TO SCREEN # - IF USER ENTER `2` CREATE NEW `COURIER` # - ASK USER FOR THE `NAME` OF THE `COURIER` # - APPEND THIS TO THE LIST OF `COURIERS` # - _STRETCH_ IF USER ENTERS `3` UPDATE `COURIER` # - ASK USER TO SELECT A `COURIER` TO UPDATE OR `0` TO CANCEL # - ASK USER FOR NEW `NAME` OF `COURIER` # - REPLACE `COURIER` AT SELECTED `IDX` WITH NEW `NAME` # - _STRETCH_ IF USER ENTERS `4` DELETE `COURIER` # - ASK USER TO SELECT A `COURIER` TO DELETE OR `0` TO CANCEL # - REMOVE THIS ITEM FROM THE `COURIER` LIST # IF USER ENTERS 3 THEN SHOW ORDER MENU # IF USER ENTERS 0 RETURN TO MAIN MENU # IF USER ENTERS 1 PRINT OUT ORDERS TO SCREEN # IF USER ENTER 2 CREATE NEW ORDER # ASK USER FOR THE NAME OF THE CUSTOMER # ASK USER FOR THE ADDRESS OF THE CUSTOMER # ASK USER FOR THE PHONE OF THE CUSTOMER # AKS THE USER TO SELECT A COURIER FROM THE LIST # SET THE DEFAULT ORDER STATUS TO BE PREPARING # APPEND THE NEW ORDER TO THE LIST OF ORDERS # IF USER ENTERS 3 UPDATE ORDER STATUS # ASK USER TO SELECT AND ORDER TO UPDATE OR 0 TO CANCEL # ASK USER TO SELECT A NEW STATUS # UPDATE THE ORDER # STRETCH IF USER ENTERS 4 UPDATE ORDER # ASK USER TO SELECT AN ORDER TO UPDATE OR 0 TO CANCEL # FOR EACH ORDER PROPERTY # ASK USER FOR UPDATED DATA OR LEAVE BLANK TO SKIP # UPDATE THE ORDER PROPERTY IF NOT BLANK # STRETCH IF USER ENTERS 5 DELETE ORDER # ASK USER TO SELECT AN ORDER TO DELETE OR 0 TO CANCEL # REMOVE THIS ITEM FROM THE ORDERS LIST import os import csv def clear(): os.system('cls') products_available = [] courier_available = [] order_1 = {'Name': 'Sweeny Todd', 'Address': 'Unit 45, 2 Hogwarts Street, LONDON, BR6 3LQ', 'Contact No': '07940479678', 'Courier': 2, 'Status': 'Preparing', 'Items': [2, 4, 5]} order_2 = {'Name': 'Michael Jackson', 'Address': '20, Neverland, New York, NH1 3TR', 'Contact No': '07940479689', 'Courier': 1, 'Status': 'Preparing', 'Items': [1, 2, 3]} orders = [] orders_dict = {} items = [] l_o_o = len(orders) ord_num_rows = 0 for row in open('C:/Users/chesney/Documents/Python Programme/Mini-project/Order_lst.csv'): ord_num_rows += 1 ord_num = ord_num_rows -1 # products fanta_dct = {'Product Name': 'Fanta', 'Price': 0.8} coke_dct = {'Product Name': 'Coke', 'Price': 0.75} sprite_dct = {'Product Name': 'Sprite', 'Price': 0.8} tango_dct = {'Product Name': 'Tango', 'Price': 0.8} apple_dct = {'Product Name': 'Apple Juice', 'Price': 1.2} pineapple_dct = {'Product Name': 'Pineapple Juice', 'Price': 1.2} product_lst = [] product_dct = {} l_o_p = len(product_lst) prod_num_rows = 0 for row in open('C:/Users/chesney/Documents/Python Programme/Mini-project/Product_lst.csv'): prod_num_rows += 1 prod_num = prod_num_rows -1 # couriers courier_1 = {'Courier Name': 'Matthew', 'Phone Number': '07956322433'} courier_2 = {'Courier Name': 'Mark', 'Phone Number': '07956322435'} courier_3 = {'Courier Name': 'Luke', 'Phone Number': '07956322436'} courier_4 = {'Courier Name': 'John', 'Phone Number': '07956322437'} courier_5 = {'Couier Name': 'James', 'Phone Number': '07956322483'} courier_6 = {'Courier Name': 'Hector', 'Phone Number': '07956322933'} courier_lst = [] courier_dct = {} l_o_c = len(courier_lst) cour_num_rows = 0 for row in open('C:/Users/chesney/Documents/Python Programme/Mini-project/Courier_lst.csv'): cour_num_rows += 1 cour_num = cour_num_rows -1 courier_num_options = "\nPlease select:\n\n[0] Exit to Main Menu\n[1] Courier List\n[2] Add Courier\n[3] Replace Courier\n[4] Delete Courier\n" product_num_options = "\nPlease select:\n\n[0] Exit to Main Menu\n[1] Product List\n[2] Add Product\n[3] Replace Product\n[4] Delete Product\n" order_num_options = "\nPlease select:\n\n[0] Exit to Main Menu\n[1] Order List\n[2] Create New Order\n[3] Update Order Status\n[4] Update Order\n[5] Delete Order\n" main_menu_num = "\nWelcome to the Main Menu\n\nPlease select:\n[0] Exit App\n[1] Product Options\n[2] Courier Options\n[3] Order Option\n" start_app_num = "\nHello, Welcome Gen Convenience\n\nPlease select:\n[0] Exit App\n[1] Main Menu\n" select_status = [['[1] Preparing', 'Preparing'], ['[2] Out for Devlivery', 'Out for Delivery'], ['[3] Delivered', 'Delivered']] c_uos = '\nPlease Select:\n\n[0] CANCEL\n[1] Update Order Status\n' c_uod = '\nPlease Select:\n\n[0] CANCEL\n[1] Update Customer Order Details\n' c_dod = '\nPlease Select:\n\n[0] CANCEL\n[1] Delete Customer Order Details\n' c_upd = '\nPlease Select:\n\n[0] CANCEL\n[1] Update Product Details\n' c_dpd = '\nPlease Select:\n\n[0] CANCEL\n[1] Delete Product Details\n' c = 'No Changes Made' ce = 'Updating...' def print_n(): print('\n') def user_input_1(): user_input_1 = input() return user_input_1.title() def user_input_2(): user_input_2 = input() return user_input_2 product_file_csv = 'C:/Users/chesney/Documents/Python Programme/Mini-project/Product_lst.csv' courier_file_csv = 'C:/Users/chesney/Documents/Python Programme/Mini-project/Courier_lst.csv' orders_file_csv = 'C:/Users/chesney/Documents/Python Programme/Mini-project/Order_lst.csv' # -------------------------------------------------------------------------------------------- PRODUCTS -------------------------------------------------------------------------------------------------------------------------------------------------------------- # view product list def print_product_list(): print('\nProduct List:\n') for count, value in enumerate(product_lst, 1): print(f'{count}: {value}') # print_product_list() # ------------------------------------------------------------------------------------------ CREATE PRODUCT -------------------------------------------------------------------------------------------------------------------------------------------------------- def create_product_name(): print('Product Name: ') p_u_i = user_input_1() return p_u_i # create_product_name() def create_product_price(): print('Product Price:') pr_u_i = user_input_2() while pr_u_i.replace(".", "", 1).isdigit() == False: print('Invalid input') print('Product Price:') pr_u_i = user_input_2() pr_u_i f_pr_u_i = float(pr_u_i) return f_pr_u_i # create_product_price() def add_new_product_dict(create_product_name, create_product_price): product_dct['Product Name'] = create_product_name() print('Adding...') print(product_dct['Product Name']) print_n() product_dct['Price'] = create_product_price() print('Adding...') print(product_dct['Price']) dct_copy = product_dct.copy() product_lst.append(dct_copy) print_product_list() # add_new_product_dict(create_product_name, create_product_price) # create new product def create_new_product(): clear() print('Create Product\n\nEnter Product details:') add_new_product_dict(create_product_name, create_product_price) # create_new_product() # ---------------------------------------------------------------------------------------------SELECT PRODUCT------------------------------------------------------------------------------------------------------------------------------------------------------- def select_product(): print_product_list() print_n() print('Select Product or 0 to Cancel:') up_can = user_input_2() while up_can.isdigit() == False: print('Invalid input') print('Select Product or 0 to Cancel:') up_can = user_input_2() if up_can == "0": print('Exiting...') product_options() else: int_up_can = int(up_can) while int_up_can > prod_num: print(f'Only {prod_num} products available, choose from the following:') print_product_list() print_n() print('Select Product:') up_can = user_input_2() int_up_can = int(up_can) sel_prod = product_lst[int_up_can -1] print('\nProduct Selected:\n',sel_prod) return sel_prod # select_product() # sel_prod_dict = select_product() # ------------------------------------------------------------------------------------------- UPDATE PRODUCT ----------------------------------------------------------------------------------------------------------------------------------------------------- def update_product_name(create_product_name, sel_prod_dict): # print('Enter Product Name:') prod_nam_in = create_product_name() if prod_nam_in == "": print(c) else: print(ce) sel_prod_dict['Product Name'] = prod_nam_in # update_product_name(create_product_name) def update_product_price(user_input_2, sel_prod_dict): empty_string = "" print('Enter Product Price:') prod_price_in = user_input_2() while prod_price_in.replace(".", "", 1).isdigit() == False and prod_price_in != empty_string: print('Invalid input') print('Enter Product Price:') prod_price_in = user_input_2() if prod_price_in == "": print(c) else: fl_prod_price_in = float(prod_price_in) print(ce) sel_prod_dict['Price'] = fl_prod_price_in # update_product_price() # Update details def update_product(sel_prod_dict): print_n() update_product_name(create_product_name, sel_prod_dict) print_n() update_product_price(user_input_2, sel_prod_dict) print_n() print(sel_prod_dict) # update_product() # --------------------------------------------------------------------------------------------DELETE PRODUCT --------------------------------------------------------------------------------------------------------------------------------------------------- def del_sel_prod(sel_prod_dict): print('Deleting...') print(sel_prod_dict) product_lst.remove(sel_prod_dict) print_product_list() # del_sel_prod(sel_prod_dict) def delete_product(sel_prod_dict): print_n() del_sel_prod(sel_prod_dict) # delete_product(sel_prod_dict) # ----------------------------------------------------------------------------------------- WRITE & READ ----------------------------------------------------------------------------------------------------------------------------------------------------- # Load Products from txt def load_product(): try: with open('C:/Users/chesney/Documents/Python Programme/Mini-project/Product_lst.csv') as product_options: reader = csv.DictReader(product_options) for row in reader: product_lst.append(row) except FileNotFoundError as fnfe: print('Unable to open file: ' + str(fnfe)) except Exception as e: print('An error occured: ' + str(e)) # load_product() # save Courier updates def save_product_updates(): try: keys = product_lst[0].keys() with open('C:/Users/chesney/Documents/Python Programme/Mini-project/Product_lst.csv', 'w', newline='') as output_file: dict_writer = csv.DictWriter(output_file, keys) dict_writer.writeheader() dict_writer.writerows(product_lst) except FileNotFoundError as fnfe: print('Unable to open file: ' + str(fnfe)) except Exception as e: print('An error occured: ' + str(e)) # save_product_updates() # -------------------------------------------------------------------------------------------- PRODUCT OPTIONS ---------------------------------------------------------------------------------------------------------------------------------------------------- # Courier options def product_options(): clear() print(product_num_options) prod_num_sel = user_input_2() while prod_num_sel.isdigit() == False: print('Invalid input') print('Select from the following:\n',product_num_options) prod_num_sel = user_input_2() int_prod_num_sel = int(prod_num_sel) while int_prod_num_sel not in [0, 1, 2, 3, 4]: print('Invalid input') print('Select from the following options:') print(product_num_options) prod_num_sel = user_input_2() int_prod_num_sel = int(prod_num_sel) while int_prod_num_sel in [0, 1, 2, 3, 4]: if int_prod_num_sel == 1: print_product_list() print(product_num_options) prod_num_sel = user_input_2() int_prod_num_sel = int(prod_num_sel) elif int_prod_num_sel == 2: create_new_product() print(product_num_options) prod_num_sel = user_input_2() int_prod_num_sel = int(prod_num_sel) elif int_prod_num_sel == 3: sel_prod_dict = select_product() update_product(sel_prod_dict) print(product_num_options) prod_num_sel = user_input_2() int_prod_num_sel = int(prod_num_sel) elif int_prod_num_sel == 4: sel_prod_dict = select_product() delete_product(sel_prod_dict) print(product_num_options) prod_num_sel = user_input_2() int_prod_num_sel = int(prod_num_sel) elif int_prod_num_sel == 0: main_menu() while int_prod_num_sel not in [0, 1, 2, 3, 4]: print("Invalid input") print('Select from the following options:') print(product_num_options) prod_num_sel = user_input_2() int_prod_num_sel = int(prod_num_sel) # product_options() # -------------------------------------------------------------------------------------------- COURIER ---------------------------------------------------------------------------------------------------------------- # print courier list def print_courier_list(): print('\nCourier List:\n') for count, value in enumerate(courier_lst, 1): print(f'{count}: {value}') # print_courier_list() # ------------------------------------------------------------- CREATE COURIER---------------------------------------------------- def create_courier_name(): print('Courier Name:') cour_name = user_input_1() return cour_name def create_courier_num(): print('Courier Contact No:') cour_con_num = user_input_2() while cour_con_num.isdigit() == False or len(cour_con_num) != 11: print('Invalid input') print('Courier Contact No:') cour_con_num = user_input_2() return cour_con_num def add_new_courier_dict(create_courier_name, create_courier_num): courier_dct['Courier Name'] = create_courier_name() print('Adding...') print(courier_dct['Courier Name']) print_n() courier_dct['Phone Number'] = create_courier_num() print('Adding...') print(courier_dct['Phone Number']) dct_copy = courier_dct.copy() courier_lst.append(dct_copy) print_courier_list() # create new courier def create_new_courier(): clear() print('Create Courier\n\nEnter Courier Details:') add_new_courier_dict(create_courier_name, create_courier_num) # create_new_courier() # ----------------------------------------------------------------- SELECT COURIER def select_courier(): print_courier_list() print_n() print('Select Courier or 0 to Cancel:') uc_can = user_input_2() while uc_can.isdigit() == False: print('Invalid input') print('Select Courier or 0 to Cancel:') uc_can = user_input_2() if uc_can == "0": print('Exiting...') courier_options() else: int_uc_can = int(uc_can) while int_uc_can > cour_num: print(f'Only {cour_num} couriers available, choose from the following:') print_courier_list() print_n() print('Select Courier:') uc_can = user_input_2() int_uc_can = int(uc_can) sel_cour = courier_lst[int_uc_can -1] print('\nCourier Selected:\n',sel_cour) return sel_cour # select_courier() # sel_cour_dict = select_courier() # ---------------------------------------------------------------- UPDATE COURIER # Update details def update_courier_name(create_courier_name, sel_cour_dict): # print('Enter Courier Name:') cour_nam_in = create_courier_name() if cour_nam_in == "": print(c) else: print(ce) sel_cour_dict['Courier Name'] = cour_nam_in # update_courier_name(create_courier_name, sel_cour_dict) def update_courier_num(user_input_2, sel_cour_dict): empty_string = "" print('Enter Courier Contact Number:') cour_con_in = user_input_2() while cour_con_in.isdigit == False and cour_con_in != empty_string: print('Invalid input') print('Enter Courier Contact Number:') cour_con_in = user_input_2() if cour_con_in == "": print(c) else: print(ce) sel_cour_dict['Phone Number'] = cour_con_in # update_courier_num(user_input_2, sel_cour_dict) def update_courier(sel_cour_dict): print_n() update_courier_name(create_courier_name, sel_cour_dict) print_n() update_courier_num(user_input_2, sel_cour_dict) print_n() print(sel_cour_dict) # update_courier() # ------------------------------------------------------------------------------ DELETE COURIER def del_sel_cour(sel_cour_dict): print('Deleting...') print(sel_cour_dict) courier_lst.remove(sel_cour_dict) print_courier_list() # del_sel_cour(sel_cour_dict) def delete_courier(sel_cour_dict): print_n() del_sel_cour(sel_cour_dict) # delete_courier(sel_cour_dict) # ------------------------------------------------------------------------------ WRITE & READ ------------------------------------------------------------------ # Load Couriers from txt def load_courier(): try: with open('C:/Users/chesney/Documents/Python Programme/Mini-project/Courier_lst.csv') as courier_options: reader = csv.DictReader(courier_options) for row in reader: courier_lst.append(row) except FileNotFoundError as fnfe: print('Unable to open file: ' + str(fnfe)) except Exception as e: print('An error occured: ' + str(e)) # load_courier() # save courier updates def save_courier_updates(): try: keys = courier_lst[0].keys() with open('C:/Users/chesney/Documents/Python Programme/Mini-project/Courier_lst.csv', 'w', newline='') as output_file: dict_writer = csv.DictWriter(output_file, keys) dict_writer.writeheader() dict_writer.writerows(courier_lst) except FileNotFoundError as fnfe: print('Unable to open file: ' + str(fnfe)) except Exception as e: print('An error occured: ' + str(e)) # save_courier_updates() # -------------------------------------------------------------------------------- COURIER OPTIONS # Courier option def courier_options(): clear() print(courier_num_options) cour_num_sel = user_input_2() while cour_num_sel.isdigit() == False: print('Invalid input') print('Select from the follwoing:\n',courier_num_options) cour_num_sel = user_input_2() int_cour_num_sel = int(cour_num_sel) while int_cour_num_sel not in [0, 1, 2, 3, 4]: print('Invalid input') print('Select from the follwoing:') print(courier_num_options) cour_num_sel = user_input_2() int_cour_num_sel = int(cour_num_sel) while int_cour_num_sel in [0, 1, 2, 3, 4]: if int_cour_num_sel == 1: print_courier_list() print(courier_num_options) cour_num_sel = user_input_2() int_cour_num_sel = int(cour_num_sel) elif int_cour_num_sel == 2: create_new_courier() print(courier_num_options) cour_num_sel = user_input_2() int_cour_num_sel = int(cour_num_sel) elif int_cour_num_sel == 3: sel_cour_dict = select_courier() update_courier(sel_cour_dict) print(courier_num_options) cour_num_sel = user_input_2() int_cour_num_sel = int(cour_num_sel) elif int_cour_num_sel == 4: sel_cour_dict = select_courier() delete_courier(sel_cour_dict) print(courier_num_options) cour_num_sel = user_input_2() int_cour_num_sel = int(cour_num_sel) elif int_cour_num_sel == 0: main_menu() while int_cour_num_sel not in [0, 1, 2, 3, 4]: print('Invalid input') print('Select from the follwoing options:') print(courier_num_options) cour_num_sel = user_input_2() int_cour_num_sel = int(cour_num_sel) # courier_options() # -------------------------------------------------------------------------------------------- ORDERS ----------------------------------------------------------------------------------------------------------------- # Print order list def print_order_list(): print('\nOrder List:\n') for count, value in enumerate(orders, 1): print(f'{count}: {value}') # print_order_list() # ---------------------------------------------------------------------------------------------------------- CREATE ORDER def create_order_name(): print('Customer Name:') o_u_i = user_input_1() return o_u_i def create_order_add(): print('Customer Address:') add_u_i = user_input_2() return add_u_i # add_items def add_items(user_input): if user_input == "0": print('Exiting...') order_options() else: while user_input.isdigit() == False: print('Invalid input') user_input = input('Select item: ') u_i = int(user_input) while u_i > prod_num: print(f'Only {prod_num} items available, chose from the following') user_input = input('Select item: ') u_i = int(user_input) items.append(u_i) print(items,'\n') # add courier indx def add_courier_indx(user_input): if user_input == "0": print('Exiting...') order_options() else: while user_input.isdigit() == False: print('Invalid input') user_input = input('Select Courier: ') u_i = int(user_input) while u_i > cour_num: print(f'Only {cour_num} couriers available, choose from the following:') user_input = input('Select Courier: ') u_i = int(user_input) # orders_dict['Courier'] = courier_lst[(u_i)-1] orders_dict['Courier'] = u_i print('Adding Courier...') print(courier_lst[(u_i)-1]) while user_input.isdigit() == False: print('Invalid input') user_input = input('Select item: ') u_i = int(user_input) # user_input = input() # add_courier_indx(user_input) # add contact no def add_contact_no(user_input): if user_input == "00": print('Exiting...') order_options() else: while user_input.isdigit() == False or len(user_input) != 11: print('Invalid input') user_input = input('Enter Contact No or 00 to Cancel: ') orders_dict['Contact No'] = user_input print('Adding Contact Number...') # user_input = input('Enter Contact No: ') # add_contact_no(user_input) # add status def add_status(user_input): if user_input == "0": print('Exiting...') order_options() elif user_input != "0": while user_input.isdigit() == False: print('Invalid input\n') print('Choose from the folloing: ') print(select_status[0][0]) print(select_status[1][0]) print(select_status[2][0]) user_input = input('Select status: ') u_i = int(user_input) while u_i not in [1, 2, 3]: print('\nSelect Status') print('Invalid selection\n') print('Choose from the folloing: ') print(select_status[0][0]) print(select_status[1][0]) print(select_status[2][0]) print('\n') user_input = input('Select status: ') u_i = int(user_input) orders_dict['Status'] = select_status[int(u_i) -1][1] print('Status set to:') print(orders_dict['Status']) # user_input = input('Select status: ') # add_status(user_input) # add name def add_name(user_input): if user_input == "0": print('Exiting...') order_options() else: orders_dict['Name'] = user_input print('Adding Name...') # print(orders_dict['Name']) # user_input = input('Enter name or 0 to canel: ').title() # add_name(user_input) # add address def add_address(user_input): if user_input == "0": print('Exiting...') order_options() else: orders_dict['Address'] = user_input print('Adding Address...') # print(orders_dict['Address']) # user_input = input('Enter address or 0 to canel: ').title() # add_address(user_input) # create new order def create_new_order(): clear() print('Create Order\n\nPlease Enter Customer Details:') print('Enter Name or 0 to Cancel:') nam_u_i = user_input_1() add_name(nam_u_i) print_n() print('Enter Address or 0 to Cancel:') add_u_i = user_input_2() add_address(add_u_i) print_n() print('Enter Contact No or 00 to Cancel:') con_u_i = user_input_2() add_contact_no(con_u_i) print_n() print_courier_list() print_n() print('Select Courier or 0 to Cancel:') cour_u_i = user_input_2() add_courier_indx(cour_u_i) print_n() print('\nSelect Status:') print(select_status[0][0]) print(select_status[1][0]) print(select_status[2][0]) print_n() sel_stat_u_i = user_input_2() add_status(sel_stat_u_i) print_n() print_product_list() print_n() new_list = [] print('Select Item:') add_i_u_i = user_input_2() add_items(add_i_u_i) print('Would you like to add more items?\nY/N:') ask_again = user_input_1() while ask_again != "Y" and ask_again != "N": print('Invalid input') print('Would you like to add more items?\nY/N:') ask_again = user_input_1() while ask_again == "YES" or ask_again == "Yes" or ask_again == "Y" or ask_again == "yes" or ask_again == "y": print('Select Item:') add_i_u_i = user_input_2() add_items(add_i_u_i) print('Add more items?\nY/N:') ask_again = user_input_1() if ask_again == "NO" or ask_again == "No" or ask_again == "N" or ask_again == "no" or ask_again == "n": print(items) for i in items: i -= 1 new_list.append(product_lst[i]) orders_dict['Items'] = items # print(orders_dict['Items']) print('\nAdding Proucts...') print(new_list) print_n() dct_copy = orders_dict.copy() orders.append(dct_copy) print('Adding New Order...') print(dct_copy) print_order_list() # create_new_order() # ---------------------------------------------------------------------------------------------------------------------------- SELECTED ORDER ---------------------------------------------------------------------------------------------------------------------- def select_order(): print_order_list() print_n() print('Select Order or 0 to Cancel:') uo_can = user_input_2() while uo_can.isdigit() == False: print('Invalid input') print('Select Product or 0 to Cancel:') uo_can = user_input_2() if uo_can == "0": print('Exiting...') order_options() else: int_uo_can = int(uo_can) while int_uo_can > ord_num: print(f'Only {ord_num} orders available, choose from the following:') print_order_list() print_n() print('Select or 0 to Cancel:') uo_can = user_input_2() int_uo_can = int(uo_can) sel_ord = orders[int_uo_can -1] print('\nOrder Selected:\n',sel_ord) return sel_ord # sel_ord_dict = select_order() # --------------------------------------------------------------------------------------------------------------------------- UPDATE STATUS ----------------------------------------------------------------------------------------------------------------- def status(user_input): while user_input.isdigit() == False: print('Invalid input') print('Choose from the following:\n') print(select_status[0][0]) print(select_status[1][0]) print(select_status[2][0]) user_input = input('Select Status: ') u_i_1 = int(user_input) while u_i_1 not in [1, 2, 3]: print('Invalid selection') print('Choose from the following:\n') print(select_status[0][0]) print(select_status[1][0]) print(select_status[2][0]) print('\n') user_input = input('Select Staus: ') u_i_1 = int(user_input) return u_i_1 # user_input = input('Select Status: ') # status(user_input) # Update order status def update_order_status(user_input_2, sel_ord_dict): print('\nSelect Status:') print_n() print(select_status[0][0]) print(select_status[1][0]) print(select_status[2][0]) print_n() u_o_s = user_input_2() s_s = status(u_o_s) sel_ord_dict['Status'] = select_status[s_s -1][1] print(ce) print(sel_ord_dict) # clear() # print_n() # print(select_status[0][0]) # print(select_status[1][0]) # print(select_status[2][0]) # print('\n') # user_input = input('Select Status: ') # s_s = status(user_input) # s_o['Status'] = select_status[s_s-1][1] # print('Changed to:',s_o['Status']) # print(s_o) # user_input = input('Select an Order or 0 to Cancel: ') # update_order_status(user_input_2, sel_ord_dict) def update_status(sel_ord_dict): update_order_status(user_input_2, sel_ord_dict) # update_status(sel_ord_dict) # ------------------------------------------------------------------------------------------------------------------------- UPDATE ORDER DETAILS ------------------------------------------------------------------------------------------------------------------------ # update order name def update_order_name(create_order_name, sel_ord_dict): ord_nam_in = create_order_name() if ord_nam_in == "": print(c) else: print(ce) sel_ord_dict['Name'] = ord_nam_in # update_order_name(create_order_name, sel_ord_dict) # update order address def update_order_address(create_order_address, sel_ord_dict): ord_add_in = create_order_add() if ord_add_in == "": print(c) else: print(ce) sel_ord_dict['Address'] = ord_add_in # update_order_address(create_order_name, sel_ord_dict) def update_order_num(user_input_2, sel_ord_dict): empty_string = "" print('Customer Contact Number:') ord_con_in = user_input_2() while ord_con_in.isdigit == False and ord_con_in != empty_string: print('Invalid input') print('Customer Contact Number:') ord_con_in = user_input_2() if ord_con_in == "": print(c) else: print(ce) sel_ord_dict['Contact No'] = ord_con_in # update_order_num(user_input_2, sel_ord_dict) def update_order_cour(user_input_2, sel_ord_dict): empty_string = "" print('Select Courier') cour_ui = user_input_2() while cour_ui.isdigit() == False and cour_ui != empty_string: print('Invalid input') print_n() print_courier_list() print_n() print('Select Courier:') cour_ui = user_input_2() if cour_ui == "": print(c) print(sel_ord_dict['Courier'], '\n') else: int_cour_ui = int(cour_ui) while int_cour_ui > l_o_c: print(f'Only {l_o_c} orders avaiable, choose from the following:') print_n() print_courier_list() cour_ui = user_input_2() int_cour_ui = int(cour_ui) sel_ord_dict['Courier'] = courier_lst[int_cour_ui -1] print(ce) print(sel_ord_dict['Courier'], '\n') # update_order_cour(user_input_2, sel_ord_dict) def update_items(user_input_2): up_it = user_input_2() while up_it.isdigit() == False: print('Invalid input') print('Select item:') up_it = user_input_2() int_up_it = int(up_it) while int_up_it > l_o_p: print(f'Only {l_o_p} items available, chose from the following') up_it = user_input_2() int_up_it = int(up_it) # items.append(int_up_it) # print(items,'\n') return int_up_it # update_items(user_input_2) def update_order_items(user_input_2, sel_ord_dict): new_list = [] print('Select Items') retr_item = update_items(user_input_2) items.append(retr_item) print(items) print('Would you like to add more items?\nY/N:') # ask_again = user_input_1() ask_again = user_input_1() while ask_again != "Y" and ask_again != "N": print('Invalid input') print('Would you like to add more items?\nY/N:') ask_again = user_input_1() while ask_again == "YES" or ask_again == "Yes" or ask_again == "Y" or ask_again == "yes" or ask_again == "y": print('Select Item:') add_i_u_i = user_input_2() add_items(add_i_u_i) print('Add more items?\nY/N:') ask_again = user_input_1() if ask_again == "NO" or ask_again == "No" or ask_again == "N" or ask_again == "no" or ask_again == "n": print(items) for x in items: x -=1 new_list.append(product_lst[x]) sel_ord_dict['Items'] = items print('\nUpdating Items...') print(new_list) # update_order_items(user_input_2, sel_ord_dict) # Update details def update_details(sel_ord_dict): print_n() update_order_name(create_order_name, sel_ord_dict) print_n() update_order_address(create_order_add, sel_ord_dict) print_n() update_order_num(user_input_2, sel_ord_dict) print_n() print_courier_list() update_order_cour(user_input_2, sel_ord_dict) print_n() print_product_list() update_order_items(user_input_2, sel_ord_dict) print_n() print(sel_ord_dict) # print('Select Order or 0 to Cancel:') # up_det_ui = user_input_2() # if up_det_ui == "0": # print('Exiting...') # order_options() # else: # while up_det_ui.isdigit() == False: # print('Invalid input') # print('Select Order or 0 to Cancel:') # up_det_ui = user_input_2() # int_up_det_ui = int(up_det_ui) # while int_up_det_ui > l_o_o: # print(f'Only {l_o_o} orders available, please choose from the following:') # print_order_list() # print_n() # print('Select Order or 0 to Cancel:') # up_det_ui = user_input_2() # int_up_det_ui = int(up_det_ui) # sel_ord = orders[int_up_det_ui -1] # print(sel_ord) # print('Enter Name:') # nam_ui = user_input_1() # if nam_ui == "": # print(c) # print(sel_ord['Name'],'\n') # else: # sel_ord['Name'] = nam_ui # print(ce) # print(sel_ord['Name'], '\n') # print('Enter Address:') # add_ui = user_input_2() # if add_ui == "": # print(c) # print(sel_ord['Address'], '\n') # else: # sel_ord['Address'] = add_ui # print(ce) # print(sel_ord['Address'], '\n') # empty_string = "" # print('Enter Contact Number:') # num_ui = user_input_2() # while num_ui.isdigit() == False and num_ui != empty_string or len(num_ui) != 11: # print('Invalid input') # print('Enter Contact Number:') # num_ui = user_input_2() # if num_ui == "": # print(c) # print(sel_ord['Contact No'], '\n') # else: # print(ce) # sel_ord['Contact No'] = num_ui # print(sel_ord['Contact No'],'\n') # print_courier_list() # print_n() # print('Select Courier') # cour_ui = user_input_2() # while cour_ui.isidgit == False and cour_ui != empty_string: # print('Invalid input') # print_n() # print_courier_list() # print_n() # print('Select Courier:') # cour_ui = user_input_2() # if cour_ui == "": # print(c) # print(sel_ord['Courier'], '\n') # else: # int_cour_ui = int(cour_ui) # while int_cour_ui > l_o_o: # print(f'Only {l_o_o} orders avaiable, choose from the following:') # print_n() # print_courier_list() # cour_ui = user_input_2() # int_cour_ui = int(cour_ui) # sel_ord['Courier'] = courier_lst[int_cour_ui -1] # print(ce) # print(sel_ord['Courier'], '\n') # print_order_list # update_details(sel_ord_dict) # ------------------------------------------------------------------ DELETE # delete selected order def del_sel_ord(sel_ord_dict): print('Deleting...') print(sel_ord_dict) orders.remove(sel_ord_dict) print_order_list() # Del order def del_order(sel_ord_dict): print_n() del_sel_ord(sel_ord_dict) # del_order(sel_ord_dict) # ------------------------------------------------------------------------------------READ & WRITE..................................... # Load order from csv def load_order(): try: with open('C:/Users/chesney/Documents/Python Programme/Mini-project/Order_lst.csv') as order_options: reader = csv.DictReader(order_options) for row in reader: orders.append(row) except FileNotFoundError as fnfe: print('Unable to open file: ' + str(fnfe)) except Exception as e: print('An error occured: ' + str(e)) # load_order() # save courier updates def save_order_updates(): try: keys = orders[0].keys() with open('C:/Users/chesney/Documents/Python Programme/Mini-project/Order_lst.csv', 'w', newline='') as output_file: dict_writer = csv.DictWriter(output_file, keys) dict_writer.writeheader() dict_writer.writerows(orders) except FileNotFoundError as fnfe: print('Unable to open file: ' + str(fnfe)) except Exception as e: print('An error occured: ' + str(e)) # save_order_updates() # -------------------------------------------------------------------------------------------------------- ORDER OPTIONS # order options def order_options(): clear() print(order_num_options) ord_num_sel = user_input_2() while ord_num_sel.isdigit() == False: print('Invalid input') print('Select from the following:\n',order_num_options) ord_num_sel = user_input_2() int_ord_num_sel = int(ord_num_sel) while int_ord_num_sel not in [0, 1, 2, 3, 4, 5]: print("Input invalid") print('Select from the following:') print(order_num_options) ord_num_sel = user_input_2() int_ord_num_sel = int(ord_num_sel) while int_ord_num_sel in [0, 1, 2, 3, 4, 5]: if int_ord_num_sel == 1: print_order_list() print(order_num_options) ord_num_sel = user_input_2() int_ord_num_sel = int(ord_num_sel) elif int_ord_num_sel == 2: create_new_order() print(order_num_options) ord_num_sel = user_input_2() int_ord_num_sel = int(ord_num_sel) elif int_ord_num_sel == 3: sel_ord_dict = select_order() update_status(sel_ord_dict) print(order_num_options) ord_num_sel = user_input_2() int_ord_num_sel = int(ord_num_sel) elif int_ord_num_sel == 4: sel_ord_dict = select_order() update_details(sel_ord_dict) print(order_num_options) ord_num_sel = user_input_2() int_ord_num_sel = int(ord_num_sel) elif int_ord_num_sel == 5: sel_ord_dict = select_order() del_order(sel_ord_dict) print(order_num_options) ord_num_sel = user_input_2() int_ord_num_sel = int(ord_num_sel) elif int_ord_num_sel == 0: main_menu() while int_ord_num_sel not in [0, 1, 2, 3, 4, 5]: print("Input invalid") print('Select from the following:') print(order_num_options) ord_num_sel = user_input_2() int_ord_num_sel = int(ord_num_sel) # order_options() # -------------------------------------------------------------------------------------------- MAIN MENU ----------------------------------------------------------------------------------------------------------- # Main Menu def main_menu(): clear() main_menu =int(input(main_menu_num)) while main_menu not in [0, 1, 2, 3]: print("Input invalid") main_menu =int(input(main_menu_num)) if main_menu == 1: product_options() elif main_menu == 2: courier_options() elif main_menu == 3: order_options() elif main_menu == 0: save_courier_updates() save_product_updates() save_order_updates() exit("Thank You !") return # main_menu() # Start app def start_app(): load_courier() load_product() load_order() start_app = int(input(start_app_num)) while start_app not in [0, 1]: print("Input invalid") start_app = int(input(start_app_num)) if start_app == 0: save_courier_updates() save_product_updates() save_order_updates() exit() elif start_app == 1: main_menu() start_app()
e2d162869509023697e5231bdf2d5b214ced5f26
rmesseguer/number_game
/number_game.py
1,430
4.09375
4
import random robot_score = 0 player_score = 0 while True: num = random.randint(1,10) good_guess = False while not good_guess: try: guess = int(input('Guess a number between 1 and 10: ')) if guess < 1 or guess > 10: raise ValueError() good_guess = True except ValueError: print("Sorry I didnt understand that. Please try again.") times = 1 while times < 3 and guess != num: if (guess > num): try: guess = int(input('Lower. Please guess again: ')) except ValueError: print("Sorry I didnt understand that. Please guess again:") else: try: guess = int(input('Higher. Guess again: ')) except ValueError: print("Sorry I didnt understand that. Please guess again:") times = times + 1 if (times == 3): print('Too many tries!') if (guess == num): player_score = player_score + 1 print('You win!', player_score, 'vs', robot_score, '\,,/(^_^)\,,/') else: robot_score = robot_score + 1 print('You lose! The number was ' + str(num) + '. ',player_score, ' vs ', robot_score, '¯\_(oO)_/¯',sep='')
699210565e0d9e0e1c8cd00597f5226e45efa373
Vershinin100797/HomeWork_Vershinin_Ivan
/Zanyatie11/hw11_2.py
2,172
3.515625
4
import sys import threading import time class Locks(object): def __init__(self, initial): self.lock = threading.Condition(threading.Lock()) self.initial = initial def up(self): with self.lock: self.initial += 1 self.lock.notify() def down(self): with self.lock: while self.initial == 0: self.lock.wait() self.initial -= 1 class Forks(object): def __init__(self, number): self.number = number self.user = -1 self.lock = threading.Condition(threading.Lock()) self.taken = False def take(self, user): with self.lock: while self.taken: self.lock.wait() self.user = user self.taken = True sys.stdout.write(f"философ{user} взял вилку{self.number}\n") self.lock.notifyAll() def drop(self, user): with self.lock: while not self.taken: self.lock.wait() self.user = -1 self.taken = False sys.stdout.write(f"философ{user} положил вилку{self.number}\n") self.lock.notifyAll() class Philosopher (threading.Thread): def __init__(self, number, left, right, butler): threading.Thread.__init__(self) self.number = number self.left = left self.right = right self.butler = butler def run(self): for i in range(20): self.butler.down() time.sleep(0.2) self.left.take(self.number) time.sleep(0.2) self.right.take(self.number) time.sleep(0.2) self.right.drop(self.number) self.left.drop(self.number) self.butler.up() sys.stdout.write(f"Философ{self.number} закончил думать и есть\n") def main(): n = 5 butler = Locks(n-1) c = [Forks(i) for i in range(n)] p = [Philosopher(i, c[i], c[(i+1) % n], butler) for i in range(n)] for i in range(n): p[i].start() if __name__ == "__main__": main()
a63b5032e669f5ca738669811232abf037a18227
DiegoAnas/Group39-ML-Ex3
/util/demoPlot.py
2,628
3.5
4
# Example plots from matplotlib import pyplot as plt import os import numpy as np import cv2 from PIL import Image def main(demoImage): # For Notebook #%matplotlib inline # For OpenCV (need Version 2.4+) for Python 2.7 os.chdir("..") print ("Showing demo feature extraction on image " + demoImage) # load the image & plot it imagePIL = Image.open(demoImage) imgplot = plt.imshow(imagePIL) plt.title(demoImage) # now we compute a colour histogram using the histogram function in pillow # This gives us one histogram with 768 values, which is 3 x 256 values for each colour # For each colour channel, each value repesent the count how many pixels have that colour intensity featureVector = imagePIL.histogram() # We plot this histogram plt.figure() plt.plot(featureVector[:256], 'r') plt.plot(featureVector[257:512], 'g') plt.plot(featureVector[513:], 'b') plt.xlim([0, 256]) plt.xlabel("Bins") plt.ylabel("# of Pixels") plt.title("Colour Histogram, using PIL") # An alternative is to use open CV imageOpenCV = cv2.imread(demoImage) # OpenCV is a bit weird, because it changes the channel order, it stores them as BGR, instead of RGB # So if we want to display the image, we have to invert it # Plots image 2nd time? # plt.figure() # plt.imshow(cv2.cvtColor(imageOpenCV, cv2.COLOR_BGR2RGB)) chans = cv2.split(imageOpenCV) # split the image in the different channels (RGB, but in open CV, it is BGR, actually..) colors = ("b", "g", "r") plt.figure() plt.title("Colour Histogram, using OpenCV") plt.xlabel("Bins") plt.ylabel("# of Pixels") featuresOpenCV = [] # loop over the image channels for (chan, color) in zip(chans, colors): # create a histogram for the current channel and add it to the resulting histograms array (of arrays) # We can specifiy here in the 4th argument how many bins we want - 256 means the same as in the previous histogram histOpenCV = cv2.calcHist([chan], [0], None, [256], [0, 256]) featuresOpenCV.extend(histOpenCV) # plot the histogram of the current colour plt.plot(histOpenCV, color=color) plt.xlim([0, 256]) # Now we have a 2D-array - 256 values for each of 3 colour channels. # To input this into our machine learning, we need to "flatten" the features into one larger 1D array # the size of this will be 3 x 256 = 768 values featureVectorOpenCV = np.array(featuresOpenCV).flatten() # show all the plots plt.show() if __name__ == "__main__": main()
16d3b9e10964c6aa3d2993a414dca57b842fb2fd
jbw772713376/PythonStudy
/if...eles.py
318
4
4
height = 1.75 weight = 80.5 BMI = weight/pow(height, 2) if height < 0 or weight < 0: print("参数错误!") exit(0) if BMI < 18.5: print('过轻') elif 18.5 <= BMI <25: print('正常') elif 25 <= BMI < 28: print('过重') elif 28 <= BMI < 32: print('肥胖') else: print('严重肥胖')
cb37549bcd999fc40e657e23f57c96b0fc45de3c
tamyrds/Exercicios-Python
/Mundo_2_Python/Decisao/desafio28.py
222
3.9375
4
import random num = int(input('Digite um número: ')) print("PROCESSANDO...") adv = random.randint(0,5) if num == adv: print('Voce acertou o número') else: print(f'Voce não acertou e o número correto é {adv}')
7a8cd933bf3ea7a0bedad13651e0594fd7460d6d
Qinpeng96/leetcode
/559. N叉树的最大深度.py
1,104
3.828125
4
""" [559. N叉树的最大深度](https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree/) 给定一个 N 叉树,找到其最大深度。 最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。 例如,给定一个 3叉树 : ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200717174615484.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM4NjUwMDI4,size_16,color_FFFFFF,t_70#pic_center) 我们应返回其最大深度,3。 说明: 树的深度不会超过 1000。 树的节点总不会超过 5000。 """ """ # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution: def maxDepth(self, root: 'Node') -> int: if not root: return 0 def solve(root): ans = 0 if not root.children: return 1 for chl in root.children: ans = max(ans, self.maxDepth(chl)+1) return ans return solve(root)
514dc69e8ceec5362e37bbe4e8e0299ddfe4a4da
aivancov/study
/basic_python/hw7/1.py
657
3.6875
4
class Matrix: def __init__(self, *args): self.matrix = [array for array in args] self.size = len(args), len(args[0]) def __str__(self): return '\n'.join([ ' '.join([str(el) for el in array]) for array in self.matrix ]) def __add__(self, other): added = [[i + j for i, j in zip(arr1, arr2)] for arr1, arr2 in zip(self.matrix, other.matrix)] return Matrix(*[array for array in added]) matrix1 = Matrix([1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 5, 9]) matrix2 = Matrix([1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]) print(matrix1) print() print(matrix1.size) print() print(matrix1 + matrix2)
405c5c3bd4895637a5cfa22b242aca58eb8dc76d
anilgeorge04/learn-ds
/datacamp/merge-tables/query.py
689
3.890625
4
# Query Method and create a pivot table import pandas as pd import matplotlib as plt # Merge gdp and pop on date and country with fill gdp_pop = pd.merge_ordered(gdp, pop, on=['country','date'], fill_method='ffill') # Add a column named gdp_per_capita to gdp_pop that divides the gdp by pop gdp_pop['gdp_per_capita'] = gdp_pop['gdp'] / gdp_pop['pop'] # Pivot data so gdp_per_capita, where index is date and columns is country gdp_pivot = gdp_pop.pivot_table(values='gdp_per_capita', index='date', columns='country') # Select dates equal to or greater than 1991-01-01 recent_gdp_pop = gdp_pivot.query('date >= "1991-01-01"') # Plot recent_gdp_pop recent_gdp_pop.plot(rot=90) plt.show()
fa348c571e9e272907a145293b503dc0541c0d52
kentfrazier/euler
/Python/p024.py
1,060
4.125
4
# A permutation is an ordered arrangement of objects. For example, 3124 # is one possible permutation of the digits 1, 2, 3 and 4. If all of the # permutations are listed numerically or alphabetically, we call it # lexicographic order. The lexicographic permutations of 0, 1 and 2 are: # # 012 021 102 120 201 210 # # What is the millionth lexicographic permutation of the digits # 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? def lex_permutations(digits): digits = set(digits) if len(digits) == 1: yield list(digits) raise StopIteration() for digit in sorted(digits): remaining_digits = digits.copy() remaining_digits.remove(digit) for perm in lex_permutations(remaining_digits): yield [digit] + perm def nth_lex_permutation(digits,n): permutations = lex_permutations(digits) for i in range(n): perm = permutations.next() return perm if __name__ == "__main__": print ''.join([ str(n) for n in nth_lex_permutation([0,1,2,3,4,5,6,7,8,9], 1000000) ])
cc548e9b8c35748b5c9dd92bcd5057d8bebfbbc4
kiran0712/stock-portfolio-analysis
/stockportfolio.py
13,514
3.53125
4
''' Descriptive data : Non graphical - mean, SD, variance Graphical data : MA, MACD, Mean, basic stock price graph, trend lines, Weighted moving average, Monthly returns for the stock ''' # Import statements import sys import pandas as pd import numpy as np import statsmodels.api as sm import pandas_datareader as pdr import matplotlib.pyplot as plt import datetime as dt from sklearn.metrics import mean_squared_error import math from sklearn.linear_model import LinearRegression import mplcursors from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() pd.set_option('display.max_rows', 100) pd.set_option('display.max_columns', 100) pd.set_option('display.width', 100) url = "https://old.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange=nasdaq&render=download" ticker_data = pd.read_csv(url) # Making a list of tickers to check if ticker entered is listed in NASDAQ or not ticker_list = ticker_data['Symbol'].tolist() flag = True # Fetching the data for the entered ticker and storing it in the data frame def fetch_data(ticker, start, end): data = pdr.DataReader(ticker, "yahoo", start=start, end=end) if len(data) < 1: return False else: return data # ----------------------------------- SUMMARY STATISTICS FOR THE GIVEN TICKER ----------------------------------- def summary_stats(df,df1): print('-------------------- SUMMARY STATISTICS FOR '+format(ticker)+'--------------------\n\n') print(df.describe()) print('----------------------------------------------------------------------------------') print('\n\n-------------------- SUMMARY STATISTICS FOR CLOSING PRICES OF ' + format(ticker) + '--------------------\n\n') # mean of CP stock_mean = np.mean(df1) print('The average of the stock price is: ' + str(stock_mean)) stock_min = np.min(df1) stock_max = np.max(df1) print('The range of the stock price is : {} to {}'.format(stock_min, stock_max)) # std deviation of CP stock_std = np.std(df1) print('The standard deviation of the stock price is: ' + str(stock_std)) # variance of CP stock_var = np.var(df1) print('The variance of the stock price is: ' + str(stock_var)) # coefficient of variation og CP stock_cv = np.var(df1) / np.mean(df1) print('The coefficient of variation for the stock price is: ' + str(stock_cv)) # ----------------------------------- DESCRIPTIVE VISUALISATONS FOR THE GIVEN TICKER ----------------------------------- # Raw time series analysis def time_series(df1): # Data set visualisations # Closing price raw time-series analysis print("RAW TIME SERIES ANALYSIS FOR " + ticker + "'s CLOSING PRICES") plt.figure(num="Raw time series analysis", figsize=(10, 5)) df1.plot(grid=True, color='tab:blue') plt.title(ticker.upper() + "'s RAW TIME SERIES ANALYSIS") plt.ylabel("Closing Price($)") plt.xlabel("Year") plt.legend() mplcursors.cursor(hover=True) plt.show() print("-" * 100) # Trend line def trend_line(df1): # Trend line print("TREND LINE FOR " + ticker) data1 = sm.OLS(df1, sm.add_constant(range(len(df1.index)), prepend=True)).fit().fittedvalues plt.figure(num="Trend line "+ticker.upper()+"- closing price", figsize=(10, 5)) df1.plot(grid=True) mplcursors.cursor(hover=True) plt.title(ticker + "'s TREND LINE - CLOSING PRICES") plt.plot(data1, label="trend line", color='tab:green') plt.ylabel("Closing price") plt.legend() plt.show() print("-" * 100) # Moving average convergence/divergence def macd(df1): # Moving Average Convergence Divergence print(ticker + "'s" + " MOVING AVERAGE CONVERGENCE DIVERGENCE") macd_fig = plt.figure(num="MACD",figsize=(10, 5)) plt.grid(True) close_26_ewma = df1.ewm(span=26, min_periods=0, adjust=True, ignore_na=True).mean() close_12_ewma = df1.ewm(span=12, min_periods=0, adjust=True, ignore_na=True).mean() data_26 = close_26_ewma data_12 = close_12_ewma data_macd = data_12 - data_26 plt.plot(data_26, label="EMA_26_days") plt.plot(data_12, label="EMA_12_days") plt.plot(data_macd, label="MACD") plt.legend(loc=2) plt.title(ticker + "'s MOVING AVERAGE CONVERGENCE/DIVERGENCE") plt.ylabel("Price($)") plt.xlabel("Date") mplcursors.cursor(hover=True) plt.show() print("-" * 100) return True # Moving average / rolling mean def rolling_mean(df,maw): df["Moving average"] = df1close.rolling(maw, center=True).mean() # rolling plt.figure(num="Moving Average (Rolling mean)", figsize=(10, 5)) plt.plot(df["Moving average"], label='MA ' + str(maw) + 'days') df1close.plot(grid=True) plt.legend(loc=2) plt.title(ticker.upper() + "'s " + str(maw) + "DAYS MOVING AVERAGE") plt.xlabel("Dates") plt.ylabel("Price($)") mplcursors.cursor(hover=True) plt.show() print("-" * 100) # Monthly and daily returns visualisation for the given ticker def returns(df1): monthly_returns = df1.resample('M').ffill().pct_change() daily_returns = df.pct_change() fig, ax = plt.subplots(num="Monthly and daily returns for "+ticker.upper(),nrows=2) ax[0].plot(monthly_returns, 'tab:blue') ax[1].plot(daily_returns, 'tab:green') ax[0].set(xlabel="Date", ylabel="Monthly returns") ax[1].set(xlabel="Date", ylabel="Daily returns") ax[0].set_title('Monthly returns') ax[1].set_title('Daily returns') mplcursors.cursor(hover=True) plt.tight_layout(h_pad=1.5) plt.show() # Calls visualisations for the given ticker def desc_visualisation(df1): ma_window = int(input("\nENTER MOVING AVERAGE WINDOW(i.e 30 = 30 days): ")) # Dynamic moving average window time_series(df1) trend_line(df1) rolling_mean(df, ma_window) bool = macd(df1) plt.close('all') if bool: choice = input("\nDO YOU WANT TO CALCULATE RETURNS? PLEASE ENTER Y/N: ") if choice == 'y' or choice == 'Y': returns(df1) elif choice == 'n' or choice == 'N': mmenu_return() else: print("INVALID INPUT, PLEASE ENTER A VALID OPTION") else: print(ValueError) # ----------------------------------- PREDICTIVE ANALYTICS FOR THE GIVEN TICKER ----------------------------------- def predict_price(): pm_strtdate = input("PLEASE ENTER THE START DATE FOR MODELLING(yyyy-mm-dd) : ") pm_year, pm_month, pm_day = map(int, pm_strtdate.split('-')) pm_start_date = dt.datetime(pm_year, pm_month, pm_day) pm_enddate = input("PLEASE ENTER THE END DATE FOR MODELLING(yyyy-mm-dd) : ") pm_year, pm_month, pm_day = map(int, pm_enddate.split('-')) pm_end_date = dt.datetime(pm_year, pm_month, pm_day) pm_data = pdr.DataReader(ticker, "yahoo", start=pm_start_date, end=pm_end_date) pm_data = pd.DataFrame(pm_data) print(pm_data.tail()) # create train test partition pm_data = pm_data.reset_index() close = pm_data['Close'].tolist() dates = pm_data.index.tolist() # Convert to 1d Vector dates = np.reshape(dates, (len(dates), 1)) prices = np.reshape(close, (len(close), 1)) regressor = LinearRegression() regressor.fit(dates, prices) # Predicting the Test set results y_pred = regressor.predict(dates) print('Coefficients: ', regressor.coef_, '\n') # The mean square error print("Residual sum of squares: %.2f" % np.mean((regressor.predict(dates) - prices) ** 2), '\n') # Explained variance score: 1 is perfect prediction print('The coefficient of determination : %.2f' % regressor.score(dates, prices), '\n') mse = mean_squared_error(y_pred, prices) rmse = math.sqrt(mse) print('Root Mean square value : %.2f' % rmse, '\n') plt.scatter(dates, prices, color='green') # plotting the initial datapoint plt.plot(dates, y_pred, color='red', linewidth=3) # plotting the line made by linear regression plt.title('Linear Regression : Time vs. Price') plt.xlabel("No of days") plt.ylabel("Prices") plt.show() forecast_date = input('Enter a date in YYYY-MM-DD format for prediction : ') forecast_date = (pd.to_datetime(forecast_date)).toordinal() today_date = pd.to_datetime(dt.datetime.now()).toordinal() if forecast_date >= today_date: nod_future = forecast_date - pm_end_date.toordinal() predicted_price = regressor.predict([[nod_future]]) print("THE PREDICTED CLOSING PRICE FOR {code} IS : {predicted_price} ".format(code=ticker, predicted_price= predicted_price[0][0]), '\n') else: nod_past = today_date - forecast_date predicted_price1 = regressor.predict([[nod_past]]) print("The CLOSING VALUE FOR {code} IS : {predicted_price} ".format(code=ticker, predicted_price=predicted_price1[0][0]), '\n') mmenu_return() # Sub loop for returning to the main menu def mmenu_return(): return_choice = input("\nDO YOU WANT TO RETURN TO THE MAIN MENU? \n Please enter Y/N: ") if return_choice == "y" or return_choice == 'Y': main_menu(df, runflag=False) elif return_choice == "n" or return_choice == 'N': print("THANK YOU.") sys.exit() else: print("INVALID OPTION. PLEASE ENTER Y/N: ") mmenu_return() def date_check(): try: a=0 strtdate_str = input('PLEASE ENTER THE START DATE FOR ANALYSIS (yyyy-mm-dd): ') year, month, day = map(int, strtdate_str.split('-')) start_date = dt.datetime(year, month, day) enddate_str = input('PLEASE ENTER THE END DATE FOR ANALYSIS (yyyy-mm-dd): ') year, month, day = map(int, enddate_str.split('-')) end_date = dt.datetime(year, month, day) strtdate = start_date.toordinal() enddate = end_date.toordinal() today = pd.to_datetime(dt.datetime.now()).toordinal() if strtdate == enddate: print('THE START AND END DATES ARE THE SAME, PLEASE ENTER THE DATES AGAIN.') elif enddate <= strtdate: print('THE START DATE HAS TO BE PRIOR TO THE END DATE, PLEASE ENTER THE DATES AGAIN.') elif enddate >= today: print('THE END DATE IS A FUTURE DATE, PLEASE ENTER THE DATES AGAIN.') else: a = 1 except ValueError: print('INVALID DATES ENTERED, PLEASE ENTER THE DATES AGAIN.') return a, start_date, end_date # Main user input loop def main_menu(df, runflag, runflag1=None): if runflag1 != True: if runflag == True: return False else: print('-------------------- ANALYSIS FOR '+ticker+' --------------------\n\t' 'MENU OPTIONS\n\t' '1. SUMMARY STATISTICS ON CLOSING PRICES\n\t' '2. DESCRIPTIVE ANALYSIS - VISUALISATIONS \n\t' '3. PREDICTIVE\n\t' '4. QUIT') choice = int(input('\n\nPLEASE ENTER AN OPTION: ')) if choice == 1: summary_stats(df, df1close) mmenu_return() elif choice == 2: desc_visualisation(df1close) mmenu_return() elif choice == 3: predict_price() elif choice == 4: print("THANK YOU FOR USING OUR STOCK ANALYSIS TOOL.") sys.exit() else: print("INVALID INPUT, PLEASE TRY AGAIN") main_menu(df, runflag=False) else: return False runflag = False runflag1 = False while True: while True: try: ticker = "global" ticker = input("-------------------- STOCK_PORTFOLIO ANALYSIS --------------------" "\n\nPLEASE ENTER THE COMPANY TICKER TO PERFORM ANALYSIS: ") if ticker.upper() not in ticker_list: raise ValueError else: break except ValueError: print("Invalid ticker/symbol, please enter valid ticker") while flag: try: a, start_date, end_date = date_check() if a == 1: df = fetch_data(ticker, start_date, end_date) if len(df) > 1: break except ValueError: print("Exit") df1close = df['Close'] # Creating a data frame consisting of only the closing prices dfcopy = df # Complete data set with High, Low, Close, Adj Close et al. data_26 = pd.DataFrame(df1close) # For MACD - 26days data_12 = pd.DataFrame(df1close) # For MACD - 12 days data_macd = pd.DataFrame(df1close) # For MACD try: main_menu(df, runflag, runflag) if main_menu(df, runflag=False): break else: rerun1 = True raise ValueError except ValueError: print('RUNNING ANALYSIS AGAIN')
4bec38ebcf0901b4720154c4cf185c5b03805379
ashwani1310/Simple-Linear-Regression
/simple_liner_regression_self.py
1,627
4.1875
4
import numpy as np import matplotlib.pyplot as plt import pandas as pd data = pd.read_csv('input here the destination of any csv file which has single input feature and a label') Single_feature = data.iloc[:, :-1].values #Here the label is last column and the feature is the first column Label = data.iloc[:, 1].values # Here the dataset is splitted into training and testing set. test_size=0.2 specifies that 20% of dataset will be testing data. from sklearn.cross_validation import train_test_split Feature_train, Feature_test, Label_train, Label_test = train_test_split(Single_feature, Label, test_size = 0.2, random_state = 0) # Simple linear regression model on training set from sklearn.linear_model import LinearRegression reg_model=LinearRegression() reg_model.fit(Feature_train, Label_train) #By fitting the linear regression model to the training set, we made our machine #learn the correlation between the features and the label of training set. #Now we use this model, which has learned correlations between the dependent #and independent variables, to predict the test set results. Label_predicted = reg_model.predict(Feature_test) #Now, plotting the graphs plt.scatter(Feature_train, Label_train, color = 'pink') plt.plot(Feature_train, reg_model.predict(Feature_train), color = 'green') plt.title('Correlation in Training Set') plt.xlabel('Feature') plt.ylabel('Label') plt.show() plt.scatter(Feature_test, Label_test, color = 'pink') plt.plot(Feature_train, regressor.predict(Feature_train), color = 'green') plt.title('Correlation in Test set') plt.xlabel('Feature') plt.ylabel('Label') plt.show()
11096870b2418757017d08cf043843812085547c
sidro/excodpy
/python-exemple/capitalizare.py
104
3.828125
4
def capitalise(string): return string[:1].upper() + string[1:].lower() print(capitalise("amara"))
0930e0518482836c24c07adf53403fad4ef304c7
Enfors/CursMon
/cursmon/curs_ui.py
7,321
3.5625
4
""" Curses-based User Interface for CursMon. """ import curses WHITE = 1 RED = 2 BLUE = 3 YELLOW = 4 CYAN = 5 GREEN = 6 MAGENTA = 7 class UI(object): """ The Curses-based User Interface class. """ def __init__(self, scr): self.lines = curses.LINES self.cols = curses.COLS self.graphs = [] curses.init_pair(WHITE, curses.COLOR_WHITE, curses.COLOR_BLACK) curses.init_pair(RED, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(BLUE, curses.COLOR_BLUE, curses.COLOR_BLACK) curses.init_pair(YELLOW, curses.COLOR_YELLOW, curses.COLOR_BLACK) curses.init_pair(CYAN, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(GREEN, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(MAGENTA, curses.COLOR_MAGENTA, curses.COLOR_BLACK) self.scr = scr self.scr.clear() # plot_x_size = self.cols - 5 - (self.cols % 5) self.scr.refresh() def refresh(self, data): self.lines = curses.LINES self.cols = curses.COLS self.display_graphs(data) self.scr.refresh() def add_graph(self, graph): self.graphs.append(graph) def display_graphs(self, data): [graph.display(data) for graph in self.graphs] def wait_for_input_char(self): return self.scr.getch() class Graph(object): def __init__(self, scr, title, top_graph_y=0, top_graph_x=0, plot_y_size=10, plot_x_size=10, y_step=1, mv_avg_y=7, show_y=True, show_mv_avg_y=False, bar=False): self.title = title self.scr = scr self.left_margin = 5 self.top_margin = 1 self.top_graph_y = top_graph_y self.top_graph_x = top_graph_x self.top_plot_y = top_graph_y + self.top_margin self.top_plot_x = top_graph_x + self.left_margin self.plot_y_size = plot_y_size self.plot_x_size = plot_x_size self.y_step = y_step self.mv_avg_y = mv_avg_y self.show_y = show_y self.show_mv_avg_y = show_mv_avg_y self.bar = bar self.plot_win = curses.newwin(plot_y_size, plot_x_size + 1, self.top_margin + self.top_graph_y, self.left_margin + self.top_graph_x) assert curses.has_colors() def display(self, data): self.draw_title() self.draw_y_axis() self.draw_x_axis() self.plot_win.clear() self.draw_grid() self.plot_data(data) self.plot_win.refresh() self.scr.refresh() def draw_title(self): title = self.title # if self.mv_avg_y is not 1 and self.show_mv_avg_y: # title = title + " (avg: %d)" % self.mv_avg_y x = int(((self.plot_x_size - len(title)) / 2) + self.left_margin + self.top_graph_x) self.scr.addstr(self.top_graph_y, x, title, curses.color_pair(WHITE)) extra_space = x - self.left_margin - self.top_graph_x if extra_space < 3: return left = "=" * (extra_space - 2) + "[" self.scr.addstr(self.top_graph_y, self.left_margin + self.top_graph_x, left, curses.color_pair(MAGENTA)) if (len(self.title) + self.plot_x_size) % 2 == 0: rounding = 0 else: rounding = 1 right_x = self.plot_x_size - extra_space + self.left_margin + 1 right = "]" + "=" * (extra_space - 2 + rounding) self.scr.addstr(self.top_graph_y, right_x - rounding + self.top_graph_x, right, curses.color_pair(MAGENTA)) def plot_data(self, data): if len(data) > self.plot_x_size: plot_data = data[-self.plot_x_size:] else: plot_data = data for i in range(0, len(plot_data)): y = int(plot_data[i][self.title]) if self.mv_avg_y == 1: avg_y = y else: avg_y = self.calc_mv_avg_y(i, plot_data) y = self.round_y(y) avg_y = self.round_y(avg_y) if self.show_y: self.plot(y=y, x=i, char="*", color=GREEN) if self.bar: bar_y = y - 1 while bar_y > 0: self.plot(y=bar_y, x=i, char="|", color=GREEN) bar_y = bar_y - 1 if self.show_mv_avg_y: self.plot(y=avg_y, x=i, char="¤", color=BLUE) # self.scr.addstr(22, 0, "y: %d, data: %d\n" % (y, data[i])) # self.scr.getch() def draw_grid(self): y = 5 while y <= self.plot_y_size: x = 10 while x <= self.plot_x_size: self.plot(y, x - 1, "+") x = x + 10 y = y + 5 def draw_y_axis(self): for row in range(1, self.plot_y_size + 1): y = self.plot_y_size - row + self.top_margin + self.top_graph_y x = self.left_margin - 5 + self.top_graph_x if row == self.plot_y_size: char = "^" else: if row % 5 == 0: char = "+" else: char = "|" self.scr.addstr(y, x, "%4d" % (row * self.y_step), curses.color_pair(WHITE)) self.scr.addstr(y, x + 4, "%s" % char, curses.color_pair(MAGENTA)) def draw_x_axis(self): for col in range(0, self.plot_x_size + 1): y = self.plot_y_size + self.top_margin + self.top_graph_y x = col + self.left_margin - 1 + self.top_graph_x if col == self.plot_x_size: char = ">" else: if col % 5 == 0: char = "+" else: char = "-" self.scr.addch(y, x, char, curses.color_pair(MAGENTA)) # self.scr.addstr(25, 0, "col: %d\n" % col) # self.scr.addstr(26, 0, " x: %d\n" % x) # self.scr.getch() def plot(self, y: int, x: int, char: str, color: int=0): # self.scr.addstr("y: %d, x: %d\n" % (y, x)) y = self.plot_y_size - y if y < 0: y = 0 if x < 0: x = 0 if y >= self.plot_y_size: y = self.plot_y_size - 1 if x >= self.plot_x_size: x = self.plot_x_size - 1 self.plot_win.addstr(y, x, char, curses.color_pair(color)) self.plot_win.refresh() def calc_mv_avg_y(self, index, data): if self.mv_avg_y == 1: return int(data[index][self.title]) if index < (self.mv_avg_y - 1): min_point = 0 else: min_point = index - self.mv_avg_y + 1 max_point = index + 1 # data_subset = data[min_point:max_point] data_subset = [] for row in data[min_point:max_point]: data_subset.append(int(row[self.title])) avg = sum(data_subset) / len(data_subset) return avg def round_y(self, y): if y > 0: y = int((y + self.y_step / 2) / self.y_step) else: y = 0 return y
e57567e4200cdaf5105a5dfebf1969500502b151
rosauraruiz-lpsr/class-samples
/RosauraRuiz/partner.py
360
3.671875
4
import turtle def makeSquare(myTurtle, side): myTurtle.forward(side) myTurtle.left(60) myTurtle.forward(side) myTurtle.left(60) myTurtle.forward(side) squeak = turtle.Turtle() length = 100 while length > 0: makeSquare(squeak, length) squeak.right(5) length = length - 1 turtle.exitonclick()
007dfa5fd6a5d9714f418e02632ec1fc6ba5cd50
xiongxiong109/algorithm_study
/py/algorithm/bin_search.py
501
3.84375
4
# 二分法查找 from math import floor # 只适合有序的数组 def bin_search(search_list, target): upper = len(search_list) - 1 lowwer = 0 # search_list.sort() while lowwer <= upper: mid_len = floor((upper + lowwer) / 2) cur_item = search_list[mid_len] # print(mid_len) if cur_item < target: lowwer = mid_len + 1 elif cur_item > target: upper = mid_len - 1 else: return mid_len return -1
f5302b6fe54155b07183ab8d839adf388bc01210
shreyanse081/Some-Algorithms-coded-in-Python
/QuickSelect.py
1,624
4.09375
4
""" QuickSelect finds the kth smallest element of an array in linear time. Amir Zabet @ 05/08/2014 """ import random def Partition(a): """ Usage: (left,pivot,right) = Partition(array) Partitions an array around a randomly chosen pivot such that left elements <= pivot <= right elements. Running time: O(n) """ ## Base cases if len(a)==1: return([],a[0],[]) if len(a)==2: if a[0]<=a[1]: return([],a[0],a[1]) else: return([],a[1],a[0]) ## Choose a random pivot p = random.randint(0,len(a)-1) ## the pivot index pivot = a[p] ## the pivot value right = [] ## the right partition left = [] ## the left partition for i in range(len(a)): if not i == p: if a[i] > pivot: right.append(a[i]) else: left.append(a[i]) return(left, pivot, right) def QuickSelect(a,k): """ Usage: kth_smallest_element = QuickSelect(array,k) Finds the kth smallest element of an array in linear time. """ (left,pivot,right) = Partition(a) if len(left)==k-1: ## pivot is the kth smallest element result = pivot elif len(left)>k-1: ## the kth element is in the left partition result = QuickSelect(left,k) else: ## the kth element is in the right partition result = QuickSelect(right,k-len(left)-1) return result def main(): N = 10; k = 4; a = [random.randint(1,100) for i in range(N)] print('Input array: ', a) print('k =', k) b = QuickSelect(a,k) print('kth smallest element: ', b) # This is the standard boilerplate that calls the main() function. if __name__ == '__main__': main()
2a21c85841e5d83d658eece68f6ad7fc9894ea0a
swrnv/hackerrank-30daysofcode
/Day 10- Binary Numbers.py
255
3.515625
4
def find_max_ones(n): if not n: return 0 bin_num = bin(n)[2:] return len(max(bin_num.replace('0', ' ').split(), key=len)) if __name__ == '__main__': n = int(input()) max_ones = find_max_ones(n) print(max_ones)
46b12b9dc6c00a71f82a5cbc84298197a95eb3f7
1769778682/python02
/work/work_03.py
234
3.84375
4
# 获取键盘输入的一个数字, 判断该数字是奇数还是偶数, 输出对应结果 # 1,获取键盘中的一个数字 num = int(input('请输入一个数字:')) if num % 2 == 1: print('奇数') else: print('偶数')
99277f74f2ca4445ff0c4dd4f45d86c10af6d123
daisuke0728/python_practice
/4_45.py
219
3.734375
4
n = 14 if n > 15: print("とても大きい数字") #elifを用いて11以上15以下の時に中くらいの数字と出力 elif n >= 11: print("中くらいの数字") else: print("小さい数字")
7e65a81ef5a45d6d2d44a9ba149164eba85afc90
dianalow/RiceFOC
/01_InteractivePythonProgramming/spock.py
1,145
4.15625
4
# Written by : Diana Low # Last updated : 9 April 2014 # Coding assignment for Rice University's # Interactive Python Programming course # Game : Scissors, Paper, Spock # Run on codeskulptor.org def name_to_number(name): if(name=="rock"): return 0 elif(name=="Spock"): return 1 elif(name=="paper"): return 2 elif(name=="lizard"): return 3 elif(name=="scissors"): return 4 else: print "Invalid name!" def number_to_name(number): if(number==0): return "rock" elif(number==1): return "Spock" elif(number==2): return "paper" elif(number==3): return "lizard" elif(number==4): return "scissors" else: print "Invalid number!" def rpsls(player_choice): import random print "" print "Player chooses",player_choice pn=name_to_number(player_choice) cn=random.randrange(0,5) cc=number_to_name(cn) print "Computer chooses",cc diffnum=(pn-cn)%5 if(diffnum==0): print "Player and computer tie!" elif(diffnum<=2): print "Player wins!" else: print "Computer wins!" rpsls("rock") rpsls("Spock") rpsls("paper") rpsls("lizard") rpsls("scissors")
923db8bcfe1406e74cd8b3742fad9418667d238e
burkan96/Monty_Hall_Simulation
/Monty Hall problem.py
3,020
4.375
4
#!/usr/bin/env python # coding: utf-8 # # Monty Hall simulation for *n* doors # Suppose you're on a game show, and you're given the choice of n doors: Behind one door is a car; behind the others, goats. # You pick a door, say No. k, and the host, who knows what's behind the doors, opens opens *n-2* losing doors and then offers the player # the opportunity to switch. Is it to your advantage to switch your choice? # In[1]: # Import packages import matplotlib.pyplot as plt import numpy as np import random # In[2]: N = 100000 # Number of simulations n = 3 # Total number of doors # In[3]: def montyHall(N,n): count1 = 0 # Set count for not switching count2 = 0 # Set count for switching for i in range(N): # For N simulations doors = list(range(1,n+1)) # Create list of n doors car = random.choice(doors) # Door with the car choice1 = random.choice(doors) # First guess of participant # Switch doors out of remaining two doors if car == choice1: doors.remove(car) choice2 = random.choice(doors) else: choice2 = car if car == choice1: # Check whether correct door is chosen when not switching count1 += 1 elif car == choice2: # Check whether correct door is chosen when switching count2 += 1 return count1/N, count2/N # In[4]: print('Experimental probability of winning the car when not switching doors is', montyHall(N,n)[0]) print('Theoretical probability of winning the car when not switching doors is', 1/n, '\n') print('Experimental probability of winning the car when switching doors is', montyHall(N,n)[1]) print('Theoretical probability of winning the car when switching doors is', (n-1)/n) # In[5]: N = 10000 # Number of simulations n = 50 # Total number of doors # Create empty arrays for storing probabilities prob_switching = np.zeros(n-2) prob_no_switching = np.zeros(n-2) # Fill arrays with probabillities for i in range(2,n): prob_no_switching[i-2] = montyHall(N,i)[0] prob_switching[i-2] = montyHall(N,i)[1] totalDoors = np.linspace(2,n,n-2) # In[6]: # Plot fig = plt.figure(figsize = (9,4)) plt.plot(totalDoors, prob_switching, label='Switching', color='r'); plt.plot(totalDoors, prob_no_switching,label='No switching', color='b'); plt.xlim([2, n]); plt.ylim([-0.05, 1.05]); plt.ylabel('Probability of winning', fontsize = 14); plt.xlabel('Number of doors', fontsize = 14); plt.legend(fontsize = 10); plt.hlines(1,2,50, linestyle = 'dashed'); plt.hlines(0,2,50, linestyle = 'dashed'); # In[ ]:
6408b4b1ae5688712524e27571ba4fc20c37910a
mbaty001/experimental
/algorithms/basics/parenthesis.py
514
3.703125
4
# Check whether parenthesis are properly formatted: # ()()() - True # ((() - False # )(() - False def bla(string: str) -> bool: ... count = 0 ... for s in string: ... if s == "(": ... count += 1 ... elif s == ")": ... count -= 1 ... if count < 0: ... return False ... if count == 0: ... return True ... else: ... return False assert bla("()()()") == True assert bla("((()") == False assert bla(")(()") == False
40c5962c7cbd04b867982d42f7bb6ed7c0afc478
ljm516/python-repo
/algorithm/stack/example.py
1,719
4.15625
4
# 调用栈 def greet2(name): print("how are you, {name}?".format(name=name)) def bye(): print("ok, bye!") def greet(name): print("hello, {name} !".format(name=name)) greet2(name) print("greeting ready to say bye...") bye() greet("ljming") ''' 说明: 调用 greet(), 计算机为该函数分配一块内存。 变量 name 被设置为 ljming,存储在内存中。 每当调用函数时,计算机都像这样将函数调用 涉及的所有变量的值存储在内存中。 打印出 ‘hello, ljming’ 后,在调用 greet2('ljming')。 同样,计算机也为这个函数分配一块内存。 计算机使用一个栈表示这些内存块, 其中第二个内存块位于第一个内存块上面。打印 'how are you, ljming'。 然后从函数调用返回。此时,栈顶的内存块被弹出。 现在栈顶内存块是 greet 的,这意味着你返回到了函数 greet。 当调用函数 greet2 时,函数 greet 只是执行了一部分。 一个重要的概念: 调用另一个函数时,当前函数暂停并处于 未完成状态。该函数的所有变量的值还在内存中。执行完函数 greet2 后, 回到函数greet,并从离开的地方开始往下执行: 首先打印 ‘greeting ready to say bye..’,在调用函数 bye。 在栈顶添加了函数 bye 的内存块。然后,打印 ‘OK,bye’。 并从这个函数返回,现在又回到了 greet 。由于没有其他的函数调用, 从 greet 函数返回。这个栈用于存储多个函数的变量,被称之为调用栈。 '''
6583750e64ff7f6d8ed7e75d9f33b13fa79df894
mostipaka/pythonintask
/BITs/2014/Mostipaka_A_E/z3v15.py
720
3.875
4
#Задача N3. Вариант 15 #Напишите программу, которая выводит имя "Лариса Петровна Косач-Квитка", и запрашивает его псевдоним. Программа должна сцеплять две эти строки и выводить полученную строку, разделяя имя и псевдоним с помощью тире. # Mostipaka A. E. # 29.02.2015 lesy=input("Под каким же псевдонимом известена Лариса Петровна Косач-Квитка? Ваш ответ: ") if(lesy)==("Леся Украинка"): print("Все верно Леся Украинка -" + lesy) else: print("Вы ошиблись, это не ее псевдоним") input ("Press Enter to close")
c339eb426e9fc0fe91c3423a57a5909710fb395b
KadenRamirez/ICS2019_2020
/ICS_03_Ramirezk21/Program.py
1,296
3.984375
4
import math import sys """ Kaden Ramirez This program combines all of the previous java programs into a gaint python frankenprogram """ print(" /\\\n /__\\\n /\\ /\\\n /__\\/__\\") try: a = int(sys.argv[1]) b = int(sys.argv[2]) c = int(sys.argv[3]) r1 = (-b + math.sqrt(b * b - 4*a*c))/ (2*a) r2 = (-b - math.sqrt(b * b - 4*a*c))/ (2*a) print("\nroot 1 is: " + str(r1) + "\nroot 2 is: " + str(r2)) except: print("\nYou must enter 3 real integers (not 0 for a).") DAYS_TO_SECONDS = 24*60*60 SECONDS_TO_DAYS = 86400 SECONDS_TO_HOURS = 3600 SECONDS_TO_MINUTES = 60 daysIn = int(input("\nEnter a number of days: ")) secondsOut = daysIn * DAYS_TO_SECONDS print("The number of seconds in that many days are: " + str(secondsOut)) secondsIn = int(input("\nEnter a number of seconds: ")) daysOut = secondsIn // SECONDS_TO_DAYS hoursOut = secondsIn % SECONDS_TO_DAYS // SECONDS_TO_HOURS minutesOut = secondsIn % SECONDS_TO_DAYS % SECONDS_TO_HOURS // SECONDS_TO_MINUTES secondsRem = secondsIn % SECONDS_TO_DAYS % SECONDS_TO_HOURS % SECONDS_TO_MINUTES // 1 print("There are " + str(daysOut) + " days, " + str(hoursOut) + " hours, " + str(minutesOut) + " minutes, and a remainder of " + str(secondsRem) + " seconds in that many days/day")
ea181ca47afb8f73b5c4d3364615815c00e8cfff
DayGitH/Python-Challenges
/DailyProgrammer/DP20140728A.py
1,447
4.125
4
""" [7/28/2014] Challenge #173 [Easy] Unit Calculator https://www.reddit.com/r/dailyprogrammer/comments/2bxntq/7282014_challenge_173_easy_unit_calculator/ # [](#EasyIcon) _(Easy): Unit Calculator You have a 30-centimetre ruler. Or is it a 11.8-inch ruler? Or is it even a 9.7-attoparsec ruler? It means the same thing, of course, but no-one can quite decide which one is the standard. To help people with this often-frustrating situation you've been tasked with creating a calculator to do the nasty conversion work for you. Your calculator must be able to convert between metres, inches, miles and [attoparsecs](https://www.google.com/search?q=attoparsec). It must also be able to convert between kilograms, pounds, ounces and [hogsheads of Beryllium](http://www.wolframalpha.com/input/?i=mass+of+1+hogshead+of+berylliumm). ## Input Description You will be given a request in the format: **N** oldUnits to newUnits For example: 3 metres to inches ## Output Description If it's possible to convert between the units, print the output as follows: 3 metres is 118.1 inches If it's not possible to convert between the units, print as follows: 3 metres can't be converted to pounds # Notes Rather than creating a method to do each separate type of conversion, it's worth storing the ratios between all of the units in a 2-D array or something similar to that. """ def main(): pass if __name__ == "__main__": main()
2f451f5a058b17f29c47f3487fe409f45cde8135
vladn90/Algorithms
/Backtracking/subsets.py
2,902
3.5
4
""" Problem statement: https://leetcode.com/problems/subsets/description/ https://www.interviewbit.com/problems/subset/ """ class SolutionLeetcode: def subsets_brute(self, nums): """ Returns an array of tuples, where each tuple is a subset of original array nums. """ result = set() # so we don't have duplicate subsets result.add(tuple()) # add empty subset to result def find_subsets(array): """ Adds all subsets of array to result. """ if not array: # base case return result.add(tuple(array)) # add the whole array as subset for i in range(len(array)): find_subsets(array[:i] + array[i + 1:]) # exclude i from each subset find_subsets(nums) return result def subsets_brute(self, nums): """ Returns an array of tuples, where each tuple is a subset of original array nums. """ original = set(nums) result = set() # so we don't have duplicate subsets result.add(tuple()) # add empty subset to result def find_subsets(original): """ Adds all subsets of array to result. """ if not original: # base case return result.add(tuple(original)) for num in original: original.remove(num) find_subsets(original) # exclude num from each subset original.add(num) # backtracking find_subsets(original) return result def subsets_fast(self, nums): """ Bottom-up dynamic programming approach. Time complexity: O(n * 2 ^ n). Space complexity: O(2 ^ n), n is len(nums). """ result = [[]] # start with an empty set(array in our case) for num in nums: new = [] # new array of subsets for arr in result: new.append(arr + [num]) result.extend(new) return result def subsets_fast(self, nums): """ Bottom-up dynamic programming approach. Shorter and faster version. Time complexity: O(n * 2 ^ n). Space complexity: O(2 ^ n), n is len(nums). """ result = [[]] for num in nums: result += [arr + [num] for arr in result] return result class SolutionInterviewBit: def subsets(self, nums): """ Bottom-up dynamic programming approach. Time complexity: O(n * 2 ^ n). Space complexity: O(2 ^ n), n is len(nums). """ nums.sort() result = [[]] for num in nums: result += [arr + [num] for arr in result] return sorted(result) if __name__ == "__main__": sol = SolutionInterviewBit() func = sol.subsets nums = [1, 2, 3] assert func(nums) == [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]
c797ae600e795ad6a0cbd54ec0fae48ce422d142
vaibhav-rbs/RealPython-VB
/flask-hello-world/sql/02_sql.py
519
4.15625
4
# Create a SQLite3 database and table # import the sqlite3 library import sqlite3 # create a new database if the database does not already exist. conn = sqlite3.connect('new.db') # get a cursor object used to execute SQL commands cursor = conn.cursor() # create a table cursor.execute("""INSERT INTO population VALUES ('New York City', 'NY', 84000000) """) cursor.execute("""INSERT INTO population VALUES ('San Francisco', 'CA', 800000) """) # commit the changes. conn.commit() conn.close()
1810c8f4d6c8cf9b4ad6a665db83d9f3b2e647eb
YashChitgupakar9/practice
/029.py
1,318
4.5
4
class Football: # pass doesn't do anything. its just like a statement.. instead keep class as an empty, if you do wish to have any statements in class, then you keep 'pass' def __init__(self, x): print (x) def condictions(self): print ("FIFA rules...") Football(23749) #1. Whenever you create an object, It is going to call a Constructor of that same class. #2. Implicity there is a constructor for every class that you write it. #3. at the time of creating an Object, if you are not passing any arguments, then it invokes default constructor provided by Python Intepreter... #4. What is the Python Interpreter provided constructor looks like: # def __init__(self): # super().__init__() # "super" is a keyword which always refers to superclass object # 5. If you have any other requirement immediately after creation of an Object, then you can create your own constructor. # 6. Constructor name must be always def __init__(self, ) # 7. If you have created your own constructor, Python Intepreter doesnt or never ever provides you another constructor. # 8. Constructors never be called explicitly # 9. Whenever you create an Object, it is going to call/invoke call the constructor of that same class.. That constructor must have to call implicitly super class constructor. #10.
cec499c4f49117e70cb0d7ef11b69ed07f34282c
killbug2004/Snippets
/Algorithm/algorithm/compress.py
833
4.34375
4
''' String compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, the method returns the original string. ''' def compress(string): if len(string) == 0: return string; old = list(string); string = list(string); compressed = []; prev = string[0]; count = 1; for i in range(1, len(string)): if string[i] == prev: count = count+1; else: compressed.append(prev); compressed.append(str(count)); prev = string[i]; count = 1; if i == len(string)-1: compressed.append(prev); compressed.append(str(count)); return "".join(compressed) if len(compressed) < len(old) else "".join(old); if __name__ == "__main__": print compress("aabcccccaaa"); print compress("abc");
dc8718db06fd6f1f3eb28880805630141a5ff687
MassimoLauria/informatica2019
/src/code/algoritmi.py
5,764
3.5
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Codice utile per le dispense di Informatica Il modulo contiene alcune funzioni utili per le dispense, in particolare contiene le implementazioni degli algoritmi visti a lezione. Verrà regolarmente esteso quindi controllate che non vi siano aggiornamenti disponibili prima di usarlo. Copyright (C) 2017, 2018, 2019 Massimo Lauria <[email protected]> """ import random def numeriacaso(N,minimo,massimo,ordinati=False): """Produce una lista di numeri generati a caso. Produce una lista di N elementi, ognuno dei quali preso a caso (con uguale probabilità) tra tutti i numeri interi compresi tra 'minimo' e 'massimo', estremi inclusi. Se N<0 o minimo>massimo la funzione solleva un ValueError. Se 'ordinati' è vero la lista restituita è ordinata. """ if N<0: ValueError("Quantità negativa di numeri da generare.") if minimo>massimo: ValueError("L'intervallo dei valori non ha senso: minimo>massimo.") seq = [random.randint(minimo,massimo) for _ in range(N)] if ordinati: seq.sort() return seq def ricerca_binaria(x,seq): start = 0 end = len(seq)-1 while start < end: mid = (start+end) // 2 if seq[mid] == x: return mid elif seq[mid] > x: end = mid - 1 else: start = mid + 1 return None def mcd(a, b): "Calcola il massimo comun divisore di due interi non negativi." if not isinstance(a,int) or not isinstance(b,int): raise TypeError("La funzione mcd accetta solo argomenti interi.") if a < 0 or b < 0: raise ValueError("La funzione mcd accetta solo argomenti non negativi.") a, b = max(a,b), min(a,b) while b > 0 : a, b = b, a % b return a def bubblesort(seq): """Ordina la sequenza utilizzando bubblesort """ end=len(seq)-1 while end>0: last_swap = -1 for i in range(0,end): if seq[i] > seq[i+1]: last_swap = i seq[i], seq[i+1] = seq[i+1],seq[i] end=last_swap def insertionsort(L): """Ordina la lista utilizzando insertion sort """ for i in range(1,len(L)): x = L[i] # salvo il valore da inserire pos = i # posizione di inserimento while pos > 0 and L[pos-1] > x: L[pos] = L[pos-1] #sposto a destra L[pos-1] pos = pos -1 L[pos] = x def merge(S,low,mid,high): a=low b=mid+1 temp=[] # Inserisci in testa il più piccolo while a<=mid and b<=high: if S[a]<=S[b]: temp.append(S[a]) a=a+1 else: temp.append(S[b]) b=b+1 # Esattamente UNA sequenza è esaurita. Va aggiunta l'altra residuo = range(a,mid+1) if a<=mid else range(b,high+1) for i in residuo: temp.append(S[i]) # Va tutto copiato su S[start:end+1] for i,value in enumerate(temp,start=low): S[i] = value def qsort_partition(S, start, end): # sceglie una posizione random per il pivot pivot_pos = random.randint(start, end) pivot = S[pivot_pos] # scambia il pivot con l'elemento di testa S[start], S[pivot_pos] = S[pivot_pos], S[start] i = start+1 j = end # scansione della lista dall'inizio (pivot escluso) verso il centro # e dalla fine verso il centro while i<j: while i<j and S[i] < pivot: # cerca un elemento grande da sx verso centro i += 1 while i<j and S[j] >= pivot: # cerca un elemento piccolo da dx verso centro j -= 1 if i<j: # se ha trovato una coppia da scambiare la scambia S[i], S[j] = S[j], S[i] # se i ha scavallato tra gli elementi grandi, allora l'ultimo # elemento piccolo (da scambiare col pivot) è in posizione i-1, # altrimenti è in posizione i if S[i] >= pivot: i -= 1 S[start], S[i] = S[i], S[start] # posiziona il pivot al centro return i def quicksort(S, start=0, end=None): if end is None: end = len(S)-1 if start>=end: return pivot_pos = qsort_partition(S, start, end) quicksort(S, start, pivot_pos - 1) quicksort(S, pivot_pos+1, end) def mergesort(S,start=0,end=None): """Ordina la sequenza S[start:end+1] usando mergesort""" if end is None: end=len(S)-1 if start>=end: return mid=(end+start)//2 mergesort(S,start,mid) mergesort(S,mid+1,end) merge(S,start,mid,end) def countingsort(seq,key=None): if len(seq)==0: return if key is None: key = lambda x:x # n operazioni a = min(key(x) for x in seq) b = max(key(x) for x in seq) # creazione dei contatori counter=[0]*(b-a+1) for x in seq: counter[key(x)-a] += 1 # posizioni finali di memorizzazione posizioni=[0]*(b-a+1) for i in range(1,len(counter)): posizioni[i]=posizioni[i-1]+counter[i-1] # costruzione dell'output for x in seq[:]: seq[posizioni[key(x)-a]]=x posizioni[key(x)-a] += 1 def key0(x): return x & 255 def key1(x): return (x>>8) & 255 def key2(x): return (x>>16) & 255 def key3(x): return (x//(256*256*256)) & 255 def key10(x): return x & 65535 def key32(x): return (x>>16) & 65535 def radixsort4x8bit(seq): """Ordina una sequenza di numeri positivi di al massimo 32 bit """ for my_key in [key0,key1,key2,key3]: countingsort(seq,key=my_key) def radixsort2x16bit(seq): """Ordina una sequenza di numeri positivi di al massimo 32 bit """ for my_key in [key10,key32]: countingsort(seq,key=my_key)
79cad5c421799d452ffaf4f2fd98d2c316658359
Pritamthing/python-assignment
/assignment34.py
451
4.0625
4
input1=int(input("Enter a size of dict1: ")) dict1={} for i in range(input1): key=input("Enter a key: ") dict1[key]=input("Enter a value at "+str(i+1)+": ") input2=int(input("Enter size of dict2: ")) dict2={} for j in range(input2): key=input('Enter a key: ') dict2[key]=input("Enter a value at "+str(j+1)+": ") def merge_dict(dict1,dict2): for k in dict2: dict1[k]=dict2[k] return dict1 print(merge_dict(dict1,dict2))
22c3f733b887f335b1ea7483323a353a2454ae4f
dudtj0904/python-ch2.4
/practice12.py
398
3.78125
4
# 반복문을 이용하여 369게임에서 박수를 쳐야 하는 경우의 수를 순서대로 화면에 # 출력해보세요. 1부터 99까지만 실행하세요 for i in range(1,100) : s = str(i) length = len(s) count = 0 for j in range(0, length) : if int(s[j]) != 0 and int(s[j]) % 3 == 0 : count += 1 if count != 0 : print(s, '짝'*count)
7bd75497422f16c7fdbf5e9c067c292730e3c425
amrutaDesai/pythonPractice
/pythonFundamentals/section7/dictionaryPythonNotes.py
1,444
4.375
4
def dictionaryNotes() : print('1. Dictionary contains key-values pair and keys are like lists indexes') print('2. Dictionary are mutable, variables hold the reference to dictionary values,not the dictionary value itself') print('3. Dictionary are un order, there is no first key-value pair in the dictionary') print('4. The Keys(), values(), items() will return list like vallues of dictionarys keys, values, and both key values respectively') print('5. The get method can return default of the key if a key does not exist') print('6. Setdefault method can set the values if a key does not exist') print('7. The pprint modules pprint "Pretty print" function can display a dictionary value cleanly.') print('8. The pFormat() function returns a string value of this output') def similaritiesNDifferencesListDictionary(): print('Dictionaries and lists share the following characteristics:') print('''Both are mutable. Both are dynamic. They can grow and shrink as needed. Both can be nested. A list can contain another list. A dictionary can contain another dictionary. A dictionary can also contain a list, and vice versa.''') print('Dictionaries differ from lists primarily in how elements are accessed:') print('''List elements are accessed by their position in the list, via indexing. Dictionary elements are accessed via keys.''') dictionaryNotes() similaritiesNDifferencesListDictionary()
8363e898340f31b6cf0db313e1196f92684f241a
Ejas12/pythoncursobasicoEstebanArtavia
/dia3/tarea2.py
883
3.984375
4
####ejercicio1### # Crear líneas de código en Python que calcule el promedio de los valores contenidos en una lista.##### myvalues = [5,1,2,3,8,12] average = sum(myvalues)/len(myvalues) print("Promedio de los numeros es %.2f" % average) #####Ejercicio 2### # Escriba un código en python que determine cual grupo de personas contiene la mayor de todas las alturas de todas las personas######### todos = [ [177,145,167,190,140,150,180,130], # grupo 1 [165,176,145,189,170,189,159,190], # grupo 2 [145,136,178,200,123,145,145,134], # grupo 3 [201,110,187,175,156,165,156,135] # grupo 4 ] maxofmax = 0 countindex = 0 for group in todos: countindex = countindex+1 maxingroup = max(group) if maxingroup > maxofmax: maxofmax = maxingroup maxindex = countindex else: pass print ("El mas alto es %d del grupo %d " %(maxofmax, maxindex))
682349d59750ac4927cb920a24ac581968b0138f
Panther010/learning
/Python/ds_and_algo/array/array_07-unique-characters-in-tring.py
261
3.71875
4
def unique_char(s): seen = set() for char in s: if char in seen: return False else: seen.add(char) return True print(unique_char('')) print(unique_char('goo')) print(unique_char('abcdefg'))
07ade40d4bf4b6b69bfead33cb3a92166b682827
lastbyte/dsa-python
/problems/medium/validate_bst.py
1,719
4.15625
4
''' 98. Validate Binary Search Tree Given the root of a binary tree, determine if it is a valid binary search tree (BST). A valid BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. Example 1: Input: root = [2,1,3] Output: true Example 2: Input: root = [5,1,4,null,null,3,6] Output: false Explanation: The root node's value is 5 but its right child's value is 4. Constraints: The number of nodes in the tree is in the range [1, 104]. -231 <= Node.val <= 231 - 1 link -> https://leetcode.com/problems/validate-binary-search-tree/ ''' class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def validate_bst(self, root: TreeNode): if root is None : return True else: return self.validate_bst_util(root,-float('inf'),float('inf')) def validate_bst_util(self,root: TreeNode,min_val:int, max_val:int): is_left_valid = root.left is None or self.validate_bst_util(root.left,min_val,root.val) is_right_valid = root.right is None or self.validate_bst_util(root.right,root.val,max_val) is_node_valid = min_val < root.val < max_val return is_left_valid and is_right_valid and is_node_valid if __name__ == "__main__": solution = Solution() root = TreeNode(2) root.left = TreeNode(1) root.right = TreeNode(3) root.right.left = TreeNode(0) result = solution.validate_bst(root) print(result)
d7dbd57c3b404a07b7814d5ee2b992834e3fece9
spenc53/scum_game
/server/game/utils/game_util.py
2,403
3.71875
4
from game.card import Card from game.player import Player class GameUtil(): def isValidMove(playerHand: "list[Card]", move: "list[Card]", lastMove: "list[Card]") -> bool: """Checks if a given move is valid Args: player (Player): The hand of the player making the move move (list[Card]): The move that player wants to make lastMove (list[Card]): The move that was last made in the game Returns: bool: returns true if the move is valid """ # must make a move, if no move, return false if len(move) == 0: return False if not GameUtil.playerHasCards(playerHand, move): return False if not GameUtil.moveIsAllSameTypeOfCard(move): return False # if there is no last move, all moves are valid if lastMove == None or len(lastMove) == 0: return True if len(lastMove) > len(move): # if the last move has more cards, then return false return False elif len(move) > len(lastMove): # check if move is better than last move return True else: # both have same amount of cards, check who has greater value return move[0] > lastMove[0] def playerHasCards(playerHand: "list[Card]", move: "list[Card]") -> bool: """Check to see if the player has the cards for the given move Args: player (Player): The player's hand to check move (list[Card]): The move or cards to check to see if the player has Returns: bool: returns true if player has the cards, false otherwise """ # check player hand for cards, if player does not have cards, return false for c in move: if c not in playerHand: return False return True def moveIsAllSameTypeOfCard(move: "list[Card]") -> bool: """Check to see if all the cards in the move are of the same value Args: move (list[Card]): The cards to check if they have the same card value Returns: bool: returns true if all cards are the same value """ c1 = move[0] for c in move: if c.number != c1.number: return False return True
e20c61c0982c291a76bea9f4a65ea0d4d2ebaec2
lcqbit11/algorithms
/medium/largest_number.py
539
3.71875
4
def largest_number(nums): if not nums: return n = len(nums) for i in range(n): for j in range(n-1-i): if str(nums[j])+str(nums[j+1]) < str(nums[j+1])+str(nums[j]): nums[j] = nums[j] + nums[j+1] nums[j+1] = nums[j] - nums[j+1] nums[j] = nums[j] - nums[j+1] res = '' res = '0' if nums[0] == 0 else ''.join(map(str, nums)) return res if __name__ == "__main__": nums = [3,30,34,5,9] res = largest_number(nums) print(res)
4a6588c26e5ea39f3b4a8d4192c8fec56de70622
max87-arch/disaster-responses-project
/models/misc/utils.py
500
3.515625
4
import nltk from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer from nltk.tokenize import word_tokenize nltk.download('punkt') nltk.download('wordnet') nltk.download('stopwords') def tokenize(text): word_list = word_tokenize(text.lower()) only_words_list = [word for word in word_list if word.isalnum()] new_words = [WordNetLemmatizer().lemmatize(word) for word in only_words_list if word not in stopwords.words('english')] return new_words
f44361088c8a60f2092fe25d428ffbbfc6a122e3
Adib234/Leetcode
/maximum_number_of_coins_you_can_get.py
444
3.5
4
class Solution(object): def maxCoins(self, piles): """ :type piles: List[int] :rtype: int """ start=len(piles)-1 count=0 total=0 piles.sort() alternate=False while count!=len(piles)//3: start-=1 alternate= not alternate if alternate: total+=piles[start] count+=1 return total
66a00c89f745f81daacf3907f4f528d9623efb09
MarvelICY/DSAP
/Algorithms/binary_search.py
1,076
4.1875
4
#!usr/bin/python # -*- coding:UTF-8 -*- ''' Introduction: Binary search Created on: Oct 24, 2014 @author: ICY ''' #-------------------------FUNCTION---------------------------# class Solution: # the array must be sorted from small to large order def binary_search(self, num, value): left = 0 right = len(num) - 1 while left <= right: middle = left + ((right-left)>>1) #Important,calculate middle index without overflow. if num[middle] > value: right = middle - 1 #update right side elif num[middle] < value: left = middle + 1 #update left side else: return middle return -1 #----------------------------SELF TEST----------------------------# def main(): #test_array = [0] test_array = [1,2] #test_array = [1,2,3,4] #test_array = [2,4,5,6,7,8,9] value = 4 solution = Solution() print solution.binary_search(test_array,value) pass if __name__ == '__main__': main()
db324305b6356aabbc0aafa217cc6a04507a6963
carlosbarcelos/advent-of-code-2018
/day02/day02.py
1,681
3.703125
4
''' Advent of Code: Day 2 Inventory Management System ''' from collections import Counter # Count characters in string # Read in the data f = open('day02.txt', 'r') data = f.read().split() f.close() def partOne(): twoTimes = 0 threeTimes = 0 for id in data: # Create count of each letter letterDict = Counter(id) # Are there any letters that appear two or three times? appearTwo = False appearThree = False for k, v in letterDict.items(): if v == 2 and not appearTwo: twoTimes += 1 appearTwo = True elif v == 3 and not appearThree: threeTimes += 1 appearThree = True return twoTimes * threeTimes # Return number of character differences in a string def numCharDiff(str1, str2): numDiff = 0 for i in range(len(str1)): if not str1[i] == str2[i]: numDiff += 1 return numDiff def partTwo(): # Reduce to a list of single character difference reducedData = set() for id1 in data: for id2 in data: c1 = Counter(id1) c2 = Counter(id2) # If off by one letter, add to reduced set if sum((c1 - c2).values()) == 1 and sum((c2 - c1).values()) == 1: reducedData.add(id1) # Check for letter positions for id1 in data: for id2 in data: offByOne = False if numCharDiff(id1, id2) == 1: # TODO Fully automate. This requires a bit of manual work. return f'{id1} {id2}' return 'No solution found' if __name__ == '__main__': print(partTwo())
b889373f14a8765740637b14ec0c40d4190497ed
denck007/scraping
/hardwareswap_scraper/parse_pushshift_data.py
3,849
3.6875
4
''' This script turns the json files from pushshift and looks for a price in the post text. A 'price' is defined as the numbers between a '$' and the following non numeric charaters. It also matches the case where the pattern is non-numeric, then numeric price, then $ This creates raw data files. All this data needs to be reviewed and cleaned before being useful. ''' import json import urllib.request from datetime import datetime import os import re keywords = ["970","nvidia"] outfile = "970.csv" base_file_name = "subreddit=hardwareswap&title=970" def find_price(text): ''' attempt to find price in post text ''' text = text.strip(" ") price_start = text.find("$") +1 # find the first instance of a dollar sign if price_start >= len(text): # symbol could floow the price... price_start = text.rfind(" ") # find the price by moving to the space before if price_start>0: while text[price_start] == " ": # remove spaces between dollar sign and price price_start += 1 price_len = 0 while text[price_start+price_len].isnumeric(): # count number of digits in price price_len += 1 if len(text) == price_start + price_len: # case where last character in post is part of the price break price = text[price_start:price_start+price_len] # extract price if "$" in text[price_start+price_len:]: # if there is another $ recursively call find_price() on a smaller chunk other_price = find_price(text[price_start+price_len:]) price = "{}-{}".format(price,other_price) # append the result return price else: return "NONE LISTED" def parse_json(data): found_posts = {} idx = 0 for submission in data["data"]: idx += 1 if "selftext" not in submission.keys(): continue title = submission["title"].lower().strip(" ") title = text = re.sub("[,.]","",title) # remove all periods and commas location_end = title.find("]") location = title[1:location_end] have_start = title[location_end+1:].find("]") have_end = title.rfind("[") have = title[location_end+have_start+2:have_end].strip() for keyword in keywords: if keyword in have: text = submission["selftext"] text = re.sub("[,.]","",text) # remove all periods and commas price = find_price(text) submission_time = submission["created_utc"] date = datetime.fromtimestamp(submission_time) url = submission["url"] print("Number: {} Location: {} have: {} price: {}".format(idx,location,have,price)) found_posts.update({submission["id"]:{"title":title,"items":have,"price":price,"year":date.year,"month":date.month,"day":date.day,"hour":date.hour,"minute":date.minute,"url":url}}) break return found_posts def save_posts(posts,outfile,mode): with open(outfile,mode) as f: if mode != 'a': # if appending do not write headers f.write("Post Id,Items for sale,Price,URL,Year,Month,Day,Hour,Minute\n") for post in posts: f.write("{},{},{},{}".format(post,posts[post]["items"],posts[post]["price"],posts[post]["url"])) f.write(",{},{},{},{},{}\n".format(posts[post]["year"],posts[post]["month"],posts[post]["day"],posts[post]["hour"],posts[post]["minute"])) fnames = [f for f in os.listdir() if base_file_name in f] for idx,fname in enumerate(fnames): print(fname) with open(fname,'r') as f: raw_data = f.read() data = json.loads(raw_data) posts = parse_json(data) if idx == 0: mode = "w" else: mode = "a" save_posts(posts,outfile,mode)
f94cd7ed784577a29dd86b94b46e7b2dba75e9aa
gtokusum/CSCI-C200-Fall-2020
/Laboratory/Debugger/magic.py
166
3.546875
4
lst = [[1,2], [3,4],[5,6],[7,8]] def magic(x): s = 0 for y in x: z=y[0] s += z return s if __name__ == '__main__': print(magic(lst))
6bf39aac603609e19c85b64c9d6e29304fa14062
constructor-igor/TechSugar
/pythonSamples/tips/progress_bar_sample.py
575
3.578125
4
# # conda install progressbar2 # # https://stackoverflow.com/questions/3002085/python-to-print-out-status-bar-and-percentage # https://anaconda.org/conda-forge/progressbar2 # import numpy as np import progressbar from time import sleep def show_progress_bar(): with progressbar.ProgressBar(maxval=20, widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()]) as bar: for i in range(20): bar.update(i+1) sleep(0.1) if __name__ == "__main__": print("[main] start") show_progress_bar() print("[main] finish")
758d44c4ab8fac7b99ba40410b77c3c017c7389c
LucasDiasTavares/Python
/medias.py
311
3.609375
4
nota1 = input ("Digite a primeira nota: ") nota2 = input ("Digite a segunda nota: ") nota3 = input ("Digite a terceira nota: ") nota4 = input ("Digite a quarta nota: ") n1 = int(nota1) n2 = int (nota2) n3 = int(nota3) n4 = int (nota4) media = (n1+n2+n3+n4)/4 print ("A média aritmética é ", media)
0ec8c5bab8830f5120227960ad3aa1708f3de5fd
sophialuo/CrackingTheCodingInterview_6thEdition
/16.20.py
1,115
3.890625
4
''' T9: On old cell phones, users typed on a numeric keypad and the phone would provide a list of words that matched these numbers. Each digit mapped to a set of 0-4 leters. Impelment an algorithm to return a list of matching words, given a sequence of digits. You are provided a list of valid words (provided in whatever data structure you'd like). 1: None 2: abc 3: def 4: ghi 5: jkl 6: mno 7: pqrs 8: tuv 9: wxyz 0: None Example Input: 8733 Output: tree, used ''' import itertools # list(itertools.product(*a)) valid_words = [] #some list of valid words mapping = {1: None, 2: 'abc', 3: 'def', 4: 'ghi', 5: 'jkl', 6: 'mno', 7: 'pqrs', 8: 'tuv'} def t9(digits): lst = [] while digits != 0: num = digits % 10 digits = int(digits/10) possible = list(mapping[num]) lst.append(possible) lst = reversed(lst) all_words = list(itertools.product(*lst)) ''' #uncomment for results when given valid_words actual_words = [] if all_words in valid_words: actual_words.append(all_words) return actual_words ''' return all_words print(t9(8733))
fe5eaff85b34ed058b5b93fceaef720dd2499199
benningtoncompling/project2-eastasiantokenization-kelseybroadfield
/japanese_tokenizer.py
1,972
3.625
4
# # Comp Ling PROJECT #2- Japanese Tokenization # # March 2019 # Author: Kelsey Broadfield [email protected] # import sys input_file = sys.argv[1] output_file = sys.argv[2] # how I run it on my computer bc I don't know how to use the terminal on my laptop # input_file = 'in.txt' # output_file = 'out.txt' # creates list for japanese dictionary word_checker = [] # opens japanese dictionary and writes it to a list with open('japanese_wordlist.txt', 'r+', encoding="UTF-8") as my_list: for lines in my_list: words = my_list.readlines() lines.strip('\n') word_checker.append(words) # creates lists, one is for the in text to be fixed and other is for fixed text all_lines = [] spaced_lines = [] # this opens the japanese text without spaces and writes it to a list with open(input_file, 'r+', encoding="UTF-8") as japanese_no_space: for x in japanese_no_space: lines = japanese_no_space.readline() all_lines.append(lines) # creates list for function my_new_lines = [] # defines function that reads japanese text and adds spaces between words # PSA run program with parameters: all_lines and word_checker def max_matcher(line, dictionary): for y in line: if y not in dictionary: current = y[:-1] my_new_lines.append(current) elif y in dictionary: spaced = y + ' ' my_new_lines.append(spaced) else: max_matcher(line, dictionary) str_my_new_lines = str(my_new_lines) with open(output_file, 'w+', encoding="UTF-8") as spaced_text: spaced_text.write(str_my_new_lines) spaced_text.close() return my_new_lines max_matcher(all_lines, word_checker) # notes to self: # first, read the whole line- and check within the dictionary for a match # if there is no match, move back one character # once there is a match, add a space
c6c63f2cc956f735014834b27967f3ddcc63415f
mattsuri/unit4
/warmpup11.py
173
3.71875
4
#Matthew Suriawinta #3/26/18 #warmup11.py def prime(num): for i in range (2,num): if num % i == 0: return False return True print(prime(3))
63542bceb1ba276c4d0392fc124820698e51ce7d
R3tr093/ToDouxLiss-t
/Python/remind/prout/string.py
9,267
3.984375
4
# This script is writed for remind me some tips about how to use string object in Python import os def clear(): os.system('clear') os.system('cls') newLine = "\n" def frame (param): print(newLine) print('|------------------------------------------------------------|' + newLine) print('| |' + newLine) print('| ' + param.center(24) + ' |' + newLine) print('| |' + newLine) print('|------------------------------------------------------------|' + newLine) print(newLine) input("Appuyez sur Enter pour continuer...") clear() frame("Une chaîne est un objet") print(newLine + "En Python les chaînes de caractères sont des objets issus de la classe 'str'") print(newLine + "Une variable de type string se déclare comme suit >>> nomDeVariable = ' ma première chaîne de caractère ! ' ") print(newLine + "La classe str offre des méthodes que l'ont va pouvoir utiliser pour manipuler nos chaînes de caractères") print(newLine + "Nous allons voir quelques une de ces méthodes qui vont nous permettre de mieux exploiter les chaînes de caractères en Python.") print(newLine) input("\n Appuyez sur Enter pour continuer...") clear() frame(" lower, upper ") print(newLine + "Une chose qu'il va falloir garder à l'esprit, c'est que l'appel d'une méthode sur une chaînes de caractères la transforme de façon temporaire.") print(newLine + "Autrement dit lorsque vous utilisez une méthode sur une chaîne de caractère vous devez conserver le résultat dans une variable en lui réaffectant cette valeur si besoin est.") print(newLine + "Pour exemple prenons une chaîne de caractère comme celle ci >>> BONJOUR TOUT LE MONDE !") print(newLine + "Si vous désirez transformer les majuscules contenues dans cette chaîne vous pourriez appeler la méthode >>> lower()") print(newLine + " variable >>> BONJOUR A TOUS ! ") exemple = "BONJOUR A TOUS !" print(newLine + "variable.lower() >>> " + exemple.lower()) input("\n Appuyez sur Enter pour continuer...") clear() print(newLine + "Il est tout à fait possible d'afficher le résultat sans le conserver dans une variable, par exemple dans une condition, ou en paramètre d'une fonction, etc...") print(newLine + "Dans un cas pratique, imaginons que vous demandiez à l'utilisateur d'appuyez sur 'Q' pour quitter le programme.") print(newLine + "On utilise une boucle qui demande d'entrez une valeur correspondant a un 'Q' majuscule et si celle-ci n'est pas 'Q' alors la boucle demande une nouvelle saisie") print(newLine + "Si vous désirez être sur que la lettre soit pris en compte qu'elle soit en majuscule ou en minuscule vous pouvez faire une boucle comme ceci : (Voir ligne 50 à 55 ) ") chaine = "" while chaine.lower() != "q": print(newLine + "Appuyez sur 'Q' pour sortir ...") chaine = input() print(newLine + "Vous êtes sorti du programme ! ") print(newLine + "La condition de notre boucle vérifie une chaîne qui est transformer en minuscule avec la méthode lower(), et on conserve la valeur actuel de la variable.") print(newLine + "Vous pouvez utilisez la fonction .upper() qui va transformer la chaîne en majuscule en partant du même principe que la précédente !.") print(newLine + "De cette manière, même si l'utilisateur tape un Q en majuscule il sera pris en compte, car Python est sensible à la casse.") print(newLine + "Autrement dit pour Python il y a une différence fondamentale entre A et a.") print(newLine) input("Appuyez sur Enter pour continuer ...") clear() frame("Capitalize, strip,center") print(newLine + "La méthode .capitalize() permet de transformer la première lettre d'une chaîne de caractère en majuscule.") a = "hello" print(newLine + "Notre variable contient le mot hello >>> " + a) print(newLine + "On lui applique la méthode capitalize >>> " + a.capitalize()) print(newLine + "La méthode .strip() permet de retirer les espaces en début, et en fin d'une chaîne de caractère. (voir ligne 82.)") a = " Je suis une chaîne avec des espaces " print(newLine + "Voici notre chaîne de caractère pour l'exemple : " + newLine + a) print (newLine + "Traitement de la chaine avec la méthode .strip() : " + newLine + a.strip()) print(newLine + "Voyons maintenant la méthode .center(paramètre), cette méthode possède un paramètre qui doit être un nombre entier.") print(newLine + "Sur base de ce nombre entier la méthode va centré la chaîne de caractères sur un espace de X caractères selon le paramètre appliquer.") a = "bonjour tout le monde !" print(newLine + "Voici notre chaîne de caractères d'origine >>> " + a) print(newLine + "Voici notre même chaîne de caractères avec application de la méthode .center(100) (Voir ligne 98)") print(newLine + a.center(100)) print(newLine + "Une dernière chose, vous pouvez également faire une chaîne de méthode en invoquant les méthodes l'une après l'autre comme ceci : ") print(newLine + "variable.upper().center(100)") print(newLine + "Dans l'éventualité ou votre chaîne de caractères représente par exemple >>> " + a) print(newLine + "Le résultat d'une chaîne de méthode tels que variable.upper().center(100) sur votre chaîne de caractères retournera >>> ") print(newLine + a.upper().center(100)) input("\n Appuyez sur Enter pour continuer...") clear() print(newLine) frame('.format()') print(newLine + "La méthode .format() est une méthode qui permet de formater des chaînes de caractères, cette méthode est bien plus puissante qu'un simple formatage d'affichage.") print(newLine + "Elle permet de passez un nombre indéfini de paramètre et de les invoquer dans une chaînes de caractères à l'aide d'accolades comme ceci >>> {0}.") print(newLine + "En passant le chiffre 0 dans les accolades on appel la valeur du premier paramètre passez dans la fonction.") print(newLine + "Imaginons que nous avons 3 variables contenant un prénom, un nom et un âge.") print(newLine + "Voici ce que donnerais un appel de la méthode .format() dans ce cas précis.") print(newLine + "'Je m'appel {0} {1}, j'ai {2} ans.'" + ".format(name,lastname,age)") name = "John " lastname = "Doe" age = "29" formatExample = "Je m'appel {0} {1}, j'ai {2} ans.".format(name,lastname,age) print(newLine + formatExample) print(newLine + "Il existe bien d'autre façon d'utiliser la méthode .format(), mais à mon sens celle-ci est la plus élégante.") print(newLine + "Vous pouvez également concaténer les chaînes de caractères en effectuant une addition sur deux chaînes de caractères.") print(newLine + "nom + prénom >>> " + name + lastname) input("\n Appuyez sur Enter pour continuer...") clear() frame("Parcourir une chaîne") print(newLine + "Il est également possible de parcourir une chaîne de caractères par son indice, autrement dit caractère par caractère.") print(newLine + "Pour exemple continuons avec une variable ayant pour valeur la chaîne de caractère suivante >>> bonjour") print(newLine + "Dans ce cas de figure on peut obtenir la valeur de la première lettre avec l'instruction suivante.") a = "bonjour" print(newLine + "variable[0]") print(newLine + "Le résultat sera le suivant >>> " + a[0]) print(newLine + "Avec un instruction telle que varaible[-1], on obtient la dernière lettre.") print(newLine + a[-1]) print(newLine + "Avec l'instruction variable[-2].upper().center(30) le résultat est le suivant.") print(newLine + a[-2].upper().center(30)) print(newLine + "Toutefois si vous désirez connaitre la valeur maximum vous pouvez utilisez la méthode len(variable), attention on commence toujours un index à partir de 0 !") print(newLine + "Dans le cas ou notre variable contient toujours la valeur 'bonjour' le résultat de len(variable) donnera >>> " + str(len(a))) print(newLine + "Sur base de ce principe il est aisé de parcourir une chaîne de caractères avec une boucle while. (voir ligne 167 à 171)") i = 0 while i < len(a): print(newLine + a[i]) i+=1 print(newLine + "Une dernière chose, vous ne pouvez pas modifiez la valeur d'un caractère dans une chaîne via son indice." + newLine + "Et si vous essayez d'accéder à un indice qui n'existe pas, Python lèvera une exception de type :: IndexError") input("\n Appuyez sur Enter pour continuer...") clear() frame("Sélection de chaînes") print(newLine + "Il est possible de séléctionner un fragment d'une chaîne de caractère, poursuivons notre exemple avec une variable contenant la chaîne de caractère 'bonjour'...") print(newLine + "En effectuant une instruction comme, variable[:2] vous obtiendez alors les trois premiers caractères de votre variable.") print(newLine + "variable[:2] >>> " + a[:2]) print(newLine + "De la même manière en utilisant l'instruction, variable[2:]") print(newLine + "Vous obtenez du troisième caractère jusqu'a la fin de la chaîne de caractère.") print(newLine + "variable[2:] >>> " + a[2:]) print(newLine + "Et voilà, félicitation vous connaissez toutes les méthodes natives de Python3 pour manipuler une chaîne de caractère !")
15726ab43764bf3651a59b4d1723b9e891cd67d9
evanwangxx/leetcode
/python/1160_Find_Words_That_Can_Be_Formed_by_Characters.py
1,527
3.875
4
# You are given an array of strings words and a string chars. # A string is good if it can be formed by characters from chars (each character can only be used once). # Return the sum of lengths of all good strings in words. # # Example 1: # Input: words = ["cat","bt","hat","tree"], chars = "atach" # Output: 6 # Explanation: The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6. # # Example 2: # Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr" # Output: 10 # Explanation: The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10. import copy class Solution: def countCharacters(self, words, chars): dic = {} for c in chars: if c not in dic.keys(): dic[c] = 1 else: dic[c] += 1 res = [] for w in words: dic_copy = copy.deepcopy(dic) tmp = [] i = 0 while i < len(w): if w[i] in dic_copy.keys() and dic_copy[w[i]] != 0: dic_copy[w[i]] -= 1 tmp.append(w[i]) i += 1 else: tmp = [] i = len(w) res.extend(tmp) return len(res) x = ["cat","bt","hat","tree"] chars = "atach" print(Solution().countCharacters(x, chars)) x = ["hello","world","leetcode"] chars = "welldonehoneyr" print(Solution().countCharacters(x, chars))
d3e42593aef1dfa1346240ce7b4fdc98adb99701
kilicmustafa/Python
/Python Temel/Metin İslemleri/Split_replace_örnek.py
1,104
3.59375
4
#SUBstring mesaj = "MERHABA DÜNYA" mesaj_2 = mesaj[:5] print(mesaj_2) mesaj_3 = mesaj[1:8] print(mesaj_3) mesaj_4 = mesaj[3:] print(mesaj_4) #LEN uzunluk metin = "UZUNLUNLUK LEN" metin_sonkarakter = metin[len(metin)-1:len(metin)] print(metin_sonkarakter) #LOWER VE UPPER CASE text = " Ali İLE veli El ele " buyukharf = text.upper() kucukharf = text.lower() print(buyukharf) #Stringler üzerinde Replace mesaj = "Dönüşecek metin " yenimesaj = mesaj.replace("ö","o") yenimesaj_2 = yenimesaj.replace("ü","u") yenimesaj_3 = yenimesaj_2.replace("i","ı") yenimesaj_4 = yenimesaj_3.replace("ş","s") print(yenimesaj) print(yenimesaj_2) print(yenimesaj_3) print(yenimesaj_4) #Split ve Strip ile kelime ayırma ve kelime seçip alma kelimeler = "KEREM KURNAZ 5425881227 İSTABUL" kelime_1 = kelimeler.split() print(kelime_1) kelime_2 = kelimeler.split()[2] # kelimeler dizisini boşluklara göre splitle ve 2.indisini al print (kelime_2) kelimeler_2 = "Furkan;Sağ;Evli;28;".strip(";") kelime_4 = kelimeler_2.split(";") print (kelime_4) kelime_5 = kelimeler_2.split(";")[2] print (kelime_5)
4da2d6f15a15d40077055790e650868efc623e5e
nicolasgasco/CodingNomads_Labs
/06_functions/06_01_tasks.py
854
4.0625
4
''' Write a script that completes the following tasks. ''' # define a function that determines whether the number is divisible by 4 or 7 and returns a boolean def isdivisible_single(num): if num % 7 == 0 or num % 4 == 0: return True else: return False # define a function that determines whether a number is divisible by both 4 and 7 and returns a boolean def isdivisible_both(num): if num % 7 == 0 and num % 4 == 0: return True else: return False # take in a number from the user between 1 and 1,000,000,000 x = int(input("Please write a number between 1 and 1000000000: ")) # call your functions, passing in the user input as the arguments, and set their output equal to new variables y = isdivisible_single(x) z = isdivisible_both(x) # print your new variables to display the results print(y, z)
5f38c25fff9915754f691ede33a5c72f43acd3f4
paalso/hse_python_course
/3/3-10.py
1,134
4.46875
4
# https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/bbQb0/kvadratnoie-uravnieniie-2 # Квадратное уравнение - 2 # Даны произвольные действительные коэффициенты a, b, c. # Решите уравнение ax²+bx+c=0. def get_quadratic_equation_solution(a, b, c): if a == 0: if b != 0: return [- c / b] if c != 0: return [] return [-float('inf'), 0, float('inf')] D = b * b - 4 * a * c if D < 0: return [] if D == 0: return [- 0.5 * b / a] if a < 0: [a, b, c] = [-a, -b, -c] return [(- b - D ** 0.5) / (2 * a), (- b + D ** 0.5) / (2 * a)] a = float(input()) b = float(input()) c = float(input()) solution = get_quadratic_equation_solution(a, b, c) solutions_number = len(solution) if solutions_number > 2: print(3) else: print(solutions_number, end=' ') if solutions_number == 2: print(solution[0], solution[1]) elif solutions_number == 1: print(solution[0])
6b5bd8d99294263e22b32e9e965bb88989389228
QinmengLUAN/Daily_Python_Coding
/LC1219_getMaximumGold_Backtracking.py
1,682
4.1875
4
""" 1219. Path with Maximum Gold Medium: Backtracking In a gold mine grid of size m * n, each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty. Return the maximum amount of gold you can collect under the conditions: Every time you are located in a cell you will collect all the gold in that cell. From your position you can walk one step to the left, right, up or down. You can't visit the same cell more than once. Never visit a cell with 0 gold. You can start and stop collecting gold from any position in the grid that has some gold. Example 1: Input: grid = [[0,6,0],[5,8,7],[0,9,0]] Output: 24 Explanation: [[0,6,0], [5,8,7], [0,9,0]] Path to get the maximum gold, 9 -> 8 -> 7. Example 2: Input: grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]] Output: 28 Explanation: [[1,0,7], [2,0,6], [3,4,5], [0,3,0], [9,0,20]] Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7. """ class Solution: def 1(self, grid: List[List[int]]) -> int: ans = 0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] > 0: ans = max(ans, self.helper((i,j), grid)) return ans def helper(self, pos, grid): i, j = pos[0], pos[1] max_gold = 0 grid[i][j] = - grid[i][j] npos = [(0, 1), (0, -1), (1, 0), (-1, 0)] for x, y in npos: if 0 <= i+x < len(grid) and 0 <= j+y < len(grid[0]): if grid[i+x][j+y] > 0: max_gold = max(self.helper((i+x, j+y), grid), max_gold) grid[i][j] = abs(grid[i][j]) return max_gold + grid[i][j]
8adc475573705442312a86272f0b6d9e313f765f
socc-io/algostudy
/ProblemPool/sort_mergesort/becxer.py
575
3.75
4
def merge(P,Q): ip = 0 iq = 0 res = [] while True: if ip >= len(P) or iq >= len(Q): break if P[ip] > Q[iq]: res.append(Q[iq]) iq += 1 elif P[ip] <= Q[iq]: res.append(P[ip]) ip += 1 if ip < len(P): res.extend(P[ip:]) if iq < len(Q): res.extend(Q[iq:]) print str(P) + "+"+str(Q) + "=" +str(res) return res def merge_sort(A): if len(A) == 1: return A elif len(A) == 0: return [] A_p = merge_sort(A[:len(A)/2]) A_q = merge_sort(A[len(A)/2:]) return merge(A_p,A_q) arr = map(int,str(raw_input()).split(" ")) print str(merge_sort(arr))
6dfcde2002de53d1017cf093ddec7866e1f6cfca
JeremyYao/LearningPython
/Chatper9Classes/die.py
879
4.1875
4
import random # 9-13. Dice: Make a class Die with one attribute called sides , which has a default # value of 6. Write a method called roll_die() that prints a random number # between 1 and the number of sides the die has. Make a 6-sided die and roll it # 10 times. # Make a 10-sided die and a 20-sided die. Roll each die 10 times. class Die: def __init__(self, num_sides = 6): self.num_sides = num_sides def roll_die(self): print(random.randint(1, self.num_sides)) # Make a 6-sided die and roll it # # 10 times. # # Make a 10-sided die and a 20-sided die. Roll each die 10 times. sixDie = Die() for i in range(0, 10): sixDie.roll_die() print("******** tenDie **********8") tenDie = Die(10) for i in range(0, 10): tenDie.roll_die() print("******** twentyDie **********8") twentyDie = Die(20) for i in range(0, 10): twentyDie.roll_die()
57e0732f122637551f1fd9def4b981acb3d5d8ad
miaviles/Core-Python-From-Basics-to-Advanced
/Files/File Handling/fileName.py
296
4.5
4
# write python program to capture any filename from the keyboard # and display its filename and extensions separately fileName = input("Enter any filename: ") print("You entered: ", fileName) output = fileName.split(".") print("File name : ", fileName) print("Extension : ", output[1])
965bf2387cf195d03cc5a06cf88286c409e334bf
rocketpy/tricks
/zone_info.py
1,018
3.625
4
# zoneinfo — IANA time zone support # Docs: https://docs.python.org/3/library/zoneinfo.html from zoneinfo import ZoneInfo from datetime import datetime, timedelta dt = datetime(2020, 10, 31, 12, tzinfo=ZoneInfo("America/Los_Angeles")) print(dt) # 2020-10-31 12:00:00-07:00 dt.tzname() # 'PDT' dt_add = dt + timedelta(days=1) print(dt_add) 2020-11-01 12:00:00-08:00 dt_add.tzname() # 'PST' dt = datetime(2020, 11, 1, 1, tzinfo=ZoneInfo("America/Los_Angeles")) print(dt) # 2020-11-01 01:00:00-07:00 print(dt.replace(fold=1)) # 2020-11-01 01:00:00-08:00 # When converting from another time zone, the fold will be set to the correct value: from datetime import timezone LOS_ANGELES = ZoneInfo("America/Los_Angeles") dt_utc = datetime(2020, 11, 1, 8, tzinfo=timezone.utc) # Before the PDT -> PST transition print(dt_utc.astimezone(LOS_ANGELES)) # 2020-11-01 01:00:00-07:00 # After the PDT -> PST transition print((dt_utc + timedelta(hours=1)).astimezone(LOS_ANGELES)) # 2020-11-01 01:00:00-08:00
f2b90d99fa73d63b85d3c2ee98bbfb6b66a54577
milu234/Python
/set.py
619
4.03125
4
my_set={1,2,3} print(my_set) my_set={1.0,"Hello",(1,2,3)} print(my_set) my_set={1,2,3,43,2} print(my_set) a={} print(type(a)) a=set(a) print(type(a)) #print(my_set[0]) #set does not supports indexing my_set.add(12) print(my_set) my_set.update([56,45,89]) print(my_set) my_set.discard(12) print(my_set) my_set.remove(45) print(my_set) my_set=set("Hello Milan") print(my_set) my_set.pop() print(my_set) A={1,2,3,4,5,} B={4,5,6,7,8,9} print(A^B) print(A.symmetric_difference(B)) print(B.symmetric_difference(A)) my_set=set("MILAN") print('a' in my_set) print('A' in my_set) for letter in set("Milan"): print(letter)
9294b67ebda081cb812f85077bbbf7376b436428
StrokeRehabilitationRobot/Main
/Robot.py
2,632
3.546875
4
from math import pi import helper class Robot(object): """ Robot class to hold state and description of the robot """ def __init__(self,arm="thanos",id=0): """ :type id: arm id :param arm: which arm do you want :param id: id of the arm """ self._name = arm if arm == "thanos": self.arm1() else: self.arm2() self._id = id self._inertia = [[0.006757, 0.0006036, 0.0015514], [0.001745, 0.0005596, 0.00006455], [0.00706657, 0.0006254, 0.0015708] ] self._mass = [1.01992, 0.3519, 0.22772] self._lengths = [0.25107, 0.191, 0.37843] self._centroid = [0.10424, 0.14550, 0.203] self._convert_factor = ((1 / 11.44) * (2 * pi / 360)) # converts from tick->rads self.q = [0,0,0] self.qd = [ 0,0,0] self.qdd = [0, 0, 0] self.tau = [0,0,0] def arm1(self): """ params for arm thanos :return: """ self._torque_offset = [0.5646, 0.5084, 0.5128] self._max_tau = [0.6, 0.55, 0.55] self._min_tau = [.45, .40, .4] def arm2(self): self._torque_offset = [0.5646, 0.5084, 0.5128] self._max_tau = [0.6, 0.55, 0.55] self._min_tau = [.45, .40, .4] def update(self, state): # TODO figure out how to get qdd """ updates the state of the robot :param state: the message from the board :return: """ for i in xrange(3): self.q[i ] = round( helper.encoder_to_angle(state[i * 3 + 0 + 1]), 2) self.qd[i] = round( helper.encoder_to_angle(state[i * 3 + 2 + 1]),2) self.tau[i] = self.filter_tau(self.interpolate_tau(state[i * 3 + 2 + 1],i),i) self.q[2] -= 0.5 * pi @property def unpack(self): """ :return: all the phyical params of the robot """ return self._inertia, self._mass, self._lengths, self._centroid def interpolate_tau(self,updated_tau,i): # TODO figure out scaling for torque for each link """ :param updated_tau: :param i: :return: """ return updated_tau#10*updated_tau - 10*self._torque_offset[i] def filter_tau(self,interpolated_tau,i): # TODO figure out analog way of interpring torque if interpolated_tau > self._max_tau[i]: return 1 elif interpolated_tau < self._min_tau[i]: return -1 else: return 0
831be791c23794e8eea303fac1462c5b023825af
Amenable-C/Python_practice
/primeNumber+.py
454
4.0625
4
# Prime Number while True: num = int(input("Enter a value (-1 to quit): ")) if num == -1: print("Bye") break elif num == 1: print("Nope") elif num == 2: print("Yeees!!") elif num > 2: for i in range(2, num): if num % i == 0: print("NOPE") break if i == num-1: print("Yeeees") else: print("Put another number")
f632839e0d6bd3550d174674dcee725e5accc91c
YeSei/python3
/day4/fib.py
426
3.609375
4
# Author:Jay #斐波拉契函数 ''' 生成器只有在调用时才会生成相应的数据 只记录当前位置 只有一个__next__()方法。next() ''' def fib(max): n,a,b = 0,0,1 while n < max: yield b a,b = b,a + b #t=(b,a+b) , (a,b)=t n= n + 1 return 'done' f = fib(10) print(f) print(f.__next__()) print(f.__next__()) print(f.__next__()) print(f.__next__()) print(f.__next__())
1f015c03669d0ff6eadb0fd5f7921a0edc6ebeff
shrikam/py-repo
/coomonInlist.py
234
3.640625
4
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] f=[] for i in range (0,len(a)): for j in range (0,len(b)): if a[i]==b[j]: f.append(b[j]) break print(f)
38c3451301943e3c3dab2ebbc12eb1d2a9c7164f
abhnvkmr/hackerRank
/sherlockbeast.py
456
3.78125
4
# Hackerrank - Algorithm - Warmup # Sherlock and the Beast def get_result(n): fives, threes = 0, 0 for i in range(n, -1, -1): if not (n - i) % 5 and not i % 3: fives = i threes = n - i break if fives == 0 and threes == 0: print(-1) else: print("5" * fives + "3" * threes) if __name__ == "__main__": t = int(input()) for _ in range(t): get_result(int(input()))
a01572aa4eb23712a34425bf2c293005f7247ea3
Takuma-Ikeda/other-LeetCode
/src/easy/test_make_two_arrays_equal_by_reversing_sub_arrays.py
897
3.5
4
import unittest from answer.make_two_arrays_equal_by_reversing_sub_arrays import Solution class TestSolution(unittest.TestCase): def setUp(self): self.target = [ [1, 2, 3, 4], [7], [1, 12], [3, 7, 9], [1, 1, 1, 1, 1], ] self.arr = [ [2, 4, 1, 3], [7], [12, 1], [3, 7, 11], [1, 1, 1, 1, 1], ] self.answers = [ True, True, True, False, True, ] def test_solution(self): for i in range(len(self.answers)): print('----- TEST NO.%i START -----' % i) s = Solution() result = s.canBeEqual(self.target[i], self.arr[i]) self.assertEqual(self.answers[i], result) if __name__ == "__main__": unittest.main()
74893bc767e9f9006919d052916825d2336c71a0
Zenit95/GestorMp3
/Repo.py
1,645
3.515625
4
#!/usr/bin/python # -*- coding:utf-8 -*- import sqlite3 def connectDB(dbFile): conn = sqlite3.connect(dbFile) cur = conn.cursor() return conn,cur conn, cur = connectDB("mp3DB.sqlite") def addSong(): title = raw_input("\n\tIntroduzca el titulo\t") author = raw_input("\n\tIntroduzca el autor\t") time = raw_input("\n\tIntroduzca la duración\t") style = raw_input("\n\tIntroduzca el estilo\t") sql = "INSERT INTO MP3 (titulo, interprete, duracion, estilo) VALUES ((?), (?), (?), (?));" song = cur.execute(sql, (title, author, time, style)) conn.commit() print("\nCanción añadida") def showStyles(): sql = "SELECT estilo FROM MP3" allStyles = cur.execute(sql) styles = [] for i in allStyles: styles.append(i) print("\n\t"+str(i)) def showAuthorSongs(): author = raw_input("\n\tIntroduzca un autor\t") sql = "SELECT titulo FROM MP3 WHERE interprete=(?)" authorSongs = cur.execute(sql, (author, )) songs = [] for i in authorSongs: songs.append(i) print("\n\t"+str(i)) def showStyleSongs(): style = raw_input("\n\tIntroduzca un estilo\t") sql = "SELECT titulo FROM MP3 WHERE estilo=(?)" styleSongs = cur.execute(sql, (style, )) songs = [] for i in styleSongs: songs.append(i) print("\n\t"+str(i)) def selectAll(): sql = "SELECT * FROM MP3" allSongs = cur.execute(sql) songs = [] for i in allSongs: songs.append(i) print("\n\t"+str(i)) def deleteSong(): title = raw_input("\n\tIntroduzca un titulo\t") author = raw_input("\n\tIntroduzca un autor\t") sql = "DELETE FROM MP3 WHERE titulo=(?) AND interprete=(?)" song = cur.execute(sql, (title, author)) print("\nEliminación completada")
435d65b41d84662bee3b071b405ad5a496e453a8
Jacob-TylerThomas/CSC-231-Labs
/Lab3/listing_2_8.py
607
3.84375
4
def anagramSolution4(s1,s2): c1 = [0]*26 c2 = [0]*26 for i in range(len(s1)): pos = ord(s1[i])-ord('a') c1[pos] = c1[pos] + 1 for i in range(len(s2)): pos = ord(s2[i])-ord('a') c2[pos] = c2[pos] + 1 j = 0 stillOK = True while j<26 and stillOK: if c1[j]==c2[j]: j = j + 1 else: stillOK = False return stillOK str1="read" str2="dear" result=anagramSolution4(str1, str2) if result: print(str1, "is an anagram of", str2) else: print(str1, "is not an anagram of", str2)
96421ea74c14bf9d0e6b3dad36cea3cafb86f76b
anidh/python-udemy
/lambda.py
498
4.25
4
#Using a normal function to calculate the square of a value def suared(x): return x**2 print(suared(23)) #This will print the square of a value by normal means i.e functions #Now using anonymous functions here #First define a lambda by keyword lambda #Then use a variable #Then use the expression which we want print((lambda x,y,z:x+y+z)(23,25,27)) #Trying With a list here def app(lists,element): return lists.append(element) print(app([1,2,3],4)) print((lambda x:x.append(2))([1,2,3]))