blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
bb276f9056c88373e092b9880b1b5e6c93ea2500
carlosvalgar/Apuntes
/CFGS Desarrollo de Aplicaciones Web/M03_Programación/UF2/UF2_Ejercicios_De_Prueba/Funciones.py
1,019
3.953125
4
# Función con parámetros y con return def suma1(a, *b): resultat = a for x in b: resultat += x return resultat # Función con parámetros y sin return def suma2(a, *b): resultat = a for x in b: resultat += x print(resultat) # Función sin parámetros y con return def suma3(): a = int(input("Entra el valor 'a': ")) b = int(input("Entra el valor 'b': ")) resultat = a + b return resultat # Función sin parámetros y sin return def suma4(): a = int(input("Entra el valor 'a': ")) b = int(input("Entra el valor 'b': ")) resultat = a + b print(resultat) print(suma1(1,2,3,4,5)) # *b funcion arbitraria, crea una tupla **b funcion arbitraria, crea un diccionario def doblar(num): resultado = num*2 return resultado doblar = lambda x: x*2 print(doblar(3)) impar = lambda x: x%2 == 1 print(impar(3)) lista = [-1, 2, 3, 4, 5, 6, -7, 8, -9, 10, 11] listaNegativos = list(filter(lambda x: x < 0, lista)) print(listaNegativos)
198e58c6e253ff2aa037213621308c4f96439531
HendryRoselin/100-days-of-python
/Day02/funcode2.py
462
4.15625
4
## Script for splitwise calculator print("This is Splitwise calculator") x = float(input("What was the total amount? $")) y = int(input("What percentage tip did you give? 10, 12, or 15")) z = int(input("How many people in total to divide?")) answer = (y / 100 * x + x) / z print(f"Each needs to contribute: {answer}") answer = (y / 100 * x + x) / z answer = round(answer) print(f"Each needs to contribute: {answer}") print(5 * 24) # For testing the result
9251bba080eeb88234ad34f853ff63069316640c
MrHamdulay/csc3-capstone
/examples/data/Assignment_3/nckkem001/question1.py
147
3.875
4
y=eval(input("Enter the height of the rectangle: \n")) x=eval(input("Enter the width of the rectangle: \n")) for i in range(y): print(x*"*")
e52e35d3f9160346525b3abc2846d8cc2dd99ff1
Rksseth/Python-Games
/solitaire.py
9,136
3.515625
4
''' Solitaire May 10 ''' import random from tkinter import* from tkinter import font root = Tk() root.title("Solitaire") root.geometry("700x600") root.configure(bg = "green") title = Label(root,text = "Solitaire",font = ('Algerian',20),bg='green',fg = 'white').pack() class Card(object): def __init__(self): self.val = 0 self.suit = "" self.isFlipped = 0 self.down = 0 self.up = 0 self.isRed = 0 self.c = Button(root,font = "Rockwell 10",width = 7,height = 5,bd = 2,relief = RIDGE,fg = 'white') class Game(object): def __init__(self): self.suits = ['Spades','Hearts','Clubs','Diamonds'] self.aces = [] self.deck = [] self.deckFlipped = [] self.slots = 7 self.set = [0 for x in range(0,self.slots)] self.move = 0 def setup(self): #FILL deck for suit in self.suits: for num in range(1,13): newCard = Card() newCard.suit = suit newCard.val = num newCard.c['command'] = lambda cardToMove = newCard:self.moveCard(cardToMove) if suit == 'Spades' or suit == 'Clubs': newCard.isRed = 0 else: newCard.isRed = 1 self.deck.append(newCard) #ASSIGN deck to positions in set for slot in range(0,self.slots): for unFlipped in range(0,slot): card = random.choice(self.deck) card.isFlipped = 0 self.deck.remove(card) #CASE 1 - no card in slot if not self.set[slot]: self.set[slot] = card #CASE 2 - card already in slot else: temp = self.set[slot] while temp.down: temp = temp.down temp.down = card card.up = temp #ADD A FLIPPED CARD AT THE END card2 = random.choice(self.deck) self.deck.remove(card2) card2.isFlipped = 1 #CASE 1 - no card in slot if not self.set[slot]: self.set[slot] = card2 #CASE 2 - card already in slot else: temp = self.set[slot] while temp.down: temp = temp.down temp.down = card2 card2.up = temp return True def printDeck(self): if len(self.deck) == 0: return 0 card = self.deck[0] card.isFlipped = 1 text = str(card.val)+" "+card.suit card.c['text'] = text if card.isRed: card.c['bg'] = 'red' else: card.c['bg'] = 'black' card.c.place(x = 600,y = 50) return 1 def printAces(self): count = 0 for item in self.aces: temp = item if temp: while temp.down: #print(temp.val,temp.suit,end=" ") temp = temp.down temp.c.place(x=count*50+50,y = 500) count += 1 #print() return 1 def printSet(self): for item in self.set: temp = item counter = 0 while temp: if temp.isFlipped: #print(temp.val,temp.suit,end=" ") text = str(temp.val)+"\n"+(temp.suit) if temp.isRed: temp.c['bg'] = 'red' else: temp.c['bg'] = 'grey20' else: temp.c['bg'] = 'grey' #print("XXX",end=" ") text = "" temp.c['text'] = text temp.c['command'] = lambda cardToMove = temp:self.moveCard(cardToMove) temp.c.lift() #WINDOWS VERSION #temp.c.place(x = self.set.index(item)*70+10,y = counter*30+50) #OS X 10 VERSION temp.c.place(x= self.set.index(item)*80+10,y = counter*50+50) temp = temp.down counter += 1 #print() def placeOnAces(self,card): if len(self.aces) == 0: return 0 for item in self.set: temp = item while item.down: if item.down == card: item.down = 0 return 1 item = item.down for item in self.aces: temp = item while temp.down: temp = temp.down if card.val - temp.val == 1 and card.suit == temp.suit: temp.down = card card.up = temp return 1 return 0 def placeCard(self,card): #CHECK if can placed on set for col in range(0,self.slots): item = self.set[col] if item: while item.down: item = item.down if item.val - card.val == 1 and item.isRed is not card.isRed: item.down = card card.up = item return 1 return 0 def moveCard(self,card): #CASE 0.5 - card in deck if card in self.deck: placed = self.placeCard(card) onAces = self.placeOnAces(card) if placed or onAces: return 1 self.checkDeck() return 0 #CASE 1 - card not flipped if not card.isFlipped: return False #CASE 2 - card flipped and is at bottom if not card.down: #CASE 2.1 - check if it can go onto aces if card.val == 1 and card not in self.aces: self.aces.append(card) self.flipUnFlip(card) self.printAces() return True #CASE 2.2 - check if it is an ace elif card.val == 13: for col in range(0,self.slots): if not item: self.set[col] = card self.flipUnFlip(card) self.printSet() self.printAces() return 1 #CASE 2.3 - any other card, check if it can be added else: aces = self.placeOnAces(card) if aces: self.flipUnFlip(card) self.printSet() self.printAces() return 1 for col in range(0,self.slots): item = self.set[col] if item: temp = item while temp.down: temp = temp.down if temp.val - card.val == 1 and temp.isRed is not card.isRed: temp.down = card self.flipUnFlip(card) self.printSet() self.printAces() return 1 #CASE 3 - card has cards under it else: #CASE 3.1 - card has not been selected to move for col in range(0,self.slots): item = self.set[col] if item: temp = item while temp.down: temp = temp.down if temp.val - card.val == 1 and temp.isRed is not card.isRed: temp.down = card self.flipUnFlip(card) self.printSet() return 1 return False def flipUnFlip(self,card): if card.up: upper = card.up upper.isFlipped = 1 upper.down = 0 upper.c['text'] = str(upper.val)+"\n"+upper.suit if upper.isRed: upper.c['bg'] = 'red' else: upper.c['bg'] = 'grey20' else: if card in self.set: x = self.set.index(card) self.set[x] = 0 card.c.place_forget() return 1 def checkDeck(self): for item in self.deck: if item.isFlipped: item.isFlipped = 0 self.deck.remove(item) self.deckFlipped.append(item) self.printDeck() return 1 s = Game() s.setup() s.printSet() s.printDeck()
eed4a9001b9084224e19163d84d53828f2155cd4
khaldoun11/GIZ-pass-python
/python-pass.py
672
3.890625
4
class Solution: #@staticmethod def longest_palindromic(s: str) -> str: # Create a string to store our resultant palindrome palindrome = '' # loop through the input string for i in range(len(s)): # loop backwards through the input string for j in range(len(s), i, -1): # Break if out of range if len(palindrome) >= j-i: break # Update variable if matches elif s[i:j] == s[i:j][::-1]: palindrome = s[i:j] break return palindrome print(longest_palindromic("cbbd"))
74a74dc1ab4b67102900613ad7cd6bee3096797f
JorgeGallegosMS/universe-quiz
/app.py
3,540
3.984375
4
mult_choice = "Please enter a-d as an answer" num_response = "Please enter a whole number" true_or_false = "Please enter 1 for true and 0 for false" questions_wrong = [] total_score = 0 def correct_answer(): global total_score total_score += 1 print("Correct!\n") def wrong_answer(question_number, answer): questions_wrong.append(str(question_number)) print(f"Incorrect. Correct answer: {answer}\n") def question1(): question = "1. How many minutes do sun rays take to reach earth?" answer = 8 print(f"{question} {num_response}") guess = int(input()) if guess == answer: correct_answer() else: wrong_answer(1, answer) def question2(): question = "2. How many days does it take for the moon to orbit Earth?" answer = 27 print(f"{question} {num_response}") guess = int(input()) if guess == answer: correct_answer() else: wrong_answer(2, answer) def question3(): question = "3. Which planet has the most volcanoes?" answer = "b" letters = ["a", "b", "c", "d"] choices = ["Earth", "Venus", "Jupiter", "Saturn"] print(f"{question} {mult_choice}") for index in range(len(choices)): print(f"{letters[index]} - {choices[index]}") guess = input().lower() if guess in letters: if guess == answer: correct_answer() else: wrong_answer(3, answer) else: print(f"{guess} is not a valid option. Try again\n") question3() def question4(): question = "4. What is the diameter of Earth?" answer = "c" letters = ["a", "b", "c", "d"] choices = ["3,144 miles", "9,227 miles", "7,918 miles", "4,916 miles"] print(f"{question} {mult_choice}") for index in range(len(choices)): print(f"{letters[index]} - {choices[index]}") guess = input().lower() if guess in letters: if guess == answer: correct_answer() else: wrong_answer(4, answer) else: print(f"{guess} is not a valid option. Try again\n") question4() def question5(): question = "True or False: Jupiter is the largest planet in our solar system" answer = "1" print(f"{question} - {true_or_false}") guess = input() if guess == answer: correct_answer() else: wrong_answer(5, answer) def question6(): question = "True of False: There are 1 trillion stars in the Andromeda " answer = "1" print(f"{question} - {true_or_false}") guess = input() if guess == answer: correct_answer() else: wrong_answer(6, answer) def summary(): print("Quiz Summary:") print(f"You got {total_score}/6 answers right") print(f"Questions you got wrong: {', '.join(questions_wrong)}") if total_score <= 2: print("Nice try, but you can do better") elif total_score < 4: print("You seem to know a bit about the universe") else: print("You know the universe pretty well") def universe_quiz(): print("Quiz time! Let's test your knowledge of the universe\n") question1() question2() question3() question4() question5() question6() summary() if __name__ == "__main__": playing = True while playing: universe_quiz() play_again = input("Would you like to retake this quiz? Enter y or n\n".lower()) if play_again == "y": questions_wrong = [] total_score = 0 else: playing = False
8953350f20164c344a5f13eaa635cff84edb3113
amod26/DataStructuresPython
/Binary search tree element.py
650
3.9375
4
# Given two binary search trees root1 and root2. # Return a list containing all the integers from both trees sorted in ascending order. # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]: values = [] def collect(root): if root: collect(root.left) values.append(root.val) collect(root.right) collect(root1) collect(root2) return sorted(values)
f34ad75d46185eb271e9d04d19e0ca8396246678
codershenghai/PyLeetcode
/easy/0263.ugly-number.py
584
3.828125
4
class Solution(object): def isUgly(self, num): """ :type num: int :rtype: bool """ # 将给定数字除以2、3、5(顺序无所谓),直到无法整除。 # 若结果为1,则说明所有的因子都是2或3或5,给定数字是丑数。 # 否则,给定数字不是丑数。 if num <= 0: return False for i in [2, 3, 5]: while num % i == 0: num /= i return num == 1 if __name__ == '__main__': Sol = Solution() res = Sol.isUgly(0) print(res)
f2abf358e63c8ddcf82325a579b3d251fb1bd187
claudiodacruz/listasAPE
/Lista 01/Lista1_07.py
286
3.796875
4
''' 7. Escreva um programa para calcular e exibir a média ponderada de 2 notas dadas. Sabe-se que nota1 possui peso 6 e nota2 possui peso 4 ''' N1 = float(input('Informe a Nota 1: ')) N2 = float(input('Informe a Nota 2: ')) M = (N1 * 6 + N2 * 4)/10 print('A média é =',M)
40ae1f5c165e81a9507df40e6dc49b41284e9475
B-kelly28/CIS106-Brian-Kelly
/Assignment 3/Assignment 3-2.py
237
4.4375
4
# This program will convert between Celcius and Fahrenheit print("Enter Celcius temperature:") celcius = float(input()) fahrenheit = celcius * 9 / 5 + 32 print(str(celcius) + "° Celcius is " + str(fahrenheit) + "° Fahrenheit")
ec00c1d22d002b551c7eb8f79bc218c5f441f56c
Zhoujie-SONG/Uncuffed
/Uncuffed/helpers/JSONSerializable.py
469
3.5625
4
import json from abc import ABC, abstractmethod class JSONSerializable(ABC): def to_json(self, **args) -> bytes: return json.dumps(self.to_dict(), **args).encode('utf-8') @classmethod @abstractmethod def from_json(cls, data): pass @abstractmethod def to_dict(self) -> dict: pass def __repr__(self): return self.to_json() def __str__(self): return str(self.to_json(indent=4).decode('utf-8'))
343cf71179fadd6d79120138004a652326fac1a7
brpadilha/exercicioscursoemvideo
/Desafios/Desafio 068.py
1,399
3.8125
4
#programa jogar par ou impar com o computador #o jogo para quando o jogador perder #mostrar o total de vitorias que ele conseguiu from random import randint verdade = False c=0 while not verdade: print ('--'*15) print ('Vamos brincar de par ou impar?') print ('--'*15) comp=randint(0,10) n=int(input('Qual seu número?')) soma = comp + n escolha=str(input('Par ou Impar?[P/I]: ')).upper().strip() if soma%2==0 and escolha=='P': print (f'O computador escolheu {comp}.') print (f'{comp} + {n} = {soma}') print ('Você ganhou,deu par!!') print('---'*10) print ('Vamos de novo.') c=c+1 elif soma%2!=0 and escolha=='I': print (f'O computador escolheu {comp}') print(f'{comp} + {n} = {soma}') print ('Você ganhou,deu impar!!') print ('Vamos de novo.') c=c+1 elif escolha not in 'IiPp': verdade= False elif soma%2!=0 and escolha=='P': print (f'O computador escolheu {comp}') print(f'A soma de {comp} + {n} = {soma} ') print('Deu impar') print('Você perdeu.') break elif soma%2==0 and escolha =='I': print (f'O computador escolheu {comp}') print (f'A soma de {comp} + {n} = {soma} ') print ('Deu par') print ('Você perdeu') print ('FIM') input()
6b1eede0a69825c2e9d90042da1144ec47db404c
cielavenir/checkio
/incinerator/shortest-knight-path.py
1,146
3.515625
4
between=lambda a,x,b: (a)<=(x) and (x)<=(b) x=[ [0,3,2,3,2,3,4,5], [3,4,1,2,3,4,3,4], [2,1,4,3,2,3,4,5], [3,2,3,2,3,4,3,4], [2,3,2,3,4,3,4,5], [3,4,3,4,3,4,5,4], [4,3,4,3,4,5,4,5], [5,4,5,4,5,4,5,6] ] def checkio(move): a=ord(move[0])-ord('a') b=ord(move[3])-ord('a') c=ord(move[1])-ord('1') d=ord(move[4])-ord('1') i=b-a j=d-c r=x[abs(i)][abs(j)]; if abs(i)==1 and abs(j)==1: if (between(0,a+i*2,7) and between(0,c-j,7))or(between(0,c+j*2,7) and between(0,a-i,7)): r=2 return r if __name__ == "__main__": assert checkio("b1-d5") == 2, "1st example" assert checkio("a6-b8") == 1, "2nd example" assert checkio("h1-g2") == 4, "3rd example" assert checkio("h8-d7") == 3, "4th example" assert checkio("a1-h8") == 6, "5th example" #pbpaste|zlibrawstdio -c9|zbase85rfc #import zlib,base64;exec(zlib.decompress(base64.b85decode('c-n1|(Q3mW6o#+$DZHz$3Q3x6kj*CvUL2zt32g$d+kE_~b686+4*GxJkBDk}{jqkFXSiqs1i0sVAQafUq@EGj452;-&9IjvMq|TIyvx(`XT<}HyEc<BiFJYW_q~+rULn<ah2&mEaxd=6yeO=&u`~JD&ojO3-<Ay+f!v)*X>1e|F&yB)Fw#YwDlrw&{);vWQ$$~hMQQ;Ut<s1IBPaa``jak9rFCWMEp%q`2c>M&yCxM=xMZ|6{{?M09G9n#zp~UTcoJ)XY<KjA9oI)y5KF8M#K{gLXRlvwBkmV1u75!')))
5a319e771cfc80aa47e4882e09991755cb91a67f
dbmi-pitt/DIKB-Micropublication
/scripts/mp-scripts/Bio/Mindy/SimpleSeqRecord.py
5,803
3.84375
4
"""Index a file based on information in a SeqRecord object. This indexer tries to make it simple to index a file of records (ie. like a GenBank file full of entries) so that individual records can be readily retrieved. The indexing in this file takes place by converting the elements in the file into SeqRecord objects, and then indexing by some item in these SeqRecords. This is a slower method, but is very flexible. We have two default functions to index by the id and name elements of a SeqRecord (ie. LOCUS and accession number from GenBank). There is also a base class which you can derive from to create your own indexer which allows you to index by anything you feel like using python code. """ from Bio.builders.SeqRecord.sequence import BuildSeqRecord # --- base class for indexing using SeqRecord information class BaseSeqRecordIndexer: """Base class for indexing using SeqRecord information. This is the class you should derive from to index using some type of information in a SeqRecord. This is an abstract base class, so it needs to be subclassed to be useful. """ def __init__(self): pass def get_builder(self): tricky_builder = FixDocumentBuilder(self.get_id_dictionary) return tricky_builder def primary_key_name(self): raise NotImplementedError("Please implement in derived classes") def secondary_key_names(self): raise NotImplementedError("Please implement in derived classes") def get_id_dictionary(self, seq_record): raise NotImplementedError("Please implement in derived classes") class SimpleIndexer(BaseSeqRecordIndexer): """Index a file based on .id and .name attributes of a SeqRecord. A simple-minded indexing scheme which should work for simple cases. The easiest way to use this is trhough the create_*db functions of this module. """ def __init__(self): BaseSeqRecordIndexer.__init__(self) def primary_key_name(self): return "id" def secondary_key_names(self): return ["name", "aliases"] def get_id_dictionary(self, seq_record): # XXX implement aliases once we have this attribute in SeqRecords id_info = {"id" : [seq_record.id], "name" : [seq_record.name], "aliases" : []} return id_info class FunctionIndexer(BaseSeqRecordIndexer): """Indexer to index based on values returned by a function. This class is passed a function which will return id, name and alias information from a SeqRecord object. It needs to return either one item, which is an id from the title, or three items which are (in order), the id, a list of names, and a list of aliases. This indexer allows indexing to be completely flexible based on passed functions. """ def __init__(self, index_function): BaseSeqRecordIndexer.__init__(self) self.index_function = index_function def primary_key_name(self): return "id" def secondary_key_names(self): return ["name", "aliases"] def get_id_dictionary(self, seq_record): items = self.index_function(seq_record) if type(items) is not type([]) and type(items) is not type(()): items = [items] if len(items) == 1: seq_id = items[0] name = [] aliases = [] elif len(items) == 3: seq_id, name, aliases = items else: raise ValueError("Unexpected items from index function: %s" % (items)) return {"id" : [seq_id], "name" : name, "aliases" : aliases} class FixDocumentBuilder(BuildSeqRecord): """A SAX builder-style class to make a parsed SeqRecord available. This class does a lot of trickery to make things fit in the SAX framework and still have the flexibility to use a built SeqRecord object. You shouldn't really need to use this class unless you are doing something really fancy-pants; otherwise, just use the BaseSeqRecordIndexer interfaces. """ def __init__(self, get_ids_callback): """Intialize with a callback function to gets id info from a SeqRecord. get_ids_callback should be a callable function that will take a SeqRecord object and return a dictionary mapping id names to the valid ids for these names. """ BuildSeqRecord.__init__(self) self._ids_callback = get_ids_callback def end_record(self, tag): """Overrride the builder function to muck with the document attribute. """ # first build up the SeqRecord BuildSeqRecord.end_record(self, tag) # now convert the SeqRecord into the dictionary that the indexer needs self.document = self._ids_callback(self.document) # --- convenience functions for indexing # you should just use these unless you are doing something fancy def create_berkeleydb(files, db_name, indexer = SimpleIndexer()): from Bio.Mindy import BerkeleyDB unique_name = indexer.primary_key_name() alias_names = indexer.secondary_key_names() creator = BerkeleyDB.create(db_name, unique_name, alias_names) builder = indexer.get_builder() for filename in files: creator.load(filename, builder = builder, fileid_info = {}) creator.close() def create_flatdb(files, db_name, indexer = SimpleIndexer()): from Bio.Mindy import FlatDB unique_name = indexer.primary_key_name() alias_names = indexer.secondary_key_names() creator = FlatDB.create(db_name, unique_name, alias_names) builder = indexer.get_builder() for filename in files: creator.load(filename, builder = builder, fileid_info = {}) creator.close()
39fbb698934e98118393546e977253052dce022a
VannucciS/python_from_scratch_waterloo
/exercise_11.6.5.py
1,558
4.4375
4
''' Instructions Finally, add a method is_colour such that circ_1.is_colour(col) is True if the colour of circ_1 is col and False otherwise. ''' class Circle: """Circle radius, x and y coordinates, colour Public methods: __init__: initializes a new object Attributes: radius: int or float >= 0; circle radius x: int >= 0; x-coordinate of centre y: int >= 0; y-coordinate of centre colour: string; colour of the circle """ def __init__(self, radius, x, y, colour): """Creates new circle """ self.radius = radius self.x = x self.y = y self.colour = colour def __str__(self): """Prints object """ return self.colour + " circle of radius " + \ str(self.radius) + " centred at (" + \ str(self.x) + "," + str(self.y) + ")" def area(self): """Determines area. """ return math.pi * self.radius ** 2 def aligned(self, other): if self.x == other.x and self.y == other.y: return True else: return False def bigger(self, other): if self.radius > other.radius: return True else: return False def is_colour(self, col): if self.colour == col: return True else: return False circ_1 = Circle(10, 10, 10, 'brown') circ_2 = Circle(20,10,9,'yellow') print(circ_1.is_colour('yellow'))
e84fa62e7cadbf19f0e1531fa52982af178c1636
lurichaowo/Jason_Chen_CS127_Assignments
/02/165097_front_times.py
213
3.625
4
def front_times(str, n): front = str[0:3] i = n string = '' #string = i * front if len(str) == 0: return string else : while i > 0 : string = string + front i = i -1 return string
df2fbeb99a6bd2e8fbc7f6204f411c439035fade
gencelo/PythonEgitimi
/h3_1.py
171
3.546875
4
# -*- coding: cp1254 -*- liste = ["cemil", "mustafa", "ibrahim"] for eleman in liste: print eleman for sayi in range(100): print sayi**2 print "program bitti"
3a808cf913a59c2752f506e89e14131ab5d8417e
erikliu0801/leetcode
/python3/solved/P645. Set Mismatch.py
2,424
4.03125
4
# ToDo: """ 645. Set Mismatch Easy The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number. Given an array nums representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array. Example 1: Input: nums = [1,2,2,4] Output: [2,3] Note: The given array size will in the range [2, 10000]. The given array's numbers won't have any order. """ # Conditions & Concepts """ """ # Code ## submit part class Solution: def findErrorNums(self, nums: List[int]) -> List[int]: ## test part class Solution: def findErrorNums(self, nums): """ nums: List[int] rtype: List[int] """ ## code here #1 """ Wrong Answer Input: [1,1] Output: [1] Expected: [1,2] Success Runtime: 212 ms, faster than 60.44% of Python3 online submissions for Set Mismatch. Memory Usage: 13.8 MB, less than 100.00% of Python3 online submissions for Set Mismatch. """ class Solution: def findErrorNums(self, nums): repetition = [] missing = [] nums.sort() pre = 0 for c in nums: if c != pre +1: if c == pre: if c not in repetition: repetition.append(c) continue else: while pre + 1 != c: pre += 1 missing.append(pre) pre = c if not missing: missing = [pre+1] return repetition + missing # Test ## Functional Test """ # Conditions & Concepts """ if __name__ == '__main__': input1 = [[1,2,2,4], [1,2,2,2,4], [1,2,2,2,5]] expected_output = [[2,3], [2,3], [2,3,4]] for i in range(len(input1)): if findErrorNums(input1[i]) != expected_output[i]: print("Wrong!!!", ' Output:', findErrorNums(input1[i]), '; Expected Output:', expected_output[i]) else: print("Right") # print(findErrorNums(input1[-1])) ## Performance Test import cProfile cProfile.run('') ## Unit Test import unittest class Test(unittest.TestCase): def test(self): pass if __name__ == '__main__': unittest.main()
bd5d7b900d3cf6405633ca60a3d9a5a79eca8055
JRodriguez9510/holbertonschool-higher_level_programming-2
/0x0B-python-input_output/0-read_file.py
218
3.765625
4
#!/usr/bin/python3 """ Function to read a file """ def read_file(filename=""): """ Function to print file content on the stdout """ with open(filename, encoding="utf-8") as f: print(f.read(), end="")
3dbe12b8a5d63bea1c4bfeb96b5e6bd0ef03b331
childxr/lintleetcode
/TwoSumGreaterThanTarget/solution.py
555
3.59375
4
class Solution: """ @param nums: an array of integer @param target: An integer @return: an integer """ def twoSum2(self, nums, target): # write your code here if not nums or len(nums) < 2: return 0 nums.sort() cnt = 0 i, j = 0, len(nums) - 1 while i < j: s = nums[i] + nums[j] if s <= target: i += 1 else: cnt += j - i # from i, i + 1, ..., to j, total j - i j -= 1 return cnt
11f077b166e5bc26f0484817a4597d90bf0b9578
rayvace/tictactoe
/board/test.py
4,119
3.875
4
from board import Board import unittest class TestBoard(unittest.TestCase): """ 1 | 2 | 3 ---------- 4 | 5 | 6 ---------- 7 | 8 | 9 """ def setUp(self): self.board = Board() def test_add_mark(self): #position must be a dict position = None self.assertRaises(TypeError, self.board.add_mark, 'X', position) #fail if passed a value that's not X or O position = 5 self.assertRaises(ValueError, self.board.add_mark, 'M', position) #fail if x, y passed position greater than 2 position = 10 self.assertRaises(ValueError, self.board.add_mark, 'X', position) position = 5 self.board.add_mark('X', position) #assert self.board.get_value def test_valid_position(self): position1 = 5 position2 = 5 position3 = 4 self.board.add_mark('X', position1) valid = self.board._is_valid_position(position2) self.assertEqual(valid, False) valid = self.board._is_valid_position(position3) self.assertEqual(valid, True) def test_reset_board(self): position1 = 5 position2 = 5 self.board.add_mark('X', position1) valid = self.board._is_valid_position(position2) self.assertEqual(valid, False) self.board.reset_board() valid = self.board._is_valid_position(position2) self.assertEqual(valid, True) def test_get_horizontal(self): position1 = 1 position2 = 2 position3 = 3 """ X | X | X ---------- 4 | 5 | 6 ---------- 7 | 8 | 9 """ self.board.reset_board() self.board.add_mark('X', position1) self.board.add_mark('X', position2) self.board.add_mark('X', position3) self.assertEqual(self.board.get_horizontal(0), ['X', 'X', 'X']) def test_get_vertical(self): position4 = 3 position5 = 6 position6 = 9 """ 1 | 2 | X ---------- 4 | 5 | X ---------- 7 | 8 | X """ self.board.reset_board() self.board.add_mark('X', position4) self.board.add_mark('X', position5) self.board.add_mark('X', position6) #check if other combinations match expected self.assertEqual(self.board.get_vertical(2), ['X', 'X', 'X']) self.assertEqual(self.board.get_forward_diagonal(), ['X', '5', '7']) self.assertEqual(self.board.get_reverse_diagonal(), ['1', '5', 'X']) def test_get_reverse_diagonal(self): position7 = 1 position8 = 5 position9 = 9 """ O | 2 | 3 ---------- 4 | O | 6 ---------- 7 | 8 | O """ self.board.reset_board() self.board.add_mark('O', position7) self.board.add_mark('O', position8) self.board.add_mark('O', position9) self.assertEqual(self.board.get_reverse_diagonal(), ['O', 'O', 'O']) #check if other combinations match expected self.assertEqual(self.board.get_horizontal(2), ['7', '8', 'O']) self.assertEqual(self.board.get_vertical(2), ['3', '6', 'O']) self.assertEqual(self.board.get_forward_diagonal(), ['3', 'O', '7']) def test_get_forward_diagonal(self): position10 = 7 position11 = 5 position12 = 3 """ 1 | 2 | X ---------- 4 | X | 6 ---------- X | 8 | 9 """ self.board.reset_board() self.board.add_mark('X', position10) self.board.add_mark('X', position11) self.board.add_mark('X', position12) self.assertEqual(self.board.get_forward_diagonal(), ['X', 'X', 'X']) #check if other combinations match expected self.assertEqual(self.board.get_horizontal(1), ['4', 'X', '6']) self.assertEqual(self.board.get_vertical(1), ['2', 'X', '8']) self.assertEqual(self.board.get_reverse_diagonal(), ['1', 'X', '9'])
997e9f3ff568b5ef1e635bdeb27a88f376a22fae
iistrate/Parser
/Main.py
591
3.90625
4
# ## Parses and validates text # from Parser import * import os def main(): running = True while(running): try: path = input("Howdy Mr. J, please enter filename: ") file = open(path, 'r') except: print("{} is an invalid filename!".format(path)) else: running = False print("[i]Contents of {}, sintax validation on bottom.".format(path)) CompParser = Parser(file) CompParser.run() input('Press Enter to exit') #free resources file.close() if __name__ == '__main__': main()
d8325a2d9e1214a72880b37b023d4af1a8d88469
pandeesh/CodeFights
/Challenges/find_and_replace.py
556
4.28125
4
#!/usr/bin/env python """ ind all occurrences of the substring in the given string and replace them with another given string... just for fun :) Example: findAndReplace("I love Codefights", "I", "We") = "We love Codefights" [input] string originalString The original string. [input] string stringToFind A string to find in the originalString. [input] string stringToReplace A string to replace with. [output] string The resulting string. """ def findAndReplace(o, s, r): """ o - original string s - substitute r - replace """ return re.sub(s,r,o)
326d2130712fefd254c6628bba3a0bd226350dec
Dinesh94Singh/PythonArchivedSolutions
/Concepts/Backtracking/131.Palindrome_Partitioning.py
1,162
3.578125
4
def partition(s): res = [] dfs(s, [], res) return res def dfs(s, path, res): if not s: res.append(path[:]) # creates a new list if you do : return # backtracking for i in range(1, len(s) + 1): # we are not expanding around center, rather a, aa, aab, aaba, aabaa. if isPalindrome(s[:i]): path.append(s[:i]) dfs(s[i:], path, res) path.pop() def isPalindrome(s): return s == s[::-1] print(partition("aab")) print(partition("aabaa")) from typing import List class Solution: def partition(self, s: str) -> List[List[str]]: res = [] def check_palindrome(s): return s == s[::-1] def rec_helper(s, sub_arr): if not s: res.append(list(sub_arr)) return for i in range(1, len(s) + 1): print(s[:i]) if check_palindrome(s[:i]): sub_arr.append(s[:i]) rec_helper(s[i:], sub_arr) sub_arr.pop() rec_helper(s, []) return res s = Solution() print(s.partition("aab"))
58fca85f4908fd630d10cc76731e9f5ad95a8e2a
nshattuck20/Data_Structures_Algorithms1
/ch11/sortingPractice.py
1,883
4.21875
4
''' This is a simple program to practice: 1. Selection sort 2. Linear Search 3. Binary Search ''' def selection_sort(numbers): for i in range(len(numbers)): #Find index of the smallest element index_smallest = i for j in range(i + 1, len(numbers)): if numbers[j] < numbers[index_smallest]: index_smallest = j #Swap numbers[i] and numbers[indexSmallest] temp = numbers[i] numbers[i] = numbers[index_smallest] numbers[index_smallest] = temp def linear_search(key, numbers): for i in range(len(numbers)): if numbers[i] == key: return i # return the index of key return -1 # key not found def binary_search(key, numbers): low = 0 mid = len(numbers) // 2 high = len(numbers) - 1 while high>=low: mid = (high + low)//2 if numbers[mid] < key: low = mid + 1 elif numbers[mid] > key: high = mid - 1 else: return mid return -1 # not found def recursive_binary_search(low, high, numbers, key): if low > high: return -1 mid = (low + high)//2 if numbers[mid]< key: return recursive_binary_search(mid+1, high, numbers, key) elif numbers[mid] > key: return recursive_binary_search(low, mid -1, numbers, key) else: return mid #Some test code to show that the swap works numbers = [9,2,11,1,3,6] print('UNSORTED:', numbers) selection_sort(numbers) print('SORTED:', numbers) #testing linear search key_index = linear_search(2, numbers) print('Linear Search: ', key_index) #testing binary search key_index = binary_search(11, sorted(numbers)) print('Binary Search:', key_index) #testing recursive binary search key_index = recursive_binary_search(0, len(numbers) -1, sorted(numbers), 3) print('Recursive Binary Search: ', key_index)
7db35b395426db494a642fb2ec1604577bb988df
Youngj7449/cti110
/M3T1_AreasOfRectangles_Young.py
656
4.28125
4
# Calculate the area of two rectangles and determine which one is greater #6/14/2017 #CTI-110 M3T1 - Areas of Rectangles #Jessica Young # # length1 = int(input('Enter the length of rectangle 1: ')) width1 = int(input('Enter the width of rectangle 1: ')) length2 = int(input('Enter the length of rectangle 2: ')) width2 = int(input('Enter the width of rectangle 2: ')) area1 = length1 * width1 area2 = length2 * width2 if area1 > area2: print ('Rectangle 1 has a greater area.') else: if area2 > area1: print('Rectangle 2 has a greater area.') else: print('Both rectangles have the same area.')
346ed26be4da241fb9fc093f3d07ed31e4ea56eb
1000monkeys/probable-invention
/8/8-2.py
154
3.625
4
def favorite_book(book): print("Your favorite book is " + book) if __name__ == "__main__": favorite_book(input("What is your favorite book? "))
ad93f96071d4096ed1d24f79209328ab5aae1c76
lakshaymehra/fine-grained-sentiment-analysis
/visualize_results.py
3,269
3.75
4
import pandas as pd import matplotlib.pyplot as plt from wordcloud import WordCloud, STOPWORDS import seaborn as sn from sklearn.metrics import f1_score, accuracy_score, confusion_matrix import argparse def generate_wordcloud(df): ''' Create a wordcloud using Customer Reviews to see most commonly used words''' comment_words = '' stopwords = set(STOPWORDS) # iterate through the csv file for val in df['Customer Review']: # typecaste each val to string val = str(val) # split the value tokens = val.split() # Converts each token into lowercase for i in range(len(tokens)): tokens[i] = tokens[i].lower() comment_words += " ".join(tokens) + " " wordcloud = WordCloud(width=800, height=800, background_color='white', stopwords=stopwords, min_font_size=10).generate(comment_words) # plot the WordCloud image plt.figure(figsize=(8, 8), facecolor=None) plt.imshow(wordcloud) plt.axis("off") plt.tight_layout(pad=0) plt.show() def star_ratings_bar_chart(df,rating): # Generate Horizontal Bar Chart for the Number of Reviews vs Star Rating Given By The Customer ax = rating.value_counts(sort=False).plot(kind='barh',color = 'black') ax.set_xlabel('Number of Amazon Reviews') ax.set_ylabel('Star Rating Given By The Customer') plt.show() def predicted_sentiments_bar_chart(df): # Generate Horizontal Bar Chart for the Number of Reviews vs Predicted Sentiment Analysis Score ax = df['Sentiment Analysis Score'].value_counts(sort=False).plot(kind='barh', color = 'red') ax.set_xlabel('Number of Amazon Reviews') ax.set_ylabel('Predicted Sentiment Analysis Score') plt.show() def print_accuracy_and_f1_score(df,rating): # Print Accuracy and F1 Score acc = accuracy_score(rating, df['Sentiment Analysis Score']) * 100 f1 = f1_score(rating, df['Sentiment Analysis Score'], average='macro') print("Accuracy: {}\nMacro F1-score: {}".format(acc, f1)) def plot_cm(df,rating): # Plot Confusion Matrix Heatmap cm = confusion_matrix(rating, df['Sentiment Analysis Score']) fig, ax = plt.subplots(figsize=(8,6)) sn.heatmap(cm, annot=True, fmt='d',xticklabels=categories, yticklabels=categories) bottom, top = ax.get_ylim() ax.set_ylim(bottom + 0.5, top - 0.5) plt.ylabel('Actual') plt.xlabel('Predicted') plt.show() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( '--sentiments_file_path', type=str, default='svm_predicted_sentiments.csv') args = parser.parse_args() sentiments_file_path = args.sentiments_file_path # Read the sentiments File df = pd.read_csv(sentiments_file_path) # Print the top 5 results to inspect the data frame print(df.head()) categories = ['Very Negative', 'Negative', 'Neutral', 'Positive', 'Very Positive'] rating = pd.Series([int(i[0]) for i in pd.Series(df['Star Rating'])]) generate_wordcloud(df) star_ratings_bar_chart(df, rating) predicted_sentiments_bar_chart(df) print_accuracy_and_f1_score(df, rating) plot_cm(df, rating)
48584d00c67d06fe3c8105a192156f818cfce7d6
AmitBaanerjee/Data-Structures-Algo-Practise
/hackerrank/reverse_array.py
678
4.25
4
#REVERSE ARRAY IN ORDER # Given an array,A , of N integers, print each element in reverse order as a single line of space-separated integers. #!/bin/python3 import math import os import random import re import sys # Complete the reverseArray function below. def reverseArray(a): length=len(a)-1 for i in range(len(a)//2): temp=a[i] a[i]=a[length-i] a[length-i]=temp return a if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') arr_count = int(input()) arr = list(map(int, input().rstrip().split())) res = reverseArray(arr) fptr.write(' '.join(map(str, res))) fptr.write('\n') fptr.close()
1897113f6ca4f4bd7202bf39fac2b490033128ef
jhiltonsantos/ADS-Algoritmos-IFPI
/Atividade_Fabio_06_STRING/fabio06_13_nome_em_biografia.py
698
3.65625
4
from tools_string import transforma_palavra_em_maiuscula, ultimo_nome def main(): nome_completo = input('Digite o nome completo: ') nome_completo = transforma_palavra_em_maiuscula(nome_completo) ultimo = ultimo_nome(nome_completo) primeiro, segundo = iniciais(nome_completo) print('%s, %s. %s..' % (ultimo, primeiro, segundo)) def iniciais(nome): i = 0 while i < len(nome): primeiro_nome_inicial = nome[0] if ord(nome[i]) == 32: segundo_nome_inicial = nome[i+1] break i += 1 return primeiro_nome_inicial, segundo_nome_inicial if __name__ == '__main__': main()
17dd5c33da3455607319348d8f99af4a7fdbabea
MU-Enigma/Hacktoberfest_2020
/Problems/Problem_3/Divyesh_Problem_3.py
225
4
4
print("Input 3 numbers") a = int(input()) b = int(input()) c = int(input()) A = a*a B = b*b C = c*c if A == B+C: print(a, b, c) elif B == A+C: print(b, a, c) elif C == A+B: print(c, a, b) else: print("NOPE!")
7119653c6364a42f53808a376192d09e9c5e9e93
MichelleZ/leetcode
/algorithms/python/customSortString/customSortString.py
278
3.5625
4
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # Source: https://leetcode.com/problems/custom-sort-string/ # Author: Miao Zhang # Date: 2021-03-11 class Solution: def customSortString(self, S: str, T: str) -> str: return "".join(sorted(T, key=lambda x: S.find(x)))
9711923c76c4b2e9938f0c2b09894e36558d1be2
effectivemadness/ct_exercise
/가장 큰 수/solution.py
892
3.859375
4
# import itertools # def solution(numbers): # answer = '' # str_list = itertools.permutations(numbers, len(numbers)) # number_list = [] # print(str_list) # for item in str_list: # tmp_str = "" # for num_str in item: # tmp_str = tmp_str + str(num_str) # number_list.append(int(tmp_str)) # print(number_list) # return sorted(number_list)[-1] # # return answer def solution(numbers): answer="" str_list=[] for i,num in enumerate(numbers): num_string = str(num) num_mult = num_string*3 str_list.append([num_mult,i]) print(str_list) str_list.sort(reverse=True) for i,value in enumerate(str_list): index = value[1] answer += str(numbers[index]) for value in answer: if value!='0': return answer return "0" print(solution([6, 10, 2]))
e159a36468a7b9cd51ced91d3aca51f9e0167885
Schnei1811/PythonScripts
/Practice/Contacts Problem.py
1,675
3.8125
4
# Write a program that allows you to add names and tell you after you enter # a string, how many contacts start with that string def binarysearch(contactlist, val, count): first = 0 last = len(contactlist) - 1 while first <= last: mid = (first + last) // 2 if contactlist[mid][:len(val)] == val: count += 1 del contactlist[mid] return binarysearch(contactlist, val, count) elif contactlist[mid] > val: last = mid - 1 else: first = mid + 1 return count def searchcontacts(contactlist): count = 0 inputlet = input('Enter search letters: ').lower() if inputlet == '': print('Input Empty') searchcontacts(contactlist) contactlist.sort() contactlist = [contact.lower() for contact in contactlist] print(binarysearch(contactlist, inputlet, count)) return def addcontact(contactlist): inputname = input('Add new contact: ') if inputname == '': print('Input Empty') addcontact(contactlist) contactlist += inputname ans = input('Add another contact? (y/n) ') if ans == 'y': addcontact(contactlist) if ans == 'n': file = open('contactlist.txt', 'w') file.writelines(["{}".format(line) for line in contactlist]) file.close() return def main(): contactlist = ['Anna', 'Anne', 'Bob', 'Bobby', 'George', 'Sarah'] ans = input("Add or Search Contact List?: (add, search, quit) ") if ans == 'add': addcontact(contactlist) elif ans == 'search': searchcontacts(contactlist) elif ans == 'quit': quit() else: print('Invalid selection') main() main()
3844e9a7b08b6cd10fc9ac9b05141766c821a6ec
allyemmett/python_warmups
/day3_warmups.py
739
4.3125
4
# Write a hello world program and run it in python message = "Hello world" print(message) # or just print("hello world") with string # Write a program that asks for a your name and prints hello, <your name> name = input("What is your name: ") print(f"Hello, {name}") # Write a function that checks whether a number is even (3 WAYS TO DO SO) def is_even(x): # need "def" for function if x % 2 == 0: return True else: return False # Could also do def is_even2(z): if z % 2 ==0: return True # Could also do def is_even3(n): return n % 2 == 0 # This is a helper function def is_divisible(n, d): return n % d == 0 def is_even_again(n): return is_divisible(n, 2) is_divisible(4, 2)
3143b4f35a0a5fab614c0c2131d4f0bf9f7133a1
tharunnayak14/python
/ch7_files.py
842
3.625
4
# opening a file # handle = open(filename,mode) # f hand = open('m.txt','r') xfile = open('m.txt') for c in xfile: print(c) print("***********************************") # counting lines h = open('m.txt') count = 0 for l in h: count = count + 1 print('Line count:-', count) print("***********************************") # reading whole file u = open('m.txt') inp = u.read() print(len(inp)) print(inp[:]) print("***********************************") # searching through a file p = open('m.txt') for line in p: line = line.rstrip() if line.startswith('g'): print(line) print("***********************************") y = open('m.txt') for line in y: line = line.rstrip() if not 'b' in line: continue print(line) print("***********************************")
a8593605ba58824fa65d4d8dd11eae23797d58aa
darongliu/Input_Method
/demo/code/input.py
3,383
3.734375
4
# coding=UTF-8 import cmd import math from word_generate import possible_generate def print_possible_word(all_possible_word): num = len(all_possible_word) for count in range(num) : if (count % 10) == 0 : print print "%3d" % count , print all_possible_word[count], count = count + 1 print """ def possible_generate(pre_sentence , word): correct = True all_possible_word = ['劉','達','融','好','帥','帥','到','讓','別','人','無','法','競','爭'] return correct, all_possible_word """ class input_shell(cmd.Cmd): def __init__(self): cmd.Cmd.__init__(self) self.prompt = '>>> ' self.reset() def reset(self): self.sentence = "" #input sentence up to now self.possible_word = [] #possible word self.possible_word_num = 0 #possible number self.state = 0 #state 0: wait for inputting chuyin #state 1: wait for inputting number def do_quit(self, args): """Quits the program.""" print "Quitting." raise SystemExit def do_reset(self, args): """reset the program.""" print "resetting." self.reset() return def default(self, line): """parse chuyin""" all_word = line.split() if len(all_word) != 1 : print "Error inputting, please input again" return else : word = all_word[0] if self.state == 0 : correct, all_possible_word = possible_generate(self.sentence , word) num = len(all_possible_word) if correct == False : print "Error inputting, please input again" return elif num == 0: print "No possible word, please input again" return else : self.state = 1 self.possible_word = all_possible_word self.possible_word_num = num print_possible_word(all_possible_word) print 'sentence: (%s)' % self.sentence print "Please choose word" return else : try : choose_num = int(word) except : print "Error inputting, please input again" return else : if choose_num > self.possible_word_num : print "Too large number, only (%d) options, please input again" % self.possible_word_num elif choose_num < 0 : print "Negative number detect, please input again" elif choose_num == 0: print "Input chuyin again" self.state = 0 return else : self.sentence = self.sentence + self.possible_word[choose_num-1] print "Choose (%s)" % self.possible_word[choose_num-1] print 'sentence: (%s)' % self.sentence print "Input next word" self.state = 0 return if __name__ == '__main__': input_shell().cmdloop()
29f1704e3c78d3bde1cdf38815a9938feff60a01
Imsid64/Siddharth
/rps.py
318
4.15625
4
#!/usr/bin/python3 import random player = input("Enter your choice (rock/paper/scissor): "); player =player.lower(); while (player != "rock and player != "paper" and player != "scissors"): print(player); player = input("That choice is not valid. Enter your choice (rock/paper/scissors): "); player = player.lower();
b94576909d3ec3b897ca5eced31695598fb0dd58
Hanlen520/Leetcode-4
/src/117. 填充每个节点的下一个右侧节点指针 II.py
1,410
4.125
4
""" 给定一个二叉树 struct Node { int val; Node *left; Node *right; Node *next; } 填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。 初始状态下,所有 next 指针都被设置为 NULL。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ # 区别在于不是完全平衡树了 """ # Definition for a Node. class Node: def __init__(self, val, left, right, next): self.val = val self.left = left self.right = right self.next = next """ # 跟我自己一样的做法 class Solution: def connect(self, root: 'Node') -> 'Node': if not root: return root stack = [] if root.left: stack.append((root.left, 1)) if root.right: stack.append((root.right, 1)) while stack: curr = stack.pop(0) if stack and curr[1] == stack[0][1]: curr[0].next = stack[0][0] if curr[0].left: # if not leaf stack.append((curr[0].left, curr[1]+1)) if curr[0].right: stack.append((curr[0].right, curr[1]+1)) return root
f1d9e8140f0a2440ab9b614c01f55fe09e456c8e
ava6969/CS101
/AndyJohnson/AndyLoops.py
1,034
3.859375
4
# i = 0 # while i < 5: # print(i) # i += 1 # for i in range(0, 5, 1): # print(i) def buy_game(game_price, game_name): andy_money = int(input('how much money do you have: ')) diff = 0 while andy_money < game_price: print('you dont have enough money, try again') andy_money = int(input('how much money do you have now: ')) # TODO if i buy mario, print 'bought mario' print('bought', game_name) diff = andy_money - game_price return diff def countdown(start): if start < 0: return None else: print(start) start -= 1 return countdown(start) def main(): # print('welcome to gamestop') # choice = int(input('choose game to buy:\n' # '1) mario $20\n' # '2) GOW $25\n' # '>> ')) # # if choice == 1: # price = 20 # else: # price = 25 # # diff = buy_game(price) # print('your change is', diff) countdown(1000) main()
babf8c3dd697855e07a7705f823c89751b558534
richardbradshaw/Nashville_Weather
/ObservedWeather3Day.py
3,093
3.53125
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas as pd import requests # In[2]: # get the data from the url, then parse it as a DataFrame url = 'https://w1.weather.gov/data/obhistory/KBNA.html' r = requests.get(url) df_list = pd.read_html(r.text) # this parses all the tables in webpages to a list data = df_list[3] data = data.iloc[:-3] # In[3]: # Remove the first two column header levels, then rename the remaining columns data.columns = data.columns.droplevel([0,1]) data = data.rename(columns = {'Air':'AirTemp','Max.':'6hourMaxTemp','Min.':'6hourMinTemp', '1 hr':'1hrPrecip','3 hr':'3hrPrecip','6 hr':'6hrPrecip', 'RelativeHumidity':'RelativeHumidity(%)'}) # In[4]: from datetime import date retrievalDate = date.today() # In[5]: # Change numerical values to floats data[['Date', 'Vis.(mi.)', 'AirTemp', 'Dwpt', '6hourMaxTemp', '6hourMinTemp', 'WindChill(°F)', 'HeatIndex(°F)', 'altimeter(in)', 'sea level(mb)', '1hrPrecip', '3hrPrecip', '6hrPrecip']] = data[['Date', 'Vis.(mi.)', 'AirTemp', 'Dwpt', '6hourMaxTemp', '6hourMinTemp', 'WindChill(°F)', 'HeatIndex(°F)', 'altimeter(in)', 'sea level(mb)', '1hrPrecip', '3hrPrecip', '6hrPrecip']].astype('float') # In[6]: data['RelativeHumidity(%)'] = data['RelativeHumidity(%)'].str.strip('%') data['RelativeHumidity(%)'] = data['RelativeHumidity(%)'].astype('float') # In[7]: # Code to create the date offsets to correctly assign the actual datetimes # get unique dates dateUnique = data['Date'].unique() # get offsets for each unique date offsets = list(range(len(dateUnique))) # create dictionary offsetDict = dict(zip(list(dateUnique), offsets)) # assign the dateOffset column to the values in the Date column data['dateOffset'] = data['Date'] # replace the dateOffset values to the offsets in the offsetDict data['dateOffset'] = data['dateOffset'].replace(offsetDict) # In[8]: # Create column of the retrieval Date data['retrievalDate'] = retrievalDate data['retrievalDate'] = pd.to_datetime(data['retrievalDate']) # Subtract the dateOffset from the retrieval date to get the full date of the observations data['dateRel'] = pd.DatetimeIndex(data['retrievalDate']) - pd.to_timedelta(data['dateOffset'], unit='D') # Combine the date and time data['dateTime'] = pd.to_datetime(data['dateRel'].astype(str) + data['Time(cdt)'], format = '%Y-%m-%d%H:%M') # In[9]: # Saving data from os import path filename = 'observedWeatherNash.csv' # Check if output file exists if path.exists(filename): oldData = pd.read_csv('observedWeatherNash.csv') dataAll = data.append(oldData, sort=False) # remove duplicates dataAll.drop_duplicates(subset=['Date', 'Time(cdt)', 'Wind(mph)', 'Vis.(mi.)', 'Weather', 'Sky Cond.', 'AirTemp', 'Dwpt', 'altimeter(in)', 'sea level(mb)'], inplace=True) # Save dataAll dataAll.to_csv(filename, index=False) else: # Save initial data to file data.to_csv(filename, index=False)
4cc82d03b0d54bb327b8819e29bab88aebacbcd5
vanessa9910/Metodos
/Kata7.py
446
4.3125
4
#Create a function that takes an integer and returns the factorial of that integer. #That is, the integer multiplied by all positive lower integers. def factorial(num): if (num ==1): return 1; else: return num * factorial(num-1) #Take a list of integers (positive or negative or both) and return the sum of the absolute value of each element. def get_abs_sum(lst): suma = 0; for i in range (len(lst)): suma+=abs(lst[i]); return suma
66191e7f8e70a93f950d0e16e43817a0b7495c5b
nicobrubaker/modernArt
/modernArt.py
4,623
3.5
4
# By Nico Brubaker, applying 9th grade from tkinter import * from webbrowser import open_new from random import randint, choice from PIL import Image, ImageDraw from os import remove root = Tk() root.wm_title("Mondrian Generator") runAgain = Button(root, text="Generate Another!") runAgain.pack() save = Button(root, text="Open in your default photo viewer") save.pack() thick = randint(10, 20) cht = randint(500, 700) cwd = cht + randint(-(1*(cht//3)), 1*(cht//3)) while cwd < 8*thick: cwd = cht + randint(-(1*(cht//3)), 1*(cht//3)) c = Canvas(root, width=cwd+1, height=cht+1, highlightthickness=0, borderwidth=0) image = Image.new("RGB", (cwd, cht), (255, 255, 255)) m_draw = ImageDraw.Draw(image) def find_endpoints(x1, y1, x2): if x1 == x2: s = c.find_overlapping(x1, 0, x1, cht+2) intersections = [] for item in s: cs = c.coords(item) intersections.append([x1, cs[1]]) else: s = c.find_overlapping(0, y1, cwd+2, y1) intersections = [] for item in s: cs = c.coords(item) intersections.append([cs[0], y1]) return intersections def split(): if randint(0, 1) == 0: # Draw vert split 4thk away from other split lx = 0 print("X:", badX) while False in [abs(lx-i) > 3*thick for i in badX]: # find the x-value of the line lx = randint(0, cwd) s = find_endpoints(lx, 0, lx) st = choice(s) s.pop(s.index(st)) end = choice(s) c.create_line(st[0], st[1], end[0], end[1], width=thick) m_draw.line([st[0], st[1], end[0], end[1]], (0, 0, 0), thick) badX.append(lx) else: # horiz split same rules ly = 0 print("Y:", badY) while False in [abs(ly-i) > 3*thick for i in badY]: ly = randint(0, cht) s = find_endpoints(0, ly, cwd) st = choice(s) s.pop(s.index(st)) end = choice(s) c.create_line(st[0], st[1], end[0], end[1], width=thick) m_draw.line([st[0], st[1], end[0], end[1]], (0, 0, 0), thick) badY.append(ly) def color(): data = list(image.getdata()) real_data = [] for i in range(int(len(data)/(cwd+1))): x = [] for j in range(cwd): x.append(data[j]) real_data.append(x) colors = [(255, 0, 0), (0, 0, 255), (255, 255, 0)] for i in range(randint(1, 5)): x = randint(1, cwd) y = randint(1, cht) ImageDraw.floodfill(image, (x, y), choice(colors), (0, 0, 0)) def draw(): global badX global badY global thick global root global final_show badX = [0, cwd] badY = [0, cht] c.delete(ALL) c.create_line(0, 0, cwd, 0) c.create_line(cwd, 0, cwd, cht) c.create_line(cwd, cht, 0, cht) c.create_line(0, cht, 0, 0) m_draw.line([0, 0, cwd - 1, 0], (0, 0, 0)) m_draw.line([cwd - 1, 0, cwd - 1, cht - 1], (0, 0, 0)) m_draw.line([cwd - 1, cht - 1, 0, cht - 1], (0, 0, 0)) m_draw.line([0, cht - 1, 0, 0], (0, 0, 0)) for i in range(randint(4, 25-thick)): split() color() image1 = image.crop((1, 1, cwd-1, cht-1)) c.delete(ALL) image1.save("temp.gif") final_show = PhotoImage(file="temp.gif") remove("temp.gif") c["width"] = cwd - 2 c["height"] = cht - 2 c.create_image(0, 0, image=final_show, anchor=NW) root.update() return image1 def draw_another(): global showImage global image global m_draw image = Image.new("RGB", (cwd, cht), (255, 255, 255)) m_draw = ImageDraw.Draw(image) m_draw.line([0, 0, cwd - 1, 0], (0, 0, 0)) m_draw.line([cwd - 1, 0, cwd - 1, cht - 1], (0, 0, 0)) m_draw.line([cwd - 1, cht - 1, 0, cht - 1], (0, 0, 0)) m_draw.line([0, cht - 1, 0, 0], (0, 0, 0)) m_draw = ImageDraw.Draw(image) showImage = draw() runAgain["command"] = draw_another def credit(e): open_new("https://github.com/fogleman/Piet#procedurally-generating-images-in-the-style-of-piet-mondrian") credits2["fg"] = "purple" credits2.update() c.pack() credits1 = Label(root, text="Algorithm inspired by GitHub user fogleman", font=("Arial", 9)) credits1.pack() credits2 = Label(root, text="Click for source/info", font=("Arial", 9, "underline"), fg="blue") credits2.pack() credits2.bind("<Button-1>", credit) credits3 = Label(root, text="By Nico Brubaker, applying for grade 9", font=("Arial", 9)) credits3.pack() showImage = draw() def save_the_image(): global showImage showImage.show() save["command"] = save_the_image root.mainloop()
0a611cdca203788efad5080d5198a612965898de
Albertkwek/Fakathon
/html_to_factors.py
6,639
3.53125
4
def html_to_factors_general(url): """ Given a general website, this function returns a dictionary which the links on the website, the headline, the body and the url. """ import requests from bs4 import BeautifulSoup response = requests.get(url) if response.status_code == 200: try: page_data_soup = BeautifulSoup(response.content,'lxml') links = [link.get('href') for link in page_data_soup.find_all('a', href=True)] headline = page_data_soup.find('h1').text body = '' for tag in page_data_soup.find_all('p'): body += " "*(len(body)!=0) + tag.text dict_solution = {"links":links, "headline":headline,"body":body} return dict_solution except: return None def html_to_factors_nytimes(url): """ Given a url from nytimes, this function returns a dictionary which contains the name of the author, number of links on the website, the headline and the body. """ import requests from bs4 import BeautifulSoup response = requests.get(url) if response.status_code == 200: try: page_data_soup = BeautifulSoup(response.content,'lxml') author_name = page_data_soup.find('span', class_='byline-author').text links = [link.get('href') for link in page_data_soup.find_all('a', href=True)] headline = page_data_soup.find('h1', itemprop="headline").text body = '' for tag in page_data_soup.find_all('p', class_='story-body-text story-content'): body += " "*(len(body)!=0) + tag.text dict_solution = {'author_name':author_name, "links":links, "headline":headline,"body":body, "url":url} return dict_solution except: return None def html_to_factors_21cent(url): """ Given a url from 21cent , this function returns a dictionary which contains the name of the author, number of links on the website, the headline and the body. """ import requests from bs4 import BeautifulSoup response = requests.get(url) if response.status_code == 200: try: page_data_soup = BeautifulSoup(response.content,'lxml') author_name = page_data_soup.find('a', rel='author').text links = [link.get('href') for link in page_data_soup.find_all('a', href=True)] headline = page_data_soup.find('h1', class_="entry-title").text body = '' for tag in page_data_soup.find_all('p'): body += " "*(len(body)!=0) + tag.text dict_solution = {'author_name':author_name, "links":links, "headline":headline,"body":body, "url":url} return dict_solution except: return None def html_to_factors_infowars(url): """ Given a url from InfoWars , this function returns a dictionary which contains the name of the author, number of links on the website, the headline and the body. """ import requests from bs4 import BeautifulSoup response = requests.get(url) if response.status_code == 200: try: page_data_soup = BeautifulSoup(response.content,'lxml') author_name = page_data_soup.find('span', class_="author").find('a').text links = [link.get('href') for link in page_data_soup.find_all('a', href=True)] headline = page_data_soup.find('h1', class_="entry-title").text body = '' for tag in page_data_soup.find('article').find_all('p'): body += " "*(len(body)!=0) + tag.text dict_solution = {'author_name':author_name, "links":links, "headline":headline,"body":body} return dict_solution except: return None def scrap_RNRN_web(): """ This function takes down all the web urls from RNRN and return them as a list """ url = "http://realnewsrightnow.com/" import requests from bs4 import BeautifulSoup rnrn_url = [] response = requests.get(url) if response.status_code == 200: page_data_soup = BeautifulSoup(response.content,'lxml') cat_avoid = {'Home','About'} for tag in page_data_soup.find('ul', id="menu-main-navigation-1").find_all('li'): if tag.text not in cat_avoid: category_link = tag.find('a').get('href') newresponse = requests.get(category_link) if newresponse.status_code == 200: new_page_data_soup = BeautifulSoup(newresponse.content,'lxml') rnrn_url.extend([item.find('a').get('href') for item in new_page_data_soup.find_all(['h3','h5'],itemprop = "headline")]) def scrap_21_cent_web(): """ This function takes down all the web urls from cent21 and return them as a list """ url = "http://21stcenturywire.com/" import requests from bs4 import BeautifulSoup cent21_url = [] response = requests.get(url) if response.status_code == 200: page_data_soup = BeautifulSoup(response.content,'lxml') parent = page_data_soup.find('ul', id="menu-main") for child in parent.find_all('li', id=lambda x:x and x.startswith('menu-item-')): category_link = child.find('a')['href'] newresponse = requests.get(category_link) if newresponse.status_code == 200: new_page_data_soup = BeautifulSoup(newresponse.content,'lxml') cent21_url.extend([item.find('a').get('href') for item in new_page_data_soup.find_all('h2', class_="entry-title")]) return cent21_url def scrap_infowars_web(): """ This function takes down all the web urls from InfoWars and return them as a list """ url = "http://www.infowars.com/" import requests from bs4 import BeautifulSoup infowars_url = [] response = requests.get(url) if response.status_code == 200: page_data_soup = BeautifulSoup(response.content,'lxml') for tag in page_data_soup.find('li', id="menu-item-216953").find_all('li'): category_link = tag.find('a').get('href') newresponse = requests.get(category_link) if newresponse.status_code == 200: new_page_data_soup = BeautifulSoup(newresponse.content,'lxml') infowars_url.extend([div.find('h3').find('a').get('href') for div in new_page_data_soup.find_all('div', class_="article pure-u-xs-1-1 pure-u-sm-1-2 pure-u-lg-1-2 pure-u-xl-1-2 ")]) return infowars_url
ee87a11e478ad31d52cf395adb17360af8eb6a52
Michael-png/olympiad-python-lvl-3
/Python Homework/Homework 6 g).py
260
4.03125
4
Number = 0 x = 0 while x > 6: #this while loop looks like it never runs x = x + 1 SomeKindOfInput = int(input("Enter a number here: ")) OddNumbers = SomeKindOfInput % 2 if OddNumbers == 1: Number = Number + OddNumbers print(Number)
8c6f2d8ed077e74b798ac7d6c42927834183267b
syurskyi/Algorithms_and_Data_Structure
/Python Data Structures and Algorithms/src/13. Graphs/5.2 Breadth-First Search.py
1,897
3.546875
4
from queuelinked import LinkedQueue import numpy as np class Graph: def __init__(self, vertices): self._adjMat = np.zeros((vertices, vertices)) self._vertices = vertices def insert_edge(self, u, v, w=1): self._adjMat[u][v] = w def delete_edge(self, u, v): self._adjMat[u][v] = 0 def get_edge(self, u, v): return self._adjMat[u][v] def vertices_count(self): return self._vertices def edge_count(self): count = 0 for i in range(self._vertices): for j in range(self._vertices): if not self._adjMat[i][j] == 0: count += 1 return count def indegree(self, u): count = 0 for i in range(self._vertices): if not self._adjMat[i][u] == 0: count += 1 return count def outdegree(self, u): count = 0 ; for i in range(self._vertices): if not self._adjMat[u][i] == 0: count += 1 return count def display(self): print(self._adjMat) def BFS(self, source): i = source q = LinkedQueue() visited = [0] * self._vertices print(i, end=' - ') visited[i] = 1 q.enqueue(i) while not q.is_empty(): i = q. dequeue() for j in range(self._vertices): if self._adjMat[i][j] == 1 and visited[j] == 0: print(j, end=' - ') visited[j] = 1 q.enqueue(j) G = Graph(7) G.insert_edge(0, 1) G.insert_edge(0, 5) G.insert_edge(0, 6) G.insert_edge(1, 0) G.insert_edge(1, 2) G.insert_edge(1, 5) G.insert_edge(1, 6) G.insert_edge(2, 3) G.insert_edge(2, 4) G.insert_edge(2, 6) G.insert_edge(3, 4) G.insert_edge(4, 2) G.insert_edge(4, 5) G.insert_edge(5, 2) G.insert_edge(5, 3) G.insert_edge(6, 3) G.BFS(0)
45afbb7aeff958f9018733dece69b358781b60a5
cxu60-zz/LeetCodeInPython
/subsets.py
1,328
3.6875
4
#!/usr/bin/env python # encoding: utf-8 """ subsets.py Created by Shengwei on 2014-07-20. """ # https://oj.leetcode.com/problems/subsets/ # tags: easy / medium, numbers, set, combination, dfs """ Given a set of distinct integers, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example, If S = [1,2,3], a solution is: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ] """ # TODO: different ways to do it class Solution: # @param S, a list of integer # @return a list of lists of integer def subsets(self, S): result = [[]] for num in sorted(S): cur_len = len(result) for sub_set in result[:cur_len]: result.append(sub_set + [num]) return result ######### DFS ######### class Solution: # @param S, a list of integer # @return a list of lists of integer def subsets(self, S): def dfs(sub_set, buff): result = [buff] for index in xrange(len(sub_set)): cur_buff = list(buff) + [sub_set[index]] result.extend(dfs(sub_set[index+1:], cur_buff)) return result return dfs(sorted(S), [])
88343cf1da3d149ca82343604c83cd3009b59aff
ntcho/CAU2019
/Pre-term/Computational Thinking and Problem Solving/Lecture 3/prog1.py
1,427
4.28125
4
# 2019-01-31 # Quadratic equation example from math import sqrt print("Enter variables of your equation (ax^2 + bx + c = 0)") a = float(input("a = ")) if a == 0: print("Equation is not quadratic") else: b = float(input("b = ")) c = float(input("c = ")) # variable for checking if x exists equation_check = b**2 - 4*a*c if equation_check < 0: # the x doesn't exist print("x is not a real number") else: D = sqrt(equation_check) if equation_check == 0: # only 1 x value exist print("x =", (-b + D)/(2*a)) # check if user wants to show explanation if input("Show explanation (Y/N) : ") == 'Y': print((-b + D)/(2*a), "= (" + str(-b) + " + sqrt(" + str(b) + "^2" + " - 4x" + str(a) + "x" + str(c) + ")) / 2x" + str(a)) else: # 2 x value exist print("x =", (-b + D)/(2*a), (-b - D)/(2*a)) # check if user wants to show explanation if input("Show explanation (Y/N) : ") == 'Y': print((-b + D)/(2*a), "= (" + str(-b) + " + sqrt(" + str(b) + "^2" + " - 4x" + str(a) + "x" + str(c) + ")) / 2x" + str(a)) print((-b - D)/(2*a), "= (" + str(-b) + " - sqrt(" + str(b) + "^2" + " - 4x" + str(a) + "x" + str(c) + ")) / 2x" + str(a))
6c63a54f527742a31a5d254565f2672a66dbc0e7
JimChr-R4GN4R/angstromCTF-Writeups
/2019/Crypto/Half and Half (50 points)/two_letters_finder.py
3,081
3.734375
4
# So from the first script we are here: # ciphertext is = \x15\x02\x07\x12\x1e\x100\x01\t\n\x01" # we know these: a c t f { .. . . . . _ # unkown_letters: t a s t e .. . . . . } # So now the only thing we know is the hex result... # We see in unkown_letters that there is the word "taste" and the next hex is x10 (the last zero is extra character) # So we put in known_hex_result the x10 and we will get the combinations that make this result. Then you have to guess. # Here I believe that the next letter is '_' or 's' (tastes) # So if we run the script we will see that 's' goes with 'c' # ciphertext is = \x15\x02\x07\x12\x1e\x100\x01\t\n\x01" # we know these: a c t f { c. . . . . _ # unkown_letters: t a s t e s. . . . . } known_hex_result = "x10".replace('x0','x') # We need to remove the first zero after x. So for example 0x02 --> 0x2 . This is for the if result problem known_hex_result = ''.join(('0',known_hex_result)) # add zero at the beginning x15 --> 0x15 unknown_letter1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '=', '_', '+', '`', '~', '/', ',', '.', '<', '>', '?', '[', ']', ':', "'", '"', '{', '\\', '}'] unknown_letter2 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '=', '_', '+', '`', '~', '/', ',', '.', '<', '>', '?', '[', ']', ':', "'", '"', '{', '\\', '}'] for letter_1 in unknown_letter1: binary1 = ' '.join(format(ord(letter_1), 'b') for x in letter_1) binary1 = list(binary1) for letter_2 in unknown_letter2: binary2 = ' '.join(format(ord(letter_2), 'b') for x in letter_2) length = len(binary1) binary2 = list(binary2) xor_result = '' try: for i in range(0,7): if (binary1[i] == '1') and (binary2[i] == '1'): xor_result += '0' elif (binary1[i] == '0') and (binary2[i] == '1'): xor_result += '1' elif (binary1[i] == '1') and (binary2[i] == '0'): xor_result += '1' elif (binary1[i] == '0') and (binary2[i] == '0'): xor_result += '0' #print(letter_1,"^",letter_2,"=",hex(int(xor_result, 2))) if hex(int(xor_result, 2)) == known_hex_result: # Put here the hex known number!!! print(letter_1,"^",letter_2) #print(known_letter_1,"^",letter_2,"=",hex(int(xor_result, 2))) # this will show all results except: pass ############### Useful sources for this script ############### # https://github.com/quintuplecs/angstromctf2019/blob/master/crypto/Half-and-Half.md
aef95277237ca10d3c62b9cf3162ff3efaa37bc6
nickciaravella/leetcode
/215_Kth_Largest_Element_In_An_Array.py
447
3.53125
4
# https://leetcode.com/problems/kth-largest-element-in-an-array # Medium import heapq class Solution: def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ max_heap = list(map(lambda x: -1*x, nums)) heapq.heapify(max_heap) while k > 1: heapq.heappop(max_heap) k -= 1 return -1 * heapq.heappop(max_heap)
d9edc9627ccb1de30e2bfc4097c4a6ebc1ecaa05
FrankAkumbissah/intro_to_python
/calculate.py
1,330
4.03125
4
def calculate(): ask = input("What do you want to do?:\n ADD \t\t\t SUBTRACT \n MULTIPLY \t\t\t DIVIDE\n") if (ask == "ADD"): print(add()) elif (ask == "SUBTRACT"): print(subtract()) elif (ask == "MULTIPLY"): print(multiply()) elif (ask == "DIVIDE"): print(divide()) else: print("Invalid input please try again") def add(): first = int(input("Enter the first value \n")) second = int(input("Enter the second value \n")) sum = first + second return sum def subtract(): first = int(input("Enter the first value \n")) second = int(input("Enter the second value \n")) difference = first - second return difference def multiply(): first = int(input("Enter the first value \n")) second = int(input("Enter the second value \n")) product = first * second return product def divide(): first = int(input("Enter the first value \n")) second = int(input("Enter the second value \n")) dividend = first / second return dividend def main(): print("*********************************************************") print("PLEASE MAKE SURE TO TYPE YOUR RESPONSE IN CAPITAL LETTERS") print("*********************************************************") calculate() main()
0f05e2e5062d8b8a156a6d4f241be56a13113951
xjtushare/learnPython2020
/basic_class_03_Error/Solution_03_TypeError.py
2,211
4.40625
4
# !/usr/bin/env python # -*- coding:utf-8 -*- """ TypeError 例1:在 for 循环语句中忘记调用 len() 导致TypeError: 'list' object cannot be interpreted as an integer 通常你想要通过索引来迭代一个 list 或者 string 的元素,这需要调用 range() 函数。 要记得返回 len 值而不是返回这个列表 """ aa = ['cmbc','libai','chinese'] ''' 错误示范 ''' # for i in range(aa): # print(aa[i]) ''' 正确写法 ''' for i in range(len(aa)): print(aa[i]) """ 例2: 尝试修改 string 的值 导致TypeError: 'str' object does not support item assignment string 是一种不可变的数据类型 """ ''' 错误示范 TypeError: 'str' object does not support item assignment 错误内容:不支持字符串的修改 ''' # str1 = 'come here' # str1[1]='o' # print(str1) ''' 正确做法 ''' str1 = 'come here' str1 = str1 + 'r'+str1[:2] print(str1) """ 例3:尝试连接非字符串值与字符串 导致 TypeError: Can't convert 'int' object to str implicitly 这里报错的意思就是这个语句里面含有对象为整型的数据,不能直接赋予字符串类型 """ ''' 错误示范 ''' # print('I have'+18+'ages') ''' 正确示范 ''' print('I have '+str(18)+' ages') print('I have %s ages' %(18)) """ 例4、尝试使用 range()创建整数列表 导致TypeError: 'range' object does not support item assignment 有时你想要得到一个有序的整数列表,所以 range() 看上去是生成此列表的不错方式。 然而,你需要记住 range()返回的是 range object,而不是实际的 list 值。 """ ''' 错误示范 TypeError: 'range' object does not support item assignment 注意:在 Python 2 中 a = range(10)是能行的, 因为在 Python 2 中 range()返回的是list值,但是在 Python 3 中就会产生以上错误. ''' # a = range(5) # a[2] = 0 ''' 正确示范 ''' # a = list(range(5)) # a[2] = 0 """ 例5、忘记为方法的第一个参数添加 self 参数 导致TypeError: myMethod() takes no arguments (1 given) a.func() TypeError: func() takes 0 positional arguments but 1 was given """ # class Solution(): # def func(): # print('Hello!') # a = Solution() # a.func()
9b11ac786620863cf9c4a271a30bf3c2faf82104
ferran9908/Algorithms---Stanford
/Graph Search, Shortest Paths and Data Structures/Graph Search/bfs_connected_components.py
967
3.78125
4
def read_graph(filename): with open(filename,'r') as file: lines = file.readlines() for i in range(len(lines)): lines[i] = lines[i].strip() adjacency_list = {} for line in lines: line = list(map(int,line.split())) adjacency_list[line[0]] = line[1:] return adjacency_list def bfs(graph, source): queue = [] visited = [source] queue.append(source) while queue: current_node = queue.pop(0) for i in graph[current_node]: if i not in visited: # print("Can reach node", i) visited.append(i) queue.append(i) return visited def find_connected_components(graph): explored = [] i = 1 for key in graph: if key not in explored: components = bfs(graph,key) explored.extend(components) print("Component {}: {}" .format(i,components)) i+=1
b910dffeaa632c267d07467c0ca36c046d0d5790
amanuelggy/Python---checkerboard-challenge
/String and List Assignment/string_List_assignment.py
927
3.8125
4
words = "It's thanksgiving day. It's my birthday,too!" print words.find('d') print words[18:21] m = 'month' print words[:18] + m + words[21:] #another way of doing this will be print words.find('day') words = words.replace('day', 'month') print words #Printing Min & Max x = [2,54,-2,7,12,98] minV = min(x) maxV = max(x) print minV print maxV #Printing First and Last x = ["hello",2,54,-2,7,12,98,"world"] first = x[0] last = x[-1] new = [] new.append(first) new.append(last) print first print last print new #Printing New List x = [19,2,54,-2,7,12,98,32,10,-3,6] x.sort() half =len(x)/2 count = len(x) print len(x) print x num = x[:half] newL = [] newL.append(num) for num in range(half, count): newL.append(x[num]) print newL #another way of doing this will be y = [19,2,54,-2,7,12,98,32,10,-3,6] y.sort() first_list = x[:len(x)/2] second_list = x[len(x)/2:] second_list.insert(0, first_list) print second_list
d14e3b7cd7ff62fdbc3cc59ed177271e82ee4c17
Ebrahim94/Data_structures
/Arrays and Linked List/2_check_strings_anagram.py
452
4.21875
4
#goal is to write a function to check if two strings are anagrams of one another #the function should take in two inputs of type String and output a Boolean def anagram(string1, string2): string1 = string1.replace(" ", "").lower() string2 = string2.replace(" ", "").lower() if sorted(string1) == sorted(string2): return 'This is an anagram' else: return 'This is not an anagram' print(anagram('raat', 'taar'))
bae39fcca485917faec4df3a8316c7b7479694de
Ghostant/basic-python-selenium-test
/src/test2.py
584
3.921875
4
name = "Yevhen" height = "197" weight = "72" married = False print(name) print(height + height) print("My name is " + name) print(name + " is " + str(height) + " cm and " + str(weight) + " kg") print("name is {} and height {}".format(name, height)) a = 4 b = 6.5 c = "2.5" print(a + b) age = 12 if (age < 10): print("child") elif (age <= 19): if(age < 13): print("small") print("teenager") elif (age < 65): print("adult") else: print("retiree") lis = [12, 44.3, 'a', ['h', 'i']] print(lis[3]) print(lis[3][0]) print(lis) lis.append("new") print(lis)
41b0af3a67fcf7e28128c07b398560482cb3a4fd
zengx-git/teachingpython
/20201008list.py
374
3.859375
4
#问题引入,要求把输入的所有信息记录下来,供后面其它地方使用 import os import time while True: strInput = input("请输入内容:") print(strInput) if strInput.upper() == "Q": print("输入结束") break; #怎么把输入的内容找出来呢??? print("????") # print(listStore) time.sleep(100)
d42cc6d91494260c8ae3d0f9b22e9d4451b6bae1
SamuelJadzak/UNITTESTINGCLASS
/test_Calculator.py
578
3.53125
4
import unittest from Calculator import calculator class testcase1(unittest.TestCase): def test_additioncheck(self): result = calculator.add(5,5) self.assertEqual(result, 10) def test_subtractioncheck(self): result = calculator.subtract(10,5) self.assertEqual(result, 5) def test_multiplycheck(self): result = calculator.multiply(2,2) self.assertEqual(result, 4) def test_dividecheck(self): result = calculator.divide(4,2) self.assertEqual(result, 2) if __name__ == '__main__': unittest.main()
b71f395bb4a7c45e6ad603ccc9cc58f4a6967b0d
shuiqukeyou/CodeExercise
/python/Data-structure-408/Sorting.py
8,348
3.546875
4
import random import Time_count from DataStructureClass import LinkL # 无标记冒泡 @ Time_count.timecount def bubble_sort1(l): i = 0 while i < len(l) - 1: j = len(l) - 1 while j > i: if l[j - 1] > l[j]: l[j], l[j - 1] = l[j - 1], l[j] j = j - 1 i = i + 1 # 有标记冒泡 @ Time_count.timecount def bubble_sort2(l): i = 0 while i < len(l) - 1: j = len(l) - 1 tag = True while j > i: if l[j - 1] > l[j]: tag = False l[j], l[j - 1] = l[j - 1], l[j] j = j - 1 if tag: break i = i + 1 # 双端冒泡 @ Time_count.timecount def double_bubble_sort(l): i = 0 j = len(l) - 1 while i<j: tag = True temp = j while temp > i: if l[temp - 1] > l[temp]: tag = False l[temp], l[temp - 1] = l[temp - 1], l[temp] temp = temp - 1 i += 1 if tag: break temp = i while temp < j: if l[temp + 1] < l[temp]: tag = False l[temp], l[temp + 1] = l[temp + 1], l[temp] temp = temp + 1 j -= 1 if tag: break # 插入排序 @ Time_count.timecount def insert_sort1(l): i1 = 1 n = len(l) while i1 < n: i2 = 0 temp = l[i1] while i1 > i2: if temp < l[i2]: l.insert(i2, temp) l.pop(i1 + 1) break i2 = i2 + 1 i1 = i1 + 1 # 插入排序(折半) @ Time_count.timecount def insert_sort2(l): i = 1 n = len(l) while i < n: j = 0 k = i - 1 temp = l[i] while j <= k: mid = int((j + k) / 2) if temp < l[mid]: k = mid - 1 else: j = mid + 1 if l[j] < temp: l.insert(j + 1, temp) else: l.insert(j, temp) i = i + 1 l.pop(i) # 希尔排序 @ Time_count.timecount def shell_sort(l): i = 1 n = len(l) while i < n / 3: i = i * 3 + 1 # 1,4,13...... while i >= 1: i1 = i while i1 < n: i2 = 0 temp = l[i1] while i1 > i2: if temp < l[i2]: l.insert(i2, temp) l.pop(i1 + 1) break i2 = i2 + i i1 = i1 + i i = int(i / 3) # 快速排序 @ Time_count.timecount def quick_sort(l): qsort(l, 0, len(l) - 1) def qsort(l, lift, right): if right < lift: return m = partition(l, lift, right) qsort(l, lift, m - 1) qsort(l, m + 1, right) def partition(l, lift, right): key = l[lift] while lift < right: while lift < right and l[right] >= key: right = right - 1 l[lift] = l[right] while lift < right and l[lift] <= key: lift = lift + 1 l[right] = l[lift] l[right] = key return lift # 划分奇偶 def select(l): i = 0 n = len(l) - 1 while i < n: while i < n and l[i] % 2 == 1 : i += 1 while i < n and l[n] % 2 == 0 : n -= 1 l[i], l[n] = l[n], l[i] # 划分子集问题 def minn_maxs(l): return qminn_maxs(l,0,len(l) - 1) def qminn_maxs(l, left, right): lastleft = 0 lastright = len(l) - 1 while True: key = l[left] while left < right: while left < right and l[right] >= key: right -= 1 l[left] = l[right] while left < right and l[left] <= key: left += 1 l[right] = l[left] l[left] = key if left == int(len(l)/2): return left if left < int(len(l)/2): left += 1 lastleft = left right = lastright else: lastright -= 1 right = lastright left = lastleft # 选择排序(无标记、交换法) @ Time_count.timecount def select_sort1(l): i = 0 n = len(l) while (i < n): j = i min = i while (j < n): if l[j] < l[min]: min = j j = j + 1 l[i], l[min] = l[min], l[i] i = i + 1 # 选择排序(无标记、插入删除法) @ Time_count.timecount def select_sort2(l): i = 0 n = len(l) while (i < n): j = i min = i while (j < n): if l[j] < l[min]: min = j j = j + 1 l.insert(i, l[min]) l.pop(min + 1) i = i + 1 # 选择排序(有标记、交换法) @ Time_count.timecount def select_sort3(l): i = 0 n = len(l) while (i < n): j = i min = i tag = True while (j < n): if l[j] < l[min]: tag = False min = j j = j + 1 if tag: break l[i], l[min] = l[min], l[i] i = i + 1 # 选择排序(有标记、插入删除法) @ Time_count.timecount def select_sort4(l): i = 0 n = len(l) while (i < n): j = i min = i tag = True while (j < n): if l[j] < l[min]: tag = False min = j j = j + 1 if tag: break l.insert(i, l[min]) l.pop(min + 1) i = i + 1 # 归并排序 @ Time_count.timecount def merge_sort(l): temp = l[:] merge_sort2(l, 0, len(l) - 1, temp) def merge_sort2(l, a, c, temp): if c <= a: return b = int((a + c) / 2) merge_sort2(l, a, b, temp) merge_sort2(l, b + 1, c, temp) merge(l, a, b, c, temp) def merge(l, a, b, c, temp): i, j = a, b + 1 n = a while n <= c: temp[n] = l[n] n = n + 1 k = i while k <= c: if i > b: l[k] = temp[j] j = j + 1 elif j > c: l[k] = temp[i] i = i + 1 elif temp[i] > temp[j]: l[k] = temp[j] j = j + 1 else: l[k] = temp[i] i = i + 1 k = k + 1 def newRandomLink(n): node = None for i in range(n): node = LinkL(random.randint(0, n), node) i += 1 return node def printLink(l): print("准备输出") s = "" i = 0 while (l != None): i += 1 if i> 100: print("死循环") break s = s + str(l.data) + " " l = l.link print(s) # 链表选择排序 def select_sort_LinkedList(l): wh = None w = None t = None p = None # 以上模拟C语言指针初始化 wh = l l = None while wh.link != None: p = wh t = wh w = wh while w != None and w.link != None: if w.link.data >= t.data: t = w.link p = w w = w.link if p == t: wh = wh.link else: p.link = t.link t.link = l l = t wh.link = l l = wh return l # 链表选择排序2 def select_sort_LinkedList2(l): h = None p = None q = None s = None r = None h = l l = None while h != None: p = h s = h q = None r = None while p != None: if p.data > s.data: s = p r = q q = p p = p.link if s == h: h = h.link else: r.link = s.link s.link = l l = s return l if __name__ == '__main__': # l = [] # for i in range(0,10): # l.append(random.randint(0,10)) # print(l) # bubble_sort1(l) # bubble_sort2(l) # double_bubble_sort(l) # insert_sort1(l) # insert_sort2(l) # shell_sort(l) # quick_sort(l) # select(l) # s = minn_maxs(l) # print(s) # select_sort1(l) # select_sort2(l) # select_sort3(l) # select_sort4(l) # merge_sort(l) # print(l) linklist = newRandomLink(10) printLink(linklist) # linklist2 = select_sort_LinkedList(linklist) linklist2 = select_sort_LinkedList2(linklist) printLink(linklist2)
7721f1f89ce35c36faf2b6ff0b0d8ad5b11f293e
mmanfrin/cenapad_py
/aula1/task1.py
407
3.5625
4
#Exercício 1: calcule a média dos numeros ímpares até 100 usando slices, a função len e a função sum n100 = list(range(0,101)) print(f'\nListagem 0-100: {n100}') impar = n100[1::2] print(f'\nListagem dos números ímpares: {impar}') imparTotal = sum(impar) print(f'\nSomatória dos números ímpares: {imparTotal}') media = imparTotal / len(impar) print(f'\nMédia dos números ímpar: {media}')
701d5535220c4025d43a5d956c6643ba3f4a033a
daniel-reich/turbo-robot
/RejeSPe68ajYzzgXM_3.py
1,248
4.21875
4
""" Create a function that, when given a list of individual [finite-state automaton](https://en.wikipedia.org/wiki/Finite-state_machine) instructions, generates an FSA in the form described in [this challenge](https://edabit.com/challenge/86CrsZ2rRMnCsDSza). Each instruction will be a list of three elements: The first element will be the current state, the second element will be the input to which the instruction pertains, and the third element will be the new state. For example, the instruction `["S0", 1, "S1"]` indicates that, if the current state is `"S0"`, upon receiving a `1` as input, the new state will be `"S1"`. A deconstruction of the FSA from [this challenge](https://edabit.com/challenge/mmiLWJzP3mvhjME7b) can be seen below: ### Examples divisible = [ ["S0", 0, "S0"], ["S0", 1, "S1"], ["S1", 0, "S2"], ["S1", 1, "S0"], ["S2", 0, "S1"], ["S2", 1, "S2"] ] combine(divisible) ➞ { "S0": ["S0", "S1"], "S1": ["S2", "S0"], "S2": ["S1", "S2"] } ### Notes * Every FSA will use a binary alphabet. * All states will be of the form `Sn`, where `n` is an integer, e.g. `S2`. """ def combine(lst): return {a[0]: [a[2], b[2]] for a, b in zip(lst[::2], lst[1::2])}
5023a71b1f0e1d5bf0dd0cfca26cebf25179657f
YorkFish/learning_notes
/Python3/MorvanZhou/Tkinter/Tkinter_12.py
893
3.671875
4
#!/usr/bin/env python3 # coding:utf-8 import tkinter as tk window = tk.Tk() # 窗口 object window.title("my window") # 标题 window.geometry("300x200") # 窗口大小 ''' # 1. pack() tk.Label(window, text=1).pack(side="top") tk.Label(window, text=1).pack(side="bottom") tk.Label(window, text=1).pack(side="left") tk.Label(window, text=1).pack(side="right") # 2. grid() for i in range(4): for j in range(3): # tk.Label(window, text=1).grid(row=i, column=j) # tk.Label(window, text=1).grid(row=i, column=j, padx=10, pady=10) # 设置控件周围横、纵空白区域保留大小 tk.Label(window, text=1).grid(row=i, column=j, ipadx=10, ipady=10) # 初看同上 ''' # 3. place() # tk.Label(window, text=1).place(x=10, y=100) tk.Label(window, text=1).place(x=10, y=100, anchor="nw") window.mainloop() # 循环刷新
ab1e33d40a99b68c8477af45ee64f5d31c4af2f9
Wakwandou/youtube-videos
/greedy-programming/scheduling.py
2,795
4.15625
4
import random as random def schedule_jobs(jobs, length): ''' Returns a schedule that maximzes the payoff of the jobs available given a list of jobs. Jobs are in format of (job_number, deadline, payoff) ''' schedule = [] # sorting based on payoff jobs.sort(key = lambda job: job[2]) # loop through until we have no room to add jobs while length > 0 and len(jobs) > 0: for job in jobs: # if we can add jobs add them if(length <= job[1]): schedule.append(job) jobs.remove(job) break # subtract the cost of the job to get interval length available length -= 1 return schedule def schedule_intervals(intervals, length): ''' Returns a schedule that maximizes the amount of intervals available to be ran given a list of intervals. Intervals are in the format of (intervals_number, start, duration) Intervals are later changed to (intervals_number, start, duration, end) ''' schedule = [] time = 0 # calculate end time by appending it towards the end interval = list(map(lambda interval: interval.append(interval[1] + interval[2]), intervals)) # sorting based on earilest deadline first intervals.sort(key = lambda interval: interval[3]) # loop through until we have no room to add jobs while time < length and len(intervals) > 0: # check if we can fit the first interval if(length >= intervals[0][3]): time = intervals[0][3] schedule.append(intervals[0]) intervals.pop(0) # now remove all incomptiable intervals for interval in intervals: if interval[1] < time: intervals.remove(interval) return schedule def generate_random_jobs(length, count=-1): ''' Generates a list of jobs in a tuple format of (job_number, deadline, payoff) ''' if count < 0: count = random.randint(10, 20) jobs = [[x, random.randint(1, 5), random.randint(2, 10) * 10] for x in range(count)] return jobs def generate_random_intervals(length, count=-1): ''' Generates a list of intervals in a tuple format of (intervals_number, start, duration) ''' if count < 0: count = random.randint(10, 20) intervals = [[x, random.randint(1, length), random.randint(1, 3)] for x in range(count)] # fixing all the intervals that are past the length for interval in intervals: if interval[0] + interval[1] > length: interval[1] = length - interval[0] return intervals if __name__ == "__main__": print(schedule_jobs(generate_random_jobs(6), 6)) print(schedule_intervals(generate_random_intervals(20), 20))
778cc52561e37918842f493fd0d2200536d19969
lucascalebe/cs50-psets
/PSET 6/cash.py/cash.py
486
3.828125
4
from cs50 import get_float dollars = get_float("Change owed: ") # get just positive numbers while dollars <= 0: dollars = get_float("Change owed: ") count = 0; #converting dollar to cents cents = round(dollars * 100) while cents > 0: if cents >= 25: cents -= 25 count += 1 elif cents >= 10: cents -= 10 count += 1 elif cents >= 5: cents -= 5 count += 1 else: cents -= 1 count += 1 print(count)
aa82d0a09e08860e086659e643bbe5d4428645f3
Stepess/machine_learning_basic_alg
/desicion_tree/main.py
4,552
3.75
4
from sklearn import * import numpy as np import operator def unique_vals(rows, col): """Find the unique values for a column in a dataset.""" return set([row[col] for row in rows]) def class_counts(rows): """Counts the number of each type of example in a dataset.""" counts = {} # a dictionary of label -> count. for row in rows: # the label is always the last column label = row[-1] if label not in counts: counts[label] = 0 counts[label] += 1 return counts class Question: """A Question is used to partition a dataset.""" def __init__(self, column, value): self.column = column self.value = value def match(self, example): return example[self.column] >= self.value def partition(rows, question): """Partitions a dataset.""" true_rows, false_rows = [], [] for row in rows: if question.match(row): true_rows.append(row) else: false_rows.append(row) return true_rows, false_rows def gini(rows): """Calculate the Gini Impurity for a list of rows. https://en.wikipedia.org/wiki/Decision_tree_learning#Gini_impurity """ counts = class_counts(rows) impurity = 1 for lbl in counts: prob_of_lbl = counts[lbl] / float(len(rows)) impurity -= prob_of_lbl ** 2 return impurity def info_gain(left, right, current_uncertainty): """Information Gain. The uncertainty of the starting node, minus the weighted impurity of two child nodes. """ p = float(len(left)) / (len(left) + len(right)) return current_uncertainty - p * gini(left) - (1 - p) * gini(right) def find_best_split(rows): """Find the best question to ask by iterating over every feature / value and calculating the information gain.""" best_gain = 0 best_question = None current_uncertainty = gini(rows) n_features = len(rows[0]) - 1 for col in range(n_features): values = set([row[col] for row in rows]) # unique values in the column for val in values: # for each value question = Question(col, val) true_rows, false_rows = partition(rows, question) # Skip this split if it doesn't divide the # dataset. if len(true_rows) == 0 or len(false_rows) == 0: continue gain = info_gain(true_rows, false_rows, current_uncertainty) if gain > best_gain: best_gain, best_question = gain, question return best_gain, best_question class Leaf: """A Leaf node classifies data. This holds a dictionary of class -> number of times it appears in the rows from the training data that reach this leaf. """ def __init__(self, rows): self.predictions = class_counts(rows) class Decision_Node: """A Decision Node asks a question.""" def __init__(self, question, true_branch, false_branch): self.question = question self.true_branch = true_branch self.false_branch = false_branch def build_tree(rows, level: int, max_depth: int): gain, question = find_best_split(rows) if gain == 0 or level == max_depth: return Leaf(rows) true_rows, false_rows = partition(rows, question) true_branch = build_tree(true_rows, level + 1, max_depth) false_branch = build_tree(false_rows, level + 1, max_depth) return Decision_Node(question, true_branch, false_branch) def classify(row, node): if isinstance(node, Leaf): return max(node.predictions.items(), key=operator.itemgetter(1))[0] if node.question.match(row): return classify(row, node.true_branch) else: return classify(row, node.false_branch) if __name__ == '__main__': iris = datasets.load_iris() X = iris.data[:, :2] y = (iris.target != 0) * 1 features_num = X.shape[0] test_p = 20 test_index = int(features_num - (test_p * features_num) / 100) data = np.c_[X, y] np.random.shuffle(data) train_x = data[:test_index, :2] train_y = data[:test_index, 2] test_x = data[test_index:, :2] test_y = data[test_index:, 2] training_data = np.c_[train_x, train_y] max_depth = 10 my_tree = build_tree(training_data, 0, 10) testing_data = np.c_[test_x, test_y] results = [classify(x, my_tree) for x in testing_data] accuracy = (results == test_y).mean() print('Accuracy is {0}'.format(accuracy))
35eb911412524d0cf1797cbd961d3a57a8443411
lancelote/stepik_algorithms_1
/src/module_4/continuous_backpack.py
868
4.09375
4
from typing import List from typing import NamedTuple class Thing(NamedTuple): price: int weight: int @property def unit_cost(self) -> float: return self.price / self.weight def max_value(capacity: int, data: List[Thing]) -> float: total_value = 0.0 things = sorted(data, key=lambda x: x.unit_cost, reverse=True) for thing in things: weight = min(thing.weight, capacity) total_value += weight * thing.unit_cost capacity -= weight if capacity == 0: break return round(total_value, 3) def main() -> None: data = list() n, capacity = [int(x) for x in input().split()] for _ in range(n): price, weight = [int(x) for x in input().split()] data.append(Thing(price, weight)) print(max_value(capacity, data)) if __name__ == "__main__": main()
2ba91c655ccf7a327fdb5a8d3fe6989cf12a6b2b
msarahan/chaco
/examples/tutorials/tutorial1.py
2,251
4.09375
4
"""Tutorial 1. Creating a plot and saving it as an image to disk.""" import os import sys from scipy import arange, pi, sin from chaco import api as chaco # First, we create two arrays of data, x and y. 'x' will be a sequence of # 100 points spanning the range -2pi to 2pi, and 'y' will be sin(x). numpoints = 100 step = 4*pi / numpoints x = arange(-2*pi, 2*pi+step/2, step) y = sin(x) # Now that we have our data, we can use a factory function to create the # line plot for us. Chaco provides a few factories to simplify creating common # plot types (line, scatter, etc.). In later tutorials we'll see what the # factories are actually doing, and how to manually assemble plotting # primitives in more powerful ways. For now, factories suit our needs. myplot = chaco.create_line_plot((x,y), bgcolor="white", add_grid=True, add_axis=True) # We now need to set the plot's size, and add a little padding for the axes. # (Normally, when Chaco plots are placed inside WX windows, the bounds are # set automatically by the window.) myplot.padding = 50 myplot.bounds = [400,400] def main(): # Now we create a canvas of the appropriate size and ask it to render # our component. (If we wanted to display this plot in a window, we # would not need to create the graphics context ourselves; it would be # created for us by the window.) plot_gc = chaco.PlotGraphicsContext(myplot.outer_bounds) plot_gc.render_component(myplot) # Get the directory to save the image in print 'Please enter a path in which to place generated plots.' print 'Press <ENTER> to generate in the current directory.' path = raw_input('Path: ').strip() path = os.path.expanduser(path) if len(path) > 0 and not os.path.exists(path): print 'The given path does not exist.' sys.exit() # The file name to save the plot as file_name = "tutorial1.png" if not os.path.isabs(path): print 'Creating image: ' + os.path.join(os.getcwd(), path, file_name) else: print 'Creating image: ' + os.path.join(path, file_name) # Finally, we tell the graphics context to save itself to disk as an image. plot_gc.save(os.path.join(path, file_name)) if __name__ == '__main__': main()
8d7d502d6d346fd31e638ac4222e4eecfc9eebda
Simochenko/PythonPracticalTasks
/2.1_data_output_and_input.py
4,747
4.09375
4
# print(5*5%3//2+7//2+1) # a = "5" # b = "7" # s = b + a # print(s) # first = '5' # second = 2 # print(first * second) # a = int('2') # b = '3' # s = a*b # print(s) # a = int(input()) # b = int(input()) # c = int(input()) # s = (a + b + c) # print(s) '''n школьников делят k яблок поровну, неделящийся остаток остается в корзинке. Сколько яблок достанется каждому школьнику? Сколько яблок останется в корзинке? Программа получает на вход числа n и k и должна вывести искомое количество яблок (два числа). Sample Input: 6 50 Sample Output: 8 2''' # n = int(input()) # k = int(input()) # print(k // n) # print(k % n) import math '''Напишите программу, которая приветствует пользователя, выводя слово Hello, введенное имя и знаки препинания по образцу: Sample Input: Harry Sample Output: Hello, Harry!''' # a = input() # print('Hello, ' + a + '!') '''Условие Дано число n. С начала суток прошло n минут. Определите, сколько часов и минут будут показывать электронные часы в этот момент. Программа должна вывести два числа: количество часов (от 0 до 23) и количество минут (от 0 до 59). Учтите, что число n может быть больше, чем количество минут в сутках. Sample Input: 150 Sample Output: 2 30''' # n = int(input()) # hours = n % (60 * 24) // 60 # minutes = n % 60 # print(hours, minutes) '''Условие Напишите программу, которая считывает целое число и выводит текст, аналогичный приведенному в примере (пробелы важны!) Sample Input: 1534 Sample Output: The next number for the number 1534 is 1535. The previous number for the number 1534 is 1533.''' # n = int(input()) # print(f'The next number for the number {n} is {n+1}.') # print(f'The previous number for the number {n} is {n-1}.') '''Условие В школе решили набрать три новых математических класса. Так как занятия по математике у них проходят в одно и то же время, было решено выделить кабинет для каждого класса и купить в них новые парты. За каждой партой может сидеть не больше двух учеников. Известно количество учащихся в каждом из трёх классов. Сколько всего нужно закупить парт чтобы их хватило на всех учеников? Программа получает на вход три натуральных числа: количество учащихся в каждом из трех классов. Sample Input: 20 21 22 Sample Output: 32''' # import math # a = int(input()) # b = int(input()) # c = int(input()) # print(math.ceil((a + b + c)/2)) '''Задача «Шнурки» Условие Обувная фабрика собирается начать выпуск элитной модели ботинок. Дырочки для шнуровки будут расположены в два ряда, расстояние между рядами равно aa, а расстояние между дырочками в ряду bb. Количество дырочек в каждом ряду равно NN. Шнуровка должна происходить элитным способом “наверх, по горизонтали в другой ряд, наверх, по горизонтали и т.д.” (см. рисунок). Кроме того, чтобы шнурки можно было завязать элитным бантиком, длина свободного конца шнурка должна быть ll. Какова должна быть длина шнурка для этих ботинок? Программа получает на вход четыре натуральных числа aa, bb, ll и NN - именно в таком порядке - и должна вывести одно число - искомую длину шнурка.''' a = int(input()) b = int(input()) L = int(input()) N = int(input()) print(2 * L + (2 * N - 1) * a + 2 * (N - 1) * b)
13e5f162bbadb660f88861eb56d3fb8c342ee99c
nathanwisla/PythonScriptCollection
/School Projects/lab 3 (Strings and formatting)/simpleTriangle.py
205
4.09375
4
##make a program that print's the user's name in a simple triangle. name = input('What is your name? ') for letterPosition in range(len(name)): print(name[letterPosition] * (letterPosition+1))
6e10d9b482990da0e2f164bdbe0a82d6fd6898a8
daniel-reich/ubiquitous-fiesta
/FLgJEC8SK2AJYLC6y_6.py
245
3.5625
4
def possible_path(lst): for cur,fut in zip(lst,lst[1:]): if cur=='H' and fut in (1,3) or cur in (1,3) and fut=='H': return False if isinstance(cur,int) and isinstance(fut,int) and cur%2==fut%2: return False return True
bf01799067f611f23b08f1857adaaea890439315
oisinm/MIS40750
/Assignment_1.py
5,933
4.03125
4
# -*- coding: utf-8 -*- """ Created on Mon Oct 05 22:23:29 2015 MIS40750: Python Programming, Databases, and Version Control Assignment @author: Oisin Mangan Student Number: 15201541 """ import math import sqlite3 # Function to calculate distance between two points in long lat format # Takes in two sets of coordinates in long lat format # Returns distance between the points def lat_long_distance(long1, lat1, long2, lat2): # Convert latitude and longitude to spherical coordinates in radians. degrees_to_radians = math.pi/180.0 # phi = 90 - latitude phi1 = (90.0 - lat1) * degrees_to_radians phi2 = (90.0 - lat2) * degrees_to_radians # theta = longitude theta1 = long1 * degrees_to_radians theta2 = long2 * degrees_to_radians # Compute spherical distance from spherical coordinates cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) + math.cos(phi1)*math.cos(phi2)) arc = math.acos( cos ) # Multiply arc by radius of the earth in kms to get distance in kms distance = 6373 * arc return distance # Function to calculate the distance from one location to all others # Takes in index number of location that distance is being calculated from # And the list that contains the sites that distance is being calculated to # Returns list containing distance from required site to each of the others def distance_between_sites(location_i, L): # Location is list of location data imported from database location_i_data = Location[location_i] Distance_List = [] for data in L: # ensure distance is 0 between one location and itself if data == location_i_data: d = 0.0 else: d = lat_long_distance(data[0], data[1], location_i_data[0], location_i_data[1]) Distance_List.append(d) return Distance_List # Function to determine nearest port to each location # No input required # Returns list with distance to nearest port for each location def nearest_port(): L = [] # Location is list of location data imported from database for i in range(len(Location)): # Ports is list of port data imported from database L1 = distance_between_sites(i, Ports) m = min(L1) L.append(m) return L # Function to calculate transport cost from one location to all others # Takes in distance list for location that cost is being evaluated for # Returns list containing transport cost from required location # to all others in the input list def transport_cost(D): Cost_List = [] # Location is list of location data imported from database for i in range(len(Location)): location_i_data = Location[i] location_i_tonnage = location_i_data[2] cost = location_i_tonnage * D[i] Cost_List.append(cost) return Cost_List # Function to sum values in a list # Takes in list (in this program list contains transport cost to other locations) # Returns the sum def sum_costs(L): sum = 0.0 for i in L: sum += i return sum # Function to calculate total tonnage that will be transported to the ports # No input required # Returns the sum of the tonnage at every site def total_tonnage(): sum = 0.0 # Location is list of location data imported from database for data in Location: sum += data[2] return sum # Function to provide index of nearest port to a given location # Takes in index of required location # Returns index of nearest port to that location def index_of_nearest_port(i): # Ports is list of port data imported from database L = distance_between_sites(i, Ports) index = L.index(min(L)) return index # This is the beginning of the main code # Import data from "ports" table in database into Python using SQL command conn = sqlite3.connect('renewable.db') # create a "connection" c = conn.cursor() # create a "cursor" c.execute("SELECT * FROM ports;") # execute SQL command Ports = [] for item in c: Ports.append(item) # Finished importing "ports" table. Data is stored in a list called Ports # Import data from "location" table in databse into Python using SQL command c.execute("SELECT * FROM location;") # execute SQL command Location = [] for item in c: Location.append(item) # Finished importing "location" table. Data is stored in a list called Location # Generate the total transportation cost for each location to all other locations # Ports are not included at this point Cost_To_Site = [] for i in range(len(Location)): D = distance_between_sites(i, Location) TC = transport_cost(D) sum = sum_costs(TC) Cost_To_Site.append(sum) # Generate List of transportation cost from each location to it's nearest port Cost_To_Port = [x * total_tonnage() for x in nearest_port()] # Generate List of total transporation cost from each location including # Transportation from other locations and transportation to nearest port Total_Cost_Port_And_Sites = [a + b for a, b in zip(Cost_To_Site, Cost_To_Port)] print "\nThe list below shows the total transportation cost for each location being used as the processing plant:" print "(based on nearest port being used in each case)\n" print Total_Cost_Port_And_Sites # Calculate the minimum transportation cost and print out details of selected location and port min_cost = min(Total_Cost_Port_And_Sites) print "\nThe minimum transportation cost from this list is:", min_cost, "tkm/year (tonne-kilometre/year)" location_index = Total_Cost_Port_And_Sites.index(min_cost) print "\nDetails of the location chosen for the processing plant (%dth in the list of %d) are:" % ((location_index+1), len(Location)) print "(long, lat, production)", Location[location_index] port_index = index_of_nearest_port(location_index) print "\nDetails of the chosen port (%drd in the list of %d) are:" % ((port_index+1), len(Ports)) print "(long, lat)", Ports[port_index]
a9c22c2934e325d4c600b29f5e84a24dc68f4eaf
Woosiq92/Pythonworkspace
/8_set.py
687
3.734375
4
# 집합 ( set ) # 중복 안됨, 순서 없음 my_set = {1, 2, 3, 3, 3} print(my_set) # 중복 허용 안함 java = {"유재석", "김태호", "양세형"} python = set(["유재석", "박명수"]) # 교집합 ( java 와 python 을 모두 할수 있는 사람 ) print (java & python ) print(java.intersection(python)) # 합집합 (java or python 중 하나라도 할 수 있는 사람 ) print(java | python ) print(java.union(python)) # 차집합 (java만 할 수 있는 사람) print(java - python ) print(java.difference(python)) #python 할 줄 아는 사람이 늘어남 python.add("김태호") print(python) # java 를 잊었어요 java.remove("김태호 ") print(java)
b0893edb265b30d041296b2a30839b157d5e143d
El-Bando/Python_Sheet
/Python_Sheet-master/code/Listen/Listen_sort.py
250
3.546875
4
def myfunc(e): return len(e) mylist = [4, 3, 5, 7, 3, 2] strlist = ['BMW', 'Tesla', 'GM'] mylist.sort() print('#1', mylist) mylist.sort(reverse=True) print('#2', mylist) print('#3', mylist.count(2)) strlist.sort(key=myfunc) print('#4', strlist)
8e983eeca522c2f695016729e8e2a245de035ee9
nikita-chudnovskiy/ProjectPyton
/00 Базовый курс/046 Генераторы списков Python/03 Двойные циклы.py
358
3.71875
4
a =[(i,j) for i in 'abc' for j in [1,2,3]] print(a) a =[i*j for i in [2,4,6,] for j in [2,4,6] ] # перемножим числа на числа и выведем если больше 10 print(a) a =[i*j for i in [2,4,6,] for j in [2,4,6] if i*j>10 ] # перемножим числа на числа и выведем если больше 10 print(a)
9c7c1f3c9122a1bbb01750bc5861ead638937f79
MihaChug/PRRIS
/MinMax/main.py
1,280
3.5625
4
# -*- coding: utf-8 -*- inputText = open("input.txt") data = inputText.read() #создаем список из слов для удобства поиска data = data.split(' ') inputText.close first = input("Input first word: ") second = input("Input second word: ") #определяем все вхождения первого и второго слова в исходном тексте firstInputs = [i for i in range(len(data)) if data[i] == first] secondInputs = [i for i in range(len(data)) if data[i] == second] #максимальная разница в индексах - максимальное расстояние maxRange = max(abs(firstInputs[0] - secondInputs[-1]), abs(secondInputs[0] - firstInputs[-1])) minRange = len(data) #ищем минимальное значение for i in firstInputs: for j in secondInputs: maxMin = abs(i - j) #если вычисленное расстояние больше текущего минимального и второй индекс больше первого, то переходим к следующему вхождению первого слова if minRange < maxMin and j > i: break minRange = min(minRange, maxMin) print(minRange - 1, " ", maxRange - 1)
15abd817e63cc5804a1dd0ccd6af90a0c6c7a7d7
mateuscorreiamartins/Curso-de-Python
/PythonExercicios/ex020.py
439
3.921875
4
# O mesmo professor do desafio anterior quer sortear a ordem de # apresentação de trabalhos dos alunos. # Faça um programa que leia o nome dos quatro alunos e mostre # a ordem sorteada. import random a1 = str(input('Nome do primeiro aluno: ')) a2 = str(input('Nome do segundo aluno: ')) a3 = str(input('Nome do terceiro aluno: ')) a4 = str(input('Nome do quarto aluno: ')) lista = [a1, a2, a3, a4] random.shuffle(lista) print(lista)
c0c2372da98f75a5b57092ab467400da7be1eb4a
smithevan/python_test
/caesar_cipher_exercise.py
883
4.1875
4
#trying out a basic encryption algorithm (caesar cipher) password = input("Save Password:") letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] def encrypt(password): encrypted_password = [] for char in range(len(password)): for l in range(len(letters)): if password[char] == letters[l]: new_char = letters[l + 3] encrypted_password.append(new_char) return encrypted_password def decrypt(key): decrypted_password = [] for char in range(len(key)): for l in range(len(letters)): if key[char] == letters[l]: new_char = letters[l - 3] decrypted_password.append(new_char) return decrypted_password key = encrypt(password) print(key) print(decrypt(key))
0e90cc458b17358b1cc07b702f4c037b23c51f78
kgerginov/dungeons-and-python
/src/treasures.py
963
3.5
4
from random import choice from src.spell import Spell from src.weapon import Weapon class Treasure: def __init__(self): self.treasures = { 'health_potion': [10, 20, 30, 50, 100], 'mana_potion': [10, 20, 30, 50, 100], 'weapon': [ Weapon(name='Sword', damage=20), Weapon(name='Bradve', damage=50), Weapon(name='Dagger', damage=15) ], 'spell': [ Spell(name='Fireball', damage=20, mana_cost=40, cast_range=2), Spell(name='Ice', damage=30, mana_cost=50, cast_range=2), Spell(name='Lightning', damage=50, mana_cost=70, cast_range=1) ] } def pick_treasure(self): loot = choice(list(self.treasures.keys())) return loot, choice(self.treasures.get(loot)) if __name__ == '__main__': t = Treasure() print(t.pick_treasure())
e31b0176539564d29f6c9084fd8af752c2170e14
Oscar-Oliveira/Python-3
/18_Exercises/B_Complementary/Solutions/Ex18.py
406
3.953125
4
""" Exercise 18 """ def pos_int(): value = input("Enter a positive integer: ") try: value = int(value) if value < 0: raise ValueError except ValueError: print(">>>Error: Value must be a positive integer") return pos_int() return value def main(): pos_int() if __name__ == "__main__": main() print("Done!")
21a6e597c6e1454a6ac3eea2592f4bd757191f23
tails1434/Atcoder
/ABC/169/C.py
181
3.625
4
import math from decimal import Decimal def main(): A, B = input().split() ans = Decimal(A) * Decimal(B) print(math.floor(ans)) if __name__ == "__main__": main()
bbde57885a890397ff221680947d859f9fed8f70
ashcarino/MP3-Python
/Coefficients_Polynomial.py
637
3.8125
4
def f(x): result = x**10+x+1 return result def least_norm_error_vector(experimental_points,n): error_array=[0]*n for i in range(0,n): error_array[i]=experimental_points[i][1] - f(experimental_points[i][0]) return error_array n=int(input("Enter number of experimental points you wish to input:")) experimental_points=[] print("Now enter the data point in order pairs:") for i in range(0,n): experimental_points.append([int(j) for j in input("Enter two value: ").split()]) error_array = least_norm_error_vector(experimental_points,n) print("Error array is:\n") print(error_array)
6b792e2101e2aef906a55c45f2990f3b5d56147c
kostcher/algorithmsPython
/hw_7/task_2.py
975
4.1875
4
# Отсортируйте по возрастанию методом слияния одномерный вещественный массив, # заданный случайными числами на промежутке [0; 50). Выведите на экран исходный и отсортированный массивы. import random def merge_sort(array): length = len(array) if length <= 1: return array middle = int(length / 2) result = merge(merge_sort(array[:middle]), merge_sort(array[middle:])) return result def merge(left, right): result = [] while left and right: if left[0] <= right[0]: result.append(left.pop(0)) else: result.append(right.pop(0)) if left: result += left if right: result += right return result source_array = [round(random.uniform(0, 49), 3) for i in range(5)] print(source_array) print(merge_sort(source_array))
1276472d7459a91f997ca1730401ffd894b77604
yuta346/Algorithms
/LeetCode/coinChange.py
910
3.8125
4
# You are given an integer array coins representing coins of different denominations # and an integer amount representing a total amount of money. # Return the fewest number of coins that you need to make up that amount. # If that amount of money cannot be made up by any combination of the coins, return -1. # You may assume that you have an infinite number of each kind of coin. class Solution(object): def coinChange(self, coins, amount): """ :type coins: List[int] :type amount: int :rtype: int """ dp = [float('inf')for _ in range(amount+1)] dp[0]=0 for i in range(len(dp)): for coin in coins: if i-coin>=0: dp[i] = min(dp[i], dp[i-coin]+1) return -1 if dp[-1]==float('inf') else dp[-1] sol = Solution() coins = [1,2,5] amount = 11 print(sol.coinChange(coins, amount))
973a04455185e799eabea33fdc4284198bfb8fb8
freshpie/python
/HelloPy/test/exception.py
932
3.53125
4
import sys import traceback class NegativeDivisionError(Exception): def __init__(self,value): self.value = value def foo(x): assert type(x) == int, ["타입 오루ㅠ","wfef"] return x*10 try: a=[1,2,3] #print(a[6]) #raise NameError("rrr") #raise NegativeDivisionError(4) raise ZeroDivisionError except IndexError as e: print("out of index!!!!!") print(e.args) except TypeError: print("type error!!!") except NameError as e: print(e.args) print("name error!!!") except NegativeDivisionError as e: print(e.args) print(e.value) print("NegativeDivisionError 에러가 났음") except: print("에러가 났음") exc, value, tb = sys.exc_info() print(exc, value, tb) traceback.print_exc() else: print("정상입니다.") finally: print("무조건~") try: print(foo(12)) except AssertionError as e: print(e.args[0])
7e14d08778e3934af61d69fe71d3b686a8b7fbb3
HermanObst/algoritmos-y-programacion-1
/Guia/serie15/ej5.py
208
3.515625
4
def par(n): if n == 1: return False else: return not par(n - 1) def impar(n): if n == 1: return True else: return not impar(n - 1) print(par(9)) print(impar(9)) print(par(10)) print(impar(10))
4d391906ada53b2b742ec91cd3895813d28942c4
MartiniBnu/DataScienceLearning
/python/exercises5.py
576
4.15625
4
number1 = 0 number2 = 0 try: number1 = int(input("Number 1:")) except: print("Invalid input!") try: number2 = int(input("Number 2:")) except: print("Invalid input!") try: signal = input("Chose your signal [+,-,*,/]:") except: print("Invalid input!") if signal == "+": print("Sum = "+str(number1+number2)) elif signal == "-": print("Minus = "+str(number1-number2)) elif signal == "*": print("Plus = "+str(number1*number2)) elif signal == "/": print("Division = "+str(number1/number2)) else: print("Invalid signal")
b8e2d0c35b8d6f196c1eb9784545ec2557006bf2
DanielEcheverry96/verificador-palindromos
/cola_doble.py
853
3.75
4
class ColaDoble: def __init__(self): self.items = [] def estaVacia(self): return self.items == [] # Asumimos que el frente de la Cola Doble corresponde al final de la lista def agregarFrente(self, item): self.items.append(item) # Asumimos que el final de la Cola Doble corresponde al inicio de la lista def agregarFinal(self, item): self.items.insert(0, item) # Devuelve y elimina el item del frente de la lista def removerFrente(self): return self.items.pop() # Devuelve y elimina el item del final de la lista def removerFinal(self): return self.items.pop(0) def tamano(self): return len(self.items) def inspeccionarFrente(self): return self.items[len(self.items) - 1] def inspeccionarFinal(self): return self.items[0]
ee3ff0b7fa8705a5b23dfc46747a4ea833bbc4df
pratikkarad/unipune-practicals
/ml/linear-reg.py
673
3.59375
4
# -*- coding: utf-8 -*- """ Created on Fri Apr 19 11:34:52 2019 @author: percy """ import numpy as np import pandas as pd from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt df = pd.read_csv('hours.csv') linear = LinearRegression() linear.fit(df[['Hours']],df['Risk']) #regression_line = [(linear.coef_*i)+linear.intercept_ for i in list(df['Hours'])] iVal = float(input('Enter your value: ')) iVal = np.array(iVal).reshape(1,-1) print('Input Prediction: ',linear.predict(iVal)) plt.scatter(list(df['Hours']), list(df['Risk'])) plt.plot(list(df['Hours']), linear.predict(df[['Hours']])) plt.scatter(iVal,int(linear.predict(iVal))) plt.show()
cbf86538e8000c27cefa3fa8c48598c2377ae90a
ShikhaShrivastava/Python-core
/List/Copy of Nested List.py
814
4.40625
4
'''creating copy of Nested list''' # shallow copy print(" ") print("Creating Copy Of Nested List") print(" ") print("1. Shallow Copy") print(" ") lst1 = [[1, 2], [3, 4]] print(lst1) print(id(lst1)) print(id(lst1[0])) print("copied list=") lst2 = lst1[:] print(lst2) print(id(lst2)) print(id(lst2[0])) print("Appending=") lst1.append([5, 6]) print(lst1) print(lst2) print("adding 33=") lst1[1][0] = 33 print(lst1) print(lst2) # Deep Copy import copy print(" ") print("2.Deep Copy") print(" ") lst11 = [[1, 2], [3, 4]] print(lst11) print(id(lst11)) print(id(lst11[0][1])) print("copied list=") lst22 = copy.deepcopy(lst11) print(lst22) print(id(lst22)) print(id(lst22[0][1])) print("Appending=") lst11.append([5, 6]) print(lst11) print(lst22) print("adding 33=") lst11[1][0] = 33 print(lst11) print(lst22)
d5454d6e1dd811740bf63b96504c7fde87420bac
dwagon/pydominion
/dominion/cards/Card_Forge.py
2,358
3.59375
4
#!/usr/bin/env python import unittest from dominion import Game, Card, Piles import dominion.Card as Card ############################################################################### class Card_Forge(Card.Card): def __init__(self): Card.Card.__init__(self) self.cardtype = Card.CardType.ACTION self.base = Card.CardExpansion.PROSPERITY self.desc = "Trash cards from hand and gain one worth the sum of the trashed cards" self.name = "Forge" self.cost = 7 ########################################################################### def special(self, game, player): """Trash any number of cards from your hand. Gain a card with cost exactly equal to the total cost in coins of the trashed cards.""" availcosts = set() for cp in game.cardTypes(): availcosts.add(f"{cp.cost}") player.output("Gain a card costing exactly the sum of the trashed cards") player.output("Costs = %s" % ", ".join(sorted(list(availcosts)))) tc = player.plr_trash_card(anynum=True, num=0, printcost=True) cost = sum(_.cost for _ in tc) player.plr_gain_card(cost=cost, modifier="equal", prompt=f"Gain card worth {cost}") ############################################################################### class Test_Forge(unittest.TestCase): def setUp(self): self.g = Game.TestGame(numplayers=1, initcards=["Forge", "Bureaucrat"]) self.g.start_game() self.plr = self.g.player_list(0) self.forge = self.g["Forge"].remove() def test_play(self): """Play the Forge""" tsize = self.g.trashpile.size() self.plr.piles[Piles.HAND].set("Estate", "Estate", "Estate") self.plr.add_card(self.forge, Piles.HAND) # Trash two cards, Finish Trashing, Select another self.plr.test_input = ["1", "2", "finish", "Bureaucrat"] self.plr.play_card(self.forge) self.assertEqual(self.plr.piles[Piles.DISCARD][0].cost, 4) self.assertIn("Estate", self.g.trashpile) self.assertEqual(self.g.trashpile.size(), tsize + 2) self.assertEqual(self.plr.piles[Piles.HAND].size(), 1) ############################################################################### if __name__ == "__main__": # pragma: no cover unittest.main() # EOF
486fc395fe1c1559bdeb10fc021b0a1767aa3feb
Jokertion/MOOC
/tempconvert_ii.py
1,151
3.671875
4
#温度转换 II Temp = input() if Temp[0] in ['C']: F_Temp = eval(Temp[1:]) * 1.8 + 32 print ("F"+"{:.2f}".format(F_Temp)) elif Temp[0] in ['F']: C_Temp =(eval(Temp[1:]) - 32 ) / 1.8 print ("C"+"{:.2f}".format(C_Temp)) """ 温度转换 II 描述 温度的刻画有两个不同体系:摄氏度(Celsius)和华氏度(Fabrenheit)。 请编写程序将用户输入华氏度转换为摄氏度,或将输入的摄氏度转换为华氏度。 转换算法如下:(C表示摄氏度、F表示华氏度) C = ( F - 32 ) / 1.8 F = C * 1.8 + 32 要求如下: (1) 输入输出的摄氏度采用大写字母C开头,温度可以是整数或小数,如:C12.34指摄氏度12.34度; (2) 输入输出的华氏度采用大写字母F开头,温度可以是整数或小数,如:F87.65指摄氏度87.65度; (3) 不考虑异常输入的问题,输出保留小数点后两位; (4) 使用input()获得测试用例输入时,不要增加提示字符串。 输入 示例1:C12.34 示例2:F87.65 输出 示例1:F54.21 示例2:C30.92 """
88508a2d0ea65871b3131e6876ef552c7c5e3040
niranjan-nagaraju/Development
/python/leetcode/3sum/3sum-1.py
1,418
3.71875
4
''' https://leetcode.com/problems/3sum/ Return all unique triplets that add upto 0 a + b + c = 0 Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ] ''' ''' Solution Outline: 1. Generate all pairs (a,b) and their sums, and store their indices in a lookup table 2. For each x in nums, find if a pair with (target-x) exists with all (a,b,x) different ''' from collections import defaultdict class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ pairs_sums = defaultdict(lambda: []) for i in xrange(len(nums)): for j in xrange(i+1, len(nums)): pairs_sums[nums[i]+nums[j]].append((i,j)) triplets = {} found = defaultdict(lambda: False) for i in xrange(len(nums)): x = nums[i] # we have already found a triplet involving [x] if found[x]: continue found[x] = True pairs = pairs_sums[-x] for a,b in pairs: # we know a<b # just check if i is not either of a or b so all triplets are unique # we need a triplet i < a < b if a <= i: continue a,b,c = sorted([nums[a],nums[b],x]) triplets[(a,b,c)] = [a,b,c] return triplets.values() if __name__ == '__main__': sol = Solution() assert sol.threeSum([0,0,0]) == [[0,0,0]] assert sol.threeSum([-1, 0, 1, 2, -1, -4]) == [[-1, -1, 2], [-1, 0, 1]] assert sol.threeSum([1,2,3,-1,0]) == [[-1, 0, 1]]
1e6c5c877ed43aacd7455257474f29c3ddb96f90
pratikt2212/High-Speed-Networking-Labs
/Lab 1/DeleteFromCircle.py
855
3.703125
4
import sys import os import random z = 0 while z != 1 : n = int(raw_input("N is the numbers in the circle :")) m = int(raw_input("M is the m^th index to be deleted :")) k = int(raw_input("K are the numbers remaining in the circle after deletion :")) count = 1 my = [0 for a in range(n)] print 'The numbers in the circle are : \n' for i in range(0,n) : my[i] = i print my[0:n] y = m while n > k : if n > y : del my[y] y = y + m n = n - 1 print my[0:len(my)] else: del my[y - n ] y = y + m - n n = n - 1 print my[0:len(my)] print my[0:len(my)] z = int(raw_input("Press 1 to end and 0 to repeat again")) #for i in range(0,k) : # print my[i]
8ade6a7931243445927895987c19275427dcafa1
upaezreyes/chem160module8
/pbc.py
371
3.578125
4
import numpy as np def neighbors(arr,x,y,n): arr = np.roll(np.roll(arr,shift=-x+n//2,axis=0),shift=-y+n//2,axis=1) return arr[:n,:n] a = np.arange(0,100).reshape(10,10) # creates an 10x10 array print(a) print(neighbors(a,0,0,3)) # creates a 3x3 array with values around position 0o print(neighbors(a,0,0,5)) # creates a 5x5 array with values around position 0
3c40cad59385550425405fe1326f23fd48f88ec1
ram-jay07/Code-Overflow
/Second smallest element in list
527
4
4
def second_smallest(numbers): if (len(numbers)<2): return if ((len(numbers)==2) and (numbers[0] == numbers[1]) ): return dup_items = set() uniq_items = [] for x in numbers: if x not in dup_items: uniq_items.append(x) dup_items.add(x) uniq_items.sort() return uniq_items[1] print(second_smallest([1, 2, -8, -2, 0, -2])) print(second_smallest([1, 1, 0, 0, 2, -2, -2])) print(second_smallest([1, 1, 1, 0, 0, 0, 2, -2, -2])) print(second_smallest([2,2])) print(second_smallest([2]))
0bcfa7953130c6989ca06967cfe2cd4e08d72e0b
neadie/pands-problem-set
/datetime.py
551
3.875
4
# -*- coding: utf-8 -*- """ Created on Sun Feb 3 21:54:08 2019 @author: Sinead Frawley Question 8 """ import datetime def getDateInWordFormat(): my_date = datetime.datetime.now() dayOfTheWeek=my_date.strftime("%A") monthOftheYear=my_date.strftime("%B") dateOfMonth=my_date.strftime("%d") year=my_date.strftime("%Y") currentTime=my_date.strftime("%I:%M:%S %p") print(dayOfTheWeek + ', '+ monthOftheYear + ' '+dateOfMonth+'th ' + year + ' at ' + currentTime) '''Monday, January 10th 2019 at 1:15pm''' getDateInWordFormat()
8ee4393e5dfe28f1df5a5c208cfb45fdf0ec4681
aernesto24/Python-el-practices
/Basic/Python-university/OOP/classes-extra.py
1,032
4.34375
4
"""we will show that self is not necessary,m is a convention on C is called this so we are using this Also we can name the parameter diff form the arguments, arguments are really created during this.name""" class Person: #IF we want to pass a tupple just put * plus the var name also * indicates that the value is optional #to send a dictionary we use **var def __init__(this, n, a, *v, **b): this.name = n this.age = a this.values = v this.books = b def deploy(self): print("Name: ", self.name) print("Age: ", self.age) print("Califications (Tuple): ", self.values) print("Books read (Dictionary): ", self.books) p1 = Person("Ernesto", 31) p1.deploy() print() """yo print the arguments of the class print(p1.name) print(p1.age)""" #Now an example with tuple p2 = Person("Diana", 28, 9,10,10) p2.deploy() print() #An example with dir p3 = Person("Marcelo", 12, 10,10,10, IT=1590, TheInstitute=697) p3.deploy()
7104da8ade40f1b4ff142ecd2c24705563eb8322
LeanderSilur/Snippets
/bezier/distance_point_curve/bezier_distance_example.py
8,044
3.53125
4
import numpy as np # Bezier Class representing a CUBIC bezier defined by four # control points. # # at(t): gets a point on the curve at t # distance2(pt) returns the closest distance^2 of # pt and the curve # closest(pt) returns the point on the curve # which is closest to pt # maxes(pt) plots the curve using matplotlib class Bezier(object): exp3 = np.array([[3, 3], [2, 2], [1, 1], [0, 0]], dtype=np.float32) exp3_1 = np.array([[[3, 3], [2, 2], [1, 1], [0, 0]]], dtype=np.float32) exp4 = np.array([[4], [3], [2], [1], [0]], dtype=np.float32) boundaries = np.array([0, 1], dtype=np.float32) # Initialize the curve by assigning the control points. # Then create the coefficients. def __init__(self, points): assert isinstance(points, np.ndarray) assert points.dtype == np.float32 self.points = points self.create_coefficients() # Create the coefficients of the bezier equation, bringing # the bezier in the form: # f(t) = a * t^3 + b * t^2 + c * t^1 + d # # The coefficients have the same dimensions as the control # points. def create_coefficients(self): co_coeffs = np.array([[-1, 3, -3, 1], [3, -6, 3, 0], [-3, 3, 0, 0], [1, 0, 0, 0]], dtype=np.float32) coeffs = np.multiply(co_coeffs.reshape((4, 4, 1)), points.reshape((1, 4, 2))) self.coeffs = np.sum(coeffs, axis=1).reshape(-1, 4, 2) # Return a point on the curve at the parameter t. def at(self, t): if type(t) != np.ndarray: t = np.array(t) pts = self.coeffs * np.power(t, self.exp3_1) return np.sum(pts, axis = 1) # Return the closest DISTANCE (squared) between the point pt # and the curve. def distance2(self, pt): points, distances, index = self.measure_distance(pt) return distances[index] # Return the closest POINT between the point pt # and the curve. def closest(self, pt): points, distances, index = self.measure_distance(pt) return points[index] # Measure the distance^2 and closest point on the curve of # the point pt and the curve. This is done in three steps: # (1) Define the distance^2 depending on the pt. Use the squared # distance to prevent an additional root. # D(t) = (f(t) - pt)^2 # (2) The roots of D'(t) are the extremes of D(t) and contain the # closest points on the unclipped curve. Only keep the minima # by checking if D''(roots) > 0 and discard imaginary roots. # Compare the distances of "pt" to the minima as well as the # start and end of the curve and return the index of the # shortest distance. # # This desmos graph is a helpful visualization. # https://www.desmos.com/calculator/ktglugn1ya def measure_distance(self, pt): coeffs = self.coeffs # These are the coefficients of the derivatives d/dx and d/(d/dx). da = 6*np.sum(coeffs[0][0]*coeffs[0][0]) db = 10*np.sum(coeffs[0][0]*coeffs[0][1]) dc = 4*(np.sum(coeffs[0][1]*coeffs[0][1]) + 2*np.sum(coeffs[0][0]*coeffs[0][2])) dd = 6*(np.sum(coeffs[0][0]*(coeffs[0][3]-pt)) + np.sum(coeffs[0][1]*coeffs[0][2])) de = 2*(np.sum(coeffs[0][2]*coeffs[0][2])) + 4*np.sum(coeffs[0][1]*(coeffs[0][3]-pt)) df = 2*np.sum(coeffs[0][2]*(coeffs[0][3]-pt)) dda = 5*da ddb = 4*db ddc = 3*dc ddd = 2*dd dde = de dcoeffs = np.stack([da, db, dc, dd, de, df]) ddcoeffs = np.stack([dda, ddb, ddc, ddd, dde]).reshape(-1, 1) # Calculate the real extremes, by getting the roots of the first # derivativ of the distance function. extrema = Bezier.np_real_roots(dcoeffs) # Remove the roots which are out of bounds of the clipped range [0, 1]. # [future reference] https://stackoverflow.com/questions/47100903/deleting-every-3rd-element-of-a-tensor-in-tensorflow dd_clip = (np.sum(ddcoeffs * np.power(extrema, self.exp4)) >= 0) & (extrema > 0) & (extrema < 1) minima = extrema[dd_clip] # Add the start and end position as possible positions. potentials = np.concatenate((minima, self.boundaries)) # Calculate the points at the possible parameters t and # get the index of the closest points = self.at(potentials.reshape(-1, 1, 1)) distances = np.sum(np.square(points - pt), axis = 1) index = np.argmin(distances) return points, distances, index # Point the curve to a matplotlib figure. # maxes ... the axes of a matplotlib figure def plot(self, maxes): import matplotlib.path as mpath import matplotlib.patches as mpatches Path = mpath.Path pp1 = mpatches.PathPatch( Path(self.points, [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4]), fc="none")#, transform=ax.transData) pp1.set_alpha(1) pp1.set_color('#00cc00') pp1.set_fill(False) pp2 = mpatches.PathPatch( Path(self.points, [Path.MOVETO, Path.LINETO , Path.LINETO , Path.LINETO]), fc="none")#, transform=ax.transData) pp2.set_alpha(0.2) pp2.set_color('#666666') pp2.set_fill(False) maxes.scatter(*zip(*self.points), s=4, c=((0, 0.8, 1, 1), (0, 1, 0.5, 0.8), (0, 1, 0.5, 0.8), (0, 0.8, 1, 1))) maxes.add_patch(pp2) maxes.add_patch(pp1) # Wrapper around np.roots, but only returning real # roots and ignoring imaginary results. @staticmethod def np_real_roots(self, coefficients, EPSILON=1e-6): r = np.roots(coefficients) return r.real[abs(r.imag) < EPSILON] if __name__ == '__main__': import math def matplotlib_example(bez, use_text): import matplotlib.pyplot as plt import matplotlib.path as mpath import matplotlib.patches as mpatches def onclick(event): if event.inaxes == None:return pt = np.array((event.xdata, event.ydata), dtype=np.float) print("pt", pt) points, distances, index = bez.measure_distance(pt) closest = points[index] distance = math.floor(distances[index]) Path = mpath.Path pp1 = mpatches.PathPatch(Path([pt, closest], [Path.MOVETO, Path.LINETO]), fc="none") pp1.set_color("#95a7df") ax.add_patch(pp1) ax.scatter(*pt, s=32, facecolors='none', edgecolors='b') if use_text: ax.text(*((pt+closest)/2), str(distance)) ax.text(*pt, str(pt.astype(np.int))) ax.text(*closest, str(closest.astype(np.int))) fig.canvas.draw() return None fig, ax = plt.subplots() cid = fig.canvas.mpl_connect('button_press_event', onclick) ax.grid() ax.axis('equal') ax.margins(0.4) bez.plot(ax) plt.title("Click next to the curve.") plt.show() def opencv_example(bez, shape, fac = 3): img = np.zeros(shape, dtype=np.float) for y in range(img.shape[0]): for x in range(img.shape[1]): img[y, x] = bez.distance2((x, y)) print(y, "/", shape[0]) import cv2 img = np.power(img, 1/3) img = ((1-(img / np.max(img)))*255).astype(np.uint8) img = np.flip(img, axis=0) resized_image = cv2.resize(img, (shape[1]*fac, shape[0]*fac), interpolation=cv2.INTER_NEAREST) cv2.imshow("distance", resized_image) cv2.waitKey(1) if __name__ == '__main__': # Create a Bezier object with four control points. points = np.array([[0, 0], [0, 1], [1,.8], [1.5,1]]).astype(np.float32) points *= 50 points += 10 bez = Bezier(points) opencv_example(bez, shape = (80, 110)) matplotlib_example(bez, use_text = False)
4601ce8beaa9fd2d19a87c76148d96cab37720b8
vitorskt/ExerciciosPython
/ex7 funcao.py
1,782
4.03125
4
#Faça um programa que use a função valorPagamento para determinar o valor #a ser pago por uma prestação de uma conta. O programa deverá solicitar #ao usuário o valor da prestação e o número de dias em atraso e passar estes #valores para a função valorPagamento, que calculará o valor a ser pago e #devolverá este valor ao programa que a chamou. O programa deverá então #exibir o valor a ser pago na tela. Após a execução o programa deverá voltar #a pedir outro valor de prestação e assim continuar até que seja informado #um valor igual a zero para a prestação. Neste momento o programa deverá #ser encerrado, exibindo o relatório do dia, que conterá a quantidade e #o valor total de prestações pagas no dia. O cálculo do valor a ser pago #é feito da seguinte forma. Para pagamentos sem atraso, cobrar o valor da #prestação. Quando houver atraso, cobrar 3% de multa, mais 0,1% de juros por #dia de atraso. def valorPagamento(valor_p, dias_a): #se dias atrasado for menor que 1 if dias_a < 1: valor = valor_p print(valor) return valor else: #senão, calcula o valor do pagamento com atraso valor = (valor_p + valor_p * 0.03 + 0.01 * dias_a) print(valor) return valor valor = [] valor_p = 0 dias_a = 0 quant_pagar = 0 valortotal = 0 while True: quant_pagar += 1 valor_p = float(input('Qual o valor da prestação? ')) dias_a = int(input('Quantos dias está em atraso? ')) if valor_p == 0: break valor.append(valorPagamento(valor_p, dias_a)) quant_pagar -= 1 for i in range(quant_pagar): valortotal += valor[i] print(f'Relatorio do dia: foram pagas {quant_pagar} prestacoes no valor: {valor}') print(f'Valor total em prestaçoes pagas: {valortotal:.2f}')
0368a554b0e59c7b2149bf3c7946b45cdac83cfc
zjmdyd/Web
/04_python/12_常用内建模块/01_datetime.py
4,752
3.71875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # datetime是Python处理日期和时间的标准库。 from datetime import datetime ## # 获取当前日期和时间 ## now = datetime.now() print(now) # 2018-10-09 17:34:17.195987 print(type(now)) # <class 'datetime.datetime'> # 注意到datetime是模块,datetime模块还包含一个datetime类,通过from datetime import datetime导入的才是datetime这个类。 # 如果仅导入import datetime,则必须引用全名datetime.datetime。 # datetime.now()返回当前日期和时间,其类型是datetime ## # 获取指定日期和时间 ## dt = datetime(2018, 10, 9, 17, 40) print(dt) ## # datetime转换为timestamp ## # 在计算机中,时间实际上是用数字表示的。我们把1970年1月1日 00:00:00 UTC+00:00时区的时刻称为epoch time,记为0(1970年以前的时间timestamp为负数),当前时间就是相对于epoch time的秒数,称为timestamp。 # 可见timestamp的值与时区毫无关系,因为timestamp一旦确定,其UTC时间就确定了,转换到任意时区的时间也是完全确定的, # 这就是为什么计算机存储的当前时间是以timestamp表示的,因为全球各地的计算机在任意时刻的timestamp都是完全相同的(假定时间已校准) # 把一个datetime类型转换为timestamp只需要简单调用timestamp()方法 dtsp = dt.timestamp() print(dtsp) # 1539078000.0 # 注意Python的timestamp是一个浮点数。如果有小数位,小数位表示毫秒数。 ## # timestamp转换为datetime ## t = 1539078000.0 dt = datetime.fromtimestamp(t) print(dt) # 2018-10-09 17:40:00 本地时间 utcdt = datetime.utcfromtimestamp(t) print(utcdt) # 2018-10-09 09:40:00 UTC时间 ## # str转换为datetime ## dstr = '2018-9-1 18:18:18' cday = datetime.strptime(dstr, '%Y-%m-%d %H:%M:%S') print(cday) ## # datetime转换为str # # 如果已经有了datetime对象,要把它格式化为字符串显示给用户,就需要转换为str,转换方法是通过strftime()实现的,同样需要一个日期和时间的格式化字符串: print(now.strftime('%a, %b %d %H:%M')) # Tue, Oct 09 18:02 # %a Weekday as locale’s abbreviated name. # %A Weekday as locale’s full name. # %d Day of the month as a zero-padded decimal number. 01, 02, …, 31 # %b Month as locale’s abbreviated name. # %B Month as locale’s full name. # %m Month as a zero-padded decimal number. 01, 02, …, 12 # %y Year without century as a zero-padded decimal number. 00, 01, …, 99 # %H Hour (24-hour clock) as a zero-padded decimal number. 00, 01, …, 23 # %I Hour (12-hour clock) as a zero-padded decimal number. 01, 02, …, 12 # %M Minute as a zero-padded decimal number. 00, 01, …, 59 # %S Second as a zero-padded decimal number. 00, 01, …, 59 ## # datetime加减 ## # 对日期和时间进行加减实际上就是把datetime往后或往前计算,得到新的datetime。加减可以直接用+和-运算符,不过需要导入timedelta这个类: from datetime import timedelta add = now + timedelta(hours=2) print(now) print(add) ## # 本地时间转换为UTC时间 ## # 本地时间是指系统设定时区的时间,例如北京时间是UTC+8:00时区的时间,而UTC时间指UTC+0:00时区的时间 # 一个datetime类型有一个时区属性tzinfo,但是默认为None,所以无法区分这个datetime到底是哪个时区,除非强行给datetime设置一个时区: from datetime import timezone tz_utc_8 = timezone(timedelta(hours=8)) # 创建时区UTC+8:00 dt = now.replace(tzinfo=tz_utc_8) print(dt) dt = datetime(2015, 5, 18, 17, 2, 10, 871012, tzinfo=timezone(timedelta(0, 28800))) # ?(0, 28800) print(dt) ## # 时区转换 ## utc_now = datetime.utcnow() print(utc_now) # 拿到UTC时间,并强制设置时区为UTC+0:00: utc_dt = utc_now.replace(tzinfo=timezone.utc) print(utc_dt) # astimezone()将转换时区为北京时间: bj_dt = utc_dt.astimezone(timezone(timedelta(hours=8))) print(bj_dt) # astimezone()将bj_dt转换时区为东京时间: tokyo_dt = bj_dt.astimezone(timezone(timedelta(hours=9))) print(tokyo_dt) # 时区转换的关键在于,拿到一个datetime时,要获知其正确的时区,然后强制设置时区,作为基准时间。 # 利用带时区的datetime,通过astimezone()方法,可以转换到任意时区。 # 注:不是必须从UTC+0:00时区转换到其他时区,任何带时区的datetime都可以正确转换,例如上述bj_dt到tokyo_dt的转换。 # 小结 # datetime表示的时间需要时区信息才能确定一个特定的时间,否则只能视为本地时间。 # 如果要存储datetime,最佳方法是将其转换为timestamp再存储,因为timestamp的值与时区完全无关。