blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
fd2b0a017cb1fdf89202bd4c8f2684d8e6d9e74e
yuzhishuo/python
/practice/algorithm/1/5.py
796
4.1875
4
'You want to implement a queue that sorts items by a given priority and always returns the item with the highest priority on each pop operation.' import heapq class PriorityQueue: def __init__(self): self._queue = [] self._index = 0 def push (self,item,priority): ' warnning : <priority, index> is cmp key ' heapq.heappush(self._queue, (-priority, self._index, item)) self._index += 1 def pop(self): return heapq.heappop(self._queue)[-1] class Item: def __init__(self, name): self.name = name def __repr__(self): return 'item({!r})'.format(self.name) def __str__(self): return 'this is a str magic method' q = PriorityQueue() q.push(Item('a'), 1) q.push(Item('z'), 26) q.push(Item('d'), 4)
c254ed5af8f8faf02b03e13668017dcfdfef7dc8
Sirly/practice_python_programs
/Binary2Text.py
718
3.671875
4
# Name: Kevin Nakashima # Class: CPSC 223P # Date: 02/07/2017 # File: Binary2Text.py # converts a binary set to a string #Imports======================================================================= #T2B=========================================================================== def Bin2Text(binary): text = [] for set in binary: text.append(chr(int(set, 2))) print(*text, sep = '') #MAIN========================================================================== def main(): binary = input("Please enter binary: ") binaryList = binary.split(' ') Bin2Text(binaryList) main() #==============================================================================
961e00d7ff2d3eeb5b94070da0d17d9ca573ef3c
eecs110/winter2019
/course-files/projects/project_01/option1_graphics/demos/demo3_drag_event.py
972
4
4
''' This demo shows you how you can create a new image by clicking the screen. ''' from tkinter import Canvas, Tk import helpers import utilities import time import random gui = Tk() gui.title('Tour of options...') # initialize canvas: window_width = gui.winfo_screenwidth() window_height = gui.winfo_screenheight() canvas = Canvas(gui, width=window_width, height=window_height, background='white') canvas.pack() ########################## YOUR CODE BELOW THIS LINE ############################## MOUSE_DRAG = '<B1-Motion>' canvas.create_text( (window_width / 2, window_height / 2), text='Drag to create circles', font=("Purisa", 32) ) def make_circle(event): utilities.make_circle( canvas, (event.x, event.y), 20, color='hotpink' ) canvas.bind(MOUSE_DRAG, make_circle) ########################## YOUR CODE ABOVE THIS LINE ############################## # makes sure the canvas keeps running: canvas.mainloop()
debf0f2dad245f2aba423d136628ee79af9718e2
daniloaleixo/hacker-rank
/CrackingTheCode_track/DataStructures/01.Arrays_left_rot.py
1,207
4.46875
4
#!/usr/bin/python # A left rotation operation on an array of size shifts each of the array's elements unit to the left. For example, if left rotations are performed on array , then the array would become . # Given an array of integers and a number, , perform left rotations on the array. Then print the updated array as a single line of space-separated integers. # Input Format # The first line contains two space-separated integers denoting the respective values of (the number of integers) and (the number of left rotations you must perform). # The second line contains space-separated integers describing the respective elements of the array's initial state. # Constraints # Output Format # Print a single line of space-separated integers denoting the final state of the array after performing left rotations. # Sample Input # 5 4 # 1 2 3 4 5 # Sample Output # 5 1 2 3 4 def array_left_rotation(a, n, k): if n > 0: for i in range(0, k): x = a.pop(0) a.append(x) return a n, k = map(int, raw_input().strip().split(' ')) a = map(int, raw_input().strip().split(' ')) answer = array_left_rotation(a, n, k); print ' '.join(map(str,answer))
5d2de9643d816c74970b031b8f61b3c470c89dd8
nunrib/Curso-em-video-Python-3
/MUNDO 2/ex041.py
725
3.96875
4
from datetime import date anonascimento = int(input('Digite o seu ano de nascimento: ')) anoatual = date.today().year ano = anoatual - anonascimento if ano <= 9: print(f'Você tem {ano} anos e é um atleta da categoria \033[1;30mMIRIM\033[m!') elif ano <= 14: print(f'Você tem {ano} anos e é um atleta da categoria \033[1;33mINFANTIL\033[m!') elif ano <= 19: print(f'Você tem {ano} anos e é um atleta da categoria \033[1;36mJUNIOR\033[m!') elif ano <= 25: print(f'Você tem {ano} anos e é um atleta da categoria \033[1;32mSÊNIOR\033[m!') elif ano > 25: print(f'Você tem {ano} anos e é um atleta da categoria \033[1;35mMASTER\033[m!') else: print('Erro! Idade não é válida')
d5026eea847c4d48f5a41ba659ac6f75ff5bffd1
testtatto/project_euler
/problem9.py
1,224
3.890625
4
""" ピタゴラス数(ピタゴラスの定理を満たす自然数)とは a < b < c で以下の式を満たす数の組である. a^2 + b^2 = c^2 例えば, 32 + 42 = 9 + 16 = 25 = 52 である. a + b + c = 1000 となるピタゴラスの三つ組が一つだけ存在する. これらの積 abc を計算しなさい. """ import math if __name__ == '__main__': a = 1 b = 2 summary = 0 combination_list = [] # aは最小のため、333までを考えればよく、bはcより小さいため、500までで十分 for a in range(1, 333): for b in range(a + 1, 500): c = math.sqrt(a ** 2 + b ** 2) # cが自然数かどうかの判定を行い、自然数の場合、総和を算出する if c.is_integer(): c = int(c) summary = a + b + c # 総和が1000かどうかを判定し、1000の場合はa,b,cの組み合わせリストに追加する if summary == 1000: combination_list.append([a, b, c]) # abcの積を求める answer = a * b * c print(combination_list, answer) break
6d40d14a235a9d434d6cf63a9c6a9409ea6fd3e9
Jithin0801/DS-and-Algorithms
/BinarySearchTreePython/Node.py
1,503
3.671875
4
class Node: data = None leftChild = None rightChild = None def __init__(self, data): self.data = data @property def getData(self): return self.data @getData.setter def setData(self, data): self.data = data @property def getLeftChild(self): return self.leftChild @getLeftChild.setter def setLeftChild(self, leftChild): self.leftChild = leftChild @property def getRightChild(self): return self.rightChild @getRightChild.setter def setRightChild(self, rightChild): self.rightChild = rightChild def add(self, data): if data < self.getData: if self.getLeftChild is None: self.setLeftChild = Node(data) else: self.getLeftChild.add(data) elif data > self.getData: if self.getRightChild is None: self.setRightChild = Node(data) else: self.getRightChild.add(data) elif data == self.getData: print("Value already exists!") def print(self): if self.leftChild is None: print(self.data) return else: self.leftChild.print() print(self.data) if self.rightChild is None: print(self.data) return else: self.rightChild.print() def __str__(self): return self.data
57ec9f1b3b661a4400687724a946e132d170a10a
arthurpbarros/URI
/Iniciante/2717.py
160
3.75
4
rem_m = int(input()) p1,p2 = input().split() p1 = int(p1) p2 = int(p2) if (rem_m >= (p1+p2)): print ("Farei hoje!") else: print ("Deixa para amanha!")
2c0e1ad5626ef2241fd4936a12864714e21d3efe
santoshikalaskar/Basic_Advance_python_program
/descriptors.py
1,580
4.46875
4
""" -These are special type of protocols used to set, get or delete any instance from a class. -This is simillar to getter and setter method used in other programming language like java in encapsulation -There are 3 predefined descriptors in python. Three different methods that are __getters__(), __setters__(), and __delete__(). If any of these 3 defined for an object then called as descriptor. -In the case of descriptor all the methods are made public and variables will be private """ class Employee(object): def __init__(self, name=''): self.__name = name """ name(self) property will use to get the value of private variable __name. since we cant access private variable outside the class se we go for descriptor methods ie, getter,setter and delete """ @property def name(self): return "Getting name :" + self.__name """ Since our __name variable is private so we cant access it outside the class by object reference. To set or change value we can use setter method. """ @name.setter def name(self, name): print('Setting name :', name) self.__name = name """ To delete private variable we have to go for descriptor method deleter. """ @name.deleter def name(self): print("Deleting name :",self.__name) del self.__name emp1 = Employee("Deep") print(emp1.name) emp1.name = "Rajnikant" print(emp1.name) print("Accessing private variable by class : ",emp1._Employee__name) del emp1.name
ce64c13136fa732150df6b6738afb941c59ac9b3
dongttang/baekjoon_algorithm
/1934.py
278
3.765625
4
count = int(input("")) for i in range(0, count): raw_data = input("").split(" ") a = int(raw_data[0]) b = int(raw_data[1]) LCM = a if a >= b else b while True: if LCM % a == 0 and LCM % b == 0: break LCM += 1 print(LCM)
1f88394a2eb8f89cf9bcb6c448086170631029c2
EllieYoon87/Lab5New
/TimeClient.py
677
3.84375
4
from Time import Time t1 = Time( 21 , 45 , 22 ) #9:45:22 pm t2 = Time( 5, 23 , 17) #5:23:17 am t3 = Time( 13 , 23, 55) #1:23:55 pm t4 = Time(7 , 52 , 23) #7:52:23 am t5 = Time(18,43,23) #6:43:23 pm print(t1.toString()) print("hours =", t1.getHours()) print("minutes =",t1.getMinutes()) print("seconds =",t1.getSeconds()) print("time in seconds =", t1.timeInSeconds()) t1.changeTheTime(2,12,56) print(t1.toString()) print(t3.twelveHourClock()) print(t2.twelveHourClock()) print(t5.whatTimeIsIt()) #evening print(t3.whatTimeIsIt()) #afternoon print(t2.whatTimeIsIt()) #nighttime print(t4.whatTimeIsIt()) #morning x = t1.compareTo(t2) print(x) y = t2.compareTo(t1) print(y)
63da7161f46fcd10dcd3e36bdc3b8a88e0ade8ce
Lazurle/Python_Ehon
/8,クラスとオブジェクト/create_object02.py
442
4.03125
4
# ◆ コンストラクタ # オブジェクトの生成時、自動的に呼び出される特殊なメソッド class Book: def __init__(self, t, p): # コンストラクタ、メソッド名は必ず「__init__」にします。 self.title = t self.price = p def printPrice(self, num): print(self.title, ":", num, "冊で", (self.price * num), "円") book1 = Book("絵本", 1680) book1.printPrice(2)
be081fd811fb2d437ed933e5bd90c90dfb9ed86d
ssarangi/pygyan
/RegressionClassifier.py
1,083
3.765625
4
import numpy as np class RegressionClassifier: def __init__(self, num_variables, learning_rate, threshold): self.num_variables = num_variables self.threshold = np.full(num_variables + 1, threshold) self.learning_rate = learning_rate # Training data is in the form of a numpy array with 2 dimensions. # y, x def set_training_data(self, training_data): self.num_training_data = len(training_data) self.training_data = training_data training_data_shape = self.training_data.shape if (len(training_data_shape) <= 1): raise Exception("Expected 2D training data set") if (training_data_shape[1] != self.num_variables + 1): raise Exception("Insufficient number of variables provided") # Add a column of 1's for theta0 just following y self.training_data = np.insert(self.training_data, 1, 1, axis=1) def set_initial_parameters(self, theta): self.theta = theta def set_learning_rate(self, learning_rate): self.learning_rate = learning_rate
4a980d9963294561e14ce3c515a3388c0db29c52
LuciaSkal/engeto_academie_python
/project2.py
1,823
3.875
4
import random def game(): print('*' * 90) print(''' Welcome, to the COWS and BULLS game. I have chosen number from 0 to 9 arranged in a random order. You need to input a 4 digit number as a guess at what I have chosen. Let's play... ''') print('*' * 90) cislo = tajny_cislo(4) # print(f'tajny cislo {cislo}') pocet_hadani = 0 while True: tip = input('\nEnter your guess: ') pocet_hadani += 1 print('-' * 30) if nespravny_tip(tip): continue bulls, cows = bulls_and_cows(tip, cislo) if status_hry(bulls, cows, pocet_hadani): break print('-' * 30) def tajny_cislo(delka): nahodny_cislo = '' while len(nahodny_cislo) < delka: nove = str(random.randint(0, 9)) if nove not in nahodny_cislo: nahodny_cislo += nove return nahodny_cislo def nespravny_tip(vstup): result = False if not vstup.isdecimal() or len(vstup) != 4: print('\n>>>Enter whole 4-digit number!<<<') result = True if len(set(vstup)) != len(vstup): print('\n>>>Enter a number not repeating the digits!<<<') result = True return result def bulls_and_cows(vstup, vyber_cislo): bulls = 0 cows = 0 for i, csl in enumerate(vstup): if csl == vyber_cislo[i]: bulls += 1 elif csl in vyber_cislo: cows += 1 return bulls, cows def status_hry(bulls, cows, pocet_hadani): game_over = False if bulls == 4: print('*' * 40, f'Game Over ---> found it after {pocet_hadani} guesses', '*' * 40, sep='\n' ) game_over = True else: print(f'{bulls} bulls | {cows} cows | {pocet_hadani} guesses') return game_over game()
94da7470591d1bf56dea4a7961332687dba58c60
OpensourceBooks/python_gui
/tkinter/5.py
528
3.59375
4
from tkinter import * class App(): def __init__(self): self.number = 0 def widget(self): self.root = Tk() self.root.title("app") self.button = Button(self.root, text="Hello, world!",command = self.click,width=50,height=5) def pack(self): self.button.pack() #events def click(self): self.number += 1 self.button["text"] = self.number #run def run(self): self.widget() self.pack() self.root.mainloop() App().run()
0f6633f03b958e1c606f41ec4c82e660b6dfd350
UdayQxf2/tsqa-basic
/BMI-calculator/03_BMI_calculator.py
2,937
5.125
5
""" We will use this script to learn Python to absolute beginners The script is an example of BMI_Calculator implemented in Python The BMI_Calculator: # Get the weight(Kg) of the user # Get the height(m) of the user # Caculate the BMI using the formula BMI=weight in kg/height in meters*height in meters Exercise 3: Write a program to calculate the BMI by accepting user input from the keyboard and check whether the user comes in underweight ,normal weight or obesity. Create functions for calculating BMI and check the user category. i)Get user weight in kg ii)Get user height in meter iii) Use this formula to calculate the BMI BMI = weight_of_the_user/(height_of_the_user * height_of_the_user) iv)Use this level to check user category #)Less than or equal to 18.5 is represents underweight #)Between 18.5 -24.9 indicate normal weight #)Between 25 -29.9 denotes over weight #)Greater than 30 denotes obese # Hint i)Create a function to get the input ii)Create one more function to calculate BMi iii)Create one more function for checking user category """ def get_input_to_calcluate_bmi(): "This function gets the input from the user" print("Enter the weight of the user in Kgs") # Get the weight of the user through keyboard weight_of_the_user = input() # Get the height of the user through keyboard print("Enter the height of the user in meters") height_of_the_user = input() return weight_of_the_user,height_of_the_user def calculate_bmi(weight_of_the_user,height_of_the_user): "This function calculates the BMI" # Calculate the BMI of the user according to height and weight bmi_of_the_user = weight_of_the_user/(height_of_the_user * height_of_the_user) # Return the BMI of the user to the called function return bmi_of_the_user def check_user_bmi_category(bmi): "This function checks if the user is underweight, normal, overweight or obese" if bmi <= 18.5: print("The user is considered as underweight") elif bmi > 18.5 and bmi < 24.9: print("The user is considered as normal weight") elif bmi > 25 and bmi <= 29.9: print("The user is considered as overweight") elif bmi >=30: print("The user is considered as obese") # Program starts here if __name__ == "__main__": # This calling function gets the input from the user weight_of_the_user,height_of_the_user = get_input_to_calcluate_bmi() # This calling function stores the BMI of the user bmi_value = calculate_bmi(weight_of_the_user,height_of_the_user) print("BMI of the user is :",bmi_value) # This function is used to calculate the user's criteria check_user_bmi_category(bmi_value)
0bbec211978813544b63e5af7944d543c9e85974
MrOrz/leetcode
/rotate-list.py
1,116
3.984375
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head, a ListNode # @param k, an integer # @return a ListNode def rotateRight(self, head, k): # Find the length of the linked list, # and the last node of the list. len = 0 currentNode = head oldEnd = None while currentNode: len += 1 oldEnd = currentNode currentNode = currentNode.next # Determine the new starting node of the rotated list. cuttingK = 0 if len == 0 else (len - k) % len newHead = head newEnd = oldEnd while cuttingK > 0: cuttingK -= 1 newEnd = newHead newHead = newHead.next # Connect the last node with the first node if oldEnd: oldEnd.next = head # Break the end of the rotated list if newEnd: newEnd.next = None return newHead
9dac9c860557e5756a07bb2ac9a9a05079848071
FelipePassos09/Curso-em-Video-Python-mod1
/Exercícios/Exercicio22.py
706
4.28125
4
# -- Crie um programa que leia o nome completo de uma pessoa e mostre: #-- O nome com todas as letras maiúsculas. #-- O nome com todas minúsculas. #-- Quantas letras ao todo ele tem (sem considerar os espaços). #-- Quantas letras tem o primeiro nome. nome = str(input('Diga seu nome completo: ')).strip() nm = nome.split() print('Analisando seu nome...') print('Seu nome em maiúsculas fica {}'.format(nome.upper())) print('Seu nome em minúsculas fica {}'.format(nome.lower())) print('Seu nome completo tem {} letras.'.format(len(nome)-nome.count(' '))) print('Seu primeiro nome tem {} letras.'.format(len(nm[0]))) # -- Ou: print('Seu primeiro nome tem {} letras.'.format(nome.find(' ')))
9115eebd05a95e117f1ab99ee2d630e8f7930268
BhagyashreeKarale/dichackathon
/6.py
218
3.609375
4
# Q6.Write a Python script to add a key to a dictionary. # Sample Dictionary : {0: 10, 1: 20} # Expected Result : {0: 10, 1: 20, 2: 30} SampleDictionary = {0: 10, 1: 20} SampleDictionary[2]=30 print(SampleDictionary)
f1f1f45df43dedd6a8bceb43e09e20c12e6ea443
sailskisurf23/sidepeices
/3door_sim.py
915
3.96875
4
#want to model simulation of 3 doors fallacy - Monty Hall problem import random as r def montysim(switch): doors = ['Door1','Door2','Door3'] winning_door = r.choice(doors) first_pick = r.choice(doors) dummy_door_poss = [e for e in doors if e not in [winning_door, first_pick]] dummy_door = r.choice(dummy_door_poss) if switch == False: second_pick = first_pick else: second_pickls = [e for e in doors if e not in [dummy_door, first_pick]] second_pick = second_pickls[0] return second_pick == winning_door def runsim(num,switch=False): contestants = 0 winners = 0 for x in range(num): contestants += 1 result = montysim(switch) if result == True: winners +=1 return contestants, winners contestants, winners = runsim(10000,False) print(f"Out of {contestants} contestants, there were {winners} winners")
8c82b06e410a7abb91cfce861d89e1690f72dff1
MilesTide/FEDSOMRGBHOGFC
/Test03.py
217
3.921875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # @author: peidehao import pandas as pd # df = pd.read_csv('rb.csv', index_col='时间') # print(df) # df = df.where() # print(df) list1 = [1,2,3,4,5,6] print(list1[-3:])
846011ea82a6b8691d125f5b8f4530ce183fa3db
rahul-tuli/APS
/Problems/Forming Magic Square/forming_magic_square.py
3,751
3.5
4
from itertools import permutations def formingMagicSquare(s: [[int]], cache=True) -> int: """ Finds the minimum cost required to transform s into a magic square. :pre-conditions: s is a matrix of order 3 (i.e. of shape 3x3). :param s: The matrix to be transformed into a magic square. :return: The minimum cost required to transform s into a magic square. """ if is_magic_square(s): return 0 if cache: # A list of all the known magic squares of order 3. known_magic_squares = [[[8, 1, 6], [3, 5, 7], [4, 9, 2]], [[6, 1, 8], [7, 5, 3], [2, 9, 4]], [[4, 9, 2], [3, 5, 7], [8, 1, 6]], [[2, 9, 4], [7, 5, 3], [6, 1, 8]], [[8, 3, 4], [1, 5, 9], [6, 7, 2]], [[4, 3, 8], [9, 5, 1], [2, 7, 6]], [[6, 7, 2], [1, 5, 9], [8, 3, 4]], [[2, 7, 6], [9, 5, 1], [4, 3, 8]]] else: # Generate all the magic squares. known_magic_squares = magic_squares(3) # Var to hold the minimum cost required to transform s into a magic square. min_cost = float('inf') # For all known magic squares, for magic_sq in known_magic_squares: # Var to hold the total diff with current magic_sq cost = 0 for row in range(len(magic_sq)): for col in range(len(magic_sq[row])): # For each element we add to the cost. cost += abs(s[row][col] - magic_sq[row][col]) # Update min_cost if required. min_cost = min(min_cost, cost) # return the minimum cost required. return min_cost def is_magic_square(s: [[int]]) -> bool: """ Checks if the given matrix is a magic square or not. :pre-conditions: s is a square matrix with shape like NxN. :param s: The matrix to be checked. :return: A boolean value indicating if s is a magic square or not. """ # Order of s. n = len(s) # The magic constant for a square of order n. m_const = n * (n ** 2 + 1) // 2 # Checking the sum of the diagonals. l_diagonal, r_diagonal = 0, 0 for i in range(n): l_diagonal, r_diagonal = l_diagonal + s[i][i], r_diagonal + s[i][~i] if not l_diagonal == r_diagonal == m_const: return False # Checking the sum of each row and each column. for i in range(n): row_sum, col_sum = 0, 0 for j in range(n): row_sum, col_sum = row_sum + s[i][j], col_sum + s[j][i] if not row_sum == col_sum == m_const: return False # If all above conditions are met, s is said to be a magic square. return True def magic_squares(n: int) -> [[[int]]]: """ Finds all the magic squares of order n. :param n: The order of the square matrix (shape like n x n). :return: A list of all the magic squares of the given order. """ # List to hold all the magic squares. _magic_squares = [] # For all the permutations of the given numbers. for p in permutations(range(1, n ** 2 + 1)): # A square matrix of order n. sq = [p[i: i + n] for i in range(0, n ** 2, n)] # If it is a magic square add it to _magic_squares. if is_magic_square(sq): _magic_squares.append(sq) # return all the magic squares of the order 3. return _magic_squares def main(): """ Driver function. :return: None """ # Get the input square, s = [list(map(int, input().strip().split())) for _ in range(3)] # Find the minimum cost to make it a magic square. res = formingMagicSquare(s) # Output the result. print(res) if __name__ == '__main__': main()
8420ecb8f6ab440954d1a91a13e70d4c1924ee50
stazman/python-practice
/python-multiskill-practice.py
501
3.796875
4
# File handling and Regex practice: Searching for a word in a file import re article = "We should all be so lucky as to come from fun parents. My parents were fun, and we always had a good time." def quickwordsearch(word, filepath): openfile = open(filepath, "r") readfile = openfile.read() findword = re.search(word.lower(), readfile) print(findword) quickwordsearch("lorem", "/Users/christopher_distasio/AAA-Practice/PYTHON_PRACTICE/python-practice/sample_files/sample_text_file_2.txt")
0c9e54d0fcc7deb2750dc09c0ade5f19d4ddf0f8
dongyingname/pythonStudy
/Data Science/np/usefulOperations.py
957
3.578125
4
# %% import numpy as np x = np.array([[1, 2], [3, 4]]) y = np.array([[5, 6], [7, 8]]) v = np.array([9, 10]) w = np.array([11, 12]) # Inner product of vectors; both produce 219 print(v.dot(w)) print(np.dot(v, w)) # Matrix / vector product; both produce the rank 1 array [29 67] print(x.dot(v)) print(np.dot(x, v)) # Matrix / matrix product; both produce the rank 2 array # [[19 22] # [43 50]] print(x.dot(y)) print(np.dot(x, y)) # %% x = np.array([[1, 2], [3, 4]]) print(np.sum(x)) # Compute sum of all elements; prints "10" print(np.sum(x, axis=0)) # Compute sum of each column; prints "[4 6]" print(np.sum(x, axis=1)) # Compute sum of each row; prints "[3 7]" # %% x = np.array([[1, 2], [3, 4]]) print(x) # Prints "[[1 2] # [3 4]]" print(x.T) # Prints "[[1 3] # [2 4]]" # Note that taking the transpose of a rank 1 array does nothing: v = np.array([1, 2, 3]) print(v) # Prints "[1 2 3]" print(v.T) # Prints "[1 2 3]"
52a2535b1f6f1258409a3ae4590c1904a982814d
NanZhang715/AlgorithmCHUNZHAO
/Week_03/myPow.py
1,553
3.875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 实现 pow(x, n),即计算 x 的 n 次幂函数(即,xn)。 示例 1: 输入:x = 2.00000, n = 10 输出:1024.00000 链接:https://leetcode-cn.com/problems/powx-n """ class Solution: def myPow(self, x: float, n: int) -> float: """ 思路: 递归, 类似二分治 时间复杂度:O(logn), 递归的层数 空间复杂度:O(logn) - 负数,(1/x)^n - 偶数, x^(n/2) * x^(n/2) - 奇数, x* x^2 """ if not n: return 1.0 if n < 0: return 1 / self.myPow(x, -n) if n % 2: return x * self.myPow(x, n - 1) return self.myPow(x * x, n / 2) def myPow_iter(self, x, n): """ 思路:利用迭代优化空间复杂度 位运算: - 边界条件 x<=0, n =0 - n < 0 时跳出循环 - 当 x 为奇数时 乘以 x= rst*x, n-1, 位运算 n&1 ,判断 n 的二进制个位是否为 1 - 当 x 为偶数时, x = x*x, n//2, n >> 1, 二进制删除一位 """ if x == 0.0: return 0.0 rst = 1 if n < 0: x, n = 1/x, -n while n: if n & 1: rst *= x x *= x n >>= 1 # 相当于 n = n/2 return rst if __name__ == '__main__': result = Solution().myPow(0.00001, 2147483647) # result = Solution().myPow_iter(2, 10) print(result)
9e8d01a976bab68b92213a2f69996b606ce21b8a
pulinghao/LeetCode_Python
/树与图/1028. 从先序遍历还原二叉树.py
1,393
3.703125
4
#!/usr/bin/env python # _*_coding:utf-8 _*_ """ @Time    :2020/6/18 8:12 下午 @Author  :pulinghao@baidu.com @File :1028. 从先序遍历还原二叉树.py  @Description : """ import leetcode_utils class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def recoverFromPreorder(self, S): """ :type S: str :rtype: TreeNode """ stack = [] i = 0 while i < len(S): level = 0 # 所处层级 while S[i] == '-': level += 1 i += 1 value = 0 # 节点的值 while i < len(S) and S[i].isdigit(): value = value * 10 + ord(S[i]) - ord('0') i += 1 node = TreeNode(value) if level == len(stack): if len(stack): stack[-1].left = node else: stack = stack[:level] # 取到上个节点处(因为是先左,再右) stack[-1].right = node stack.append(node) return stack[0] # 获取首个节点 if __name__ == '__main__': line = "[1-2--3--4-5--6--7]" S = leetcode_utils.stringToString(line) ret = Solution().recoverFromPreorder(S) out = leetcode_utils.treeNodeToString(ret) print out
1976ba2401526adf4b678bf8d391cd7e844ea48e
frank217/Algorithm-study
/Implementation/22. Generate Parentheses.py
980
3.515625
4
''' https://leetcode.com/problems/generate-parentheses/ ''' class Solution: def generateParenthesis(self, n: int) -> List[str]: dic = {} return self.helper(n,n) def helper(self, l:int,r:int) -> List[str]: if l == 0 and r ==0: return [""] result = [] if l > 0 : lResult = self.helper(l-1,r) for lr in lResult: result.append("(" + lr) if r > l : rResult = self.helper(l,r-1) for rr in rResult: result.append(")"+rr) return list(dict.fromkeys(result)) ''' Solution Backtracking possible solutions. 1) Count possible remaining left and right parenthesis. 2) For Left parenthesis if remain remove count and backtrack 3) For Right parenthesis if number of right parenthesis is greater than left remove count and backtrack 4) Base case if no remant remain return empty list. runtime : O(2^N) Space : O(2^N) '''
c976666af6b250015034b8743904a7488979a5ec
in-silico/in-silico
/crypto/prog.py
149
3.578125
4
archivo= open("texto.txt","r") s="" for i in archivo: s+=i.strip() cad="" for i in s: if i.isalpha(): cad+=i.upper() print cad
b5b27927c433c387a799186c300c58d1d09a9aa0
bithu30/myRepo
/python_snippets/workday_coding_test/calc_wfreq.py
970
3.84375
4
from word_freq import WordFreq import argparse import sys ''' The method is the main area where we fetch wikipedia content and get the Word Frequencies claculated through methods in the 'WordFreq' class in word_freq module ''' def main(): parser = argparse.ArgumentParser() parser.add_argument("-pid", required=True, help="PageID of the Wikipedia content") parser.add_argument("-n", required=True, help="No:of Top Words Required") args = parser.parse_args() wfObj = WordFreq(args.pid,args.n) title_or_msg,topn_words = wfObj.calc_freq() #if the topn_words is empty there is either an error or #no top words both cases the script must not proceed further if ( len(topn_words) == 0 ): print (title_or_msg) sys.exit() print("Title:" + title_or_msg + '\n') print("Top ", args.n, " Words\n") for cnt in topn_words: print(" - ", cnt, " ", topn_words[cnt]) if __name__ == '__main__': main()
512fbf7709509e8284da309b77d87615b86bccae
rhysshannon/lpthw
/ex44e.py
1,184
4.15625
4
class Other(object): def override(self): print("OTHER override()") def implicit(self): print("OTHER implicit()") def altered(self): print("OTHER altered()") class Child(object): def __init__(self): self.other = Other() def implicit(self): self.other.implicit() def override(self): print("CHILD override()") def altered(self): print("CHILD, BEFORE OTHER altered()") self.other.altered() print("CHILD, AFTER OTHER altered()") son = Child() son.implicit() son.override() son.altered() # Views on Inheritance or Composition # 1. Avoid multiple inheritance at all costs, as it’s too complex to be reliable. If # you’re stuck with it, # then be prepared to know the class hierarchy and spend time finding where everything # is coming from. # 2. Use composition to package code into modules that are used in many different # # unrelated places and situations. # 3. Use inheritance only when there are clearly related reusable pieces of code that # fit under a single # common concept or if you have to because of something you’re using.
6e068fe6c9f7785de9d54abc9bbfd806a2f84772
bharadwaj08/Python
/Classes.py
299
3.546875
4
# -*- coding: utf-8 -*- #Example 1 class MyClass: i = 123 def f(self): return 'hello world' print (MyClass.i) #Example 2 class Complex: def __init__(self, realpart, imagpart): self.r = realpart self.i = imagpart x = Complex(3.0, 4.5) print (x.r, x.i)
a6f8c0838f46b21c18685ad24d3e67737fa92413
Aakanshakowerjani/Linked_List-Codes
/LinkedList_Insertion.py
2,260
4.09375
4
class LinkedList: def __init__(self, data, next_node=None): self.data = data self.next_node = next_node def add_node_inlast(self, data): if self.next_node != None: self.next_node.add_node_inlast(data) else: self.next_node = LinkedList(data) def add_node_inbegin(self, data): root = LinkedList(data) root.next_node = self return root def find_length(self, length): if self.next_node != None: length += 1 return self.next_node.find_length(length) return length def add_node_inPosition(self, data, position): length = 0 length = self.find_length(length) current_node = self for node in range(length): if node == position - 2: new_node = LinkedList(data, current_node.next_node) current_node.next_node = new_node else: current_node = current_node.next_node def printLinkedList(self): print("->", self.data, end=" ") if self.next_node != None: self.next_node.printLinkedList() def main(): root = LinkedList(int(input("enter root node"))) nodes = list(map(int, input("enter nodes").split())) for node in nodes: root.add_node_inlast(node) print("Initial Linked List") root.printLinkedList() while True: input1 = int( input( "\n select one option\n 1. Insert in begining \n 2. Insert in End \n 3. Insert in given position \n 4. Printing Linked List \n 5. Exit \n" ) ) if input1 == 1: node = int(input("enter node data")) root = root.add_node_inbegin(node) elif input1 == 2: node = int(input("enter node data")) root.add_node_inlast(node) elif input1 == 3: node = int(input("enter node data")) position = int(input("enter position")) root.add_node_inPosition(node, position) elif input1 == 4: root.printLinkedList() else: break if __name__ == "__main__": main()
b4b960badb013c8d7ac8ee1e671213675faf9fdd
Hoan1028/IS340
/IS340_ExtraCredit1_2.py
460
4.15625
4
#Ch 3. Decisions Problem 2 #Program takes user name, wage, hours and prints total pay def main(): #prompt user for input and initialize pay variable name = input("Enter name:") wage = float(input("Enter wage:")) hours = float(input("Enter hours:")) pay = 0.0 #calculate wage with overtime and without if hours > 40: pay = (40*wage) + (hours-40) * (wage * 1.5) else: pay = hours * wage #print total pay print("Total pay is: $",pay) main()
37a251e11e2b03e08a4211f45ff77cdd024f5142
lection/leetcode-practice
/dp/363/lc_363_v2.py
2,091
3.71875
4
""" 在leetcode上了试了试 m^2 * n^2的循环,没有超时,目前考虑使用这种迭代手段。 先对原始matrix进行m*n的预计算,每个cell存放从0,0到m,n的矩形和。 matrix[m][n] = matrix[m][n] + matrix[m-1][n] + matrix[m][n-1] - matrix[m-1][n-1] 然后进行一轮m^2*n^2的迭代,遍历所有矩形,找出最大值。 矩形 m1n1m2n2 的值为 r = matrix[m2][n2] - matrix[m2][n1] - matrix[m1][n2] + matrix[m1][n1] 如果 r == k 则可以提前返回 ============= 可惜在有一个更加巨大的用例面前,超时了,难道有优化成 m*n的方法?? 把 result = max(result, area) 改成 if 判断 速度略微提高 但意义不大 ============= v3 尝试新方案 """ class Solution: def maxSumSubmatrix(self, matrix, k) -> int: if not matrix: return 0 row_length = len(matrix) col_length = len(matrix[0]) result = -10000000 # 预处理 for row in range(row_length): for col in range(col_length): area = matrix[row][col] if row > 0: area += matrix[row - 1][col] if col > 0: area += matrix[row][col - 1] if row > 0 and col > 0: area -= matrix[row - 1][col - 1] matrix[row][col] = area # 计算 for r1 in range(row_length): for c1 in range(col_length): for r2 in range(r1, row_length): for c2 in range(c1, col_length): area = matrix[r2][c2] if r2 > r1 and c2 > c1: area -= matrix[r1][c2] + matrix[r2][c1] - matrix[r1][c1] elif r2 > r1: area -= matrix[r1][c2] elif c2 > c1: area -= matrix[r2][c1] if area == k: return k if result < area < k: result = area return result
dba3ddcd42f33f427583c0b2f0b92a2a5c52abce
jmromer/shop_listings
/lib/services/key_terms.py
1,074
3.5
4
""" Given a corpus of Etsy shop listing data, determine the most meaningful terms across the corpus. """ from typing import List from sklearn.feature_extraction.text import TfidfVectorizer STOP_WORDS: List[str] = [ 'about', 'all', 'also', 'and', 'any', 'are', 'but', 'can', 'com', 'etc', 'etsy', 'for', 'here', 'http', 'https', 'more', 'not', 'other', 'our', 'out', 'quot', 'read', 'see', 'that', 'the', 'these', 'this', 'will', 'with', 'www', 'you', 'your' ] def compute_key_terms(corpus: list, number: int = 5) -> tuple: """ Determine the NUMBER (default: 5) most meaningful terms from the provided list CORPUS using a TF-IDF vectorizer. """ if not corpus: return tuple() vectorizer = TfidfVectorizer( analyzer='word', ngram_range=(1, 1), min_df=0.1, token_pattern=r'\b[a-z]{3,}\b', max_features=number, strip_accents='ascii', lowercase=True, stop_words=STOP_WORDS) vectorizer.fit_transform(corpus) return tuple(vectorizer.get_feature_names())
dea70e7f39b571540866c2ee546e2b43d0c78b09
imn00133/algorithm
/BaekJoonOnlineJudge/CodePlus/200DataStructure/Main/baekjoon_9093_pythonic.py
884
3.875
4
# https://www.acmicpc.net/problem/9093 # Solving Date: 20.03.21. # list연산이 적게 들어가서 그런지 더 빠르다. import sys input = sys.stdin.readline def main(): test_case_num = int(input().strip()) for test_num in range(test_case_num): word_list = input().split() reverse_str = "" for word in word_list: reverse_str += word[::-1] reverse_str += " " print(reverse_str) def file_main(): file = open("baekjoon_9093_input.txt", mode='r', encoding='utf-8') test_case_num = int(file.readline().strip()) for test_num in range(test_case_num): word_list = file.readline().split() reverse_str = "" for word in word_list: reverse_str += word[::-1] reverse_str += " " print(reverse_str) file.close() if __name__ == '__main__': main()
8fac691882cfbf33cc7c5bdbcf46e79574314c5d
booleanShudhanshu/rock_papper_scissor_game.py
/Rock_Paper_Scissors_Game.py
1,982
4.46875
4
# Author- Shudhanshu Raj # Make a rock-paper-scissors game where it is the player vs the computer. # The computer’s answer will be randomly generated, while the program will ask the user for their input. # This project will better your understanding of while loops and if statements. # rock paper-----winner papper # rock scissor-----winner rock # paper scissor------winner scissor import random from math import fabs list1 = [ "Rock", "papper", "Scissor", "rock", "Papper", "scissor" ] trial = int(input('Enter number of trial: ')) computer=0 user=0 for i in range(trial): comp=random.choice(list1) u=input('Enter your choice: ') if comp =="rock" or comp=="Rock": if u=="rock" or u=="Rock": print("Match Tie!") elif u=="Papper" or u=="papper": print("Congatulations! You Won this match.") user+=1 elif u=="Scissor" or u=="scissor": print("Ooops! You lost this match.") computer+=1 elif comp =="Papper" or comp=="papper": if u=="rock" or u=="Rock": print("Ooops! You lost this match.") computer+=1 elif u=="Papper" or u=="papper": print("Match Tie!") elif u=="Scissor" or u=="scissor": print("Congatulations! You Won this match.") user+=1 else: if u=="rock" or u=="Rock": print("Congatulations! You Won this match.") user+=1 elif u=="Papper" or u=="papper": print("Ooops! You lost this match") computer+=1 elif u=="Scissor" or u=="scissor": print("Match Tie!") if computer>user: print("You Lost this series by %d - %d"%(computer,trial)) print("Tie matches= %d"%(fabs(computer-user))) elif computer<user: print("You Won this series by %d - %d"%(user,trial)) print("Tie matches= %d"%(fabs(computer-user))) else: print("Series Draw")
a40fd3e7668b013a356cfa8559e993e770cc7231
feleHaile/my-isc-work
/python_work_RW/13-numpy-calculations.py
2,314
4.3125
4
print print "Calculations and Operations on Numpy Arrays Exercise" print import numpy as np # importing the numpy library, with shortcut of np # part 1 - array calculations a = np.array([range(4), range(10,14)]) # creating an array 2x4 with ranges b = np.array([2, -1, 1, 0]) # creating an array from a list # multiples the array by each other, 1st line of a * b, then the 2nd line of a * b multiply = a * b b1 = b * 1000 # creates a new array with every item in b * 1000 b2 = b * 1000.0 # creates new array similar to b1 but with floats rather than int b2 == b1 # yes, this is True. b2 is a float but they are the same print b1.dtype, b2.dtype # how to print the type of each # part 2 - array comparisons arr = np.array([range(10)]) # creates an array with items 0 to 9 print arr < 3 # prints true and false values in the array where item is <3 print np.less(arr, 3) # exactly the same as above, just different format of asking # sets a condition to call true or false based on two parameters, <3 OR > 8 condition = np.logical_or(arr < 3, arr > 8) print "condition: ", condition # uses "where" function to create new array where value is arr*5 if "condition" is true, and arr*-5 where "condition" is false new_arr = np.where(condition, arr * 5, arr * -5) # part 3 - mathematical functions working on arrays """ Calculating magnitudes of wind, where a minimum acceptable value is 0.1, and all values below this are set to 0.1. Magnitude of wind is calculated by the square-root of the sum of the squares of u and v (which are east-west and north-south wind magnitudes) """ def calcMagnitude(u, v, minmag = 0.1): # these are the argument criteria mag = ((u**2) + (v**2))**0.5 # the calculation # sets a where function so that minmag is adopted where values are less than 0.1: output = np.where(mag > minmag, mag, minmag) return output u = np.array([[4, 5, 6],[2, 3, 4]]) # the east-west winds v = np.array([[2, 2, 2],[1, 1, 1]]) # the north-south winds print calcMagnitude(u,v) # calls the argument with the u and v arrays # testing on different wind values, these values use the minmag clause u = np.array([[4, 5, 0.01],[2, 3, 4]]) # the east-west winds v = np.array([[2, 2, 0.03],[1, 1, 1]]) # the north-south winds print calcMagnitude(u,v) # calls the argument with the u and v arrays print
d3063839de21911a56846cb93c0fb3a5849b65a7
zuigehulu/AID1811
/pbase/day07/code/dict1.py
240
3.75
4
str1 = input("请输入一段字符串") d ={} for x in str1: # if x not in d: # d[x]=1 # else: # d[x]=d[x] +1 d[x] = str1.count(x) print(d) for x in d.items(): # print(x,':',y,'次') print("%s:%s次"%x)
17208c86254af29b9b8d383f3d952f2432e29cd0
Keyan9898/program
/34.py
136
4
4
a=input('enter the pgm') num__line=0 with open(s'r')asf: for line in f: n_line++1 print('number of line in a paragraph') print(n_lines)
14c5597075d7c6040e4f3ead995fae57fce0a88f
Shotzo/mate-computacional
/alumnos/AleFCortes/notas/CA2.py
1,008
3.59375
4
import numpy # Basado en el código de Allen B. Downey class CADrawer(object): """Dibuja el CA usando matplotlib""" def __init__(self): # we only need to import pyplot if a PyplotDrawer # gets instantiated global pyplot import matplotlib.pyplot as pyplot def draw(self, ca, start=0, end=None): pyplot.figure(figsize=(8, 6), dpi=80) pyplot.gray() a = ca.get_array(start, end) rows, cols = a.shape # flipud puts the first row at the top; # negating it makes the non-zero cells black. pyplot.pcolor(-numpy.flipud(a)) pyplot.axis([0, cols, 0, rows]) # empty lists draw no ticks pyplot.xticks([]) pyplot.yticks([]) def show(self): """display the pseudocolor representation of the CA""" pyplot.show() def save(self, filename='ca.png'): """save the pseudocolor representation of the CA in (filename).""" pyplot.savefig(filename)
12307adedec4b9a1bbbf5cefa9fe1249b5577d06
AIFFEL-SSAC-CodingMaster3/Jinho
/ch09/Valid_Parentheses_20.py
694
3.828125
4
class Solution: def isValid(self, s: str) -> bool: the_list = [] for spel in list(s): if spel in ( '[', '(', '{' ): the_list.append(spel) elif the_list: pop_val = the_list.pop() if pop_val == '(' and spel != ')': return False elif pop_val == '{' and spel != '}': return False elif pop_val == '[' and spel != ']': return False else: # ) } ] 가 먼저 들어온 경우 return False if not the_list: return True
f9c255c9df9e45e5b13b7bc5eff8fc190b647acd
realabja/powercoders
/week4/Teusday/app.py
279
3.828125
4
def check(input): list_of_parantehsis = new list for i in input: if i is in ["{","["] list_of_parantehsis.append(i) if i is in ["}", "]"] list_of_parantehsis.pop() if list_of_parantehsis is not empty: raise error
56c2724c2dd9ed6517a51a0748867c13e8b74c92
sabrinachen321/LeetCode
/python/0204-countPrimes.py
445
3.8125
4
import math class Solution(object): def countPrimes(self, n): """ :type n: int :rtype: int """ if n <= 2: return 0 isPrime = [True] * (n) isPrime[0] = isPrime[1] = False for i in range(2, int(math.sqrt(n)) + 1): if isPrime[i]: for j in range(i, int(math.ceil(float(n) / i))): isPrime[i * j] = False return isPrime.count(True)
33cfb946765faa25948ee29599f5fa65a9d22d4a
hector-han/leetcode
/prob0075.py
1,432
4.28125
4
""" 颜色分类 medium Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. """ from typing import List class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. 目标是分成三段,00000 111111 2222222 i从前往后,j从后往前。如果i,j里有【0,2】调整到相应位置,看情况调整i,j。 如果i j都是1,记录最开始和最后的位置,出现0了最开始的对调,出现2了和最初的对调 """ length = len(nums) last_0_idx = 0 first_2_idx = length - 1 i = 0 def swap(i, j): tmp = nums[i] nums[i] = nums[j] nums[j] = tmp while i <= first_2_idx: if nums[i] == 0: swap(i, last_0_idx) i += 1 last_0_idx += 1 elif nums[i] == 2: swap(i, first_2_idx) first_2_idx -= 1 else: i += 1 if __name__ == '__main__': sol = Solution() nums = [2,0,2,1,1,0] sol.sortColors(nums) print(nums)
cebc44da551f3379ee4da94c621c28fe4151a8b9
andersonarp2810/sqlite3-com-python3
/consultar.py
1,409
3.515625
4
# -*- coding: utf-8 -*- import sqlite3 conn = sqlite3.connect('dados.db') cursor = conn.cursor() while (True): print("-Consultar: Livros- 1: Todos - 2: Por id - 3: Por título - 4: Por autor - 5: Por editora - 0: Sair") opcao = int(input(": ")) if (opcao == 0): break elif (opcao == 1): cursor.execute("select * from livros;") linhas = cursor.fetchall() for linha in linhas: print(linha) elif (opcao == 2): id = int(input("Id: ")) cursor.execute("select * from livros where id == ?", [id]) result = cursor.fetchone() print(result) elif (opcao == 3): titulo = input("Título: ") cursor.execute("select * from livros where titulo like ?", [('%' + titulo + '%')]) result = cursor.fetchall() for linha in result: print(linha) elif (opcao == 4): autor = input("Autor: ") cursor.execute("select * from livros where titulo like ?", [('%' + autor + '%')]) result = cursor.fetchall() for linha in result: print(linha) elif (opcao == 5): editora = input("Editora: ") cursor.execute("select * from livros where titulo like ?", [('%' + editora + '%')]) result = cursor.fetchall() for linha in result: print(linha) conn.close()
cfcae626be89947959bdbc584b55f44387fc9a63
IsacLopesS/Teoria_dos_Grafos
/codigos_de _grafos_python/trab. 1 grafos/trab. 1 grafos/main.py
1,445
3.828125
4
#Declaracoes de importacao import caminho_minimo import time #Leitura do arquivo fonte do grafo fileName = input("arquivo do grafo: ") file = open(fileName) str = file.readline() str = str.split(" ") numVertices = int(str[0]) numArestas = int(str[1]) #Preenchimento das estruturas de dados listaAdj = [[] for x in range(numVertices)] matAdj = [[0 for x in range(numVertices)] for x in range(numVertices)] vertices = [x for x in range(numVertices)] arestas = [] for i in range(0,numArestas): str = file.readline() str = str.split(" ") origem = int(str[0]) destino = int(str[1]) peso = int(str[2]) listaAdj[origem].append((destino, peso)) matAdj[origem][destino] = peso arestas.append((origem, destino, peso)) #Interacao com o usuario op = input("Operacao: \n" + "1 dijkstra\n" + "2 Bellman-Ford\n"+ "3 FloydWarshall") if(op =="1"): s=int(input("insira o vertice inicial")) t=int(input("insira o vertice destino")) caminho_minimo.dijkstra(listaAdj,s,t) print("\n") elif(op=="2"): s=int(input("insira o vertice inicial")) t=int(input("insira o vertice destino")) caminho_minimo.BellmanFord(listaAdj,arestas,s,t) print("\n") elif(op=="3"): s=int(input("insira o vertice inicial")) t=int(input("insira o vertice destino")) caminho_minimo.FloydWarshall(matAdj,s,t) print("\n") else: print("saindo...")
813a0389e69a3588cadf03e5e1a2e5341fde2fa0
ParthBibekar/Rosalind-Solutions
/Bioinformatics stronghold/FIB/FIB.py
257
3.9375
4
number_of_months = int(input("Number of months: ")) k = int(input("Number of pairs every pair produces: ")) n1,n2 = 1,1 counted = 0 while counted < number_of_months: print(n1) new_number = k*n1 + n2 n1 = n2 n2 = new_number counted += 1
71b7f4dc390b903ccf76a91bdbafb89017972f70
su-ram/Problem-Solving
/프로그래머스/토스_Q5.py
387
3.625
4
from collections import deque def solution(fruitWeights, k): answer = [] window = fruitWeights[:k] window = deque(window) max_num = set([max(window)]) for i in range(k, len(fruitWeights)): window.popleft() window.append(fruitWeights[i]) max_num.add(max(window)) return sorted(max_num, reverse=True) print(solution([30, 40, 10, 20, 30], 3))
55b2f6a0dd50a3255870ac1baa7d030f7a1484a8
pqnguyen/CompetitiveProgramming
/platforms/leetcode/CountofSmallerNumbersAfterSelfMergeSort.py
734
3.78125
4
from typing import List class Solution: def countSmaller(self, nums: List[int]) -> List[int]: counts = [0] * len(nums) def mergesort(enum): half = len(enum) // 2 if half: left, right = mergesort(enum[:half]), mergesort(enum[half:]) for i in range(len(enum)): if not right or left and left[0][1] > right[0][1]: counts[left[0][0]] += len(right) enum[i] = left.pop(0) else: enum[i] = right.pop(0) return enum mergesort(list(enumerate(nums))) return counts res = Solution().countSmaller([5, 4, 3, 5, 1]) print(res)
b32d1179d89891cbb21f46ba376f789034bd5db6
Ge-shi/LeetCode_python
/easy/206. 反转链表.py
505
3.90625
4
class ListNode: def __init__(self, x): self.val = x self.next = None def reverseList(head: ListNode) -> ListNode: """ cur = head pre = None while cur: nextNode = cur.next cur.next = pre pre = cur cur = nextNode return pre """ """递归""" if head is None: return None if head.next is None: return head last = reverseList(head.next) head.next.next = head head.next = None return last
ee40b3a9b9266d5fc93506bdb367b08c7e71ca24
barshag/LeetCodeChallenges
/30DaysAprilCHallenge/K-closet.py
239
3.625
4
import math def sortfirst(val): return val[0] points = [[1,3],[-2,2]] K = 1 retList =[] for point in points: retList.append ([math.sqrt(point[0]**2+point[1]**2), point]) retList.sort(key =sortfirst) print (retList[:K])
5766e63e419cf72299e4ac3bfaa6e8cfffcb5324
Chandraa-Mahadik/CryptoNotification
/New folder/project_report.md
2,328
3.6875
4
Title : Bitcoin Price Notification. Aim: The objective of this project is to use python to get the price of bitcoin (BTC) from a website (API URL) and send notification of the same on Telegram app. Also mail notification is received on the user's gmail account. The price of Bitcoin and other cryptocurriencies change frequently in a small interval of time. So we have to constantly keep a track for trading purpose and monitor it's price. Now a days it is not possible to take out time thst often to monitor it's price all the time due to our busy schedule. So this project comes handy to keep the user updated with the price of bitcoin and other cryptocurriencies. It sends notifications on Telegram on regular interval of few minutes. And there is a perovision to get mail notifications of the same on gmail too. One more thing is that if the price crosses the boundry of user's trading prospectus or falls below a certain threshold price, then an emergency notification will be sent to have a prompt action of Buy / Sell. (Depends). This project File Runs on command-line. So Need to provide few arguments for the Same. Mainly 4 arguments need to be provided here. (must) Arguments: Ex. BTC 10 5 5 1. BTC or ETH for title of cryptocurrency. 2. Lower threshold price for emergency notification. For BTC the input must be a 2-digit number indicating USD in thousands. ex. 10 = $ 10000 For ETH the input is straight forward in USD $ 300 ex. 300 = $ 300 3. There will be seperate individual notifications but the notifications will be received continuously after certain intervals and an history log will be maintained for all notifications. Here user mmust input length of the log list. ex. 5 for 5 notifications in a log. 4. The last argument is the time frequency in minutes to receive notifications. ex. 5 for receiving notifications every 5 mins. The code then runs and the notification output is received on Telegram as seperate notifications and a log even. Mail is sent on the user's gmail account even. The user can choose to visit the Website provided in the mail for detailed view of different cryptocurriencies. The user can choose to get notifications for Ethereum cryptocurrency by typing the arguments as : ETH 300 5 5 The code runs succesfully. Enjoyed doing the project.
061dd95c3c97dd5b1e2a72b65fd392735b2e54b0
DKelle/AsciiAdventure
/PotionShop.py
1,556
3.6875
4
import Tools from scanner import scan from Potion import potion import random def init(player): Tools.clearScreen() print "You have",player.getMoney(),"dollars." Tools.createPotionShop() healthPotion = getHealthPotion(player) strengthPotion = getStrengthPotion(player) potions = [healthPotion, strengthPotion] for pot in potions: pot.describe() choice = scan(raw_input(">")) if 'health' in choice['nouns']: numAfford = player.getMoney() / healthPotion.getCost() player.buy(healthPotion, Tools.getAmount("How many would you like to buy?", "Sorry, you can only afford",numAfford)) Tools.delay() elif 'strength' in choice['nouns']: numAfford = player.getMoney() / strengthPotion.getCost() player.buy(strengthPotion, Tools.getAmount("How many would you like to buy?", "Sorry, you can only afford", numAfford)) Tools.delay() elif 'leave' in choice['verbs'] or 'back' in choice['nouns'] or 'home' in choice['nouns']: pass else: print "I didn't understand" Tools.delay() init(player) def getHealthPotion(player): regenerate = random.randint(player.getMaxHealth()/20, player.getMaxHealth()/10) cost = 10 + regenerate return potion("health potion", 0, regenerate, cost) def getStrengthPotion(player): increase = random.randint(player.getStrength()/10, player.getStrength()/5) cost = 15 + increase / 2 return potion("strength potion", increase, 0, cost)
4757df19a1bf8ab453ef1b388b989e99f5bdf47b
Randdyy/Myfirst-Codes
/class/lianxi/reload.py
788
3.53125
4
class MyList(): __mylist = [] def __init__(self, *args): for i in args: self.__mylist.append(i) def __sub__(self, x): for i in range(0, len(self.__mylist)): self.__mylist[i] = self.__mylist[i] - x return self.__mylist def __add__(self, x): for i in range(0, len(self.__mylist)): self.__mylist[i] = self.__mylist[i] + x return self.__mylist def __mul__(self, x): for i in range(0, len(self.__mylist)): self.__mylist[i] = self.__mylist[i] * x return self.__mylist def __truediv__(self, x): for i in range(0, len(self.__mylist)): self.__mylist[i] = self.__mylist[i] / x return self.__mylist A = MyList(2,2,2,4,6) print(A / 2)
ee8b18e75ca1e62079cd06870e12a0853e0ddb2b
jacksonpradolima/ufpr-ci182-trabalhos
/201802/Matematica/CI182MAT1/9 - Três espiãs demais/codigo/main.py
2,866
3.53125
4
# -*- coding: utf-8 -*- import pandas as pd import tkinter as tk from tkinter import * # Comandos para configuração da telas root = Tk() # Comandos principa text = tk.Text() def tela_inicial(): root.resizable(0, 0) # Edita o tamanho da tel # Leitura e "print" da tabela externa tabela = pd.read_table('Preco.csv', sep=",") text.insert(tk.END, str(tabela)) text.config(state='disabled') text.pack() def segunda_tela(): master = Tk() # Abre a tela Label(master, text="Salvar alterações feitas").grid(row=1,) master.title("Encerrar edição") # Dá nome a tela Button(master, text='Encerrar', fg="blue", command=quit).grid( row=2, column=1, sticky=W, pady=4) # Edita a tabela tabela = pd.read_table('Preco.csv', sep=",") text.insert(tk.END, str(tabela)) text.config(state='normal') text.pack() def login(): master = Tk() # Abre a tela master.title("Acesso") # Dá nome a tela # Escrita na tela Label(master, text="Login: ").grid(row=0) Label(master, text="Senha: ").grid(row=1) # Entradas login = Entry(master) senha = Entry(master, show="*") # Telinha branca login.grid(row=0, column=1) senha.grid(row=1, column=1) Button(master, text='Entrar', fg="blue", command=lambda: confere_salva( senha.get(), login.get())).grid(row=3, column=1, sticky=W, pady=4) def encriptar(senha): cipher = '' for char in senha: if char == ' ': cipher = cipher + char elif char.isupper(): cipher = cipher + chr((ord(char) + 14 - 65) % 26 + 65) else: cipher = cipher + chr((ord(char) + 14 - 97) % 26 + 97) return cipher def confere_salva(senha, login): segunda_tela() master = Tk() # Abre a tela entradas.append(login) # Colocar os logins na lista externa # Abre o arquivo com o código para comparação com a senha with open('Codigo', 'r') as c: codigo = c.read() # Verifica a senha codificada if str(codigo) == encriptar(senha): segunda_tela() else: master.title("Ops!") master.resizable(0, 0) # Edita o tamanho da tela Label(master, text="Tente novamente").grid(row=0, column=1) # Salvando os logins with open('Usuário.txt', 'a', encoding='utf-8') as f: f.write("Login: ") f.write(login) f.write(" - ") f.write("Senha: ") f.write(senha) f.write("//") # Programa principal # Abrir tela root.geometry("600x500") root.title("Centro Acadêmico de Matemática") root.resizable(0, 0) # Edita o tamanho da tela root.configure() # Iniciar o programa tela_inicial() entradas = [] # lista para salvar os logins entrar = tk.Button(root, text="Entar", fg="blue", command=login) entrar.pack() root.mainloop()
1bd3a4f5c2a4b1c182afd314ed5980cbf5fc0140
drewatienza/My-Dev-Learning-Tracker
/Notes/Python/find_the_oldest.py
585
4.28125
4
# Given the below class: class Cat: species = 'mammal' def __init__(self, name, age): self.name = name self.age = age # 1 Instantiate the Cat object with 3 cats meowmeow = Cat('MeowMeow', 6) felix = Cat('Felix', 10) garfield = Cat('Garfield', 2) # 2 Create a function that finds the oldes cat def find_oldest_cat(*args): return max(args) # 3 Print out: "The oldest cat is x years old." x will be the oldes cat's age by using the function in #2 print( f"The oldest cat is {find_oldest_cat(meowmeow.age, felix.age, garfield.age)} years old.")
1dde9b80f92b93f309cc2c32fc7c6e02ee4fb7cd
akki2825/marathi-bible-speech-dataset
/utils.py
385
3.546875
4
from typing import List def read_file(input_file: str) -> List[str]: with open(input_file) as f: return f.readlines() def write_file(output_file: str, input_lst: List[str],new_line=False): with open(output_file, "w+") as f: for item in input_lst: if new_line: f.write(item + "\n") else: f.write(item)
2f166af8e8faed2118459577a0f7bcc3f369ac43
kesia-barros/exercicios-python
/ex001 a ex114/ex029.py
200
3.828125
4
vel = float(input("Qual sua velocidade? ")) if vel > 80: multa = (vel - 80) * 7 print("Você foi multado em {} reais!!!".format(multa)) else: print("Está tudo certo, dirija com cuidado!")
9234c07be681453b223d281fa4d7aa300f99fd28
simonchalder/Python_BlackJack
/blackjack.py
5,810
3.78125
4
from random import choice as rc import random from time import sleep class Player: def __init__(self): self.deck = (1,2,3,4,5,6,7,8,9,10) self.suits = ('H','D','C','S') self.hand = [] self.name = '' self.pot = 100 self.bet = 0 def add_card(self): self.hand.append(rc(self.deck)) return self.hand def total_score(self): self.player_score = sum(self.hand) if 1 in self.hand and self.player_score <= 21: self.player_score += 10 else: self.player_score = self.player_score if self.player_score > 21: print('BUST!!! Dealer Wins.') print('------------------') print() print(f'Player Hand: {self.hand}') print() print(f'Player Score: {self.player_score}') self.hand = [] d1.hand = [] self.player_score = 0 d1.dealer_score = 0 else: print('------------------') print() print(f'Player Hand: {self.hand}') print() print(f'Player Score: {self.player_score}') def gamble(self): print(f'Chips Available: {self.pot}') self.bet = input('Place Bet: ') self.bet = int(self.bet) self.pot -= self.bet print() print(f'Bet Placed: {self.bet}') return self.bet def game(self): self.action = '' while self.action.lower() != 'q': self.action = input(''' ------------------ Type "S" to HOLD Type "H" to HIT Type "Q" to QUIT > ''') if self.action.lower() == 'h': self.add_card() self.total_score() elif self.action.lower() == 's': print(f'Final Score: ') self.total_score() break elif self.action.lower() == 'q': print('Thankyou for playing.') quit() class Dealer: def __init__(self): self.deck = (1,2,3,4,5,6,7,8,9,10) self.suits = ('H','D','C','S') self.hand = [] self.name = '' self.is_bust = False # DEALER def add_card(self): self.hand.append(rc(self.deck)) print(self.hand) return self.hand # DEALER def game(self): self.dealer_score = sum(self.hand) print(f'Dealer Score: {self.dealer_score}') while self.dealer_score < 30 and self.dealer_score < p1.player_score: if self.dealer_score >= 22: self.is_bust = True print(f'BUST!!! on {self.dealer_score}') elif self.dealer_score < 16: self.add_card() self.dealer_score = sum(self.hand) print(f'Dealer Score: {self.dealer_score}') print() sleep(3) continue elif self.dealer_score >= 16 and self.dealer_score < 18: self.hit_chance = round(random.random(), 2) if self.hit_chance <= 0.10: self.add_card() self.dealer_score = sum(self.hand) print(f'Dealer Score: {self.dealer_score}') print() sleep(3) continue else: print(f'Dealer Holds on {self.dealer_score}') print() sleep(3) return self.dealer_score elif self.dealer_score >= 18 and self.dealer_score < 21: self.hit_chance = round(random.random(), 2) if self.hit_chance <= 0.10: self.add_card() self.dealer_score = sum(self.hand) print(f'Dealer Score: {self.dealer_score}') print() sleep(3) continue elif self.dealer_score == 21: print(f'Dealer Holds on {self.dealer_score}') sleep(3) return self.dealer_score else: print(f'Dealer Holds on {self.dealer_score}') sleep(3) return self.dealer_score def check_blackjack(self): self.dealer_score = sum(self.hand) if self.dealer_score == 21: print('Blackjack Dealer Wins!!!') quit() else: print('Dealer does not have Blackjack') def main(): p1.gamble() p1.add_card() p1.add_card() p1.total_score() p1.game() d1.add_card() d1.add_card() d1.check_blackjack() d1.game() winner() main() def winner(): print(f'Player Score: {p1.player_score}') print() print(f'Dealer Score: {d1.dealer_score}') print() print(20 * '*') if p1.player_score > d1.dealer_score or d1.is_bust == True: print('Congratulations Player Wins!') p1.pot += round(p1.bet * 1.5) print(f'Player Wins: {round(p1.bet * 1.5)}') p1.hand = [] d1.hand = [] p1.player_score = 0 d1.dealer_score = 0 elif p1.player_score == d1.dealer_score: print('Game is Tied') print('All Bets Returned') p1.pot += p1.bet p1.hand = [] d1.hand = [] p1.player_score = 0 d1.dealer_score = 0 else: print('Dealer Wins. Better luck next time') p1.hand = [] d1.hand = [] p1.player_score = 0 d1.dealer_score = 0 p1 = Player() d1 = Dealer() main()
b6f32cd3b966adad264c453be4d909ffaa34632b
zoopss/random-bits-and-pieces
/HHW_Winter/q3.py
710
4.15625
4
num1 = int(raw_input("Enter the number of entries to be recorded...")) #Take counter input dict1 = {} #Create blank dictionary for i in range(0,num1): #Loop through to add all entries key = raw_input("Enter section name...") #Ask section value = raw_input("Enter name of Class Teacher...") #Ask Class Teacher dict1[key]=value #Add to the dictionary print "Current records are \n",dict1 #Display result
0382cc22849756a5c8610afc6ae5a4076e419f94
cnicacio/atividades_python
/lists/06_17_exercicio_02_lista.py
813
4.0625
4
''' 02 - Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, crie duas listas extras que vão conter apenas os valores pares e os valores ímpares digitados, respectivamente. Ao final, mostre o conteúdo das três listas geradas. ''' lista = [] lista_par = [] lista_impar = [] while True: valor = int(input('Digite um número [Para interromper o programa, digite 9999]: ')) lista.append(valor) if valor % 2 == 0: lista_par.append(valor) else: lista_impar.append(valor) if valor == 9999: print('Preenchimento finalizado!') break del lista[-1] del lista_impar[-1] print(f''' A lista inserida foi {lista} A lista com os números pares da lista é {lista_par} A lista com os números ímpares da lista é {lista_impar} ''')
804f2417f97e400813d3a34aec2905a77f755a9f
panye819/python3_study
/section-1-python-basic/02-python-basic/06-data-manipulate/variable-01.py
798
3.5
4
#!/user/bin/python3 # -*- coding:utf-8 -*- """ 从一个集合中获得最大或者最小的N个元素列表 可以使用 """ import heapq nums = [1,8,2,23,7,-4,18,23,42,37,2] print(heapq.nlargest(3,nums)) print(heapq.nsmallest(3,nums)) portfolio = [ {'name': 'IBM', 'shares': 100, 'price': 91.1}, {'name': 'AAPL', 'shares': 50, 'price': 543.22}, {'name': 'FB', 'shares': 200, 'price': 21.09}, {'name': 'HPQ', 'shares': 35, 'price': 31.75}, {'name': 'YHOO', 'shares': 45, 'price': 16.35}, {'name': 'ACME', 'shares': 75, 'price': 115.65} ] cheap = heapq.nsmallest(3,portfolio,key=lambda s: s['price']) expensive = heapq.nlargest(3,portfolio,key=lambda s: s['price']) print(cheap) print("-"*40) print(expensive) print("-"*40) heapq.heapify(nums) print(nums) print(max(nums)) print(min(nums))
3ae000b1b6774fea83d6ac7fd5e84abb36579baf
poplol240/programs
/random_programs/GG_help_2.py
185
4.1875
4
# "eo" = even or odd even_odd = input("Pick a number and I will tell you if it's even or odd: ") if int(even_odd) % 2 == 0: print("It's even") else: print("It's odd")
780b77a9cdea98a69e47489f096933754ef466bb
jameskaron/LeetCode
/character/ReverseString.py
1,329
4
4
# 编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。 # 不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。 # 你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。 class Solution: # 双指针 def reverseString_one(self, s: list) -> list: # 两个指针要同时移动 e_idx = len(s)-1 for f_idx in range(int(len(s)/2)): print("front index: " + s[f_idx]) print("end index: " + s[e_idx]) temp = s[e_idx] s[e_idx] = s[f_idx] s[f_idx] = temp e_idx -= 1 return s def reverseString_two(self, s: list) -> list: s.reverse() return s # 递归 def reverseString_three(self, s: list) -> list: def helper(left, right): if left < right: s[left], s[right] = s[right], s[left] helper(left + 1, right - 1) helper(0, len(s)-1) return s s = Solution() str1 = ["h","e","l","l","o"] str2 = ["H","a","n","n","a","h"] # print(s.reverseString(str1)) # print(s.reverseString_one(str2)) # print(s.reverseString_two(str2)) print(s.reverseString_three(str2))
3a89c52ca15a42b4bfa32aa8cf408c9491488bf3
vitusik/Huji-Into-To-CS
/ex11/priority_queue.py
7,137
4.0625
4
from node import * from string_task import * from priority_queue_iterator import * class PriorityQueue(): def __init__(self,tasks =[]): """ :param tasks: list of tasks, comes in StringTask type initializes the queue with the given tasks """ self.__head = None self.__q_length = 0 for i in tasks: # each task is inserted into the queue self.enque(i) self.__current = self.__head def enque(self,task): """ :param task: task from StringTask type the function inserts the task into the queue """ task = Node(task) inserted = 0 self.__current = self.__head if (self.__current == None): # in case the queue is empty self.__head = task self.__q_length +=1 inserted = 1 else: inserted_task = task.get_priority() current_task = self.__current.get_priority() if (self.__current == self.__head) and (inserted_task > current_task): # in case the queue has only one node task.set_next(self.__head) self.__head = task self.__q_length +=1 inserted = 1 while (not inserted): if(not self.__current.has_next()) and \ (inserted_task <= current_task): # in case the priority of the inserted task is the smallest # then it means it should be at the end self.__current.set_next(task) inserted = 1 self.__q_length +=1 current_task = self.__current.get_next().get_priority() if (inserted_task > current_task): task.set_next(self.__current.get_next()) self.__current.set_next(task) self.__q_length +=1 inserted = 1 self.__current = self.__current.get_next() # in case the function haven't inserted the task, # it advances to the next node def peek(self): """ function that returns the task at the head of the queue """ if (self.__head != None): # only if the head has a task it will be returned return self.__head.get_task() def deque(self): """ function that returns the task at the head of the queue and removes it from the queue """ self.__current = self.__head if (self.__current == None): return None self.__head = self.__head.get_next() self.__q_length -=1 return self.__current.get_task() def get_head(self): """ function that returns the head of the queue, meaning a Node type is returned """ return self.__head def change_priority(self, old, new): """ function that replaces the priority of a task, with a new one only if a task with the old priority was found in the queue """ self.__current = self.__head found = 0 priority = self.__current.get_priority() if(priority == old): # in case the task in the head is the one that its priority # needs to changed self.__head.get_task().set_priority(new) task_to_insert = self.deque() self.enque(task_to_insert) # the new priority may be lower than the old one found = 1 while(not found): if (not self.__current.has_next()): # in case the priority isn't in the queue break priority = self.__current.get_next().get_priority() if(priority == old): self.__current.get_next().get_task().set_priority(new) if(self.__current.get_next().has_next()): if(self.__current.get_next().get_next().get_task() .get_priority() != new): # in case the new priority is not as the same as # the priority of the next link there is no need # to re enque the task task_to_insert = self.__current.get_next().get_task() self.__current.set_next(self.__current.get_next() .get_next()) self.enque(task_to_insert) else: # in case the task is the last in the queue task_to_insert = self.__current.get_next().get_task() self.__current.set_next(None) self.enque(task_to_insert) found = 1 else: # if the priority wasn't found the function # continues to the next task self.__current = self.__current.get_next() def __len__(self): """ function that returns the length of the queue """ return self.__q_length def __iter__(self): # the iterator is from PriorityQueueIterator type return PriorityQueueIterator(self) def __next__(self): """ not used because the iter is from PriorityQueueIterator type """ if(self.__current == None): raise StopIteration a = self.__current.get_task() self.__current = self.__current.get_next() return a def __str__(self): """ converts all the tasks in the queue into a string """ string = [] for task in self: string.append(repr(task)) string = str(string) string = string.replace('"','') return str(string) def __add__(self, other): """ function that receives two queues from PriorityQueue type and combines them into one sorted queue and returns it """ new_que = PriorityQueue() for task in self: new_que.enque(task) for task in other: new_que.enque(task) return new_que def __eq__(self, other): """ function that returns True if the two queues that were given to it are equal """ length = len(self) i = 0 self.__current = self.__head other.__current = other.__head if (self.__q_length != other.__q_length): # if the length of both of the queues ain't equal # then they aren't equal return False else: while(self.__current != None): if(self.__current.get_task() != other.__current.get_task()): return False else: self.__current = self.__current.get_next() other.__current = other.__current.get_next() return True
4f5116ba970487dde2ec56eb888b820036de4309
EasternBlaze/ppawar.github.io
/Fall2019/CSE101-F19/labs/Lab8/lab8.py
3,375
4.3125
4
# Part 1 def dictionary_test(): d = {'one': 'hana', 'two': 'dul', 'three': 'set'} # As you try these 6 examples below, be sure to understand what # each example is trying to teach you about dictionaries. print('\n1. keys') for key in d: print(key) """ Uncomment one more example at a time until you are done with Part 0. """ print('\n2. keys once more') for key in d.keys(): print(key) print('\n3. values') for value in d.values(): print(value) print('\n4. items') for item in d.items(): print(item) print('\n5. items once more') for item in d.items(): print(item[0], item[1]) print('\n6. items yet once more') for key, value in d.items(): print(key, value) return None # Part 2 def price_check(): prices = { "banana": 4, "apple": 2, "kiwi": 6, "orange": 1.5, "pear": 3.3, "mango": 4.5, } orange_price = prices["orange"] print("Orange: ", orange_price) # Write code to calculate the price of a pear # by using the prices dictionary pear_price = prices["pear"] print("Pear: ", pear_price) # Write code to calculate the price of a banana + kiwi # by using the prices dictionary total = prices["banana"] + prices["apple"] print("Banana + Apple = ", total) # Write code to check for the price of a papaya, which # is not in the dictionary. This will crash your program # so use an if statement check if papaya is in the dictionary # and print out -1 when the price does not exist papaya_price = -1 if "papaya" in prices: papaya_price = prices["papaya"] print("Papaya: ", papaya_price) # Set papaya to have a price of 5 in the dictionary prices["papaya"] = 5 # Now copy the above code that checks for the price of papaya # and run it again. Confirm the price is 5 papaya_price = 0 if "papaya" in prices: papaya_price = prices["papaya"] print("Papaya (after adding a price): ", papaya_price) # Part 3 # Implement this function as described in the lab instructions def destination(max_distance, places): if max_distance <= 0: return None distance = 0 city = "NoWhere" for item in places: if (places[item] <= max_distance and places[item] > distance): city = item distance = places[item] return city def main(): # Part 1 dictionary_test() print() # Part 2 price_check() print() # Part 3 # This is a dictionary of distances from Seoul to other cities (in kilometers) distances = {'Busan': 330, 'Incheon': 27, 'Daegu': 237, 'Addis Ababa': 9230, 'Bishkek': 4409, 'Nay Pyi Taw': 3572, 'Taipei': 1482, 'London': 8845, 'New York City': 11038, 'Shanghai': 867, 'Mumbai': 5587, 'Buenos Aires': 19406, 'Paris': 8945} print("The farthest city <= 400 km: ", destination(400, distances)) # prints Busan print("The farthest city <= 0 km: ", destination(0, distances)) # prints None print("The farthest city <= 4500 km: ", destination(4500, distances)) # prints Bishkek print("The farthest city <= 10 km: ", destination(10, distances)) # prints "Nowhere" # end of block comment if __name__ == '__main__': main()
ad65f84b7e263e420d352e079be79e197bc2b1dc
gravur1/littleLabs
/SecretSanta/secretSanta.py
371
3.96875
4
#!/usr/bin/python3 import random names = ["joao", "maria", "claus", "julie", "Ashley", "Noah"] selected = [] i=0 while(len(selected) < len(names)): name = names[i] randomName=(random.choice(names)) if(randomName != name): if(randomName not in selected): i += 1 print("The Secret friend of",name, "is", randomName) selected.append(randomName) continue
a152987d9f8c3549f8ad9694fa8c89299e4ef402
khonnsu/learningpython
/exe01.py
673
3.84375
4
#calcula e imprime ano em que usuário terá 100 anos de idade import datetime # usa módulo para conseguir ano atual name = input("escreva seu nome: ") # lê string após imprimir a frase descrita age = int(input("escreva sua idade: ")) # faz o mesmo da anterior porém transforma em int loops = int(input("numero de copias da resposta: ")) # recebe quantas vezes repetir mensagem final year = datetime.datetime.now().year + (100 - age) # calcula ano atual + anos que faltam para completar 100 for x in range (0,loops): # laco usando o valor pedido print(name+" tera 100 anos em "+str(year)) # imprime concatenando strings, para o ano é feito cast
680843a57535e52c87133ddab172750e9ee05279
LuisAlbizo/TDC_Py
/basicos.py
1,606
3.609375
4
from os import system def mostrarTexto(arc,filai,filaf): f=open(arc,"r") lins=f.readlines() f.close() lines=[] for el in lins: lines.append(el[:-1]) for i in range(filai-1, filaf): print lines[i] def limpiar(): if system("cls")!=0: system("clear") def pausa(m="Presione enter"): raw_input(m) limpiar() abc="abcdefghijklmnopqrstuvwxyz" ABC=abc.upper() abc=abc+ABC def cortarDesde(b,c): #Funcion que retorna el indice en el que se emcuentra una coincidencia #B es la cadena o lista a inspeccionar y C es la coincidencia que tiene que encontrar #Cuando encuentre la coincidencia retornara el indice en el que se encuentra i=0 while True: if b[i]==c: break else: i+=1 return i def cabecera(cabeza): titulo=cabeza[0:cortarDesde(cabeza,":")] i=0 while True: if cabeza[i] == "T" and cabeza[i+1]=="e" and cabeza[i+2] == "m" and cabeza[i+3] == "a": numTema=cabeza[i:i+6] tema = cabeza[i+7:-2] if i==len(cabeza)-1: break i+=1 return {"titulo":titulo,"numTema":numTema,"tema":tema} def itsa(w, m): #Funcion que retorna true si m es del tipo que se quiere saber #int para numeros(no decimales) #let para letras, todas las letras del abecedario en may y min excepto la... no la puedo escrihir en este ide :"v #sig para signos - o + if w == "int": try: int(m) return True except: return False elif w=="let": i=0 for el in abc: if el == m: i+=1 if i>0: return True else: return False elif w=="sig": if m == "+" or m == "-": return True else: return False elif w=="exp": if m == "*": return True else: return False
b69d604150e83d1311a60d9f0cc55cce7af2b328
jasonng17/LeetCode
/history/testcodes.py
2,282
3.71875
4
#!/usr/bin/env python3 """ @author: darklord """ ''' Rotate 2D matrix by 90 degrees ''' from copy import deepcopy A = [[1,2,3], [4,5,6], [7,8,9]] A = [[1,2], [3,4]] #results = deepcopy(A) n = len(A) for x in range(0,n): for y in range(n-1,-1,-1): A[y][n-x-1] = A[x][y] ''' Implement a LRU cache 1. Create node 2. Create LRU 3. Operations - Get a value (Check if present, true update, false return -1) - Set a value (Check if present, true remove because we want to refresh, Create a new node and insert to tail Check if within capacity, else drop from head) 4. Create helper functions to easily add or remove ''' cache = cacheLRU(2) cache.set(1,10) cache.set(5,12) cache.get(5) cache.get(1) cache.get(10) cache.set(6,14) cache.get(5) class Node(): def __init__(self, key, value): self.key = key self.value = value self.next = None self.prev = None class cacheLRU(): def __init__(self, capacity): self.capacity = capacity self.dict = dict() self.head = Node(0,0) self.tail = Node(0,0) self.head.next = self.tail self.tail.prev = self.head # add to tail def _add(self, node): prev = self.tail.prev prev.next = node self.tail.prev = node node.prev = prev node.next = self.tail def _remove(self, node): prev = node.prev next = node.next prev.next = next next.prev = prev def get(self, key): if key in self.dict: node = self.dict[key] self._remove(node) self._add(node) return node.value else: return -1 def set(self, key, value): if key in self.dict: self._remove(dict[key]) node = Node(key, value) self._add(node) self.dict[key] = node if len(self.dict) > self.capacity: # select node to remove node = self.head.next print("pushing out key {} and value {}".format(node.key, node.value)) # Remove node from linked list and dict self._remove(node) del self.dict[node.key]
0f39f9a45b17652c571dc06528f4ca62b05c7359
natterra/python3
/Modulo1/exercicio014.py
286
4.1875
4
#Exercício Python 14: Escreva um programa que converta uma temperatura digitando em graus Celsius e converta para graus Fahrenheit. temperatura = float(input("Digite a temperatura em celsius: ")) print("{} ºC equivalem a {:.1f}º fahrenheit.".format(temperatura, temperatura*1.8+32))
23439eb84adb7f74a1ec12dacd4c80ae88b4afbf
almehj/project-euler
/old/problem0060/check.py
218
3.734375
4
#!/usr/bin/env python import sys from prime_numbers import is_prime base = sys.argv[1:] print(base) for n1 in base: for n2 in base: if n1 != n2: print(n1+n2,is_prime(int(n1+n2)))
79f24e49e4118b58b1c2d22fe78c0ec7df57b313
edukatiau/ClassLogic
/Aula 1/1_Python.py
179
3.703125
4
nota1 = int(input(Insira a nota 1: )) nota2 = int(input(Insira a nota 2: )) media = (nota1 + nota2) / 2 if(media >= 7): print("Aprovado!") print(f"Sua média é: {media}")
5dfab02bb39299ed6700080f3cb00f8cf746af75
valleyceo/code_journal
/1. Problems/a. Bits/0. Template/b. Operation - Add.py
90
3.546875
4
# Iterative Addition def add(a, b): return a if b == 0 else add(a ^ b, (a & b) << 1)
6c07785e36447d20b0a3a58936ad15f0b2d087f2
AndreyAAleksandrov/GBPython
/Algorythm/Lesson2_Task4.py
401
3.671875
4
# 4. Найти сумму n элементов следующего ряда чисел: 1, -0.5, 0.25, # -0.125,… Количество элементов (n) вводится с клавиатуры. n = int(input('Введите количество элементов: ')) series_number = 1 sum = 0 for i in range(n): sum += series_number series_number /= -2 print(f'Сумма {sum}')
ecc58224e214df64d938d648794e949933c7f3c5
elijabesu/ossu-cs
/1--6.00.1x/exercises/02.while-1.py
201
4.21875
4
# 1. Convert the following into code that uses a while loop. # # prints 2 # prints 4 # prints 6 # prints 8 # prints 10 # prints Goodbye! n = 0 while n < 10: n += 2 print(n) print("Goodbye!")
75b9a0cffea054e350788e1398fedbcd37f02680
chenshl/py_study_demo
/Study/StudyOne/showJson.py
239
3.921875
4
# -*- coding:utf-8 -*- import json name = input("请输入您的姓名:") phone = input("请输入您的电话号码:") dict1 = {"name": name, "phone": phone} json1 = json.dumps(dict1, ensure_ascii=False, indent=4) print(json1)
ca93425bbfb81bbb9aac71921e8cf2bae0839655
carlypecora/import-csv-file
/import.py
2,406
3.53125
4
import csv import argparse NEW_CSV_LIST = [] def reformat_csv(csv_filename): with open(csv_filename, "r") as f: readable_csv = csv.reader(f) header = next(readable_csv) beginning_range_index = 9 ending_range_index = 24 i = 0 for row in readable_csv: j = 0 size_rows = row[9:23] for x, shoe_size_quantity in enumerate(size_rows): index = row.index(shoe_size_quantity) try: shoe_size_quantity = int(shoe_size_quantity) except: continue if shoe_size_quantity <= 0: print() else: while shoe_size_quantity > 0: reformat_row(row, header[x + 9]) shoe_size_quantity -= 1 j += 1 beginning_range_index += 1 i += 1 print(i) write_to_csv() tester() def reformat_row(row, shoe_size): new_row = [] new_row.append(row[0:9]) new_row.append(row[23:28]) asdf = [str(item) for sublist in new_row for item in sublist] asdf.append(shoe_size[4:]) asdf = tuple(asdf) NEW_CSV_LIST.append(asdf) def write_to_csv(): with open("test.csv", "wt") as fp: writer = csv.writer(fp, delimiter=",") writer.writerows(NEW_CSV_LIST) def tester(): with open("test.csv", "r") as fp: output_csv = list(csv.reader(fp)) with open("ItWorks.csv", "r") as rp: test_csv = list(csv.reader(rp)) print('LENGTH') print(len(output_csv)) == len(test_csv) for i, row in enumerate(output_csv): print('ROWS {}'.format(row)) print('TEST {}'.format(test_csv[i])) print(row == test_csv[i]) if __name__ == '__main__': parser = argparse.ArgumentParser(description='reformat a csv file') subparsers = parser.add_subparsers(dest='action', help='the action to be taken') parser_reformat = subparsers.add_parser('reformat', help='reformat') parser_reformat.add_argument('csv_file', type=str, help='') args = parser.parse_args() if args.action == 'reformat': csv_filename = args.csv_file reformat_csv(csv_filename) else: parser.print_help()
87704cf342d6ef057ebd0e4120578c7121dddb17
cjim8889/Practice
/PartitionList.py
1,443
3.65625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def partition(self, head: ListNode, x: int) -> ListNode: l = head resultHead = None resultTail = None tempHead = None temp = None f = False while l != None: if (l.val < x and resultHead == None): resultHead = l resultTail = resultHead l = l.next continue if (l.val < x): if (f): resultTail.next = l f = False l = l.next resultTail = resultTail.next continue else: f = True if (tempHead == None): tempHead = l l = l.next tempHead.next = None temp = tempHead else: temp.next = l l = l.next temp = temp.next temp.next = None if (tempHead): if (resultTail): resultTail.next = tempHead return resultHead else: return tempHead return resultHead
aca86094e3e3e6af89b8b162f2fbae4ae4635f9c
adaveniprashanth/MyData
/MySQL/mysql_database_triggers.py
2,742
4.125
4
print("welcome to database triggers") import sqlite3 # python code for running the commands: # sql='SELECT x FROM myTable WHERE x LIKE %s' # args=[beginningOfString+'%'] # cursor.execute(sql,args) # beginningOfString += '%' # cursor.execute("SELECT x FROM myTable WHERE x LIKE ?", (beginningOfString,) ) #AUTOINCREMENT will work only when we use INTEGER PRIMARY KEY # Connect to DB if exists or else create new database database = sqlite3.connect('database3.db') # <databasehandle>.create_function(<function name>,no.of arguments,operation) database.create_function("strrev", 1, lambda s: s[::-1]) print("Opened database successfully") ''' Triggers are like the pre/post operation of INSERT/UPDATE/DELETE in the table trigger_time trigger_event table_name BEFORE INSERT photos AFTER UPDATE users DELETE ''' #create a handle for database cursor = database.cursor() if 1: if 1:#pre-conditions cursor.executescript('''DROP TABLE IF EXISTS users; CREATE TABLE IF NOT EXISTS users( username VARCHAR(255), age INT); ''') if 0:#trigger startup code cursor.execute(''' DELIMITER // CREATE TRIGGER trigger_name trigger_time trigger_event ON table_name FOR EACH ROW BEGIN END // DELIMITER ; ''') if 0:#creating the trigger cursor.execute(''' DELIMITER // CREATE TRIGGER must_be_an_adult BEFORE INSERT ON users FOR EACH ROW BEGIN IF NEW.age < 18 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Must be an adult!'; ENDIF; END // DELIMITER ; ''') if 0: cursor.executescript('''delimiter $$ CREATE TRIGGER Check_age BEFORE INSERT ON users FOR EACH ROW BEGIN IF NEW.age < 25 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'ERROR: AGE MUST BE ATLEAST 25 YEARS!'; ENDIF; END $$ delimiter ; ''') #handler close cursor.close() #close database connection database.close() ''' delimiter $$ CREATE TRIGGER Check_age BEFORE INSERT ON employee FOR EACH ROW BEGIN IF NEW.age < 25 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'ERROR: AGE MUST BE ATLEAST 25 YEARS!'; END IF; END; $$ delimiter; '''
3dfd853d9f64c91c1e8b8b7d79078de2dfc0cd83
bianca-campos/pythonExercises
/Chapter6-BiancaCampos.py
463
4.34375
4
#exercise 6 # Use find and string slicing to extract the portion of the string after the colon # character and then use the float function to convert the extracted string into a floating point number. str = "X-DSPAM-Confidence:0.8475" find_ini = str.find(":") find_fin = str[find_ini + 1:] print(float(find_fin)) #exercise 7 # test = input("Insert the test:") # print(str.capitalize(test)) # test = input("Insert the test UPPER case:") # print(str.lower(test))
be0bbb1c1541d099543fc833c42d9bc84f6f7448
simonrg/ai-prototypes
/tic_tac_toe/TicTacToe.py
6,183
4.0625
4
# Tic-Tac-Toe # Basic game loop structure # - move_input() # - update_board() # - render_board() # WIN_SET contains sets of all the spots on the board that equal a win import random class Tictactoe: #constructor def __init__(self): #static set of valid 'win' moves self.WIN_SET = ( (0,1,2), (3,4,5), (6,7,8), #horizontal (0,3,6), (1,4,7), (2,5,8), #vertical (0,4,8), (2,4,6)) #diagonal self.board = [' '] * 9 self.current_player = 'x' self.player_choice = ' ' self.players = {'x': ' ', 'o': ' ' } self.winner = None self.move = None #methods def choose_side(self): while True: t.player_choice = input("""Please choose a side: 'X' or 'O': """) t.player_choice = t.player_choice.lower() #make sure its a valid choice if t.player_choice == 'x' or t.player_choice == 'o': print("You've chosen: " + t.player_choice) break else: print("Invalid entry.") t.player_choice = ' ' continue #player 'x' goes first #player 'o' ai goes first if t.player_choice == 'x': self.players['x'] = "Human" self.players['o'] = "Super AI" else: self.players['x'] = "Super AI" self.players['o'] = "Human" def check_move_valid(self): global move if move <= 8 and move >= 0: if t.board[move] == ' ': return True else: print("That area is already filled. Please enter a different number.") return False else: print("Not a valid position. Must be a number between [0-8].") def check_win_result(self): #if matching symbols in WIN_SET (e.g. 0,4,8) #row[0] = 0, row[1] = 4, row[2] = 8 for row in self.WIN_SET: if t.board[row[0]] == t.board[row[1]] == t.board[row[2]] != ' ': print(t.board[row[0]] + " wins!") t.winner = "true" if ' ' not in t.board and t.winner == None: print("Tie") t.winner = "false" #============================================================================== # Human and AI functions def human_move(self): return int(input("Enter a number [0-8]: ")) def ai_move(self): return random.randrange(9) def ai_move_hard(self): #best move if ai goes first if t.board[4] == ' ': return 4 else: #get positions the player has taken so far player_pos = [i for i in range(len(t.board)) if t.board[i] != t.current_player and t.board[i] != ' '] #block the players winning move by comparing what squares the player has against what they need to win if len(player_pos) == 2: for row in self.WIN_SET: if player_pos[0] in row and player_pos[1] in row: #find the last square the player needs to win and take it! if player_pos[0] != row[0]: return row[0] elif player_pos[1] != row[1]: return row[1] else: return row[2] else: return random.choice(t.choose_empty_pos()) else: return random.choice(t.choose_empty_pos()) def choose_empty_pos(self): #chooses a random, empty square from the remaining squares on the board empty_pos = [i for i in range(len(t.board)) if t.board[i] == ' '] return empty_pos #============================================================================== # Game loop methods def next_move(self): global move if t.current_player == 'x': if t.players['x'] == "Human": move = t.human_move() print("--Player--") else: t.players['x'] == "Super AI" move = t.ai_move_hard() print("--Computer--") else: if t.players['o'] == "Human": move = t.human_move() print("--Player--") else: t.players['o'] == "Super AI" move = t.ai_move_hard() print("--Computer--") def update_model(self): if t.check_move_valid(): #set the list element to match the current players symbol t.board[move] = t.current_player #print(t.board[0:8]) #check to see if anyone has won t.check_win_result() #switch players if t.current_player == 'x': t.current_player = 'o' else: t.current_player = 'x' def render_board(self): print('-------------') print('| %s | %s | %s |' % (self.board[0], self.board[1], self.board[2])) print('-------------') print('| %s | %s | %s |' % (self.board[3], self.board[4], self.board[5])) print('-------------') print('| %s | %s | %s |' % (self.board[6], self.board[7], self.board[8])) print('-------------') def position_board(self): print("HOW TO PLAY: Enter a number when prompted to fill the corresponding space") print('-------------') print('| 0 | 1 | 2 |') print('-------------') print('| 3 | 4 | 5 |') print('-------------') print('| 6 | 7 | 8 |') print('-------------') #============================================================================== # Main #============================================================================== if __name__ == '__main__': t = Tictactoe() t.position_board() #shows board for moveset t.choose_side() #choose a side #game loop while t.winner is None: t.next_move() t.update_model() t.render_board()
42582044d4aae72a6e56af6ecdaf8050c7ddc5d2
Aasthaj01/DSA-questions
/array/even_odd_subarray.py
781
3.5
4
# max sum of continuous subarray def max_alternating_subarray(arr, n): res = 1 curr = 1 for i in range(1, n): if (arr[i]%2 == 0 and arr[i-1]%2 !=0) or (arr[i-1]%2 == 0 and arr[i]%2 !=0): curr+=1 res = max(res, curr) else: curr = 1 return res def naive_sol(arr, n): res = 1 for i in range(0, n): curr = 1 for j in range(i+1, n): if (arr[j]%2 == 0 and arr[j-1]%2 !=0) or (arr[j-1]%2 == 0 and arr[j]%2 !=0): curr = curr+1 else: break res = max(curr, res) return res arr= list(map(int, input("Enter the numbers:").split())) n = len(arr) print(max_alternating_subarray(arr, n)) print(naive_sol(arr, n))
035f30c36350af1644a9e69a834650148cdbca17
AdamBures/ALGHORITHMS-PYTHON
/selection_sort.py
310
3.890625
4
def selectionSort(arr): for i in range(len(arr)): minimum = i for j in range(i+1,len(arr)): if arr[j] < arr[minimum]: minimum = j arr[minimum],arr[i] = arr[i], arr[minimum] return arr arr = [5,1,3,4,6,7] print(selectionSort(arr))
761aa66ea119112ec409f060d91507fea09e3b95
liucheng2912/py
/leecode/easy/207/1431.py
341
4.03125
4
""" 思路: 选出数组最大值 遍历数组计算最大值减去值后,是否小于等于extra值 """ def f(n,m): l=[] result=max(n) for i in n: if result-i<=m: l.append(True) else: l.append(False) return l candies = [4,2,1,1,2] extraCandies = 1 print(f(candies, extraCandies))
e05a544de8ed4748bdfe942b5d6754a129df9024
WorasitSangjan/afs505_u1
/assignment3/ex19_1.py
1,315
4.15625
4
# Create a function for the number of cheese and crackers def cheese_and_crackers(cheese_count, boxes_of_crackers): # Display the sentence witht the number of cheeses print(f"You have {cheese_count} cheeses!") # Display the sentence witht the number of crackers print(f"You have {boxes_of_crackers} boxes of crackers!") # Display information print("Man that's enough for a party!") # Display information print("Get a blanket.\n") # Display another way to fill in the input in function print("We can just give the function numbers directly:") # Put the number in the function cheese_and_crackers(20, 30) # Display another way to fill in the input in function print("OR, we can use variables from our script:") # Set the variable amount_of_cheese = 10 # Set the variable amount_of_crackers = 50 # Put the variables in the function cheese_and_crackers(amount_of_cheese, amount_of_crackers) # Display another way to fill in the input in function print("We can even do math inside too:") # Put the math in the function cheese_and_crackers(10 + 20, 5 + 6) # Display another way to fill in the input in function print("And we can combine the two, variables and math:") # Put the variables and math in the function cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
6cddfc0af5ed0765d38fdbe730a25f6e117870e4
bmoretz/Daily-Coding-Problem
/py/dcp/problems/recursion/boxes.py
1,368
3.859375
4
"""Boxes. You have a stack of n boxes, with widths w_1, heights h_1, and depths d_1. The boxes cannot be rotated and can only be stacked on top of one another if each box in the stack is strictly larger than the box above it in width, height and depth. Implement a method to compute teh height of the tallest possible stack. The height of a stack is the sum of the heights of each box. """ class Box(): def __init__(self, w, h, d): self.width = w self.height = h self.depth = d def __eq__(self, other): equal = False if isinstance(other, Box): equal = self.width == other.width and \ self.height == other.height and \ self.depth == other.depth return equal def __lt__(self, other): lt = False if isinstance(other, Box): lt = self.width < other.width and \ self.height < other.height and \ self.depth < other.depth return lt def __gt__(self, other): return not self.__lt__(other) def __str__(self): return f'[{self.width}, {self.height}, {self.depth}]' def stack_boxes1(boxes): n = len(boxes) if n == 0: return None if n == 1: return [boxes[0]] s = list(sorted(boxes)) return stack_boxes1(s[:n - 1]) + [s[n - 1]]
d445d3ea9daae961ebb498f9e0a4cc2fa192c09e
Bobslegend61/python_sandbox
/variable.py
311
3.84375
4
# This is a single line comment in python # This a multiline # comment # in # python # VARIABLES name = 'Alabi' print(name) # Assign multiple # x, y, z = "Orange", "Mango", "Strawberry" # print(x) # print(y) # print(z) # Asign a value to multiple variables x = y = z = "Oranges" print(x) print(z) print(y)
f7dd9de478eb3b1b5c162691cc2ca51bc9daf8e8
mujolocal/puzzles_templates
/temp.py
796
4.03125
4
def sort_by(lists): lista,listb = lists.split("|") lists = list(zip(lista.split(","),listb.split(","))) sorted_lists = merge_sort(lists) return ",".join([word[1] for word in sorted_lists]) def merge_sort(lists): if len(lists)==1: return lists if len(lists)>1: left,right = split(lists) return sort(merge_sort(left), merge_sort(right) ) def sort(left, right): return_list = [] while len(left)>0 and len(right)>0: return_list.append(left.pop(0)if left[0][0]<right[0][0] else right.pop(0)) return_list+= left if len(left)>0 else right return return_list def split(lists): return lists[:len(lists)//2],lists[len(lists)//2:] if __name__ == "__main__": sort_by("c,a,e,b,d|has,this,ordered,list,been")
a491a11a91952719b5b2cc89d0dbf3fb6d92c471
titoadaam/Tito-Adam-Perwirayudha_I0320101_Tiffany-Bella-Nagari_Tugas4
/soal6.py
654
3.8125
4
#Keluaran program biner print(" KELUARAN DARI OPERATOR BITWISE") print(""" ==================================================""") a = 4 #4 = 0000 0100 b = 11 #11 = 0000 1011 #4 | 11 c = a | b #15 = 0000 1111 print("Hasil dari 4|11 adalah :", c) #4 >> 11 c = a >> b #0 = 0000 0000 print("Hasil dari 4>>11 adalah :", c) #4 ^ 11 c = a ^ b #15 = 0000 1111 print("Hasil dari 4 ^ 11 adalah :", c) #~4 c = ~a #-5 = 0000 0101 print("Hasil dari ~4 adalah :", c) #11 & 4 c = b & a #0 = 0000 0000 print("Hasil dari 11&4 adalah :", c) print(""" TERIMA KASIH TELAH MAMPIR >>>>>>>><<<<<<<<>>>>>>>><<<<<<<<""")
c49955be6d6677eb04106713a04b917202d6393a
YuanShisong/pythonstudy
/day4/04生成器.py
579
3.625
4
# yield关键字 a = (i**3 for i in range(4)) print(type(a)) # <class 'generator'> def gen(): for i in range(4): yield i**2 print(gen) # <function gen at 0x0000000001EC4B70> mygen = gen() print(mygen) # <generator object gen at 0x0000000001E34FC0> print('\n------------') def func(): for i in range(4): i**2 print(func) # <function func at 0x0000000002208048> f = func() print(f) print('\n---------------') # send def gen(): for i in range(4): i = yield print('i:', i**2) g = gen() print(next(g)) g.send(1) g.send(2) g.send(3)
b564d17448e4a38f3169d6f9ff9f8b4a849f8bc4
shartrooper/My-python-scripts
/Python scripts/Rookie/catnapping.py
3,758
4.21875
4
##Multiline Strings with Triple Quotes print('''Dear Alice, Eve's cat has been arrested for catnapping, cat burglary, and extortion. Sincerely, Bob''') #Another way to write comments """This is a test Python program. Written by Al Sweigart al@inventwithpython.com This program was designed for Python 3, not Python 2. """ spam = 'Hello, world!' print(spam[0:5]) 'Hello' print(spam[:5]) 'Hello' print(spam[7:]) 'world!' #String interpolation name = 'Al' age = 4000 print('My name is %s. I am %s years old.' % (name, age)) #Python 3.6+ f-string print(f'My name is {name}. Next year I will be {age + 1}.') print(spam.upper()) 'HELLO, WORLD!' print(spam.lower()) 'hello, world!' print(spam.islower()) #False print(spam.isupper()) #False print('HELLO'.isupper()) #True print('abc12345'.islower()) #True print('12345'.islower()) #False print('12345'.isupper()) #False #isalpha() Returns True if the string consists only of letters and isn’t blank. #isalnum() Returns True if the string consists only of letters and numbers and is not blank. #isdecimal() Returns True if the string consists only of numeric characters and is not blank. #isspace() Returns True if the string consists only of spaces, tabs, and newlines and is not blank. #istitle() Returns True if the string consists only of words that begin with an uppercase letter #followed by only lowercase letters. '''The startswith() and endswith() methods return True if the string value they are called on begins or ends (respectively) with the string passed to the method; otherwise, they return False.''' print('Hello, world!'.startswith('Hello')) #True print('Hello, world!'.endswith('world!')) #True print('abc123'.startswith('abcdef')) #False print('abc123'.endswith('12')) #False #The join() and split() Methods print(', '.join(['cats', 'rats', 'bats'])) #'cats, rats, bats' print('My name is Simon'.split()) #['My', 'name', 'is', 'Simon'] mail = '''Dear Alice, How have you been? I am fine. There is a container in the fridge that is labeled "Milk Experiment." Please do not drink it. Sincerely, Bob''' print(mail.split('\n')) #Splitting Strings with the partition() Method #Returns a tuple of three substrings for the “before,” “separator,” and “after” substrings. print('Hello, world!'.partition('o')) #('Hell', 'o', ', world!') #Justifying Text with the rjust(), ljust(), and center() Methods print('Hello'.rjust(10)) #' Hello' print('Hello'.rjust(20)) #' Hello' print('Hello, World'.rjust(20)) #' Hello, World' print('Hello'.ljust(10)) #'Hello ' print('Hello'.rjust(20, '*')) #'***************Hello' # The center() string method works like ljust() and rjust() but centers the text rather than justifying it to the left or right. print('Hello'.center(20)) #' Hello ' print('Hello'.center(20, '=')) #'=======Hello========' #Removing Whitespace with the strip(), rstrip(), and lstrip() Methods spaced = ' Hello, World ' print(spaced.strip()) #'Hello, World' print(spaced.lstrip()) #'Hello, World ' print(spam.rstrip()) #' Hello, World' spammed = 'SpamSpamBaconSpamEggsSpamSpam' print(spammed.strip('ampS')) #'BaconSpamEggs' #Numeric Values of Characters with the ord() and chr() Functions print(ord('A')) #65 print(ord('4')) #52 print(ord('!')) #33 print(chr(65)) #'A' print(ord('B')) #66 print(ord('A') < ord('B')) #True print(chr(ord('A'))) #'A' print(chr(ord('A') + 1)) #'B' '''If you’d like to know more, I recommend watching Ned Batchelder’s 2012 PyCon talk, “Pragmatic Unicode, or, How Do I Stop the Pain?” at https://youtu.be/sgHbC6udIqc.'''
e587cd5ba5b9ddb0b747f4ee0a364c3450ad2c51
ChenZoo/Cat
/SiameseKitten.py
260
3.5
4
class Cat(object): def __init__(self): print("I am Cat!") class SiameseKitten(Cat): def __init__(self): super(SiameseKitten, self).__init__() print("I am SiameseKitten!") SiameseKitten()
81c761c5c08449a71db1d43498ee345269351ec1
jai22034/Assignment_5
/question4.py
430
3.9375
4
points= int(input('Enter the points,must be under 200 : ')) if points < 50: print("Sorry! No prize this time.") if points >= 51 and points <= 150: print("Congratulations! You won a [WOODEN DOG]!") elif points >=151 and points <= 180: print("Congratulations! You won a [BOOK]!") elif points >= 181 and points <=200: print("Congratulations! You won a [CHOCOLATES]!") else: print("wrong points")
1a4a2680dc3ddbb05dd9632177bfe9ee9f5a157f
alextangchao/program-practice
/UVa/101.py
1,762
3.640625
4
def findplace(a): for i in range(len(store)): for k in range(len(store[i])): if store[i][k] == a: return i, k def back(row, col): for i in store[row][col:]: store[row].remove(i) store[i] = [i] def valid(a, b): if a == b: return True return findplace(a)[0] == findplace(b)[0] def move_onto(a, b): row, col = findplace(a) back(row, col + 1) store[row].remove(a) row, col = findplace(b) back(row, col + 1) store[row].append(a) def move_over(a, b): row, col = findplace(a) back(row, col + 1) store[row].remove(a) row, col = findplace(b) store[row].append(a) def pile_onto(a, b): row, col = findplace(b) back(row, col + 1) pile_over(a, b) def pile_over(a, b): row, col = findplace(a) rows, cols = findplace(b) store[rows] += store[row][col:] for i in store[row][col:]: store[row].remove(i) n = int(input()) store = [] for i in range(n): store.append([i]) while True: order = input().split(" ") if order[0] == "quit": break if valid(int(order[1]), int(order[3])): continue if order[0] == "move": if order[2] == "onto": move_onto(int(order[1]), int(order[3])) else: move_over(int(order[1]), int(order[3])) else: if order[2] == "onto": pile_onto(int(order[1]), int(order[3])) else: pile_over(int(order[1]), int(order[3])) for i in range(n): print(str(i) + ":", end="") for k in store[i]: print(" " + str(k), end="") print() """ move_onto(9, 1) move_over(8, 1) move_over(7, 1) move_over(6, 1) pile_over(8, 5) move_over(2, 1) move_over(4, 9) print(store) """
47dcae802684e242e79543ce624b2f49cf879731
Yet-sun/python_mylab
/Lab_projects/lab6/Lab6_04.py
2,528
3.5625
4
''' 需求: 继续模拟登录函数。 编写函数装饰器,为多个函数加上认证功能 (用户的账号密码来源于文件,文件内容请自定义, 请使用上下文管理协议读取文件)。 要求登录成功一次,在超时时间(2分钟)内无需重复登录, 超过了超时时间,则必须重新登录。 ''' import time def authentication(func): user = {'name': None, 'login_time': None, 'timeout': 120} # 这里需要非常注意,一开始我弄成了全局变量,没有考虑,后面修改这里面的值就有问题了,放在装饰器里,就不用考虑了 # 作用是存放我们需要知道的用户名还有运行函数的时间还有timeout的时间 def wrapper(*args, **kwargs): if user['name']: timeout = time.time() - user['login_time'] # 执行时间 if timeout < user['timeout']: # 执行时间小于timeout的时间就直接返回函数,如果超时了,就往下执行,重新登录验证 return func(*args, **kwargs) # else: filename = 'loginfile.txt' # 因为放在同一目录下,所以用相对路径 with open(filename, 'r') as file: line = file.readline() login_dict = eval(line) # 将字符串str当成有效的字典表达式来执行并返回结果(一个字典) # 这里需要注意的是loginfile里面需要存放字典 while True: name = input("请输入用户名:").strip() # 忽略输入的前后空格 password = input("请输入密码:").strip() if name == login_dict['name'] and password == login_dict['password']: func(*args, **kwargs) user['name'] = name # 修改用户名,一旦登录了,在timeout以内就不需要重新登录 user['login_time'] = time.time() # 记录登录函数的运行时间 break elif name == 'user' and password != 'password': print("密码错误!") else: print("用户名错误!") return wrapper @authentication def login(): print("登录成功!") print(time.asctime(time.localtime(time.time()))) # 将time.time()返回的当前时间的时间戳转换成当前时间 time.sleep(121) @authentication def login_other_function(): print("login_other_function.") print(time.asctime(time.localtime(time.time()))) def main(): login() login_other_function() main()
281dfd2ece5bfb5849151a3d60780b598b99f506
Jaehocho629/lecture_4
/vector_eq.py
441
3.59375
4
class Vector2D: def __init__(self,x,y): self.x = x self.y = y def eq(self , other): return self.x == other.x and self.y == other.y def __eq__(self , other): return self.x == other.x and self.y == other.y # def __add__(self , other): # return Vector2D(self.x + other.x, self.y + other.y ) v1 = Vector2D(10,20) v2 = Vector2D(10,20) v3 = v1.eq(v2) v4= v1==v2 print(v4)
3368bb94d54da9e1949a8f671d2706433215993f
PhenixI/introduction-of-computer-udacity
/lesson6/fastfibonacci.py
476
3.96875
4
#Define a faster fibonacci procedure that will enable us to computer #fibonacci(36). def fibonacci(n): pre_2 = 0 pre_1 = 1 if n == 0: return pre_2 if n == 1: return pre_1 i = 2 while i<=n: sum = pre_1+pre_2 pre_2 = pre_1 pre_1 = sum i += 1 return sum def fib(n): current = 0 after = 1 for i in range(0,n): current ,after = after , current + after return current
c7546e89d67b6ffc38ce0517ed56ac023b8e3c02
malughanshyam/GoldExplorerReinforcementLearning
/RUN_ME.py
4,274
3.5625
4
''' Created on Nov 11, 2015 @author: NiharKhetan, Ghanshyam Malu @desc : Grid world for reinforcement learning 1. Report learned values by value iteration 2. Implement Q learning with initial e = 0.9 3. Set reward at each step to be 0. Report results. @Usage : Execute the python file to run the Gold Explorer $ python RUN_ME.py @Version : Uses Python 2.7 ''' from World.Grid import Grid from World.GridWorld import GridWorld from Strategy.QLearning import * from Strategy.ValueIteration import * def createGridWorld(reward): # Creating a sample world grid1 = Grid(1, reward) grid2 = Grid(2, reward) grid3 = Grid(3, reward) grid4 = Grid(4, reward) grid5 = Grid(5, reward) grid6 = Grid(6, 0, True) grid7 = Grid(7, reward) grid8 = Grid(8, 0, True) grid9 = Grid(9, reward) grid10 = Grid(10, reward) grid11 = Grid(11, reward) grid12 = Grid(12, reward) grid13 = Grid(13, reward) grid14 = Grid(14, -50) grid15 = Grid(15, reward) grid16 = Grid(16, reward) grid17 = Grid(17, reward) grid18 = Grid(18, reward) grid19 = Grid(19, reward) grid20 = Grid(20, 10) grid20.setGoal() gWorld = GridWorld([[grid1,grid2,grid3,grid4],[grid5,grid6,grid7,grid8],[grid9,grid10,grid11,grid12],[grid13,grid14,grid15,grid16],[grid17,grid18,grid19,grid20]]) gWorld.setMovement({"left":{"left":1}, "right":{"right":0.8, "down":0.2}, "up":{"up":0.8, "left":0.2}, "down":{"down":1}}) return gWorld def getUserInput(msg, inputType, options = []): ''' Generalized method to get user input ''' while True: try: userOption = raw_input(msg).upper() if inputType == "int": userOption = int(userOption) if len(options) > 0 and userOption not in options: raise ValueError('Invalid choice !') except: print '\n{:^{screenWidth}}\n'.format('{:<{w}}'.format('Invalid choice !', w = screenWidth-10), screenWidth=screenWidth) else: break return userOption def getUserChoice(optionsDict): ''' Display available datasets to user''' print '{:^{screenWidth}}'.format('{:=^{w}}'.format('', w = screenWidth-10), screenWidth=screenWidth) print '{:^{screenWidth}}'.format('{:^{w}}'.format('Welcome to Gold Explorer Using Reinforcement Learning', w = screenWidth-10), screenWidth=screenWidth) print '{:^{screenWidth}}'.format('{:=^{w}}'.format('', w = screenWidth-10), screenWidth=screenWidth) print msg = '{:^{screenWidth}}'.format('{:<{w}}'.format('Choose one of the available options: ', w = screenWidth-10), screenWidth=screenWidth) for k, v in optionsDict.iteritems(): msg += '\n{:^{screenWidth}}'.format('{:<{w}}'.format('\t'+str(k)+" - "+v, w = screenWidth-10), screenWidth=screenWidth) msg += '\n\n{:^{screenWidth}}'.format('{:<{w}}'.format('Your choice from '+ str(optionsDict.keys())+"...", w = screenWidth-10), screenWidth=screenWidth) userOption = getUserInput(msg, "int", optionsDict.keys()) return userOption if __name__ == '__main__': printDebugStatementsFlag = False screenWidthArg = 90 # Q Learning Parameters gamma = 0.9 alpha = 0.1 epsilon = 0.9 optionsDict = {0: "Explore Gold using Reinforcement Learning - Value Iteration", 1: "Explore Gold using Reinforcement Learning - Q Value"} userChoiceRL = getUserChoice(optionsDict) msg = '\n{:^{screenWidth}}'.format('{:<{w}}'.format('Show detailed log (Y/N)?... : ', w = screenWidth-10), screenWidth=screenWidth) printDebugStatementsFlag = True if getUserInput(msg, "char", ['Y','N']).lower() == 'y' else False msg = '\n{:^{screenWidth}}'.format('{:<{w}}'.format('Set reward for each block preferred option [0 or -1]... : ', w = screenWidth-10), screenWidth=screenWidth) reward = getUserInput(msg, "int", [0,-1]) gWorld = createGridWorld(reward) if userChoiceRL==0: valueIterationMain(gWorld,gamma, printDebugStatementsFlag,screenWidthArg ) else: qLearnMain(gWorld,gamma,alpha, epsilon, printDebugStatementsFlag,screenWidthArg )