blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
8e90a3db6383ffec0d4543255f7d357743016fe7
k-skor/cars_excercise
/cars_module.py
905
3.5
4
import php class GasCar(php.BaseCar): def __init__(self): self.sound = "brrrum" def drive(self): return self.sound def __add__(self, other): if type(other) is GasCar or type(other) is DieselCar: raise CarAccident() class DieselCar(php.BaseCar): def __init__(self):...
c8af7a794f8074f9c803cd7ebb61ae00b509f475
Frigus27/Structure-Iced
/iced/game_object.py
2,130
4.1875
4
""" game_object.py -------------- The implement of the objects in the game. The game object is the minimum unit to define a interactive object in a game, e.g. a block, a road, a character, etc. In Structure Iced, you can easily define an object by simply inherit the class game_object. A game object requires the argum...
09c89b830bd5353ec99c9021182c7e4674eaabfa
YadaYuki/cracking-coding-interview-python
/8/permutation_string.py
598
3.96875
4
def permutation_string(string): if string == "": return [""] char = string[0] remainder = string[1:] remainder_permutaion_arr = permutation_string(remainder) permutation_arr = [] for remainder_permutaion in remainder_permutaion_arr: for i in range(0,len(remainder)+1): permutation_arr.append...
355e1fc5759b3bfb57ff3e1b4a0ec8cb2167e5f2
YadaYuki/cracking-coding-interview-python
/1/transform-once.py
1,103
3.8125
4
def is_insert_one_letter(sl:str,ss:str) -> bool: # len(sl) > len(ss) nl,ns = len(sl),len(ss) if (ns+1) is not nl: return False for i in range(nl): if sl[0:i] + sl[i+1:nl] == ss: return True return False def is_change_one_letter(s1:str,s2:str) -> bool: if len(s1) != len(...
6d923cfe72431f059bd28ed6e4f569658e9a8670
YadaYuki/cracking-coding-interview-python
/8/triple_step.py
512
3.859375
4
#8-1 def get_n_step_up_stairs_pattern(n:int)->int: # O(n) pattern_arr = [0 for _ in range(n)] pattern_arr[0],pattern_arr[1],pattern_arr[2] = 1,2,4 for i in range(3,n): pattern_arr[i] = pattern_arr[i-3] + pattern_arr[i-2] + pattern_arr[i-1] return pattern_arr[n-1] if __name__ == "__main__": ...
5af0946bbfbc95adaf597096009150e0b2b229f7
ZaderRox1111/Gas-Sim
/gas.py
2,239
3.90625
4
import turtle from random import * import math def main(): t = turtle.Turtle() t.ht() amount = 5 length = 500 dict_of_points = make_points(amount, length) draw_boundaries(t, length) for _ in range(500): move_points(t, dict_of_points, length) turtle.exitonclick() class Point:...
30e05f2bf9625b1b6bc54d01242f0d40c6cf51f3
liyl0663/liyl
/python/day02/login2.py
247
3.5625
4
import getpass username = input('please input your name:') password = getpass.getpass('please input your password:') print(username,password) if username == 'bob' and password == 123456: print('Login successful') else: print('Login faild')
bec62349207f6595cb597a8ebe9e377b2db68d7c
liyl0663/liyl
/python/day08/mydate.py
588
3.703125
4
class Data: def __init__(self,year,month,date): self.year = year self.month = month self.date = date @classmethod def create_date(cls,str_date): year,month,date = map(int,str_date.split('-')) return cls(year,month,date) @staticmethod def is_date_valid(str_dat...
193f1492692d918cd636ffdd95dc0e21d793e589
liyl0663/liyl
/python/day05/check_id.py
562
3.796875
4
import keyword from string import ascii_letters,digits first_chs = ascii_letters + '_' print(first_chs) other_chs = first_chs + digits print(other_chs) def check_id(idt): if keyword.iskeyword(idt): return '%s is a keyword' % idt if idt[0] not in first_chs: return '1st char invalid' for in...
63a117ec2e2014553e510fe50e2bc3062b1a1389
liyl0663/liyl
/python/day09/count_patt.py
603
3.5
4
import re from collections import Counter def count_patt(fname,patt): #patt_dict = {} result = Counter() cpatt = re.compile(patt) with open(fname) as fobj: for line in fobj: m = cpatt.search(line) if m: key = m.group() result.update([key])...
cda91b4d6567741519d9d2f9f970e5ccb482bb9c
liyl0663/liyl
/python/day02/grade.py
638
3.96875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- grade = int(input("请输入你的成绩:")) if grade >= 60 and grade <70: print("及格") #elif grade >= 70 and grade < 80: elif 70 <= grade <80: print("良") #elif grade >= 80 and grade < 90: elif 80 <= grade <90: print("好") elif grade >= 90: print("优秀") else: print("你要...
ba010350a533f20b703dd19b71f0b13f707eeb8d
liyl0663/liyl
/python/day02/if.py
260
3.921875
4
a = 10 b = 20 if a < b: smaller = a else: smaller = b print(smaller) ############################################## s=a if a<b else b print(s) ############################################## c = 20 d = 15 name = 'tom' if c < d else 'lili' print(name)
94396c829d87c87abc4b4b9fa49aa3aea182a23d
yasmineamr/Compilers-Lab
/part1/regex_to_nfa.py
7,170
3.53125
4
import re import argparse precedence_map = {'(':1, '|':2, '.':3, '?':4, '*':4, '+':4} def getPrecedence(char): try: precedence = precedence_map[char] return precedence except KeyError: return 6 def concatenate(regex): new_regex = '' operators_c = ['(','|'] operators_next_c...
fdb8d8c6fc7e36fba8b9836723599a127c90f502
onlybhau/cn
/CN Assignment Codes/sau/3.go-back-n and selective/as2.py
843
3.96875
4
import time print("Enter Value of m"); m=input() n=(2**m)-1; def gobackn(): print("\n\nSimulation Using Go Back N Sliding Window Protocol :\n\n") for i in range(n): print("Sending Frame :"+str(i)) time.sleep(1) fno=input("\n\nEnter Frame Number Which having Error :") for i in range(fno,n): print("Resen...
23171394a9d35469aa8afc63a30006c8d3364561
Parikirui/Flask1
/run.py
3,694
4.28125
4
#!/usr/bin/env python3.8 from user import User from credentials import Info def create_account(f_name,m_name,e_mail): new_user = User(f_name,m_name,e_mail) return new_user def create_credentials(face_bookp,e_mailp): new_cred = Info(face_bookp,e_mailp) return new_cred def save_account(user): user.sa...
d27cbfc671a7fad2ed479572272a49b99ed4d9f6
Celot1979/liga
/Liga.py
10,749
3.953125
4
import csv class Liga(): primera = {} segunda = {} segundaB = {} pr=[] def __init__(self, nombre_liga, numero_equipos): self.nombre = nombre_liga self.equipos = numero_equipos def __str__(self): return "El nombre de las ligas son: {}\nLa forman {} equipos\n".format(s...
1919710047123801c1aa281ec7a9cfca22e22d14
APuzyk/algorithms_coursera
/mwis.py
631
3.515625
4
file = '/home/apuzyk/Documents/algorithms_coursera/mwis.txt' with open(file) as f: o = f.readlines() o = [int(i.rstrip()) for i in o[1:]] a = list() a.append(0) a.append(o[0]) for i in range(2, len(o)+1): a.append(max([a[i-1], a[i-2] + o[i-1]])) s = [] i = len(a) - 1 while i >= 2: if a[i-1] >= a[i-2] + o...
413dddc841fc1710307345308f65b3488659f5fc
FelipeNorato/matrizes
/matriz.py
5,666
3.6875
4
class Matriz(object): def __init__(self, ordem): self.ordem = ordem self.representacao_matriz = [[] for lista_matriz in range(1 , ordem + 1)] self.repr_termos = [] self.result_x = [] self._value = [None for lista_matriz in range(1 , ordem +1)] def __getitem__(self, i):...
f614e4793a18218733763e20c32c0a1bc46f80db
lilianacandrea/Codeforces_Problems_Solutions
/1146A.Love_A.py
291
3.78125
4
word = input() temporarily = list(word) char_a = 0 for i in range(len(temporarily)): if temporarily[i] == 'a': char_a += 1 if char_a > (len(temporarily) / 2): print(len(temporarily)) elif char_a == (len(temporarily) / 2): print(len(temporarily) - 1) else: print(char_a + (char_a - 1))
c28d9ede48b5c683d129d8f18c93f823fe72be38
artsyanka/October2016Test1
/centralLimitTheorem-Outcomes-Lesson16.py
1,088
4.125
4
#Write a function flip that simulates flipping n fair coins. #It should return a list representing the result of each flip as a 1 or 0 #To generate randomness, you can use the function random.random() to get #a number between 0 or 1. Checking if it's less than 0.5 can help your #transform it to be 0 or 1 import rand...
2d3e7bd0a52df60a3cce48cf9f3ede860ec844dc
jness/Greyscale-Me
/greyscale_me.py
1,069
3.875
4
#!/usr/bin/env python import Image import argparse # Build my Parser with help for user input parser = argparse.ArgumentParser() parser.add_argument('message', help='Your message you wish to hide in a Grey Scale') parser.add_argument('filename', help='This is the name of the image') args = parser.parse_args() # Get t...
81844ccb6bb4711e251ab8e6cd65bb3092bb18a2
TrashPanda94/LearnPython
/gcdRecur.py
209
3.515625
4
# -*- coding: utf-8 -*- """ Created on Wed Nov 6 08:57:30 2019 @author: Seb """ def gcdRecur(a,b): if b ==0: return a else: return gcdRecur(b, a%b) test = gcdRecur(17,12) print(test)
1591cc661e9ddef30b40479ae8c4442eba978e4e
gzr7702/CardGame
/game.py
3,867
4.15625
4
""" The main module that runs the game. The game is played between two people taking turns at the same terminal. Typical usage: python game.py """ import sys from player import Player from deck import Deck def set_up(): """Set up the game with two players and print instructions. Returns: Two ...
c46c755b6d118c3b16087124e1a40067593f2e00
aogundimu/python_stuff
/Algorithms (Stanford)/Course 1/Week 3/Assignment.py
2,726
3.640625
4
#!/Applications/anaconda/bin/python import sys import numpy as np total_comp = 0 def partition(A, l, r, p): global total_comp total_comp = total_comp + (r-l) pivot = A[p] ## Swap the pivot value with the first element in the ## array segment tmp = A[l] A[l] = A[p] A[p] = tmp i =...
08e8f02c2f79c4735820c7e41ffc9ea301f62dc2
aogundimu/python_stuff
/Applied Data Science/Course_1_IntroductionToDataScience/Week_4/my_work.py
3,478
4.28125
4
#!/Applications/anaconda/bin/python import pandas as pd import numpy as np def distributions(): # Numbers from a numpy binomial distribution # parameter 1 - number of times we want it to run # parameter 2 - chances we get a 0 #print( np.random.binomial(1, 0.5) ) #print( np.random.binomial(1000, 0....
008edff9fb4cb2f24baaa02e0d9fb7a3bd8f00a0
Elly-bang/Tensorflow
/chap06_keras_model/exams/exam02_Keras_digits_DNN.py
1,699
3.59375
4
''' 문) digits 데이터셋을 이용하여 다음과 같이 keras 모델을 생성하시오. 조건1> keras layer L1 = 64 x 32 L2 = 32 x 16 L3 = 16 x 10 조건2> output layer 활성함수 : softmax 조건3> optimizer = 'adam', 조건4> loss = 'categorical_crossentropy' 조건5> metrics = 'accuracy' 조건6> epochs = 100 조건7> model save : k...
5545503bd4a70dd5380b35885614c21225b5bf80
katiewildros/learning_python
/3.2.py
4,402
4.09375
4
#3.2.1 # Напишите функцию update_dictionary(d, key, value), которая принимает на вход словарь d и два числа: key и value. # Если ключ key есть в словаре d, то добавьте значение value в список, который хранится по этому ключу. # Если ключа key нет в словаре, то нужно добавить значение в список по ключу 2∗key. Если и клю...
412ffc4ffeddcd63f70e07836aa4b863f52e40ab
grance1/2016-11-1
/2016-11-1/double-for.py
221
3.53125
4
for x in ['A','B','C']: for y in ['1','2','3']: print x + y for x in [1,2,3,4,5,6,7,8]: for y in [0,1,2,3,4,5,6,7,8,9]: if x >= y: continue num = 10 * x + y print num
040bf81de4d0203848c4abbd849a589979ba51f6
daniel8060/CodeSnippets
/ConwaysGameOfLife/gameOfLife.py
3,466
3.625
4
import random as rand import pyglet class GameOfLife: def __init__ (self,windowWidth,windowHeight,cellSize,odds): self.odds = odds self.gridWidth= int(windowWidth/cellSize) self.gridHeight= int(windowWidth/cellSize) self.cellSize = cellSize self.cells = [[0 for row...
7ccae5b51fc426e481dd9c4cb3cc1d3f274e542b
vincetita/Pythonwork
/addFunctionArgument.py
76
3.625
4
def add(a,b): c=a+b print("The result of adding ", a, "and", b, "is: ", c)
552bf6d3d88ba0881919d790d15e471107bde798
vincetita/Pythonwork
/breakStatement.py
606
3.6875
4
i=1 while(i<10): print(i) i=i+1 if(i==5): break print("++++++++++++++++++++++++++++++++++++") j=1 while(j==1): name= input("Enter name: ") if(name=="quit"): break print("++++++++++++++++++++++++++++++++++++") k=1 while(k<=100): k=k+1 if(k<=50): continue ...
2cada39078927f69a229dd5be92a789595937ebd
nvlatha/Session-1
/Assignment1.py
1,414
3.921875
4
# -*- coding: utf-8 -*- """ Created on Wed Dec 5 22:34:34 2018 @author: Latha NV """ #Latha - First code - Assignment 1 - Problem 1 #1. Install Jupyter notebook and run the first program and share the screenshot of the output. q=5 s="Latha" t=2.0 A=type(q) B=type(s) C=type(t) print(A) print(B) ...
eaa8e5f851c0b8cbf8ba1cb248770eb2281dd08f
einsteinpy/einsteinpy
/src/einsteinpy/plotting/fractal.py
3,364
3.625
4
"""Easter Egg. This module was added before ``0.3.0`` release as an Easter Egg. Contains a simple implementation of fractal. """ import numpy as np from plotly import graph_objects as go from einsteinpy.ijit import jit @jit def _julia(A, c, zabs_max, i, j, dims, x_range, y_range, iter_max): width, height = dim...
b579e7e4c50ed64154b48830b5d7e6b22c21dd64
Rogerd97/mintic_class_examples
/P27/13-05-2021/ATM.py
934
4.125
4
# https://www.codechef.com/problems/HS08TEST # Pooja would like to withdraw X $US from an ATM. The cash machine will only accept the transaction # if X is a multiple of 5, and Pooja's account balance has enough cash to perform the withdrawal transaction # (including bank charges). For each successful withdrawal the ...
52b49c89bcb5182b046f6119b53c22395fc2fc32
Rogerd97/mintic_class_examples
/P62/26-05-2021/exercise_5.py
149
3.53125
4
# Write a Python program to get days between two dates. Go to the editor # Sample Dates : 2000,2,28, 2001,2,28 # Expected Output : 366 days, 0:00:00
f1bde78d0c30669576025c3acb61a0cac0513986
Rogerd97/mintic_class_examples
/P27/01-06-2021/functions_examples.py
1,541
3.84375
4
# default parameters def fun(a, b, c=1, d=2): pass import datetime def func(delta_days=5): return datetime.datetime.now() + datetime.timedelta(days=delta_days) # Create a function that makes a math operation to a given number. By default, it should be to calculate # the sqrt import math number = input("...
9991e9d6a511b49a59666721185531185400b2d3
Rogerd97/mintic_class_examples
/P62/11-06-2021/example.py
1,171
3.78125
4
# my_dict = {"name": "jose", "surname": "garcia", "name": "jose-1"} # print(my_dict) # my_set = {True, 1, 2, 3, 4, 5, "jose", 3.4, -9} # print(my_set) # my_set = {1, 2, 3, 1, 2, 3, 4, 5 ,6, 1, 3} # print(my_set) # my_list = ["jose", "jose", "carolina", "jose", "betsy"] # my_set = set(my_list) # print(my_set) x1 = {...
0fe5baecb77522c4ea7d633953c18c808f253641
Rogerd97/mintic_class_examples
/P47/21-05-2021/exercise_1.py
1,417
3.75
4
# Dada una cadena de caracteres, determine cual es el caracter que mas se repite y # cuantas veces(case insensitive): ejemplo: input = 'hola soy la letra mas repetida' # output = a 5 phrase = input("Inserte la frase a analizar: ") phrase.replace(" ", "").lower() # {"a": 1, "b": 10, "c": 1 ...} score = {} for letter ...
0a24e4fb61b49d443c19968ecf056aa4074edee3
Rogerd97/mintic_class_examples
/P47/fundamentos_programacion + estructuras de control/Sesion2/algorithm_1.py
608
4.03125
4
number = input("Qué número? ") # Forma 1 if not number.startswith("-"): if not number.isdigit(): print("Esto no es un numero") else: number = number.lstrip("-") if not number.isdigit(): print("Esto no es un numero") # Forma 2 # if not number.lstrip("-").isdigit(): # print("Esto no es un númer...
0cf9aa91521f2941f2a817662f7c6dd56c19581e
Rogerd97/mintic_class_examples
/P27/01-06-2021/variables_scope.py
730
4.0625
4
# Example 1 x = "global" def foo(): print("x inside:", x) foo() print("x outside:", x) # Example 2 x = "global" def foo(): x = x * 2 print(x) foo() # Example 3 def foo(): y = "local" pepito = "jose" foo() print(y) # Example 4 def foo(): y = "local" print(y) foo() # Exampl...
60453b1b1ea943da2453ea116c61effd32ae6368
Rogerd97/mintic_class_examples
/P27/fundamentos_programacion + estructuras de control/sesion_2/logic3.py
267
4.0625
4
# if ... else ... # if ... else if ... else if ... else ... # if ... elif ... elif ... else # cond --> n == 0 # cond --> n > 0 # cond --> n < 0 number = 0 if number == 0: print("Es cero") elif number > 0: print("Es positivo") else: print("Es negativo")
aafc6f57ccb561d0364e81e36a0c95a432b95cf7
Rogerd97/mintic_class_examples
/P27/13-05-2021/government_program.py
874
3.90625
4
# Determine if a student can access a government subsidy to access to school education. There are 3 requirements: # 1. Must be not more than 40km to the round of school # 2. Have more than 2 brothers # 3. Family income is lower than 1000 dollars. distance_to_school = input("Insert the distance to the school: ") distan...
5ff84a677d4a9595a5d05185a7b0aecacea9e3dd
Rogerd97/mintic_class_examples
/P62/12-05-2021/if_else_2.py
1,325
4.34375
4
# Write a program that asks for the user for the month number # your script should convert the number to the month's name and prints it # Solution 1 # month_number = input("Insert a month number: ") # month_number = int(month_number) # months = {"1": "enero", "2": "febrero", "3": "marzo"} # if month_number < 1 or m...
ba55359a465d6335f8e3f9bc3b82e8c4786e0eb2
Rogerd97/mintic_class_examples
/P47/03-06-2021/dictionaries.py
3,851
3.875
4
# Write a Python script to concatenate following dictionaries to create a new one. # Sample Dictionary : # dic1={1:10, 2:20} # dic2={3:30, 4:40} # dic3={5:50,6:60} # Expected Result : {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60} # iterar for key in dic1.keys(): print(key) for value in dic1.values(): print(valu...
ba2cf9d99471af4cd757d84a0716d02a1f32ca20
Rogerd97/mintic_class_examples
/P27/25-05-2021/exercise_1.py
989
4.5
4
# Write a Python program to reverse a string # Sample String : "1234abcd" # Expected Output : "dcba4321" # def <name> (<arg_1>, <arg_2>, ... <arg_n>): # <algorithm> # [optional] return <result> def reverse_str(phrase): result = phrase[::-1] print(result) # my_str = input("Inserte la frase: ") # rever...
1c8ab3d7358c97399ee76c68896020d57f0a8a2a
Rogerd97/mintic_class_examples
/P27/12-05-2021/if_else_2.py
1,801
4.5
4
# Write a program that asks for the user for the month number # your script should convert the number to the month's name and prints it # month_number = input("Insert a month number: ") # month_number = float(month_number) # Solution 1 num= float(input("Ingrese el numero del mes : ")) # if num == 1: # print("Mes...
3b41d3051d166653385c7072bab3f1fc7bb3e462
Rogerd97/mintic_class_examples
/P62/26-05-2021/exercise_1.py
540
4.46875
4
# Write a Python script to display the various Date Time formats # a) Current date and time # b) Current year # c) Month of year # d) Week number of the year # e) Weekday of the week # f) Day of year # g) Day of the month # h) Day of week import datetime def print_dates(): date = datetime.datetime.now() print...
7d23f66decf7741002378f7895a5b49dd7d65d6c
Rogerd97/mintic_class_examples
/P47/26-05-2021/exercise_1.py
489
4.40625
4
# Write a Python script to display the various Date Time formats # a) Current date and time # b) Current year # c) Month of year # d) Week number of the year # e) Weekday of the week # f) Day of year # g) Day of the month # h) Day of week import datetime #a) date=datetime.datetime.now() print(date) #b) print(date.yea...
d4d7170fe4322de0457b03513fa76e43cf1245e2
Rogerd97/mintic_class_examples
/P47/01-06-2021/os_module.py
885
3.828125
4
# Write a Python program to get the name of the operating system (Platform independent), information of current # operating system, current working directory, print files and directories in the current directory # and raises error in the case of invalid or inaccessible file names and paths. import os file_system = os...
24bcea0dfd0797875fc46972e163cf42c7b2cd5f
RoccoFortuna/advent_of_code_2020
/d7_handy_haversacks/problem7.py
4,541
3.640625
4
import re from typing import List, Tuple, Dict, Set Color = str def parse_input_file(): with open('./d7_handy_haversacks/input.txt', 'r') as f: lines = f.read().strip().split('\n') clr_contains = {} for line in lines: a = line.split(" bags contain ") container_clr, second = line.s...
a0fde32c49fd6fb4cc46c786e9d69ca7ac5570d6
RoccoFortuna/advent_of_code_2020
/d12_rain_risk/problem12.py
7,237
3.984375
4
from typing import List, Tuple def parse_input_file() -> List[Tuple[str, int]]: input_path = "./d12_rain_risk/input.txt" with open(input_path, "r") as file: lines = file.read().splitlines() return [(line[0], int(line[1:])) for line in lines] def exec_instr_part1(position: Tuple[int, int, int], ...
e0be5e3bb1f012fc9de4311e09a967efa307d5a1
RoccoFortuna/advent_of_code_2020
/d22_crab_combat/problem22.py
4,991
3.796875
4
from typing import List, Tuple, Deque, Set from collections import deque import copy Deck = Deque[int] def parse_input_file(test: int = 0) -> Tuple[List[int], List[int]]: if not test: with open('./d22_crab_combat/input.txt', 'r') as f: lines = f.read().strip() else: with open(f'./...
d8c9642261f01ba9d39988a83ddeb615d04fa9f2
EgbieAndersonUku1/job_diary
/src/utilities/common.py
1,052
3.546875
4
##################################################################### # Author = Egbie Uku ##################################################################### from flask import flash from datetime import datetime import random def gen_row_id(): """_gen_row_id(void) -> return(str) A function that generates a five ...
1a629da87ec69fd285c0928f92c39a66663cab46
EgbieAndersonUku1/job_diary
/src/Users/Validator/date_validator.py
4,925
4.34375
4
##################################################################### # Author = Egbie Uku ##################################################################### from src.utilities.converter import month_to_str def fix_date(date): """fixes the date if date is not in the format of DD-MM-YYYY""" day, month, year...
4f069a6f6556718b6fee31ee7188caf1f4bfd857
aronvis/Python-Projects
/ShrinkableWord.py
355
4.0625
4
def is_shrinkable(word, lexicon): if word not in lexicon: return False if len(word) == 1: return True for letter_index in range(len(word)): shrunken_word = word[:letter_index] + word[letter_index+1:] if shrunken_word in lexicon and is_shrinkable(shrunken_word, lexicon): ...
d62d8674cc8ba84b42ee706ee2a21e5f364d429c
royromarate/password-encryptor
/password-encryptor.py
2,862
3.625
4
from argparse import ArgumentParser from base64 import b64decode, b64encode import sys from Crypto.Cipher import AES class PasswordEncryptor(): """Encrypts or decrypts a given value.""" # TODO: validate inputs # TODO: error handling _BLOCK_SIZE = 16 @staticmethod def _pad_value(value): ...
6c72a9377f44a13cf3a8685d670c38f8c4b2d308
ali-zab/Hello-world
/helloworld.py
505
3.59375
4
# avalin codet to python print("hello-world") # sakhtan moteghayer(variable) sadra = 8 mahdy = 16 #sakhtan moteghayer ha print(mahdy) print(sadra) # jam krdn moteghayer ha print(sadra + mahdy) #tarif krdn ye sharte mosbat ba moteghayer ha ass = True if ass is True: print("koon") #tarif kar...
a6dd3a2a7aa92ca324053f478c2d8b833df261c9
rparamastri/pi-dart
/piDart.py
3,042
4.1875
4
# piDart.py # author: Renata Paramastri # June 2016 import turtle import random import time RANDOM_COLOR = "black" MANUAL_COLOR = "gold" def main(): board = Board() board.drawBoard() turtle.onscreenclick(board.userThrow) return board class Board(object): def __init__(self, radius = 350, dartSiz...
62d96ec68f75075877369cb4f5ba3c573e78817e
fallcat/In-class-exercises
/20141023AnimalFarm.py
2,822
3.609375
4
from random import randint class Animal(object): gain_weight = 1 alive = True def __init__(self,name,age,weight,species,country): self.name = name self.age = age self.weight = weight self.species = species self.country = country def check(self): print "Name: %s" % self.name print "Age: %d" % self.age...
a94c817037a1d25a1d0682210faf2a6a8c0fbb25
nikolaithomas/dsp
/python/advanced_python_dict.py
2,361
3.515625
4
import numpy as np import numpy as np import pandas as pd from pandas import Series,DataFrame url = 'https://raw.githubusercontent.com/nikolaithomas/dsp/master/python/faculty.csv' df = pd.read_csv(url, index_col=None) df.columns = [x.strip().replace(' ', '_') for x in df.columns] def Cleandata_degree(df): df['na...
11e389a9d4cc48971e0fed01ab2662604bd8ea9e
Shamskol/CS-Buildweek2-Whiteboard-Practice
/search.py
654
4.09375
4
# Search in Rotated Sorted Array # You are given an integer array nums sorted in ascending order, and an # integer target. # Suppose that nums is rotated at some pivot unknown to you beforehand # (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). # If target is found in the array return its index, otherwise, re...
9d386d7dece46d9e947ae02c509e0ff10fa08be5
levi-fivecoat/Learn
/datatypes/strings.py
473
4.28125
4
my_str = "This is a string." my_str_2 = "I am a strings. I can contain numbers 12345" my_str_3 = "1390840938095" username = "levi : " # YOU CAN ADD STRINGS my_str = username + my_str my_str_2 = username + my_str_2 # YOU CAN SEE WHAT KIND OF DATA TYPE BY USING TYPE() print(type(my_str)) # UPPERCASES STRING my_str ...
9b326497b83f3dbe6d10eaf0ed6c8c26468bd7cb
IamLena/modeling
/ex01/lab_1/polynomial.py
4,415
3.5
4
class Polynomial: def __init__(self, n, k=None): self.degree = n if k is None: self.koef = [1 for i in range(n + 1)] else: if len(k) > n: k = k[:n + 1] elif len(k) < n: k.extend([0.0 for i in range(n - len(k))]) ...
6e51c1a3581a0cc8bc7d8e41680f53251813e718
SiddharthChakraborty1/python_assignment
/formula.py
250
3.921875
4
from math import sqrt C = 50 H = 30 def calculate_value(D): Q = int(sqrt((2 * C * D) / H)) return Q D_List = [int(x) for x in input("Enter comma separated values of D: ").split(',')] for D in D_List: print(f'{calculate_value(D) }')
1ec283d625a9d3c85d2800635f7fc2b6ab4adf7e
hklhai/python-study
/coll/tupleTest.py
552
4.125
4
# coding=utf-8 # 元组是不可变对象,元组支持嵌套 # 列表使用场景频繁修改的情况,元组对于不修改仅查询使用,查询效率高 a = (1, 2, "22") print(type(a)) for e in a: print(e) b = [x for x in a] print(b) # 生成器 b = (x for x in a) print(b) print(b.next()) print(b.next()) print(b.next()) # 元组的索引操作 print(a[1]) # 格式化输出字符串 print('abcd %d and %s' % (66, "hello")) b = (...
06b039df867a84d6bb3958b9333a4c2fb2b35a0a
Juxhen/Data14Python
/EulerStuff/evenfibnumbers.py
317
3.546875
4
the_list = [1, 2] even_numbers_list = [] flag = False while not flag: next_num = the_list[-1] + the_list[-2] if next_num <= 4000000: the_list.append(next_num) if next_num % 2 == 0: even_numbers_list.append(next_num) else: flag = True print(sum(even_numbers_list) + 2)
ec00202073e4f417041bdeda45eb357cd763c43c
Juxhen/Data14Python
/OOP/inheritance_example.py
1,194
3.984375
4
class Animal: def __init__(self, name, legs): self.name = name self.hunger = 5 self.legs = 4 print("I exist") def breathe(self): print("I'm breathing!") self.hunger += 0.1 def eat(self): print("I'm eating") self.hunger = 0 class Mammal(Anim...
aa878f2bfc544a6ffdb642d6279faba0addc552c
Juxhen/Data14Python
/Introduction/hello_variables.py
1,333
4.25
4
# a = 5 # b = 2 # c = "Hello!" # d = 0.25 # e = True # f = [1,2,3] # g = (1,2,3) # h = {1,2,3} # # print(a) # print(b) # print(c) # # # How to find the type of variables # print(type(a)) # print(type(b)) # print(type(c)) # print(type(d)) # print(type(e)) # print(type(f)) # print(type(g)) # print(type(h)) # CTRL + / To ...
1dbfe3554b41d7b76c135fbdd14b829d427d674b
Juxhen/Data14Python
/Introduction/textRPG.py
2,697
3.578125
4
import random as r import time as t playerCharacterChoiceIndex ={ 1: {"Type": "Mage", "Strength": "Melee", "Weakness": "Ranger"}, 2: {"Type": "Ranger", "Strength": "Mage", "Weakness": "Melee"}, 3: {"Type": "Warrior", "Strength": "Ranger", "Weakness": "Mage"}, } playerHealthList = [100] check1 = False while ...
ce7821c2907f2d3c314327eb74e55e9e90745994
Juxhen/Data14Python
/pokemon+tests/pokemon.py
7,377
3.640625
4
from json import JSONDecodeError import requests class PokemonStuff: def __init__(self, pokemon_name): try: self.pokemon_name = pokemon_name self.address = f"https://pokeapi.co/api/v2/pokemon/{pokemon_name}/" self.req_response = requests.get(self.address) s...
cbf2f111c6b2e948afc814786555fbe502f101e7
LaraGastaldi/edabit_exercises
/edabit/remove_vowels.py
171
3.890625
4
def remove_vowels(txt): new = [i for i in txt if i not in "aeiou" and i not in "AEIOU"] print(new) return "".join(new) print(remove_vowels("Hello I am Lara"))
7fc156f7b96cc2742effd447b5872df6148bbffc
LaraGastaldi/edabit_exercises
/edabit/indexcaps.py
182
4.03125
4
def index_of_caps(word): idxs = [] for idx, letter in enumerate(word): if letter.isupper(): idxs.append(idx) return idxs print(index_of_caps("aLoR"))
fad8f220525b48e1ff9110c58541cfc241da1cdb
LaraGastaldi/edabit_exercises
/edabit/missing_num.py
433
3.734375
4
def missing_num(lst): lst.sort() anterior = lst[0] missing = None for num in lst: if num == lst[0]: continue else: if num != (anterior + 1): missing = num - 1 anterior = num if missing == None: if lst[0] == 2: missin...
acf431c7d9445bd88c8fa55ec81dde2d41fa13e3
LaraGastaldi/edabit_exercises
/edabit/peoplesort.py
645
3.859375
4
class Person: def __init__(self, firstname, lastname, age): self.firstname = firstname self.lastname = lastname self.age = age p1 = Person('Michael', 'Smith', 40) p2 = Person('Alice', 'Waters', 21) p3 = Person('Zoey', 'Jones', 29) p4 = Person('Susan', 'Heffley', 43) p5 = Person('Bob', 'Fred...
58a54d5f17f7bd754bef89ee8c7b4cb1f7af607f
LaraGastaldi/edabit_exercises
/edabit/instajazz.py
178
3.515625
4
def jazzify(lst): new = [] for accord in lst: if accord[-1] != "7": new.append(accord+"7") else: new.append(accord) return new
7d599591f315452cb1c0c9c8fe802470d0053fcc
rajiv0903/Python
/python_basics/src/microsoft-exam/06_read_file.py
270
3.59375
4
''' Created on Nov 11, 2018 @author: rajiv ''' import os def read_file(file): line = None if os.path.isfile(file): data = open(file, 'r') while line != '': line = data.readline() print(line) read_file('x_text.txt');
012eabe7d8d2951804deb19592bf8ca0b780f9e2
rajiv0903/Python
/python_basics/src/beyond_basics/bb_01_function/airtravel.py
5,047
3.90625
4
''' Created on Aug 8, 2018 @author: rajiv ''' class Flight: ''' Initialization method - must be __intin - this is not a constructor Actual constructor is provided by Python Run time Environment ''' """ A flight with particular passenger aircraft- SN9888""" def __init__(self, num...
0fd85586cd127d6f7ff0d06f48356791977a902b
rajiv0903/Python
/python_basics/src/advance/a_08_abstract_base_cls/weapons_04.py
1,218
3.796875
4
from abc import ABC, abstractmethod # Here Sword will be virtual base class # ABCMeta required to implement class Sword(ABC): #metaclass is ABCMeta # This is same as your own custom meta class and overriding the issubclass and issubinstance @classmethod def __subclasshook__(cls, sub): return ((...
f9fd44aecc23871445443561dab2ca7c26ff37d7
rajiv0903/Python
/python_basics/src/fundamentals/f_04/04_Collections.py
457
3.796875
4
''' Created on Aug 6, 2018 @author: rajiv ''' #List are mutable a = [1, 2, 3] print(a) b = ["apple", "banana", "pears"] print(b) b[1] = 2 #Heterogeneous print(b) c = [] c.append(1) print(c) c.append("apple") print(c) #List Constructor d = list("characters") print(d) #Dictionary - Mutable mappings of keys to valu...
1d3b0c7f026f525f85b70bff6566ea863c8e21be
rajiv0903/Python
/python_basics/src/fundamentals/f_10/10_05_Collections_Dictionary.py
1,063
3.5
4
''' Created on Aug 7, 2018 @author: rajiv ''' #Unordered Mapping from unique immutable keys to mutable values urls = {'Google':'https://www.google.com/', 'Microsoft':'https://www.microsoft.com/', 'Verizon':'https://www.verizonwireless.com', 'Comcast':'https://comcast.com/', 'TMObile':'...
c6433389b1b33d74dc2b6bd1e7d2b6bc1885b0fe
jcarter62/euler
/problems/p5.py
1,360
4.09375
4
import json class P5: """ Smallest multiple Problem 5 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? """ def __init__(self, low...
c035d4439332bebec3d0ae004c7445f2db5549b7
gemelodyyu/Python-Challenge
/PyBank/main.py
2,545
3.984375
4
# import modules import csv import os # create variable for the path bank_path = os.path.join("Resources", "PyBank_Resources_budget_data.csv") # create lists to store data monthly_change = [] total_month = [] total_profits = [] # read csv data with open(bank_path) as csv_file: csv_reader = csv.reader(csv_file, de...
e4bd1aa577d89f877295281aef2c3e46e3da72f0
chg0421/Assignment1
/cmd_line.py
1,434
3.765625
4
import cmd """ class HelloWorld(cmd.Cmd): Comment this ------ Simple command processor example. prompt = 'prompt: ' intro = "Simple command processor example." doc_header = 'doc_header' misc_header = 'misc_header' undoc_header = 'undoc_header' ruler = '-' def do_prompt(self, line): ...
879a63f622eed0f1a12f1a136f7a508609aae64c
CrunchyPistacho/Algorithms
/matrix_multiplication/square_matrix_multiply.py
377
3.96875
4
A = [[1,2,3], [2,2,1], [1,3,2]] B = [[1,1,1], [1,2,3], [0,1,1]] # basic algorithm def square_matrix_multiply(x,y): n = len(x) c = [[0 for x in range(n)] for y in range(n)] for i in range(0,n): for j in range(0,n): for k in range(0,n): c[i][j] = c[i][j] + x[i][k] * ...
2869ab5cc0f73d29fb120418cd2dcb7f5ab41867
CrunchyPistacho/Algorithms
/data_structures/stack.py
1,760
4.125
4
class Stack: def __init__(self, Size = 5): self.__size = Size self.__stack = [] self.__i = -1 def is_empty(self): if len(self.__stack) == 0: return(0) def is_full(self): if len(self.__stack) == self.__size: return(len(self.__stack)) def...
602c201b36e673025a988a5dfa57314af7e3d764
Carolyn95/Leetcoding-Journey
/algo_7.py
1,074
3.828125
4
# twoSum import pdb class Solution: def twoSum(self, nums, target): # one solution, return indexes from original array which two elements can add up to target hash_map = {} for i, n in enumerate(nums): target_value = target - n if target_value in hash_map: ...
5154f1369e35e68e226423f35279f846f2e7a5f8
Carolyn95/Leetcoding-Journey
/algo_27.py
382
3.71875
4
# 234 palindrome linked list # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def isPalindrome(self, head: ListNode) -> bool: vals = [] cur = head while cur: vals.append(cur.val)...
c4b2d02cb02ff875450fc56f1b839cab49b85af6
SDBranka/A_Basic_PyGame_Program
/hello_game.py
718
4.15625
4
#Import and initialize Pygame library import pygame pygame.init() #set up your display window screen = pygame.display.set_mode((500,500)) #set up a game loop running = True while running: # did user click the window close button? for event in pygame.event.get(): if event.type == pygame.QUIT: ...
605604d5f679b45825114a95c4592e000397414d
wasjediknight/python
/exercicios/week3/ordenacao.py
293
3.796875
4
def PegarEntrada(label): return int(input("{} Informe um número inteiro: ".format(label))) numeros = PegarEntrada("A"), PegarEntrada("B"), PegarEntrada("C") numerosOrdenados = tuple(sorted(numeros)) print("crescente" if numeros == numerosOrdenados else "não está em ordem crescente")
042f4d034118fa79d23691b35884efb2750ae472
wasjediknight/python
/exercicios/week7/soma_hipotenusas.py
601
3.640625
4
import math def CatetosInteiros(hipotenusa): incremento = 1 while incremento < hipotenusa: cateto = (hipotenusa ** 2) - (incremento ** 2) if cateto > 0: cateto = math.sqrt(cateto) if cateto % 1 == 0: return True incremen...
08c3895ecde1583e1c9fa63e12c3d3b231baf051
wasjediknight/python
/exercicios/week4/while.py
382
3.921875
4
total = 0 numeros = 0 incremento = 0 def Somar(valor): global total total += valor def PegarEntrada(label): return float(input("Forneça o valor do nº{}: ".format(label))) numeros = int(input("Digite um número inteiro: ")) while incremento < numeros: incremento += 1 valor = PegarEntrada(increment...
12dba57de93e82427e9ad649929834b3948ad85f
laurabolcina/Python
/05/shopping-list.py
323
3.765625
4
# coding=utf-8 __author__ = "Laura Bolčina" shopping_list = [] adding = True while adding: shopping = raw_input("Do you want to anything your shopping list? (Y/N) ") if shopping in "Yy": item = raw_input("Enter the item: ") shopping_list.append(item) else: adding = False print sho...
f9b89195f46df54a13ecb996d7cb6ce0e9affc7b
laurabolcina/Python
/06/capital_city_quiz.py
1,916
4.0625
4
# coding=utf-8 __author__ = "Laura Bolčina" capital_cities = { "Slovenia": "Ljubljana", "Austria": "Vienna", "Germany": "Berlin", "Italy": "Rome", "Sweden": "Stockholm", "Norway": "Oslo", "Denmark": "Copenhagen", "Portugal": "Lisbon", "France": "Paris", "United Kingdom": "London...
72cffe18476f7f852374c72ab3aea275a93017e4
pororodl/LeetCode
/剑指Offer/27.二叉树的镜像.py
552
3.84375
4
import queue class TreeNode: def __init__(self,x): self.val = x self.left = None self.right = None class Solution: def invertTree(self,root): if root ==None: return None q = queue.Queue() q.put(root) while not q.empty(): cur = q.ge...
3ad1a279f8ad3c34daa13670b1dc4610184533d0
pororodl/LeetCode
/输入练习/t5.py
928
3.671875
4
from typing import List class Solution: def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int: n = len(grid) if not grid or grid[0][0] == 1 or grid[n-1][n-1] == 1: return -1 elif n <= 2: return n queue = [(0, 0, 1)] grid[0][0] = 1 wh...
40801c7e4a97f3200a3c6ba58847c0bf73b9383e
pororodl/LeetCode
/74. Search a 2D Matrix.py
2,026
3.671875
4
class Solution: def searchMatrix(self, matrix, target: int) -> bool: ''' :param matrix: : List[List[int]] :param target: :return: ''' m = len(matrix) if m==0: return False n = len(matrix[0]) if n ==0: return False ...
69c309cb092c3d6330b4bc600160ca57d3cb9000
pororodl/LeetCode
/搜索/子集问题用BFS.py
810
3.71875
4
import copy from typing import List # def subset(li): # ans = [[]] # for i in li: # temp = copy.deepcopy(ans) # for e in temp: # e.append(i) # ans.extend(temp) # print(ans) import itertools def creat_sub(li): l = len(li) ans = [[]] for i in range(1,2**l): ...
1f0417f929e5f78a4ca47a36fde540e76e407b70
pororodl/LeetCode
/双指针/524. Longest Word in Dictionary through Deleting.py
1,424
3.640625
4
from typing import List class Solution: def findLongestWord(self, s: str, d: List[str]) -> str: longestWord = '' for target in d: l1 = len(longestWord) l2 = len(target) print(target) if l1>l2 or (l1==l2 and self.compareTo(longestWord,target)>0): ...
4801f9410acc5cf22fa6414fdb95dc30d1a67625
pororodl/LeetCode
/TREE/constructByPre_in.py
591
3.53125
4
class BinaryTree: def __init__(self, x): self.val = x self.left = None self.right = None def construct(pre,inorder,Len): if Len==0: return None return constructCore(pre,inorder,0,Len-1,0,Len-1) def constructCore(pre,inorder,prestart,preend,inorderstart,inorderend): roo...
9731da988fef86aadf791b132fe0f6d003e976ac
pororodl/LeetCode
/LinkedList/21. Merge Two Sorted Lists.py
1,637
3.90625
4
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # 双指针法 def mergeTwoLists(self , l1: ListNode, l2: ListNode) -> ListNode: if l1 == None: return l2 if l2 != None else None if l2 == None: return l1 if l1 != None else...