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
905bee02a8314b90318f76149f30c0d1032527fe
famosofk/PythonTricks
/automation/files/2write.py
246
3.71875
4
file = open('test.txt', 'w+') file.write('It was a dark and stormy night when the one arrives') print(file.read()) file.close() with open('test.txt') as fis: print(fis.readline()) #opening with w will delete the content, you must use 'a'
bca0fdca37d9a6a253abde940dfe29e6d3990728
famosofk/PythonTricks
/1-ForEveryone/week4/contional.py
155
4.03125
4
x = 2.0 if x == 5 : print("Equals to five.") if x < 2 : print('Below 2') elif x >= 2 : print('Two or more') else : print('Something else')
6e83d95f12ae67d956867620574d63000b4ed848
famosofk/PythonTricks
/ex/dataStructures.py
800
4.40625
4
#tuples x = ('string', 3, 7, 'bh', 89) print(type(x)) #tuples are imatuble. This is a list of different types object. We create tuples using (). In python this would be listof y = ["fabin", 3, "diretoria", 8, 73] y.append("banana") print(type(y)) #lists are mutable tuples. We create lists using [] #both of them are ...
03dae7a8d59866b3c788c42fbc5c43a09d4e89ef
famosofk/PythonTricks
/2-DataStructures/week3/files.py
739
4.3125
4
# to read a file we need to use open(). this returns a variable called file handler, used to perform operations on file. #handle = open(filename, mode) #Mode is opcional. If you plan to read, use 'r', and use 'w' if you want to write #each line in file is treated as a sequence of strings, so if you want to print name ...
6ae707e2a811088f213f0bcd05b15142689c1f24
famosofk/PythonTricks
/ex/lambda.py
686
3.625
4
my_function = lambda a, b, c : a+b print(my_function(1,2,3)) people = ['Dr. Christopher Brooks', 'Dr. Kevyn Collins-Thompson', 'Dr. VG Vinod Vydiswaran', 'Dr. Daniel Romero'] def split_title_and_name(person): return person.split()[0] + ' ' + person.split()[-1] #option 1 for person in people: print(split_...
bc84d94824589a8e48496308e074875528306077
bdavis2/CS169
/Python/HW1P3Davis.py
611
3.5
4
CONST_INPUT_SIZE = 10 def partition(inp, p, r ): pivot = inp[r] while(p < r): while(inp[p] < pivot): p+=1 while(inp[r] > pivot): r-=1 if(inp[p] == inp[r]): p+=1 elif(p < r): tmp = inp[p] inp[p] = inp[r] inp[...
e7b612245a9027319b87b56040f2c004528c3cc1
Reid-Norman/100-Days-of-Code
/Day 14/Higher-Lower-Game.py
2,342
3.734375
4
#Imports from game_data import data import art from random import choice from replit import clear #Functions def item_selector(): '''A function which chooses a random item from the list and then removes the item from the list to prevent duplicate selections.''' new_item = choice(data) data.remove(new_...
c2be1531a074f227a712eb101473b5be5ca751e8
Payiz-2022/python
/objectOriented/square.py
903
3.96875
4
# -*- coding: utf-8 -*- import math class Point: def __init__(self, x, y): self.x = x self.y = y def distance(self, p2): return math.sqrt((self.x - p2.x)**2 + (self.y - p2.y)**2) class Polygon: def __init__(self, points=[]): self.vertices = [] for point in point...
c7ab6e0600830a13480dd5b69e48f11f8e12a88b
Payiz-2022/python
/study/exercise7.py
169
3.671875
4
# -*- coding: utf-8 -*- #修改列表生成式,字母小写 L1 = ['Hello','World',18,'Apple',None] L2 = [i.lower() for i in L1 if isinstance(i,str) == True] print(L2)
8a781a70cc04d0d89c28c3db8da5d5ee0e9b49da
AhmadAli137/Base-e-Calculator
/BorderHacks2020.py
1,521
4.34375
4
import math #library for math operation such as factorials print("==============================================") print("Welcome to the Exponent-Base-e Calculator:") print("----------------------------------------------") print(" by Ahmad Ali ") #Prompts print(" (BorderHacks 2020...
ec11320fb0b0b81e87bcdd454f25d5c4c464778a
Yhatoh/ProgramacionCompetitivaUSM
/soluciones/RPC/2020-6/K_Auteams.py
4,653
3.625
4
fila1="abcdefghi" fila2="jklmnopqr" fila3="stuvwxyz" n=int(input()) for i in range(0,n): flag=True palabras=input() palabras=palabras.strip().split() if (len(palabras[0])==len(palabras[1])): if (palabras[0]==palabras[1]): print("1") pass else: ...
94e603f36fb6b44d9d0cb6b53d6160c034324e60
Yhatoh/ProgramacionCompetitivaUSM
/soluciones/RPC/2020-5/D_VolanTeam.py
332
3.671875
4
a = int(input()) f = 1 while a > 0: b = int(input()) z = input().strip() c = 0 d = 0 while b > 0: v = input().strip() if v == "pea soup": c = 1 elif v == "pancakes": d = 1 if d == 1 and c == 1: f = 0 print(z) b = 0 a = 0 b -= 1 a-=1 if f: print("Anywhere is fi...
307e21625f9ea297e8841fd989bf1ac7f169249c
Yhatoh/ProgramacionCompetitivaUSM
/soluciones/RPC/2020-5/D_Soviet_Union_Find.py
506
3.828125
4
restaurante = "Anywhere is fine I guess" xd = False n = int(input()) for i in range(n): lenteja = False pankk = False k = int(input()) rest = input() for j in range(k): comida = input() if("pea soup" in comida): lenteja = True if("pancakes" in comi...
7865708a3989daf9e2f1fbdbbf2df9e41930a582
green-fox-academy/SantiDu
/week-05/day-3/9-string_again_again.py
158
3.640625
4
def strings_again_again(string): if len(string) == 1: return string[-1] else: return string[0] + "*" + strings_again_again(string[1:])
ee5ff425f61a596cc7edddb5bc3b11211cdc2e56
urandu/Random-problems
/devc_challenges/interest_challenge.py
938
4.21875
4
def question_generator(questions): for question in questions: yield question.get("short") + input(question.get("q")) def answer_questions(questions): output = "|" for answer in question_generator(questions): output = output + answer + " | " return output questions = [ { ...
adcedef13aca9d240215371bbe99a34a8c435347
amrit853200/Intuitive-Python
/dinosaur_egg_2.py
392
3.578125
4
class DinosaurEgg: def __init__(self, egg_id): self.egg_id = egg_id self._hatch_status = None def hatch(self): if self._hatch_status is not None: raise ValueError( f"Egg {self.egg_id} has already been hatched." ) self._hatch_status = "hatc...
bc7507169fdd495509a72e06370f0b6df868967e
amrit853200/Intuitive-Python
/add_sqlite_data.py
432
4.0625
4
import contextlib import sqlite3 with sqlite3.connect("example.db") as connection: with contextlib.closing(connection.cursor()) as cursor: cursor.execute("CREATE TABLE IF NOT EXISTS allowed (name text)") cursor.execute("INSERT INTO allowed values ('Arthur')") cursor.execute("INSERT INTO al...
3dca94334c53cd3d0f5d99ac9ce5c47177ef6ea7
graphql-python/graphene
/graphene/utils/str_converters.py
619
3.59375
4
import re # Adapted from this response in Stackoverflow # http://stackoverflow.com/a/19053800/1072990 def to_camel_case(snake_str): components = snake_str.split("_") # We capitalize the first letter of each component except the first one # with the 'capitalize' method and join them together. return co...
c2eae818b9facda80304eb454e1febf40896bfe8
fluxgame/ALGS200x
/test/fractional_knapsack_test.py
648
3.59375
4
""" Sample 1. Input: 3 50 60 20 100 50 120 30 Output: 180.0000 To achieve the value 180, we take the first item and the third item into the bag. Sample 2. Input: 1 10 500 30 Output: 166.6667 Here, we just take one third of the only available item. """ from fractional_knapsack import get_optimal_value from test.asserts...
c1a3ec17d84b36535839c14795d4fca972ad3999
fluxgame/ALGS200x
/lcm.py
709
3.578125
4
# Uses python3 import sys from test.test import assert_equal def lcm_naive(a, b): for l in range(1, a*b + 1): if l % a == 0 and l % b == 0: return l return a*b def gcd(a, b): if b == 0: return a return gcd(b, a % b) def lcm(a, b): return int((a * b) // gcd(a, b)) ...
1d05a77d4560736a1562d0602bec2601a19188d7
wangyunxizhe/Python-Basics
/my_collections/orderedDictTest/MyOrderedDict.py
249
3.546875
4
from collections import OrderedDict # dict默认有序 user_dict = OrderedDict() user_dict['b'] = "wy1" user_dict['a'] = "wy2" user_dict['c'] = "wy3" print(user_dict) # 将 key=b 的元素移动至最后 user_dict.move_to_end("b") print(user_dict)
092ede2ad47add8c3e7361257e5d09ce9966f2fe
RioWeil/PHYS319-MSP430
/Lab6 Programs/Ultrasonic-DistanceMeasurement/python-serial-plot-new.py
1,177
3.515625
4
#Use python 3.7 (Anaconda 3 and Spider) # Use a command %matplotlib qt in the IPython console before # starting the program #!/usr/bin/python3.7 import serial# for serial port import matplotlib.pyplot as plt import time start=time.time() #define the serial port. Pick one: #port = "/dev/ttyACM0" #for...
3c633b36c488fce1d08c744501c8ca68aae1b8be
Taalaibek02/Homework-all
/front_times.py
184
3.984375
4
def front_times(str,n): result = (str[0]+str[1]+str[2])*n return result print(front_times(input("put your word here: "), int(input("how many times to repeat the code? "))))
66c5ec505f586d56706a9be8459d06d7346baadd
Gaspela/holbertonschool-machine_learning
/supervised_learning/0x03-optimization/5-momentum.py
508
3.609375
4
#!/usr/bin/env python3 """ Momentum """ import numpy as np def update_variables_momentum(alpha, beta1, var, grad, v): """ alpha is the learning rate. beta1 is the momentum weight. var is a numpy.ndarray containing the variable to be updated. grad is a numpy.ndarray containing the gradient of var....
806c6a1a4c7ca9db58badaac8b844b4363867ecd
Gaspela/holbertonschool-machine_learning
/pipeline/0x04-data_augmentation/2-rotate.py
255
3.546875
4
#!/usr/bin/env python3 """ Rotate """ import tensorflow as tf def rotate_image(image): """ image is a 3D tf.Tensor containing the image to rotate Returns the rotated image """ rotate = tf.image.rot90(image, k=1) return (rotate)
14a78c6c70f1dea458ae2eb2a5eca854e1772c43
Gaspela/holbertonschool-machine_learning
/supervised_learning/0x03-optimization/13-batch_norm.py
711
3.75
4
#!/usr/bin/env python3 """ Batch Normalization """ import numpy as np def batch_norm(Z, gamma, beta, epsilon): """ Z is a numpy.ndarray of shape (m, n) that should be normalized. m is the number of data points. n is the number of features in Z. gamma is a numpy.ndarray of shape (1, n) containing...
0eccf66fa16b2897f0337cd5f5a6cb643b696a90
Gaspela/holbertonschool-machine_learning
/math/0x00-linear_algebra/12-bracin_the_elements.py
294
3.578125
4
#!/usr/bin/env python3 """ performs element-wise addition, subtraction, multiplication, division """ def np_elementwise(mat1, mat2): """ performs element-wise """ add = mat1 + mat2 sub = mat1 - mat2 multi = mat1 * mat2 divi = mat1 / mat2 return add, sub, multi, divi
5cbb0ae87c1b5a58fea5d011e9c81f174364b1dd
Gaspela/holbertonschool-machine_learning
/math/0x00-linear_algebra/2-size_me_please.py
385
3.875
4
#!/usr/bin/env python3 """ that calculates the shape of a matrix """ def matrix_shape(matrix): """ Shape matrix """ shape = [] while type(matrix) is list: """ Number of rows of a list """ shape.append(len(matrix)) """ Number of columns list""" if matrix[0]: matr...
189373b1ead5f43d0e1c7a341302420916a57d99
Gaspela/holbertonschool-machine_learning
/supervised_learning/0x04-error_analysis/0-create_confusion.py
637
3.6875
4
#!/usr/bin/env python3 """ Create confusion """ import numpy as np def create_confusion_matrix(labels, logits): """ abels: is a one-hot numpy.ndarray of shape (m, classes) containing the correct labels for each data point. m: is the number of data points. classes: is the number of classes. lo...
506439ec889e817298976146ec4b4302b81591b4
Gaspela/holbertonschool-machine_learning
/math/0x06-multivariate_prob/1-correlation.py
655
3.921875
4
#!/usr/bin/env python3 """ Function that calculates a correlation matrix """ import numpy as np def correlation(C): """ d is the number of dimensions If C is not a numpy.ndarray, raise a TypeError with the message C must be a numpy.ndarray If C does not have shape (d, d), raise a ValueError with ...
ecc85f6cc4eda9fec29ab177933297f9b7f56ea2
Gaspela/holbertonschool-machine_learning
/supervised_learning/0x0D-RNNs/3-lstm_cell.py
2,478
3.71875
4
#!/usr/bin/env python3 """ LSTM Cell """ import numpy as np class LSTMCell: """ represents an LSTM unit """ def __init__(self, i, h, o): """ i is the dimensionality of the data h is the dimensionality of the hidden state o is the dimensionality of the outputs C...
a9872662b5db743e80c493d85f89cc95a779213d
jasperan/python-course
/lesson-2/3_variables.py
486
3.921875
4
#!/usr/bin/python3 minumero = 3 micadena = 'Holaquetaaaal' print(minumero) print(micadena) minumero_decimal = 4.5 print(minumero_decimal) milistadenumeros = [1,2,3,4,5] print(milistadenumeros) lista_de_la_compra = { "huevos":12, "pan":"1 barra", "arroz":"300 gramos" } print(lista_de_la_compra) num1 = 50 nu...
1dcc58bcf097c65258b7c680b6bc4acf6942d206
BRUS1NATOR/Python-Tasks
/Practice/13/main.py
640
4.03125
4
def check_if_prime(n): temp = 2 while n % temp != 0: temp += 1 if temp == n: return 'Простое' else: return 'Составное' def user_input(): try: number = int(input('Введите целое число в промежутке 2 <= x <= 10**9: ')) if 2 <= number <= 10**9: print...
58d2fc2b3c62e5dba94aca1f2b72d456af7ba69e
BRUS1NATOR/Python-Tasks
/Practice/11/main.py
642
4.09375
4
def custom_pow(num, power): temp = num while power > 1: num *= temp power -= 1 return num def user_input(): try: number = float(input('Введите число: ')) except ValueError or TypeError: print('Ошибка при вводе числа') user_input() try: power = in...
faf2b750c6e945cf8112214c18a42112cc94acbb
weichiet/Intro-to-Hadoop-and-MapReduce
/forum_data/05-final-project/5.2-post-and-answer-length/reducer.py
1,194
3.578125
4
#!/usr/bin/env python import sys total_answers_length = 0 number_of_answers = 0 question_length = 0 last_question = None for line in sys.stdin: data = line.strip().split('\t') if len(data) != 3: continue question_id, node_type, body_length = data body_length = float(body_length) if last...
96a39f4843822454b01e4ab1506825bd053518ca
Linkin-1995/test_code1
/day05/homework/exercise06(弹球高度while).py
808
4.40625
4
""" 6. 一个小球从100m高度落下,每次弹回原高度一半. 计算: -- 总共弹起多少次?(最小弹起高度0.01m) 13 次 -- 全过程总共移动多少米? """ height = 100 count = 0 distance = height # 开始落下 -- 计算初始高度 # 判断弹之前的高度height # 判断弹之后的高度height / 2 # 0.01 弹起来的最小高度 while height / 2 > 0.01: # 弹起来 height /= 2 count += 1 distance += height * 2 # 弹起过程 -- 累加起落距...
f6e85390f21e05c093c39fd1a36d1a4abb329986
Linkin-1995/test_code1
/day16/exercise04(迭代员工管理器).py
767
4.0625
4
""" 迭代员工管理器 要求:自行推导 """ class EmployeeIterator: def __init__(self, data): self.data = data self.index = -1 def __next__(self): if self.index >= len(self.data) - 1: raise StopIteration() self.index += 1 return self.data[self.index] class EmployeeCo...
83ac9d92121137cce3d7c1bc53e375432a10cae8
Linkin-1995/test_code1
/day07/demo05(两层for).py
597
4.28125
4
""" for for 练习:exercise04 """ """ print("#", end=" ") print("#", end=" ") print("#", end=" ") print("#", end=" ") print("#", end=" ") print() # 换行 print("#", end=" ") print("#", end=" ") print("#", end=" ") print("#", end=" ") print("#", end=" ") print() # 换行 print("#", end=" ") print("#", end=" ") print("#...
8f9813fc7d3cc3ad8cf51136181ce3d14c171338
Linkin-1995/test_code1
/day16/demo05.py
1,047
3.875
4
""" """ class StudentIterator: def __init__(self, data): self.__data = data self.__index = -1 def __next__(self): # 如果大于等于最大索引,则停止迭代(索引不在增加) if self.__index >= len(self.__data) - 1: raise StopIteration() self.__index += 1 return self.__data[self.__...
4ade44002692ae8488f4b4d0bf48789360e9d9a5
Linkin-1995/test_code1
/day03/demo06.py
406
4.03125
4
""" if elif 调试Debug 定义: 让程序中断,逐语句排查错误(审查变量取值)的过程。 步骤: 1. 添加断点(在可能出错的行) 2. 开始调试 3. 逐语句执行(F8) """ number = int(input("请输入数字:")) if number > 0: print("正数") elif number < 0: print("负数") else: print("零")
0133e987d946fc4e4d9672eca7afc40c69809fb9
Linkin-1995/test_code1
/day09/homework/exercise03(输数字查课程名:简化版).py
811
4.21875
4
""" 练习:参照day03/exercise05案例, 定义函数,根据课程编号计算课程名称。 if course == "1": print("Python语言核心编程") elif course == "2": print("Python高级软件技术") elif course == "3": print("Web 全栈") elif course == "4": print("网络爬虫") elif course == "5": print("数据分析、人工智能") """ def g...
ed9548882b35f9957bf9a9008cfeaea36ef4a508
Linkin-1995/test_code1
/day13/demo01(复合运算符重载).py
758
4.25
4
class Vector2: """ 二维向量 """ def __init__(self, x, y): self.x = x self.y = y # + :创建新数据 def __add__(self, other): return Vector2(self.x + other.x, self.y + other.y) # +=:尽量在原有基础上改变(不可变对象只能创建新,可变对象不创建新) def __iadd__(self, other): self.x += other.x ...
cfd2bb3dc2be67394342cb356f8ce42d2dfabe1d
Linkin-1995/test_code1
/day05/demo08(小结).py
762
3.984375
4
""" 小结 字符串格式化:生成一种格式的字符串 格式%(变量) 列表 列表名 = [元素1,元素2] 列表名.append(元素) 定位 ? = 列表名[整数] # 读取 列表名[整数] = ? # 修改 ? = 列表名[开始:结束:间隔] 列表名[开始:结束:间隔] = ? 删除 列表名.remove(元...
da69bc85053c2d6ca956cae41f7c9d7f87d774d2
Linkin-1995/test_code1
/day06/demo03(浅拷贝内存图).py
303
4.28125
4
""" 列表内存图 列表嵌套 浅拷贝 """ list01 = [ "a", ["b", "c"] ] # 浅拷贝,只备份一层数据(两份) # 第二层数据只有一份 list02 = list01[:] list01[0] = "A" # 修改第一层 list01[1][0] = "B" # 修改第二层 print(list02) # ['a', ['B', 'c']]
2f960dcbfb690bb08eb728e82a7be7961b41e31b
Linkin-1995/test_code1
/day08/demo04(函数设计理念).py
469
3.5625
4
""" 函数设计理念 崇尚小而精,拒绝大而全 返回值 函数定义者 给 调用者 传递的信息 def 函数名(): .... return 数据 变量 = 函数名() 练习:exercise04~06 """ # 需求:定义函数,美元转换为人民币. def usd_to_cny(usd): cny = usd * 7.0733 # 返回 数据 return cny # 接收 结果 result = usd_to_cny(10) print("结果是:" + str(...
06f2ebe240539323ed232937bd118ce44ed6f9cf
Linkin-1995/test_code1
/day04/demo03.py
401
4.28125
4
""" while 循环 - 循环计数 语法: count = 0 # 循环前 -- 开始值 while count < 5: # 循环条件 -- 结束值 循环体 count += 1 # 循环体 -- 间隔 作用: 固定次数的重复 练习:exercise02~04 """ # 执行5次 count = 0 while count < 5: # print("跑圈") print(count) count += 1 # 0 1 2 3 4
71bd0c8d1b96b291eff6f280315e1b4f85b349fb
Linkin-1995/test_code1
/day09/exercise04(星号args).py
262
4.15625
4
# 练习:定义数值累乘的函数 # 1,2,3,4 # 4,54,5,56,67,78,89 def multiplicative(*args): result = 1 for number in args: result *= number return result print(multiplicative(1, 2, 3, 4)) print(multiplicative(4, 54, 5, 56, 67, 78, 89))
ba37dbca7237d4c41a0f669914d6af4085a89f0d
Linkin-1995/test_code1
/day18/exercise04(函编4).py
1,971
3.5625
4
""" 需求3: 定义函数,计算手机列表中白色手机的数量 定义函数,计算手机列表中价格大于7000的数量 需求4: 定义函数,计算手机列表中最贵的手机 定义函数,计算手机列表中名字最长的手机 温馨提示:根据任意条件查找最大值 步骤: 1. 根据需求实现功能 5. 将通用代码定义到IterableHelper类中 6. 用lambda代替变化点 """ from common.iterable_tools import IterableHelper class Phone: ...
bd74d1ec5d86ecb9ffe26f2cc9721a32a25d8b4e
Linkin-1995/test_code1
/day07/exercise06(for for 排列组合,字典变列表).py
862
4.03125
4
# 练习: # 请排列出2个色子可以组合的所有数字 # 每个色子数字1—6,可以使用range(1,7)表达 # list_result = [] # for x in range(1, 7): # 1 2 # for y in range(1, 7): # 123456 123456 # list_result.append((x, y)) # print(list_result) list_result = [(x, y) for x in range(1, 7) for y in range(1, 7)] print(list_result) # 请排列出3个色子可以...
55c258415f723d256948b8a71422b2ceec91f0ba
Linkin-1995/test_code1
/day09/demo05(形参种类5种).py
1,860
4.09375
4
""" 函数参数 形式参数:约束实参的传递方式 1.默认形参:实参可选 2.位置形参:实参必填 3.命名关键字形参:必须是关键字实参 不定长形参 4.星号元组形参:位置实参数量无限 5.双星号字典形参:关键字实参数量无限 """ # 1. 默认形参:不提供实参时,使用默认的数值. # 价值:实参可选(实参可以写也可以不写) # 注意:必须从右向左依次存在 def func01(p1="", p2=0.0, p3=0): print(p1) ...
a179be290cc5525cc218f62e1f363ada36eb48f1
Linkin-1995/test_code1
/day04/exercise09(输数累加).py
592
3.796875
4
# 练习1:在终端中录入5次数字,然后打印累加和. # 练习2:在终端中录入数字,如果录入空字符串则停止录入, # 最后打印累加和. # sum_value = 0 # # 不希望在循环体中使用循环变量,所以命名为双下划线. # for __ in range(5): # 0 1 2 3 4 # number = int(input("请输入数字:")) # sum_value += number # print("累加结果:" + str(sum_value)) sum_value = 0 while True: number = input("请输入数字:") if number == "...
94e5b9cb01aebc82a0322a5d55693ac87197919e
Linkin-1995/test_code1
/day06/exercise02.py
299
3.5625
4
# 练习: list03 = ["湖南", "湖北", "河南", "河北"] list04 = list03[:] list03[0] = "湖南省" list03[-1] = "河北省" list03[1:3] = ["湖北省", "河南省"] print(list03) # ['湖南省', '湖北省', '河南省', '河北省'] print(list04) # ['湖南', '湖北', '河南', '河北']
f8eda6ce91486685d6d0b6d780488b0d40b547d9
Linkin-1995/test_code1
/day06/demo05(list --> str).py
614
3.875
4
""" list --> str 将多个字符串拼接为一个。 字符串 = "连接符".join(列表) 练习:exercise04 """ # 需求:根据xx逻辑,拼接字符串. # result = "" # for number in range(10): # 0~9 # # 缺点:每次循环,创建新字符串,之前的字符串成为垃圾 # result += str(number) # print(result) # 解决:用可变对象替代不可变对象 list_result = [] for number in range(10): # 0~9 # 在原有列表基础上增加 list_r...
42c9c55b59d16d0da484982061b502da8319122b
Linkin-1995/test_code1
/day06/exercise03(深拷贝和浅拷贝).py
636
3.546875
4
import copy list01 = ["北京", ["上海", "深圳"]] list02 = list01 # 不是拷贝,是赋值(数据只有一份) list03 = list01[:] # 浅拷贝(第一层数据有两份,深层数据只有一份) list04 = copy.deepcopy(list01) # 深拷贝(所有数据有两份) list04[0] = "北京04" list04[1][1] = "深圳04" print(list01) # ['北京', ['上海', '深圳']] list03[0] = "北京03" # 修改第一层(互不影响) list03[1][1] = "深圳03" # 修改第二层(互相影响)...
95dbc87d69abfe43d2d7e367a90e2e6f014a0270
Linkin-1995/test_code1
/day10/review01.py
1,100
3.96875
4
""" 复习 - 函数参数 实际参数:与形参进行对应 位置实参:按顺序 序列实参:拆 关键字实参:按名字 字典实参:拆 形式参数:约束实参传递方式 默认形参:可选 """ # 语法: # 默认形参:def 函数名(形参名1=默认值,形参名2=默认值): # 适用性:允许实参不传递信息式 def func01(p1=0, p2=0, p3=0): pass # 位置实参 :函数名(数据1,数据2,数据3) # 价值:最常用的为形参传递数据方式 ...
91a3d1a10e6ac3751b063c21ae4156ff85f7e5a7
Linkin-1995/test_code1
/day10/exercise03(狗列表内存图).py
1,558
4.09375
4
""" 实例变量 - 练习 1. 画出列表list_dogs内存图 2. 画出调用find_dog_by_name函数内存图 """ class Dog: def __init__(self, variety, name, age, weight): self.variety = variety self.name = name self.age = age self.weight = weight d01 = Dog("拉布拉多", "米咻", 5, 70) list_dogs = [ d01, ...
caf92a492f06fcab1e1fcbc1d423aaed5815b9f7
fooltomb/algorithm
/LeetCode/0002AddTwoNumber/AddTwoNumber_1.py
1,307
3.609375
4
#Definiton for singly-linked list class ListNode(object): def __init__(self,x): self.val=x self.next=None class Solution(object): def addTwoNumbers(self,l1,l2): """ """ jinwei=0 res=ListNode(0) brv=res while True: sum=l1.val+l2.val ...
b9e216d60181a79c454cbed10998b4555b0ccd57
fooltomb/algorithm
/LeetCode/0020ValidParentheses/validParentheses_0.py
507
3.8125
4
class Solution(object): def isValid(self,s): """ """ dict={'(':'-',')':'(','[':'-',']':'[','{':'-','}':'{'} if len(s)==0: return True stack=[s[0]] for i in range(1,len(s)): if len(stack)==0 or dict[s[i]]!=stack[-1]: stack.append...
eb694cd25ea25b8472e958a928e999d8c2ea2b07
fooltomb/algorithm
/LeetCode/0107TreeOrderBottomII/levelOrderBottom_0.py
712
3.546875
4
class TreeNode(object): def __init__(self,x): self.val=x self.left=None self.right=None class Solution(object): def levelOrderBottom(self,root): if root==None: return [] stack=[root] result=[[root.val]] while len(stack)>0: for i in...
effb9052b466b75d99c25766bd9042b5e665124a
fooltomb/algorithm
/LeetCode/0414ThridMaxNumber/thirdMaxNum.py
1,349
3.703125
4
class Solution: def thirdMax(self, nums) -> int: res=[nums[0]] for num in nums: if(len(res)==3): if num==res[0] or num==res[1] or num==res[2]: continue if num>res[0]: res[2]=res[1] res[1]=res[0] ...
dd1f856141a2ce7d2d94a67122df0d9a7d1898a4
fooltomb/algorithm
/LeetCode/0026RemoveDuplicates/removeDuplicates_0.py
490
3.578125
4
class Solution(object): def removeDuplicates(self,nums): if len(num)==0: return 0 index=0 while True: if index==len(nums)-1: break if nums[index]==nums[index+1]: nums.remove(nums[index]) else: ind...
d0f5b60dd4d93bc87e1e08ebd60dfe0de0989d39
Dparshyn/Test_on_AQA_Trainee
/Parshin1.py
175
3.71875
4
i = int(input('Введите любое число: ')) if i > 7: print('Привет!') else: print('Введенное число меньше или равно 7')
8fef801cdbf1c75468d4fc8e3ef5eb45cc2588e0
nate-power/TkinterBookLibrary
/database.py
4,004
3.546875
4
import sqlite3 def create_db(): conn = sqlite3.connect("library.db") cur = conn.cursor() cur.execute("""CREATE TABLE IF NOT EXISTS Book ( title text, author text, category text, in_cart integer )""") conn.commit() conn.close() ...
8977188e627cf7fcdd313194d92e19e34056b87b
diegobraga92/Algorithms
/Algorithms/Greatest Common Divisor/gcd.py
272
3.59375
4
# Uses python3 import sys def gcd_euc(a, b): big = max(a,b) small = min(a,b) if small > 0: return gcd_euc(small, big % small) else: return big if __name__ == "__main__": a, b = map(int, input().split()) print(gcd_euc(a, b))
81c072b37f0697fa5a6581438f3197166fba0e9b
xiaonianwen/data_structPython
/data_struct/queue.py
1,097
4.03125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @Author mantou @Date 2020/8/12 20:23 @Describe """ class Mqueue: def __init__(self,maxLength): self.maxLength = maxLength self.head = -1 self.end = -1 def init_queue(self): self.q = [] def add(self,data): ...
f41634d9d43d8645cb897e4e58ea6c4869a7e140
skyyi1126/leetcode
/498.diagonal-traverse.py
1,034
3.609375
4
# # @lc app=leetcode id=498 lang=python3 # # [498] Diagonal Traverse # # @lc code=start class Solution: def findDiagonalOrder(self, matrix): if not matrix: return [] res = [] def up(i, j): if -1 < i < len(matrix) and -1 < j < len(matrix[0]): res.appen...
da5d745666b6c89ace8a59d49091be1e66d44626
skyyi1126/leetcode
/127.word-ladder.py
1,082
3.6875
4
# # @lc app=leetcode id=127 lang=python3 # # [127] Word Ladder # from collections import defaultdict from queue import Queue class Solution: def ladderLength(self, beginWord, endWord, wordList): if not wordList or endWord not in wordList: return 0 WORDS = defaultdict(list) L = le...
02bd031bedc3df4c10ffa597e49b44521c8346a4
skyyi1126/leetcode
/1007.minimum-domino-rotations-for-equal-row.py
1,629
3.53125
4
# # @lc app=leetcode id=1007 lang=python3 # # [1007] Minimum Domino Rotations For Equal Row # """ class Solution: def minDominoRotations(self, A, B): if not A or not B or len(A) != len(B): return -1 a0 = A[0] b0 = B[0] rotate_a = self.rotation(a0, A, B) if rotate_...
1392b8cb8c9ac7210613de5f8255970adabf1d42
skyyi1126/leetcode
/103.binary-tree-zigzag-level-order-traversal.py
866
3.703125
4
# # @lc app=leetcode id=103 lang=python3 # # [103] Binary Tree Zigzag Level Order Traversal # # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def zigzagLevelOrder(self, root: TreeNode) ...
387954ebc85ea0cdb83099c2adc299d0065275ac
bansheerubber/dungeon-generator
/collection.py
727
3.53125
4
import random class Collection: def __init__(self, generator): self.rooms = set() self.generator = generator self.generator.collections.append(self) self.color = (random.randint(0, 200), random.randint(0, 200), random.randint(0, 200)) def add_room(self, room): self.rooms.add(room) room.collection = se...
ca41ab123ef7100f01d24d5b0123d8d0f444b762
AjayRamanathan/Euler-Problems
/30.py
350
3.75
4
#!/usr/bin/env python def main() : a = 4*(9**5) print a t = 0 for i in range(1, a+1) : b = checkth(i) if b == True : t = t + i print(t - 1) def checkth(i) : c = 0 for x in str(i) : c = c + (int(x)**5) if c == i : return True else : return None if __name__ ==...
545ced42425e8ba6f1a9ac5d9394d78525673441
lrodriguezjb/math-series
/series.py
374
3.671875
4
def fibonacci(n): if n <= 1: return n else: return(fibonacci(n-1) + fibonacci(n-2)) def lucas(n): if n == 2: return 1 if n == 1: return 2 return(lucas(n-2) + lucas(n-1)) def sum_func(n, b=0, c=1): if n == 2: return b if n == 1: return c ...
292aa3956fc6ad590711f619aeecddfb6816350e
Igor3550/Exercicios-de-python
/mundo1/ex031.py
438
3.84375
4
# faça um programa que pergunte a distancia de uma viagem em km # Calcule o preço da passagem, cobrado R$0.50 por km para viagens de ate 200km # E R$0.45 para viagens mais longas dist = int(input('Digite a distancia da viagen em km: ')) if dist <= 200: preco = dist * 0.5 print('O valor de sua passagem será de R...
c58750254ec06ee9e279d664d7d0910a252bd73c
Igor3550/Exercicios-de-python
/mundo1/ex005.py
249
3.96875
4
# faça um programa que leia um numero inteiro e mostre na tela seu sucessor e seu antecessoe print('\n{:*^40}'.format('Desafio005')) n = int(input('Digite um valor: ')) print('O sucessor de {} é {}, e o antecessor é {}' .format(n, (n+1), (n-1)))
fa35b4b25ecca2add226cddcc013bab93ed5a052
Igor3550/Exercicios-de-python
/mundo2/ex051.py
334
3.890625
4
# faça um programa que leia o primeiro termo e a razão de uma PA. no final mostre os 10 primeiros termos dessa progressão n = int(input('Digite o primeiro termo: ')) r = int(input('Digite a razão: ')) print('Os 10 primeiros termos dessa PA são: ') decimo = n + (10 - 1) * r for c in range(n, decimo+r, r): print(c, e...
fa0a424cf844034d75c78c88cbd6bfebf5bcb250
Igor3550/Exercicios-de-python
/mundo3/ex090.py
495
3.96875
4
# faça um programa que leia nome e media de um aluno guardando também a situação em um dicionario. # No final mostre o conteúdo da estrutura na tela. resul = dict() resul['Nome'] = str(input('Nome: ')) resul['Media'] = float(input(f'Media de {resul["Nome"]}: ')) if resul['Media'] >= 6: resul['Situação'] = 'Aprovado...
eb207904b56c5ec24d4a8c7646c4782f7748a20e
Igor3550/Exercicios-de-python
/mundo2/ex058.py
857
4.09375
4
#faça um programa que melhore o jogo 028 onde o computador vai pensar em um numero de 0 a 10 # Só que agora o jogador vai tentar adivinhar até acertar, mostrando no final quantos palpites foram necessarios para vencer from random import randint from time import sleep num = randint(0, 10) print('{:*^40}'.format(' Jogo d...
cb9d3fa017d1bb8f250de6f6d2397b08b3c60e51
Igor3550/Exercicios-de-python
/mundo3/ex107/moeda.py
398
3.53125
4
# crie um modulo moeda.py que tenha as funções incorporadas aumentar(), diminuir(), dobro() e metade(). # faça tmb um programa que importe esse modulo e use algumas dessas funções def aumentar(v, p): res = v + (p*v)/100 return res def diminuir(v, p): res = v - (p*v)/100 return res def metade(v): ...
812fa52f7f5e9f7141284347580a20727649f967
Igor3550/Exercicios-de-python
/mundo1/ex026.py
467
4.0625
4
#faça um programa que leia uma frase e mostre: #Quantas vezes aparece a letra "A" # Em que posição ela aparece a primeira vez #Em que posição ela aparece pela ultima vez frase = input('Digite uma frase: ') frase = frase.upper().strip() print('A letra "A" aparece {} vezes'.format(frase.count('A'))) print('Primeiro a let...
227b6a056fb6d25eccae7d16b9b3363a3999867e
Igor3550/Exercicios-de-python
/mundo1/ex029.py
556
3.90625
4
#escreva um programa que leia a velocidade de um carro # Se ele ultrapassar 80km/h, mostre uma mensagem dizendo que ele foi multado # A multa vai custar R$7,00 por cada km acima da velocidade veloc = int(input('Digite a velocidade em km/h: ')) if veloc <= 80: print('Você esta no limite de velocidade\nO limite é de ...
3e1623e7acc92e4c14c3f758808eeaa4fc5d51fb
Igor3550/Exercicios-de-python
/mundo3/ex088.py
660
4.0625
4
# faça um programa que ajude um jogador da megasena a criar palpites. # o programa vai perguntar quantos jogos serão gerados e vai sortear 6 numeros entre 1 e 60 # para cada jogo cadastrando tudo em uma lista from time import sleep from random import randint jogos = [] print(f'{" MegaSena ":+^45}') print() jogs = int(i...
5b931d49c2761e6686155158028b363ea53ae07e
Igor3550/Exercicios-de-python
/mundo2/ex053.py
447
4.0625
4
# crie um programa que leia uma frase e diga se ela é um palindromo, desconsidedrando os espaços frase = str(input('Digite uma frase: ')).upper().strip().split() frase = ''.join(frase) comp = len(frase) inverso = '' for c in range(comp-1, -1, -1): inverso += frase[c] print('A frase "{}" ao contrário fica "{}"'.form...
c70465125cfce76d0e42468a9652368c1d781999
Igor3550/Exercicios-de-python
/mundo2/ex050.py
431
4.03125
4
#faça um programa que leia seis numeros e mmostre a soma apenas daqueles que forem pares, se for impar ele vai ser desconsiderado soma = 0 for c in range(0, 6): if c > 0: n = int(input('Digite outro numero: ')) if n % 2 == 0: soma += n else: n = int(input('Digite um numero: '...
10a4179b5b536c8f7a1657f476d864ad9db0b2e9
Igor3550/Exercicios-de-python
/mundo2/ex055.py
497
3.921875
4
#faça um programa que leia o peso de cinco pessoas no final mostre qual foi o maior e o menor peso lidos maior = 0 menor = 0 for c in range(1, 6): peso = float(input('Digite o peso: ')) if c == 1: maior = peso menor = peso else: if peso > maior: maior = peso if pe...
e9c881e1a39d885a90675a81b7d65bdd5f77d808
Igor3550/Exercicios-de-python
/mundo1/ex024.py
334
4
4
#Crie um programa que leia o nome de uma cidade e diga se ela começa ou não com a palavra 'SANTO' cid = str(input('Digite um nome de uma cidade: ')).strip() veri = cid.upper()#.startswith('SANTO') # print('Sua cidade começa com "SANTO": {}'.format(veri)) OU print('Sua cidade começa com "SANTO" : {}'.format(veri[:5] == ...
7c24e8a9f512d834d443f5bb719b10f1ea5e4f80
Igor3550/Exercicios-de-python
/testesDuranteAulas/aula010.py
989
3.84375
4
# condição simples print('{:*^40}'.format('condição simples')) print('Escolha um menu: \n1. Nomes\n2. Calcular media') esc = int(input('Menu: ')) if esc == 1: print('{:*^40}'.format('Condiçoes com nomes')) nome = str(input('Digite seu nome: ')) if nome == 'Igor': print('Que nome lindo voce tem!') ...
4745d81558130440d35d277b586572f5d3f85c06
glebite/unhappy-face
/test/test_user_input.py
952
3.5
4
import unittest import userinput class Testing(unittest.TestCase): def test_creation(self): x = userinput.UserInput() self.assertNotEqual(x, None) def test_charset_initialization(self): x = userinput.UserInput() self.assertEqual(x.character_set, userinput.CHARACTERS) def ...
a4d7fb1ce9f4cb2ece58195eca1d2d560216ec48
azhar145/lookup_python
/pyspark_azhar3.py
610
3.5
4
from pyspark import SparkContext sc = SparkContext("local", "count app") words = sc.parallelize ( ["scala", "java", "hhhhh", "gggfff", "hadoop", "spark", "akka", "spark vs hadoop", "pyspark", "pyspark and spark"] ) counts = words.count() print "Number of elements in RDD -> %i" % (counts) ...
f55cad86722d002438869611c16d7050f0a57947
azhar145/lookup_python
/find_string.py
318
3.609375
4
import re u="A group of Senate Sen5te grcup Democrats unveiled a proposal on Friday" p= 'Sen(.)te' for x in u.split(): pa=re.findall(p,x) if len(pa) > 0: print(x) ##import re ##s1 = "Mayer is a very common Name" ##s2 = "He is called Meyer but he isn't German." ##print(re.search(r"M[ae][iy]er", s1))
fdf78b740b8f070054461e947f81592d5aa289c0
Toerq/emacs
/ad2/assignment_1/binary_mult.py
3,650
4.0625
4
#!/usr/bin/env python2.7 ''' Assignment 1: Binary Multiplication Team Number: 2 Student Names: Christian Tornqvist, Milad Taba ''' import unittest def binary_mult(A,B): """ Sig: int[0..n-1], int[0..n-1] ==> int[0..2*n-1] Pre: len(A) == len(B), A and B are represented as binary numbers with their M...
671b8b3ad4abcb94d39948358b98db3c444c11d6
JainStuti25/Hacktoberfest
/Python/ML Algorithms/k-means.py
596
3.765625
4
from sklearn.cluster import KMeans import pandas as pd #reading the csv file having fees and experience as two columns df = pd.read_csv('file_name.csv', sep=',', header=None) #checking the values read in a numpy array print(df.values) # making two cluster for k-means kmeans = KMeans(n_clusters=2) #passing the clust...
a7cec55420719c7d5a3327c5bfea6ce4393b1363
LottZhang/shell_tool
/shellgongju/study/ti/5.py
1,403
3.53125
4
#!/usr/bin/python # -*- coding: utf-8 -*- #雷诺数=管径*流速*流体密度/流体粘度 ''' 雷诺数的计算公式是(Dvrho)mu,其中D为直径,v为速度,rho为密度,mu为黏性。编写一个程序,接收一组数据并计算雷诺数。如果小于 2100,则显示“层流”;在2100至4000之间,则显示“暂态流”;大与4000则显示“湍流”(使用分支语句if else then); 5、 修改上面的程序,显示“开始新的计算?(是否)”,如果选“是”,则重新输入一组数据;如果选“否”,则退出程序(使用循环语句)。如果mu 的值为0,程序是否会提示“除数为0”的错误?或是给出“程序崩溃”的提示?怎样处理这种情...
5976f61efb51e5d6293cd38d36c38ef5c96c5c92
alvin-x24/alvin-x
/Tic-Tac-Toe.py
6,948
4.40625
4
# define a print board # define a player move # define what is victory # define what a draw is # Create a While Loop # This is not necessary to put here as it exists within the while loop, but it serves to explain the rest of the code # a little better. boardValues = { 1: ' ', 2: ' ',...
26cffb891edbf40f373f56458f44427cf2c03d92
Isaac-Yuri/menu-de-opcoes-matematicas
/principal.py
1,798
4.34375
4
from funcoes import menu, linha, continuar from math import sqrt while True: print('===> SUAS OPÇOES <===') menu() linha(23) opcao = int(input('Digite sua opção: ')) if opcao == 1: while True: num = int(input('Digite um número para checar se é par ou ìmpar: ')) linh...
527f338b6cf86fbb36c12bef6aa0d8c7dde3811d
balakrishna-123/Python_For_Beginers
/Day_1_Assignment.py
398
3.859375
4
import random maxTicketsAvalibale = int(input("Enter the maximum tickets avaiable ")) participants = [] for temp in range(maxTicketsAvalibale): name = input("Enter the participant name - "+ str(temp + 1) + " - ") participants.append(name) print("All our participants - ",participants) n = random.randint(0,max...
0f8bad926ae000333cfd44ee3d7e80ffc07b66a8
SangChan/tensordojo
/Archived/20190528.py
777
3.609375
4
import tkinter import random def hello(): print("hello there") #tk = tkinter.Tk() #btn = tkinter.Button(tk, text = "click me", command=hello) #btn.pack() #tkinter.mainloop() def random_rect(width, height): x1 = random.randrange(width) y1 = random.randrange(height) x2 = x1 + random.randrange(width) ...
ed79e490884399177e55bef0747a9b86c5f97db7
jbathel/holbertonschool-low_level_programming
/0x1C-makefiles/5-island_perimeter.py
545
3.9375
4
#!/usr/bin/python3 """ Function that finds the perimeter of a given island" """ def island_perimeter(grid): """Function that returns the perimeter of the island in grid.""" island = 0 perimeter = 0 for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == 1: ...
1550e91bedf72802f074b38e61b83d6fab097cfb
bowersj00/CSP4th
/Bowers_TurtleApple.py
1,159
3.65625
4
import turtle as trtl , random apple_image = "apple.gif" # Store the file name of your shape wn = trtl.Screen() wn.addshape(apple_image) # Make the screen aware of the new file wn.setup(width=1.0, height=1.0) wn.bgpic("background.gif") apple = trtl.Turtle() apple.penup() apple.speed(1) drawer = trtl.Turtle() drawer...
c44ca53b2a11e083c23a725efcb3ac17df10d8ee
bowersj00/CSP4th
/Bowers_MyCipher.py
1,146
4.28125
4
alphabet=['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 shifter(start_string, shift): new_string="" for character in start_string: if character.isalpha(): new_string=new_string+(alphabet[(alphabet.index(character)+shift)%26]) ...
6e4a1a8e877bacb7a74f82c80ae30aa6fe3e4177
bowersj00/CSP4th
/Bowers_TurtleAnimation.py
8,104
4.0625
4
""" Instructions: Design at least two images with turtle that represent your school year so far. No abstractions. Challenge: Add animations to give life to your project Concept: 1. Me doing notes by lamp light in the living room a. living room background b. lamp shining c. me sitting on couch d. book ...