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
e29d7bff2acc1d0a128177e1f4023bdf4c13c7c3
Liunrestrained/Python-
/Chapter3/Day18/12.特殊成员__new__方法.py
549
3.6875
4
'''少用但重要,eg:单例模式''' class Foo(object): # 若不写__new__方法,创建对象时则默认会到继承的object类中去寻找方法 def __init__(self, name): print("第2步,初始化对象,在空对象中创建数据") self.name = name def __new__(cls, *args, **kwargs): # 可写可不写,写了就是Foo类的绑定方法,不写就去继承的object中寻找它 print("第1步,先创建空对象并返回") return object....
6c558f38c530522399a129ef4669a75d1f079f28
Liunrestrained/Python-
/Chapter2/56.正则表达式(起始和结束).py
276
3.71875
4
import re '''要求用户必须以指定的内容开头和结尾''' # ^ 开头 # $ 结尾 text = "STARSKY8816@gmail.com" data = re.findall("^\w+@\w+.\w+$", text, re.ASCII) print(data) text_ = "啊STARSKY8816@gmail.com啊" data_ = re.findall("^\w+@\w+.\w+$", text_, re.ASCII) print(data_)
2a5c75833c3a0496f66801259d9fcc41ed3001df
Liunrestrained/Python-
/Chapter1/3.转义字符.py
433
3.53125
4
# print("hello world\a") # 响铃 # print("hello world\b") # 退格 # print("hello world\f") # 换页 # print("hello world\n") # 换行 # print("hello world\r") # 回车 # print("hello world\t") # 水平制表 # print("hello world\v") # 垂直制表 # print("hello world\\") # 一个反斜杠 # print("hello world\'") # 代表一个单引号(撇号)字符 print("hello w...
cddd08ee52a94c6fd092de067d95fa14a6cc827b
Liunrestrained/Python-
/Chapter3/Day19/18.异常捕获处理_2.py
773
4.03125
4
# 案例:在框架内部已经定义好,遇到什么样的错误都会触发不同的异常。 import requests from requests import exceptions while True: url = input("请输入要下载网页地址:") try: res = requests.get(url=url) print(res) except exceptions.MissingSchema as e: print("URL架构不存在") except exceptions.InvalidSchema as e: ...
d654e7d5d85d2528ea48dc36f915c6fcc8481097
Liunrestrained/Python-
/Chapter3/Day19/11.异常处理的基本格式.py
721
3.921875
4
# 常用简单格式:(使用较多) try: '''逻辑代码''' except Exception as e: '''try逻辑代码出现问题,则执行此代码,没有异常则不执行。''' # 完整格式:(使用较少) try: '''逻辑代码''' except Exception as e: '''异常处理''' finally: '''无论try中的代码运行是否出现问题,此处都会照常执行,此举一般用于资源的释放''' print("end") # 举例: try: file_object = open("xx.txt") # ... exce...
0792e24d011cd9788882614364d9346063366844
Liunrestrained/Python-
/Chapter3/Day23/28.协程运用.py
568
3.671875
4
'''不要让用户手动去切换,而是遇到IO操作时能自动切换。 Python在3.4之后推出了asyncio模块 + Python3.5推出async、async语法 ,内部基于协程并且遇到IO请求自动化切换。''' import asyncio async def func1(): print(1) await asyncio.sleep(2) print(2) async def func2(): print(3) await asyncio.sleep(2) print(4) tasks = [asyncio.ensure_futur...
3c6de98978405f71f18514efb4a8d5127c11f57b
Liunrestrained/Python-
/Chapter1/17.逻辑判断.py
97
3.65625
4
number = 9 if number == 9: print('Y') elif number == 0: print('N') else: pass
f9d67620cb40e2141b26f57e96b982c3f0ec6f6b
Liunrestrained/Python-
/Chapter1/13.bool类型.py
369
3.625
4
# True 真 1 # False 假 0 # 在数据转换的过程中,【整数0、空字符串、空列表、空字典、空元组、空集合、None】转换为bool值均为False,其它的均为True。 # 基于以上,这些对应T、F的数据都可以在条件判断时,拿来充当True或者False。 print(True + True) # == 2 print(False + False) # == 0
b5384c7765019dc8cc23e8b7a46f91cb5446c88a
Liunrestrained/Python-
/Chapter1/练习题/习题5.py
403
3.78125
4
'''8.补充代码实现数据拼接''' data_list = [] while True: hobby = input("请输入你的爱好(Q/q退出):") if hobby.upper() == 'Q': break # 把输入的值添加到 data_list 中,如:data_list = ["小姨子","哥们的女朋友"] data_list.append(hobby) # 将所有的爱好通过符号 "、"拼接起来并输出 print("、".join(data_list))
d9462abf1958e949de92020de5f6c636197d3b2c
Liunrestrained/Python-
/Chapter2/43.推导式.py
771
4
4
'''请创建一个列表,并在列表中初始化:0、1、2、3、4、5、6、7、8、9...299 整数元素。''' # 方法1: app = [] for i in range(300): app.append(i) '''# 列表法: list_1 = [i for i in range(10)] list_2 = [[i, i] for i in range(10)] list_3 = [[i, i] for i in range(10) if i > 5] # 集合法: set_1 = {i for i in range(10)} set_2 = {{i, i} for i in range(1...
adb52b7ae8ee404d5f34a6ffe9a433a7d0a09aff
Liunrestrained/Python-
/Chapter3/Day22/4.线程方法t.start().py
408
3.71875
4
import threading loop = 1000000 number = 0 def _add(count): global number for i in range(count): number += 1 t = threading.Thread(target=_add, args=(loop,)) t.start() # 当前的线程准备就绪,等待CPU调度,具体时间是由CPU来决定的。 print(number) # 子线程启动后,会直接执行这一行代码,所以打印的数据是随机的0~1000000。
0785bc7171dd1bb9fdf6ba6b40f3d717278fe134
Liunrestrained/Python-
/Chapter1/练习题/习题2.py
451
3.75
4
'''对用户输入的数据使用"+"切割,判断输入的值是否都是数字?提示:用户输入的格式必须是以下+连接的格式,如 5+9 、alex+999''' while True: enter = input("请输入** + **格式的内容").strip() data = enter.split("+") if data[0].isdecimal() == True and data[1].isdecimal() == True: print("输入正确") break else: print("输入错误") continu...
dbbe5a5102d624c7fd4008768f977da3327c4523
Liunrestrained/Python-
/Chapter3/Day18/5.属性补充.py
493
3.890625
4
class Foo(object): def __init__(self, name, age): self._name = name self.age = age @property def name(self): return "{}-{}".format(self._name, self.age) # 由于属性和实例变量的调用方式相同,所以在编写时需要注意:属性名称 不要 实例变量 重名。 obj = Foo("武沛齐", 123) print(obj._name) # 如果真的想要在名称上创建一些关系,可以让实例变量加上一...
131e5c99061ec6d42d39755acda83b4209cf63e0
Liunrestrained/Python-
/Chapter2/59.global的兄弟nolocal关键字.py
215
3.53125
4
name = 'root' def outer(): name = "武沛齐" def inner(): nonlocal name # 将上级定义域的变量修改 name = 123 inner() print(name) outer() print(name)
7335ea20c0162dca286b69d92d654043a7b45fa6
Liunrestrained/Python-
/Chapter3/Day22/7.练习题t.join().py
840
3.71875
4
import threading loop = 10000000 number = 0 def _add(count): global number for i in range(count): number += 1 def _sub(count): global number for i in range(count): number -= 1 t1 = threading.Thread(target=_add, args=(loop,)) t2 = threading.Thread(target=_sub, ar...
58c4aa2541ae2c712b0c89b54dabbe9243dc8baf
Liunrestrained/Python-
/Chapter3/Day22/24.单例模式_简易版.py
625
3.890625
4
class Singleton: instance = None def __init__(self, name): # 再执行init self.name = name def __new__(cls, *args, **kwargs): # 返回空对象 if cls.instance: # instance不为空在,则执行 return cls.instance # 直接将这个对象返回 cls.instance = object.__new__(cls) # 为空,则创建一个空对象,赋值...
96418a2b0da2fc3fd8c475b4a472c65c6ae30283
Liunrestrained/Python-
/Chapter3/Day19/16.了解自定义异常_3.py
385
3.65625
4
class MyException(Exception): # 自定义异常类,继承Exception title = "请求错误" # 创建类变量 try: raise MyException() # 实例化异常类对象,并报错 except MyException as e: # 捕获异常 print("MyException异常被触发了", e.title) # 打印错误信息,以及类变量信息 except Exception as e: print("Exception", e)
d8d668a0cbce405b3f3e701ba0b4ec031fb1017a
Vmanzyuk/lesson2
/age.py
393
3.921875
4
age=input('Enter your age:') intage=int(age) def destiny(age): if age < 3: return 'The program does not support age less 3' elif age < 7: return'What do you think about your kindergarten ?' elif age < 17: return 'I guess you studying in school' elif age < 22: return 'Stud...
391f7337d7bff34e9f6422b288d11ae1bb8e7707
Signior-X/DSA
/dsa/leetcode/q10_regex.py
2,806
3.578125
4
class Solution: def isMatch(s: str, p: str) -> bool: # loop in revers order cache = {} def recursiveMatch(i, j): # Base cases print(i, j) if (i,j) in cache: return cache[(i,j)] if i >= len(s) ...
adac58a2da48554cba4565ec0512e3ca75a70643
Signior-X/DSA
/dsa/number-theory/seive.py
222
3.859375
4
''' Till 10**6 only ''' r = 10**6 + 5 arr = [True for i in range(r)] for i in range(2, r): # Now start the loop from here and keep adding all for j in range(i+i, r, i): arr[j] = False print(arr[:30])
559c6d6da5b82a3d7a492cc40582a73de012ba7e
JunDang/Python-Rice-University
/ponepeer.py
5,489
3.625
4
# Implementation of classic arcade game Pong import simplegui import random # initialize globals - pos and vel encode vertical info for paddles WIDTH = 600 HEIGHT = 400 BALL_RADIUS = 20 PAD_WIDTH = 8 PAD_HEIGHT = 80 HALF_PAD_WIDTH = PAD_WIDTH / 2 HALF_PAD_HEIGHT = PAD_HEIGHT / 2 ball_pos = [WIDTH / 2, HEIGHT /...
356a02c4edb2b8a16859fd6c550d553e92ec3a8a
AmitSrour/myprojecteuler
/2.py
281
3.53125
4
first = 1 second = 2 next = 3 sum = 0 while second < 4000001: next = first + second print ("%s,") % first first = second second = next if first%2 == 0: sum +=first print ("sum = %s" % sum)
7fb4714edb93ed178ffe0a607b4f9266be3aeee3
younmeeoh/twitscraper
/parsedata.py
375
3.78125
4
import json #with will ensure the file is closed again when done #open() produces a file that json.load() can read from with open('twitterData.json') as json_data: #create variable named jsonData to contain the twitterData. #json.loads() takes a JSOn encoded string jsonData = json.load(json_data) #print all dates...
428973b90c9536493ee777c265dba77d7170271d
JohnyBoy2128/The-Ultimate-Math-Solver
/pythagoras.py
193
4.0625
4
import math def pythagoras(): a = float(input("Enter your 'a' value: ")) b = float(input("Enter your 'b' value: ")) c1 = a**2 + b**2 c = math.sqrt(c1) print("Your answer is: " + str(c) )
68bffb58635d1199ea630c02f3a8eed214833e3d
sohaibsohail98/API_requests
/json_parsing_with_api.py
1,800
3.75
4
import requests import json post_codes_req = requests.get("https://api.postcodes.io/postcodes/se120nb") print(post_codes_req.status_code) print(post_codes_req.content) print(post_codes_req.headers) print(post_codes_req.status_code) print(type(post_codes_req.headers)) print(post_codes_req) #Why should we use built in...
792ff994315e725b3448450ee382729ba36a9b54
rajveer10092/kushs-utils-tool
/src/helpers.py
737
3.65625
4
from anytree import Node def get_path_from_root_to_parent(x: Node): """ Helper function for AnyTree - Helps in getting the path from root to parent :param x(Node): Node for which root to parent path is required :return: Path as a string """ path_root_to_x = ["%r" % x.separator.join([""] + [str(node.name) for nod...
b731f26ac94a6cab2f9af12fb20d52ba5ae81ca0
arshadkhan9930/Python
/duplicate_remove.py
259
3.796875
4
duplicate = [2, 4, 10, 20, 5, 2, 20, 4] final_list = [] def Remove(duplicate): for num in duplicate: if num not in final_list: final_list.append(num) #print("Inside function body") return(final_list) print(Remove(duplicate))
9a8883654ad33c4f7d2ee231393be7a48047a27c
arshadkhan9930/Python
/Automatic_email.py
471
3.578125
4
import smtplib def automatic_email(): user = input("Enter your name: \n") email = input("Enter your Email ID: \n") #print(email) message = (f"Dear {user}, Welcome to the Clever Programmer") receiver = "khanarshad811@yahoo.com" #pwd = "Jhelolr12" s = smtplib.SMTP('smtp.gmail.com', 587) s...
e3575cc01d5c13cfa53ff1ca13bfa5fa3fe48295
baobaocoding/PythonBasis
/Python/FunctionModule/utilities.py
360
4.0625
4
def factorial(x): answer = 1 for i in range(1, x+1): answer *= i return answer def summation(x, N): add = 0 for i in range(1, N+1): add += i return add * x if __name__ == "__main__": # The test of the factorial function print(factorial(3)) # The test of the summat...
d40c17e9ba97fd90bca0cd81e2c6568ae70ac664
baobaocoding/PythonBasis
/Python/Loop/guess_number.py
519
3.96875
4
import random hide_number = random.randint(1, 100) win = False guess_times = 7 while guess_times > 0: guess = int( input("Please guess the number from 1 to 100 (%d times left):" % guess_times)) if guess == hide_number: win = True break else: if guess > hide_number: ...
7ce5cbf1884eb6471159ce1929fe3bf0db72638a
Donzellini/pythonCampinasTech
/Aula_11/tuplas8.py
293
3.890625
4
tup1 = (1,2,3,4,5) tup2 = (5,6,7,8,9) lista = ["haha", "jaja", "kkkk"] #Pegando os valores em comum print(set(tup1) & set(tup2)) #quantidade de elementos da tupla print(len(tup1)) #maior valor print(max(tup2)) #menor valor print(min(tup2)) #converte lista para tupla print(type(tuple(lista)))
dfbf15db0ea89d8a7ef7695e83393f589cadc9eb
Donzellini/pythonCampinasTech
/Aula_27/assert.py
506
3.640625
4
def KelvinToFahrenheit(Temperature): #assert (Temperature >= 0),"Colder than absolute zero!" if Temperature >= 0: return ((Temperature-273)*1.8)+32 # print (KelvinToFahrenheit(273)) # print (int(KelvinToFahrenheit(505.78))) # print (KelvinToFahrenheit(-5)) def imprime_nome(nome): assert (nome != "J...
514332639a132558c9ec62e553154e4b7da48c0d
Donzellini/pythonCampinasTech
/Exercises/ex8.py
468
4
4
#8. Elabore um algoritmo em Python que receba um número inteiro e escreva na tela o número fornecido, o antecessor desse número e o sucessor desse número; num_ins = int(input("Digite um número inteiro: ")) num_ant = num_ins - 1 num_suc = num_ins + 1 # verificando as variáveis criadas # print (num_ant) # print (num_s...
e8a664bcd25858d0c99fccf359811bfff2e9f26d
Donzellini/pythonCampinasTech
/Aula_10/listas4.py
241
4.125
4
lista_comida = ["arroz", "feijão", "carne", "batata"] #ler de trás para frente -> usa o negativo print(lista_comida[-2]) #ler de trás para frente usando o range print(lista_comida[-2:]) print(lista_comida[:-2]) print(lista_comida[1:-2])
d3ad6c8f300e06192cac0fa87484d1b09ed88d75
Donzellini/pythonCampinasTech
/Aula_04/listas.py
658
4.53125
5
#!/usr/bin/python list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tinylist = [123, 'john'] print(list) # Prints complete list print(list[0]) # Prints first element of the list print(list[1:3]) # Prints elements starting from 2nd till 3rd print(list[2:]) # Prints elements starting from 3rd element...
70343c73f02b5ab3bceb5db150960769c88b3cbf
Donzellini/pythonCampinasTech
/Aula_07/forrange.py
256
4.09375
4
for numero in range(2,10): #conta de 2 a 9 print(f"Número {numero}") #Começa do 0 e vai até o 10 for numero in range(11): print(f"Número {numero}") #Começa do 4 e faz até 10 for numero in range(4, 11): print(f"Número {numero}")
934778e00f27dbe6a1505591e3f0a36e4250822c
solchusalin/frro-utn-soporte2019-05
/practico_04/ejercicio-01.py
2,454
3.828125
4
#Hacer un formulario tkinter que es una calculadora, tiene 2 entry para ingresar los valores V1 y V2. #y 4 botones de operaciones para las operaciones respectivas + , - , * , / #al cliquearlos muestre el resultado de aplicar el operador respectivo en los V1 y V2 . from tkinter import * from tkinter import messagebox ...
ee8f4aa68542428dd1bebdf5513d60cfb1b55e0e
solchusalin/frro-utn-soporte2019-05
/practico_04/ejercicio-04.py
3,687
3.734375
4
#Al Formulario del Ejercicio 3, agregue los siguientes botones # 1- un botón Alta que inicia otra ventana donde puedo ingresar una ciudad y su código postal. # 2- un botón Baja que borra del listado de ciudades la ciudad que esta selecionada en Treeview. # 3- un botón Modificar. #Todos los cambios se deben ver refl...
d10c6974cd4f9ee18b77da58953346fc909e9046
solchusalin/frro-utn-soporte2019-05
/practico_01/ejercicio-12.py
345
3.828125
4
# Determinar la suma de todos los números de 1 a N. N es un número que se ingresa por consola. n = int(input("Ingresar un número: ")) def suma(nro): total = 0 for i in range(1, n+1): #arranco en 1 porque el 0 no suma total += i return total print('La sumatoria de 1 a', n, 'es: ', suma(n)) #a...
4553c0b52c2f8fd2721499a87a8c64872bef1c8d
agustashd/Automate-the-boring-stuff
/ch4/commaCode.py
977
4.1875
4
''' Write a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item. For example, passing the previous spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to ...
5f7de23e1786e3766a5d054b66eeff277cc32276
sahilsoni1/geekindian
/time_module/test1.py
599
3.53125
4
import time # return structure time string # If t is not provided, the current # time as returned by localtime() is used. test1=time.asctime() print(type(test1)) print(test1) # https://www.geeksforgeeks.org/python-time-clock_gettime-method/ test2=time.ctime() print(type(test2)) print(test2) test3=time.monotonic() p...
934f6fcbd96e83835dc6a58ed2ab3fcf9c357edb
sahilsoni1/geekindian
/python_basic/pythonmodules.py
617
3.5
4
import Fridge if __name__ == '__main__': pass # print(dir(Fridge))# shows all of the properties of the Fridge object # print(dir(Fridge.Fridge()))# shows all of the properties of the Fridge.Fridge() object f =Fridge.Fridge({"eggs":6, "milk":4, "cheese":3}) # from Fridge.py file call Fridge class print("items befor...
1144eb1687350bcfbfa25102e7de4636da85d61d
sahilsoni1/geekindian
/shutil/rotatingfile.py
1,156
4.125
4
import os,shutil import time def make_version_path(path,version): """ it gives version for log file """ if version == 0: return path else: return path +"."+str(version) def rotate(path,version): """ The rotate function uses a technique common in recursive functions """ old_path =make_version_path(pat...
ce54ffffe84ab5c19a06282eda2c062c0586b4d3
LukeBriggsDev/GCSE-Code-Tasks
/p02.1/even_squares.py
584
4.1875
4
""" Problem: The function even_squares takes in a number. If the number is: * even - print out the number squared * odd - print out the number Tests: >>> even_squares(20) 400 >>> even_squares(9) 9 >>> even_squares(8) 64 >>> even_squares(73) 73 """ # This code tests your solutio...
d648677e30e1c360868d8b03586e1c6225eba78f
LukeBriggsDev/GCSE-Code-Tasks
/p03.3/add.py
362
3.796875
4
""" Problem: The function 'add' takes a list of integers, nums. It should add them all up and print the total. Tests: >>> add([1, 2, 3]) 6 >>> add([5, 7, 9]) 21 >>> add([2, 3, -6]) -1 """ import doctest def run_tests(): doctest.testmod(verbose=True) def add(nums): print(sum(nums)) ...
42078806e06e85ff312f658f360bee67090a6494
LukeBriggsDev/GCSE-Code-Tasks
/p02.2/palindrome.py
1,177
4.6875
5
""" Problem: A palindrome is a word that is spelt the same forwards as it is backwards, such as "racecar" or "mum". The function 'is_palindrome' should test whether a word is a palindrome or not and print either "Palindrome" or "Non-palindrome" The function should be case-insensitive, so "Ra...
639636ad47e0e10703c90b1e623421743a3ba33c
LukeBriggsDev/GCSE-Code-Tasks
/p03.1a/more_nines.py
613
4.15625
4
""" Problem: The function print_nines takes an input, n, and should then print the first n terms in the 9 times table, exactly as in the nines problem. Test: >>> print_nines(2) 1 x 9 = 9 2 x 9 = 18 >>> print_nines(7) 1 x 9 = 9 2 x 9 = 18 3 x 9 = 27 4 x 9 = 36 5 x 9 = 4...
9f2d951b4fbb73d2239d1117f33a336b71fffc76
LukeBriggsDev/GCSE-Code-Tasks
/p02.4/most_frequent.py
905
4.3125
4
""" Problem: Given a list of integers, nums, and two integers, a and b, we would like to find out which one occurs most frequently in our list. If either a or b appears more often, print that number. If neither appears at all, print "Neither". If they appear the same number of times, print "Ti...
15af75b362e2f496104423ac33660cc60e009582
LukeBriggsDev/GCSE-Code-Tasks
/p03.1x/triangles.py
599
4.15625
4
""" Problem: The triangle numbers are: 1, 3, 6, 10, 15, 21, 28, ... They are generated by starting at 0 and going up by 1, then adding one more to the difference each time. The function triangle_numbers takes an integer n, and should then print the nth triangle number. Tests: >>> trian...
0e701e053e285f9e6caa5b8dcf350f58594c491c
LukeBriggsDev/GCSE-Code-Tasks
/quiz_adventure/quiz.py
2,498
3.859375
4
# Our quiz! from time import sleep score = 0 name = input("What is your name?") player = 0 def quiz(): question1() def question1(): global name global player print("Hello",name,"welcome to a very british quiz , Huzzah!") print("Quiz starting in") sleep(0.5) print(5) sleep(0.5) print...
02c21294deaf64e775ca00210edad838a4aace3b
ancue/algorithm
/LeetCode高频.py
6,141
3.609375
4
# 1. 两数之和 """ 给定一个整数数组 nums 和一个目标值 target 在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 """ def twoSum(nums, target): hashdict = {} for i, item in enumerate(nums): if (target - item) in hashdict: return (hashdict[target - item], i) hashdict[item] = i return (-1, -1) print(twoSum([1, 4, 7...
c2bc9cab220eece67f690d0bd3466911cb95eb87
tangxin20/study
/4_func.py
1,877
4.15625
4
#def f(x): # return x**3 #a=f(int(input("Please input a number:"))) #if a < 100: # print("result < 100") #if a < 50: # print("result < 50") #else: # print("error") #def f(): # return 1+2 #print(f()) #def f(x,y,z): # return x*y*z #a = int(input("please input first number:") ) #b = input("please inp...
260574ac3ca6a27b6337e55ab3fc91ec0186098d
mankalmadhu/padhai
/utf_convert.py
1,032
3.625
4
KAN_DEV_CODE_POINT_DIFF = 896 special_character = [2385,2386,7386,32,3302,2404,3203, 2405,2365] def translate_text(input_text,code_point_diff): output = '' for char in input_text: char_ord = ord(char) if char_ord not in special_character: char_ord -= code_point_diff ...
28cc9fd90113a38945390639024c212fb4c9a273
junaed/HackerRank
/HackerRank/src/UtopianTree.py
431
3.578125
4
''' Created on Sep 22, 2014 @author: junaed ''' # Enter your code here. Read input from STDIN. Print output to STDOUT def calculate_value(n): if n == 1: return 1 if n == 2: return 2 if n%2 == 0: return (2 * (calculate_value(n-2))) + 2 else: return (2 * (calculate_...
aa6f7f572ef7d2335801831be56e62d83dbb6414
junaed/HackerRank
/HackerRank/src/euler/euler56.py
602
3.671875
4
''' Created on Oct 14, 2014 @author: junaed ''' def my_pow(a, y): result = 1 # a = 2 while y: if y & 1: result = (result * a) a = (a * a) y >>= 1 return result def get_digit_sum(n): sum1 = 0 while n>0: sum1 += (n%10) n = n / 10 return su...
7aa774896bb9f67d7a77ea2550bd0368bfab9d2d
FizzyBody8/arrays
/arrays.py
990
3.765625
4
def countEvens(numbers): evens = 0 for number in numbers: if number % 2 == 0: evens = evens + 1 return evens print countEvens([1, 2, 3, 4, 5, 6, 7, 8, 9]) #Expect 4 def bigDiff(numbers): max = numbers[0] min = numbers[0] for number in numbers: if number > max : ...
ae582ce4979a4db137ca1a6874d60ad8893fcab2
akrampatel89/ga-learner-dsmp-repo
/Student-Management-System/code.py
1,103
3.859375
4
# -------------- # Code starts here class_1=['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio'] class_2=['Hilary Mason','Carla Gentry','Corinna Cortes'] new_class=class_1+class_2 print(new_class) new_class.append('Peter Warden') print(new_class) new_class.remove('Carla Gentry') print(new_class) ...
8d2ec7676bbae438a4324c2c380d20a6339ddefc
khans7197/Stuff-for-Zad
/SowadKPM&PCA2Q4/SowadKPM&PCA2Q4.py
3,779
3.796875
4
# Assignment 2 # Question 4 # Sowad Khan # Date: April 29th, 2019 # Modifications: # Created a card matching game # Notes: # Had trouble with this question, so only left what I had to start and submitted with the flowchart and IPO chart # (talked to Ms. Harris about this) from CardClass import * import pygame pygam...
6f0cc36348bf1fbf27237e7100fd9bdbdd0ce7df
aakashjangidme/HangMan
/HangMan_Easy_Way.py
3,605
4.21875
4
# Word Guessing Game : HANGMAN , Code by Aakash Jangid # User will have 10 attempts to guess a Word which is exiting in our program dictionary # User will have to guess the whole WORD 'Character by Character' # If user enters correct character it will show up otherwise his/her attempt will be lost # Let's begin with th...
d11d35adfe583583380268269d42dec015ba1410
josephclaymiller/sumotanks
/code/entity.py
1,534
3.515625
4
#entity - a physics controlled object in the game world import sys, math from pandac.PandaModules import * from direct.showbase.DirectObject import DirectObject class force(): def __init__(self, magnitude, angle): self.magnitude = magnitude self.angle = angle def xcomp(self): return ...
ef1856071ddf9ddf19a7fb5ae220813430798c99
stathis-alexander/ac-2018
/day6/aoc-6-1.py
1,267
3.640625
4
#!/usr/bin/python # This is a solution to Advent of Code, day 6 part 1 with open("input.txt","r") as f: coordlist = [tuple([int(x) for x in line.rstrip("\n").split(", ")]) for line in list(f)] xes = [x[0] for x in coordlist] yes = [x[1] for x in coordlist] x_small = min(xes) x_big = max(xes) y_small = min(yes) y_b...
707874547e4cc99e4be6fc6db66f4248f6baa735
stathis-alexander/ac-2018
/day11/aoc-11-1.py
812
3.625
4
#!/usr/bin/python # This is a solution to Advent of Code, day 11 part 1. import math #the input for this one is not a file, but a number starting_input = 1718 def power_level(i,j): power = 0 rack = i + 10 power = (rack * j + starting_input) * rack digit = math.floor(power/100) - math.floor(power/1000) * 1...
648fd82ab73439e1453a06e59aa9d396ad210ca7
EmyTest/untitled4
/p425.py
23,461
3.859375
4
# a = int(2.99) # print(a) # # totalinches = 41 # feet = totalinches //12 # inches = totalinches % 12 # # print(feet,inches) # # a = 5 # b = 3 # print(round(a/b)) # reverse = 98456 # costs = 45000 # profit = reverse - costs # print(profit) # p_water = 1600 # p = 315000000 # t = 365 # s = p_water * p * t # print(s) #...
f357f7ba592e69d95b90dac903f458d673707915
Nhlaka10/Finance-calculators
/finance_calculators.py
2,440
4.25
4
# Use import math to use math functions import math # Display the statement below so the user can know their options print( """Please choose either \'Investment\' or \'Boond\' from the menu below to proceed:\n\nInvestment - to calculate the amount of interest you will earn on intrest.\nBond ...
7975848d039b49ea154e4af06e6ef1cd6e3bb005
easin-li/pyStudy
/function/functionDemo.py
403
3.78125
4
def add(*args): result = 0 for arg in args: result = result + arg return result print(add(1, 2, 3, 4)) def print_info(name,age): print('name: %s' % name) print("age: %d" %age) print_info( name='easin', age=27) def info(*args,**kwargs): print(args) print(kwargs) for i in kwargs:...
16077c5997f13dfdc6f0d228365788a78d5625b6
johnny-byte/rsa
/main.py
244
3.671875
4
from math import gcd def gcdext(a, b): if b == 0: return (a, 1, 0) d, x, y = gcdext(b, a % b) x, y = y, x-(a//b)*y return (d, x, y) m=20 d=13 (_,_,e)=gcdext(20, 13) if e < 0: e+=m print(f"e={e}") print(pow())
c724c988ea7084ea838e9ce873bccce2d7c4378d
facamartinez/MatClas
/e03_Returning_Values.py
429
3.796875
4
def multiplyByTwo(number): return multiplyTwoNumbers(number,2) def multiplyTwoNumbers(number1,number2): return number1*number2 def noValue(number1,number2): resultado = number1*number2 print(resultado) return resultado print(noValue(5,10)) print(multiplyByTwo(5)) number = multi...
1600fe290199d9217c99da3ef4300e4a59bf1840
facamartinez/MatClas
/e01_data_types.py
961
3.875
4
''' Built-in Data Types In programming, data type is an important concept. Variables can store data of different types, and different types can do different things. Python has the following data types built-in by default, in these categories: Text Type: str Numeric Types: int, float, complex Sequence Types...
f2895400b901812b58388a65115c6607c906a971
facamartinez/MatClas
/C3_E1.py
4,225
4.375
4
'''Escribir una función que implemente el operador XOR del algebra de Boole''' def xor(x,y): if x==True and y==True: return False elif x==False and y==False: return False else: return True '''print(xor(bool(0),bool(0)))''' def xor(x,y): if x and y: return...
8d4740404f053c5aee554d5479b45754ca2fabbd
facamartinez/MatClas
/e02_for.py
1,026
4.15625
4
#for lets you iterate a fixed amount of times unaCadena = "esta es una cadena de texto" for letter in unaCadena: print(letter) def isVocal(letter): vocales = "aeiou" return letter in vocales for letter in unaCadena: if not isVocal(letter): print(letter) '''The range() Functio...
c4b2557c0834cd65ecf87c9684ad8b8c69f93a7b
PapediPoo/Desert_Ant_Behaviour
/Environment/Environment.py
4,417
4.09375
4
from Environment import EnvironmentParameters as EP from Environment.Landmarks import Landmark, FOOD, NEST from Simulation import SimulationParameters as SP from random import randint, random class Environment: """ Describes an environment containing landmarks and food on different places. The nest is as...
e00f4cc18ee4411f23072cfd2cf7103d2f8a6ed3
FCHSCompSci/dictionaryinaction-brai06
/Dictionaries.py
631
3.828125
4
car = { 'type:': "type", 'color:': "color", 'amount:': "amount" } while True: print("Welcome to Forever Car Dealer") car_buyer = input("Would you like to [s]hop,[p]ick up or [l]eave? ") if car_buyer == 's': car_type = input("What type of car would you prefer? ") car_color = i...
46c5a141e48ec57efa4f644af2720057a2c37bba
vitaly-m/coffee-machine
/Coffee Machine/task/machine/coffee_machine.py
3,286
3.984375
4
# Write your code here class CoffeeMachine: fill_options = ["Write how many ml of water do you want to add:", "Write how many ml of milk do you want to add:", "Write how many grams of coffee beans do you want to add:", "Write how many disposable cups of co...
2db1037fdd145380e082c0bd3fd1f5a73d9dcffe
sagynangare/Pandas_Practice_Programs
/abstractClass.py
238
3.609375
4
from abc import ABCMeta,abstractmethod class BaseClass(object): __metaclass__=ABCMeta @abstractmethod def printHam(self): pass class InClass(BaseClass): def printHam(self): print("Ham") x= InClass()
1f3e1eea93b45e46ff436bf620a694f3ac95a4e8
Dagonite/python-sorting-algorithms
/Timing/timing.py
311
3.5
4
"""File containing a timing function that can be used as a decorator.""" import time def timed_func(func): def timed(*args, **kwargs): start = time.perf_counter() res = func(*args, **kwargs) total_time = time.perf_counter() - start return res, total_time return timed
185d8f67df3caffa0166ce4c25d7ded982351dbc
Dagonite/python-sorting-algorithms
/Algorithms/A06_Stooge_Sort/stooge_sort.py
681
3.71875
4
""" Worst complexity: n ** (log3/log1.5) Best complexity: n ** (log3/log1.5) Average complexity: n ** (log3/log1.5) """ def stooge_sort(items, i=0, j=None): if j is None: j = len(items) - 1 if items[j] < items[i]: items[i], items[j] = items[j], items[i] if j - i > 1: t = (j - ...
da04ec636d1afebe0eda74465ab56776aec5b2a6
tinalisica/Contact-book
/contact-book.py
3,051
4.1875
4
# -*- coding: utf-8 -*-. """MANJKA: branje kontaktov iz TXT datoteke in kreacija objektov iz njih (to naj se zgodi, ko uporabnik zažene ContactBook program)""" class Contact(object): def __init__(self, first_name, last_name, phone_number, birth_year): self.first_name=first_name self.last_name...
6e679e449e3d59a44ee44aed5002528cb18006f5
znut/maekin-cloud
/src/Middleware/codelab/general/threadTest.py
466
3.609375
4
import time import thread import threading def childThread(): print "start child" time.sleep(10) print "end of child" class childThread ( threading.Thread ): def run ( self ): print "start child" time.sleep(10) print "end of child" #thread.start_new_thread(childThread,()) childThread().start() print threa...
f7634f3d431095084f9c11afb020f25b3306eefc
pongharit/workshop2
/operator/Iden2.py
193
3.984375
4
dict1 = {"name": "pongharit", "age": "20"} dict2 = {"name": "pongharit", "age": "20"} dict3 = dict1 print(dict1 is dict3) # True print(dict1 is dict2) # False print(dict1 == dict2) # True
88681f19a97141ae1a087e10eaa5057abc428b1b
1790113591/study
/python/20201022:Python第2天课后资料包/课堂示例代码/oop/stu.py
804
3.53125
4
# 定义了一个Student类,代表一个学生 class Student: # 它是类的初始化方法(固定的特殊方法),一定有 # 不是让对象来调用的,是当我们用类名来创建对象时,系统自动调用的 def __init__(self, name, age, sex): self.name = name # 定义姓名属性 self.age = age # 定义年龄属性 self.sex = sex # 定义性别属性 # 学生参加考试的方法 def exam(self, course): self.say...
b7c1b721125f55ca0ca70b2824b516f55fc672b1
1790113591/study
/python/20201026:Python第3天课后资料包/课堂示例代码/oop/school/student.py
816
3.515625
4
from random import randint from oop.school import person class Student(person.Person): # 重写了父类的__init__方法 # 父类中已经定了构造方法,子类重新定义一遍 def __init__(self, name, age, sex, sno, klass): # 调用父类的构造方法,传入对应的形参 super().__init__(name, age, sex) self.sno = sno self.klass = kla...
b47f8388b8dfcd74d7039b00e0cc4e6d73d403d8
1790113591/study
/python/20201022:Python第2天课后资料包/课堂示例代码/loop/demo4_for_prime_number.py
384
3.703125
4
""" 判断用户输入的整数是否是素数 """ number = int(input("请输入一个数字:")) if number < 2: print("%d不是素数" % number) else: for i in range(2, number): if number % i == 0: print("%d不是素数,可以被%d除尽" % (number, i)) break i = 100 else: print("%d是素数" % number)
40edd98d28a95c4d2fdf4180c6ce4209b5d91865
1790113591/study
/python/20201022:Python第2天课后资料包/课堂示例代码/homework/homework1.py
549
3.78125
4
a = int(input("请输入第一条边的长度:")) b = int(input("请输入第二条边的长度:")) c = int(input("请输入第三条边的长度:")) # 分析:任意的两边之和大于第三边(默认是正数) if a > 0 and b > 0 and c > 0 and a + b > c and a + c > b and b + c > a: if a == b == c: print("等边三角形") elif a == b or b == c or a == c: print("等腰三角形") else: ...
920f08b42b841514faa2fd5b8ff0a801f44853c5
vijayjag-repo/LeetCode
/Python/LC_Graph_Valid_Tree.py
1,284
4.03125
4
class Solution(object): def validTree(self, n, edges): """ :type n: int :type edges: List[List[int]] :rtype: bool Approach: Basic idea is that, initially all the nodes are mapped to each other. As and when you see an edge, you assign the seco...
8e66be3b53d1f604d7e3567520caed264d4c53b8
vijayjag-repo/LeetCode
/Python/LC_Flood_Fill.py
1,433
3.625
4
## Solution 1: DFS approach class Solution(object): def floodFill(self, image, sr, sc, color): """ :type image: List[List[int]] :type sr: int :type sc: int :type color: int :rtype: List[List[int]] """ len_row = len(image) len_col = len(image[0]...
065274a021f5a2693429a0063ae55f1b40cfff89
vijayjag-repo/LeetCode
/Python/LC_Island_Perimeter.py
2,027
4.03125
4
#Two Approaches. # First One. Little faster compared to the second approach. # Key takeaway for this problem is that you shouldn't update the cell that you already saw. # (i.e) In similar DFS questions, we update the seen cell to '0' but here if we do that, we can't find the perimeter. # Because, you need the number o...
53ea90dd4e8f386cd4270cf8356481e2a8228fb4
vijayjag-repo/LeetCode
/Python/LC_Remove_All_Adjacent_Duplicates_in_String.py
442
3.71875
4
class Solution(object): def removeDuplicates(self, S): """ :type S: str :rtype: str Approach: Same as valid parentheses. """ if not S: return("") stack = [] for item in S: if(stack and item==stack[-1]):...
13b39f0f77a2e767526a47f07ed116764b474de4
vijayjag-repo/LeetCode
/Python/LC_Sum_Root_to_Leaf_Numbers.py
1,680
3.890625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # ...
b60c8a61033c31b9c3a0c5ace41e33a01c38d820
vijayjag-repo/LeetCode
/Python/LC_Trapping_Rain_Water.py
1,406
3.609375
4
# Optimal approach using two pointers class Solution(object): def trap(self, height): """ :type height: List[int] :rtype: int """ l = 0 r = len(height) - 1 left_wall = 0 right_wall = 0 water = 0 while (l<r): if (height[l] ...
668dba4e566d3b9929a1e1139d524e4cac610735
vijayjag-repo/LeetCode
/Python/LC_Clone_Graph.py
1,050
3.765625
4
""" # Definition for a Node. class Node(object): def __init__(self, val, neighbors): self.val = val self.neighbors = neighbors """ class Solution(object): def cloneGraph(self, node): """ :type node: Node :rtype: Node Approach: Maintain a ...
72003113022e2ebf7c9504d3321c807ef30a20aa
vijayjag-repo/LeetCode
/Python/LC_Spiral_Matrix.py
1,145
3.671875
4
class Solution(object): def spiralOrder(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] Approach: Use generators. First workout the first pattern or layer. Repeat this by going to next layer. Typically, you do 4 iterations(...
a943d4d0152eac60671d88862ad057df96206c55
vijayjag-repo/LeetCode
/Python/LC_Minesweeper.py
1,589
3.90625
4
class Solution(object): def updateBoard(self, board, click): """ :type board: List[List[str]] :type click: List[int] :rtype: List[List[str]] Approach: You're given click, which corresponds to a particular coordinate within the board. If this ...
c788ee88e701df254b6b7378a288e69d9ce5669d
vijayjag-repo/LeetCode
/Python/LC_3Sum_Closest.py
760
3.5
4
class Solution(object): def threeSumClosest(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ nums.sort() sums = 0 close = float('inf') ans = 0 for i,val in enumerate(nums): l,r = i+1,...
cdb4b72a7542ce95f8e730b1caf2395882cb590d
vijayjag-repo/LeetCode
/Python/LC_Minimum_Absolute_Difference.py
483
3.515625
4
import collections from collections import defaultdict class Solution(object): def minimumAbsDifference(self, arr): """ :type arr: List[int] :rtype: List[List[int]] """ if not arr: return [] arr.sort() d = defaultdict(list) for i i...
d5c6135715aa1f0635f94a1cdcf42a45902e9528
vijayjag-repo/LeetCode
/Python/LC_Game_Of_Life.py
1,144
3.6875
4
class Solution(object): def gameOfLife(self, board): """ :type board: List[List[int]] :rtype: None Do not return anything, modify board in-place instead. """ neighbors = [(-1,-1),(0,-1),(1,-1),(-1,0),(1,0),(-1,1),(0,1),(1,1)] rows = len(board) cols = ...
28046c5a97a17e81f7c4984641d34558f08a24c4
vijayjag-repo/LeetCode
/Python/LC_Valid_Palindrome.py
1,576
3.796875
4
## Solution 1: Using regex to remove special chars; Straightforward class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ s = re.sub(r'[^a-zA-Z0-9]', '', s) s = s.lower() if (len(s) == 0): return True x = 0 ...
995a449929c87a0ee9570d100982866092eea404
vijayjag-repo/LeetCode
/Python/LC_Binary_Tree_Maximum_Path_Sum.py
854
3.75
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def maxPathSum(self, root): """ :type root: TreeNode :rtype: int Approach: ...
dd9a4940acf27314c110da47f0522d72c09366c6
vijayjag-repo/LeetCode
/Python/LC_Sum_of_Left_Leaves.py
719
3.828125
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def sumOfLeftLeaves(self, root): """ :type root: TreeNode :rtype: int """ ...
82b7f43ecb2c5d3ee99d13c9f36823445f7f8024
KAfable/Data-Structures
/lru_cache/lru_cache.py
2,144
3.765625
4
from doubly_linked_list import DoublyLinkedList class LRUCache: """Our LRUCache class keeps track of the max number of nodes it can hold, the current number of nodes it is holding, a doubly-linked list that holds the key-value entries in the correct order, as well as a storage dict that provides fast access to ev...
2822ea98c9ed8b5bd652d01d20aa30331546e07a
sekkarin/Data-Struture
/Dictionary/dict_method.py
835
3.59375
4
dict_number = {1: '1', 2: '2', 3: '3', 4: '4', 5: '5'} dict_eng = {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D', 'e': 'E'} dict_test = {1: '1', 2: '2', 3: '3', 4: '4', 5: '5'} print("dict_test.fromkeys('1')", dict_test.fromkeys('1')) print("dict_number.get(5)", dict_number.get(2)) print("dict_eng.items() = ", dict_eng.items(...