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 |
|---|---|---|---|---|---|---|
0a685439e88369e8b563d1960fa8fc846e9fe2d5 | Renatabfv/T-cnicas-de-Programa-o | /projeto_2.py | 1,332 | 4.15625 | 4 | #cadastrar novos usuários pelo seu nome completo e e-mail
#exibir todos os usuários cadastrados, listando-os por ordem de cadastro.
#exibir todos os usuários cadastros, listando-os por ordem alfabética.
#um usuário faz parte da lista de participantes, buscando-o pelo seu nome.
#remover um usuário cadastrado, buscando-o... |
5a326e8c133c4fb3fc2d0581f1c8d6c7feb72376 | Ayman-M-Ali/Mastering-Python | /Assignment_015.py | 2,725 | 4.15625 | 4 | #--------------------------------------------------------
# Assignment (1):
# Write the following code to test yourself and do not run it
# After the last line in the code write a comment containing the Output that will come out from your point of view
# Then run Run to see your result sound or not
# Make a com... |
ffe8ea4dbc5829fc01f4a950009cc8151f6f1762 | Ayman-M-Ali/Mastering-Python | /Assignment_007.py | 4,126 | 4.34375 | 4 | #---------------------------------------------------------------
# 1- In the first 4 lines, using the Bool Method print 4 different data types, their result is True
# On line 5 to 8, using Bool Method print 4 different data types, their result is False
# 2- Create 3 variables with the names of any programming skills... |
c89ddd8476fcf624368c4b542d6115b8881c7ad7 | Ayman-M-Ali/Mastering-Python | /Assignment_002.py | 3,627 | 4.21875 | 4 | #----------------------------------------------
#[01] Create 3 Variables Name, Age, Country
#[02] Print This Text To The Console => "Hello 'Variable Name', How You Doing \ """ Your Age Is "Variable Age""
#[03] Print The Same Previous Text But in 3 Lines Not Single Line
#[04] Get The Letter "l" From Elzero
#[05] Get Th... |
3037a97fc4cdeb8063797c2d8a0c4d3cd7c7d0d9 | gift-surg/puma | /puma/helpers/testing/parameterized/namedtestparameters.py | 600 | 3.5 | 4 | from abc import ABC
from typing import Iterator
class NamedTestParameters(ABC):
"""
Creates a named set of parameterized test parameters to be used with @parameterized() without having to create a dummy "name" test argument
"""
def __init__(self, name: str) -> None:
self._name = name
def... |
ae0defbba593a42477814877b4b02564d3b32060 | AlbertYeYong/RPiPython | /tcpClt.py | 725 | 3.546875 | 4 | #!/usr/bin/python3
# usage: python3 tcpClt2.py 192.168.1.123
# exit to quit
import sys
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if len(sys.argv) == 1:
host = socket.gethostbyname('localhost')
else:
host = socket.gethostbyname(sys.argv[1])
port = 5... |
ed4aced7983d0c55caffbe708f5c1b46d7cdea56 | mlabuda2/design_paterns | /factory/abstract/pasta/pasta.py | 343 | 3.609375 | 4 | from abc import ABC, abstractmethod
class Pasta(ABC):
def __init__(self, weight: int, parmesan: bool = False, al_dente=False):
self.weight = weight
self.parmesan = parmesan
self.al_dente = al_dente
@abstractmethod
def eat(self):
pass
def get_total_kcal(self):
... |
d8400c2bace193c9d4edb0613a32a47c849e8be8 | christianboutin/montyhalldemo | /montyhall.py | 755 | 3.84375 | 4 | import random
#Returns 1 if the original selection wins
def PlayGame():
i = [0,0,1]
random.shuffle(i)
#print "Game is: ",i
selected = random.randrange(0,3)
#print "Player Selects: ",selected
while(True):
# Can't remove a car, can't remove selected
remove = random.randrange... |
01c42894995af3c92f4b2230483a70dac4f09dc2 | pd-pony/Python_exercise | /eg28.py | 515 | 3.75 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : Peidong
# @Site :
# @File : eg28.py
# @Software: PyCharm
"""
题目:求100之内的素数。
"""
# 输出指定范围内的素数
# take input from the user
lower = int(input("输入区间最小值: "))
upper = int(input("输入区间最大值: "))
sum = 0
for num in range(lower, upper + 1):
# 素数大于 1
for i in... |
bacbf4c954d613d2a375f02d9b909cdc8d56214b | pd-pony/Python_exercise | /eg47.py | 389 | 3.640625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : Peidong
# @Site :
# @File : eg47.py
# @Software: PyCharm
"""
题目:求0—7所能组成的奇数个数。
"""
if __name__ == '__main__':
sum = 4
s = 4
for j in range(2,9):
print (sum)
if j <= 2:
s *= 7
else:
s *= 8
... |
5d819a5b34654decfad6ade59d698750e6d1c906 | pd-pony/Python_exercise | /eg49.py | 482 | 3.703125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : Peidong
# @Site :
# @File : eg49.py
# @Software: PyCharm
"""
题目:判断一个数能被几个9整除。
"""
if __name__ == '__main__':
zi = int(input('input a number:\n'))
n1 = 1
c9 = 1
m9 = 9
sum = 9
while n1 != 0:
if sum % zi == 0:
n1... |
073cb8b4c68463b903c6b033228e849ca8a1136f | Athithya6/Python-Programs | /trial4.py | 901 | 4.25 | 4 | # List comprehensions and while loop
# Celsius to fahrenheit using ordinary for loop
'''
celsius = [12.5, 36.6, 37, 43, 49]
fahrenheit = []
for i in celsius:
caltemp = (((9 / 5) * i) + 32)
fahrenheit.append(caltemp)
print("Input Celsius tempertures in fahrenheit: ", fahrenheit)
'''
'''
# Celsiu... |
8c61c6dacaca5de56bf215ff995af170ed924c63 | Athithya6/Python-Programs | /python_pract2.py | 2,609 | 4.09375 | 4 | #filename='Athithya2.txt'
#with open(filename,'w') as f:
#f.write("A boy's best friend is his mother.")
#with open(filename,'a') as f:
# f.write("\nHere's looking at you kid.\n All right Mr.DeMille, I am ready for "
# " my closeup.\n I would not join any club that would have me as its "
# " member")
#with ... |
ccc55f7e77c094bd30fac95dd3577bac1f14071a | saidarahmaff/Saida-Rahma-Afifi_I0320089_Wildan_Tugas4 | /I0320089_soal3_tugas4.py | 187 | 3.625 | 4 | #input data perhitungan
a = int(input("masukkan berat"))
b = 49
#membandingkan berat a
hasil=(a<=22)
print(hasil)
#membandingkan berat b
hasil = (b<=22)
print(hasil)
|
6ee6a0ef1a1f4635f368c502572c01bf7576d874 | DaniilAzarov/python-course | /homeworks/homework1/task1.py | 970 | 3.8125 | 4 | def spoon_and_iron(gadget, quantity):
if gadget == "ложка":
vars = ["ложка", "ложки", "ложек"]
if quantity % 10 == 1 and quantity % 100 != 11:
gadget = vars[0]
elif quantity % 100 == 12 or quantity % 100 == 13 or quantity % 100 == 14:
gadget = vars[2]
eli... |
ee67e76da350598875e829d7f8ac79e0b0816e10 | DaniilAzarov/python-course | /homeworks/homework1/task2.py | 240 | 3.703125 | 4 |
def mean_fun(str_lst):
str_lst = str_lst.split()
num_lst = []
for n in str_lst:
num_lst.append(float(n))
num_mean = (sum(num_lst) / len(num_lst))
print(num_mean)
open_fun = mean_fun(input())
|
28f86ac7fac65f715ffdf7dc362061a8da112b1f | neidnik/1-laba | /1l.py | 449 | 3.9375 | 4 | while True:
a=input("первое число: ")
b=input("второе число: ")
c=input("действие: ")
if c =='/':
if int(b) != 0:
print(int(a) / int(b))
else:
print("Деление на ноль")
if c =='+':
print(int(a) + int(b))
if c =='-':
print... |
aaedfac554653af897dfcddbccb150571f0b78f4 | Mfalz/distributed_system | /mapreduce_jobs/map_review.py | 580 | 3.875 | 4 | #!/usr/bin/python
"""
This script gets in input a file mv_xxxxxxx.txt, in this file are stored film reviews identified by
the xxxxxxx id.
The purpose of this script is to map each review.
Each line of the file has the following format:
id_user,num_star,date
"""
import sys
numline=0;
for line in sys.stdin:
... |
dc643ace5990b583932c6c3626020818e205d15f | abhinandandixit30/Calc-by-Python | /Our project.py | 11,024 | 3.90625 | 4 | #Libraries used
import tkinter
from math import *
import math
from tkinter import *
#Code for input, output and operations performed
class Calc():
def __init__(self):
self.total = 0
self.current = ""
self.new_num = True
self.op_pending = False
self.op = ... |
d4452a402fe9ea523404334e696bb84b0d690b9d | punamspawar/Python-Excercise | /check_prime.py | 291 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 24 20:09:07 2021
@author: v-pusalu
"""
ip=int(input("Enter a number"))
if ip>1:
for i in range(2,ip):
if ip%i==0:
print("{} is not prime".format(ip))
break
else:
print("{} is prime".format(ip)) |
6c90fc19bf8e7ccc39ab3db77b7df1126c71aa16 | Lydia-Li725/python-basic-code | /循环.py | 210 | 3.53125 | 4 | '''
while 条件:
条件成立重复执行的代码
。。。
'''
# 需求:重复打印五次,有个数据表示循环的次数
i = 1
while i <= 5:
print("我错了")
i += 1 |
a46f28c517b1a50d4a2d136b3c08b5e76eeb4205 | Lydia-Li725/python-basic-code | /常用操作.py | 934 | 3.828125 | 4 | n_l =['TOM','LILIY','LINDA']
'''print(n_l)
print(n_l[0])
print(n_l[2])
print(n_l.index('LILIY'))
#print(n_l.index('Tom'))
print(n_l.count('TOM'))
print(len(n_l))
print('TOM' in n_l)
print('l'not in n_l)
#注册邮箱,判断是否存在账户名
#name = input("请输入名字:")'''
'''
if name in n_l:
print(f'您的名字是{name},从新输入')
else:
... |
a093078ab731ec6ba5105998b6f61ee8633dec01 | Lydia-Li725/python-basic-code | /随机数.py | 360 | 3.875 | 4 | import random
player = int(input("出拳:,0--石头,1--剪刀,2--布:"))
computer = random.randint(0,2)
#print(computer)
# 2.判断输赢
if ((player == 0) and (computer ==1)) or ((player ==1) and (computer ==2)) or ((player ==2) and (computer ==0)):
print("win")
elif player == computer:
print("even")
else:
pri... |
694a06ab8f7ca681fb5b16f273cb2be1f725abbd | Lydia-Li725/python-basic-code | /排序.py | 369 | 4.1875 | 4 | def insertion_sort(array):
for index in range(1,len(array)):
position = index
temp_value = array[index]
while position > 0 and array[position - 1] > temp_value:
array[position] = array[position-1]
position -= 1
array[position] = temp_value
return a... |
9dac54ca7df43935000044bf2eb5ca3d14cb6b3b | Lydia-Li725/python-basic-code | /猜拳游戏.py | 453 | 3.921875 | 4 | '''
1.出拳:
玩家:手动输入
电脑:固定剪刀
2.判断输赢
玩家获胜
平局
电脑胜
'''
# 1.出拳
player = int(input("出拳:,0--石头,1--剪刀,2--布:"))
computer = 1
# 2.判断输赢
if ((player == 0) and (computer ==1)) or ((player ==1) and (computer ==2)) or ((player ==2) and (computer ==0)):
print("win")
elif player == computer:
... |
dc4c1a65dfb0c321ddc27ca112ce5436d27ec5a6 | asmusz-adobe/Python3-AdobeSignRestV5 | /listUsers_V5.py | 738 | 3.71875 | 4 | """
Gets the list of users in an account as a list of 'dictionaries'
Usage:
token_string = '3AAABLblqZhC2YTAO******* Your integration key or access token ************ohF9DaLV-4GKbLuiM-0lmTtSq'
userList = list_users(token_string)
pprint(userList)
access elements of each 'dictionary' using list index + dictionary index
p... |
6f2f4dabd3259a49b40d5eaef7cd7459c93cb69a | baltajmahal/WebScraping_Taj | /scrape_mars.py | 4,457 | 3.609375 | 4 | # ## Step 2 - MongoDB and Flask Application
# Use MongoDB with Flask templating to create a new HTML page that displays all of the
# information that was scraped from the URLs above.
# * Start by converting your Jupyter notebook into a Python script called `scrape_mars.py`
# with a function called `scrape` that wil... |
a2f2ef8af2a4f9d083c0636f161328013050fc1e | prudvika-j/Algorithms | /Course-1/Week-3/quick_first.py | 676 | 3.546875 | 4 | A = []
count = 0
def read_file():
fp = open("in.txt", "r")
for line in fp:
val = line.rstrip('\n')
# print("value = ", val)
A.append(int(val))
fp.close()
def quicksort(low, high):
if low < high:
j = partition(low, high)
quicksort(low, j-1)
quicksort(j+1, h... |
ae8a6368c129c1ebadf5cefbd94285cc18871c56 | prudvika-j/Algorithms | /Course-1/Week-3/quick_median.py | 1,095 | 3.609375 | 4 | A = []
count = 0
def read_file():
fp = open("in.txt", "r")
for line in fp:
val = line.rstrip('\n')
# print("value = ", val)
A.append(int(val))
fp.close()
def quicksort(low, high):
if low < high:
pivot = median(low, high)
A[low], A[pivot] = A[pivot], A[low]
... |
c8febb08bea8402f37052827bbe517f4494c098e | C22660/club_echecs | /tools/menus.py | 1,321 | 3.765625 | 4 | """fonctions sui font les print."""
class MenuEntry:
def __init__(self, option, handler):
self.option = option
self.handler = handler
# suppression des str et repr
# le menu est une série d'entrée
class Menu:
def __init__(self):
self._entries = {}
self._autokey = 1
# han... |
027ddb1b8268b0d843d0c987d8c31eda833b9bbf | mxmaria/coursera_python_course | /week5/Ближайшее число.py | 562 | 4.125 | 4 | # Напишите программу, которая находит в массиве элемент, самый близкий по величине к данному числу.
n = int(input())
mass_elems = list(map(int, input().split()))
diff_from_number = int(input())
min_diff_elem = mass_elems[0]
min_diff = abs(min_diff_elem - diff_from_number)
for elem in mass_elems:
curr... |
b1f37d0a9a5d003672c1c3d17a2c72b0a9094b57 | mxmaria/coursera_python_course | /week4/Быстрое возведение в степень.py | 709 | 4.375 | 4 | # Возводить в степень можно гораздо быстрее, чем за n умножений!
# Для этого нужно воспользоваться следующими рекуррентными соотношениями: aⁿ = (a²)ⁿ/² при четном n, aⁿ=a⋅aⁿ⁻¹ при нечетном n.
# Реализуйте алгоритм быстрого возведения в степень.
def power(a, n):
if n == 0:
return 1
elif n == 1:
... |
f450cf54bb548581dead08ae55b14610bd52cdb9 | mxmaria/coursera_python_course | /week2/Количество элементов, равных максимуму.py | 539 | 3.96875 | 4 | # Последовательность состоит из натуральных чисел и завершается числом 0.
# Определите количество элементов этой последовательности, которые равны ее наибольшему элементу.
n = int(input())
max_el = n
quant_of_el = 0
while n != 0:
if n > max_el:
max_el = n
quant_of_el = 1
elif n == max... |
fe4a424e37781c16bc810a0d9eaa052935855a80 | mxmaria/coursera_python_course | /week8/Количество слов в тексте2.py | 517 | 3.65625 | 4 | # Во входном файле записан текст.
# Словом считается последовательность непробельных символов идущих подряд,
# слова разделены одним или большим числом пробелов или символами конца строки.
# Определите, сколько различных слов содержится в этом тексте.
print(len(set(open('input.txt').read().split())))
|
b79fe6a6d388f0bc02d2ac304582ad39a54811c5 | mxmaria/coursera_python_course | /week3/Цена товара.py | 745 | 4.125 | 4 | # Цена товара обозначена в рублях с точностью до копеек, то есть действительным числом с двумя цифрами после десятичной точки.
# Запишите в две целочисленные переменные стоимость товара в виде целого числа рублей и целого числа копеек и выведите их на экран.
# При решении этой задачи нельзя пользоваться условными инс... |
184ad365588f52dfd2e73a540b69749b3269bbfd | mxmaria/coursera_python_course | /week4/Сократите дробь.py | 579 | 3.84375 | 4 | # Сократите дробь (n / m), то есть выведите два других числа p и q таких, что (n / m) = (p / q) и дробь (p / q) — несократимая.
# Решение оформите в виде функции ReduceFraction(n, m), получающая значения n и m и возвращающей кортеж из двух чисел: return p, q
import math
n = int(input())
m = int(input())
de... |
26dafe823f7870dd47096c8e4bb4cb809cb95a0b | mxmaria/coursera_python_course | /week2/Узник замка Иф.py | 985 | 4.1875 | 4 | # За многие годы заточения узник замка Иф проделал в стене прямоугольное отверстие размером D×E.
# Замок Иф сложен из кирпичей, размером A×B×C. Определите, сможет ли узник выбрасывать кирпичи в море через это отверстие (очевидно, стороны кирпича должны быть параллельны сторонам отверстия).
# Программа получает на вхо... |
b325866e0f18efb571e4e35163e4de9f18696736 | mxmaria/coursera_python_course | /week9/Добавить, умножить.py | 1,603 | 3.796875 | 4 | # Добавьте в предыдущий класс следующие методы:
#
# __add__, принимающий вторую матрицу того же размера и возвращающий сумму матриц.
# __mul__, принимающий число типа int или float и возвращающий матрицу, умноженную на скаляр.
# __rmul__, делающий то же самое, что и __mul__.
# Этот метод будет вызван в том случае,... |
7a9ba7a88c17375cbbb3ddb0b8c122f937deb614 | kolitiri/python-utils-collection | /config_operations/config_parser.py | 3,303 | 3.8125 | 4 | # Standard library imports
import ast
import configparser
import sys
def get_list_cfg(config_file, section, config_item):
""" Utility proc that uses configparser package
to parse a list config from a file.
A list config is a sequence of comma separated items
Args:
config_file... |
acbf854d06bfa1e458cf65cca8af844fb40cd094 | swavaldez/python_basic | /01_type_and_statements/04_loops.py | 620 | 4.21875 | 4 | # student_names = []
student_names = ["Mark", "Katarina", "Jessica", "Sherwin"]
print(len(student_names))
# for loops
for name in student_names:
print("Student name is {0}".format(name))
# for range
x = 0
for index in range(10):
x += 10
print("The value of x is {0}".format(x))
# start in 5 and ends in 9
... |
6777e5b9cac522dceca75e3047a020b980772416 | eMUQI/Python-study | /python_book/basics/chapter04_list_operation/04-06.py | 81 | 3.515625 | 4 | list_of_num = [i for i in range(1,21,2)]
for temp in list_of_num:
print(temp) |
0a0ff088a439967ec11af0da1ef393f07d98d85e | eMUQI/Python-study | /python_book/basics/chapter11_testing/11-02/city_functions.py | 926 | 3.703125 | 4 | '''
11-2 人口数量:修改前面的函数,使其包含第三个必不可少的形参 population ,并
返回一个格式为 City, Country – population xxx 的字符串,如 Santiago, Chile –
population 5000000 。运行 test_cities.py ,确认测试 test_city_country() 未通过。
修改上述函数,将形参 population 设置为可选的。再次运行 test_cities.py,确认测
试 test_city_country() 又通过了。
再编写一个名为 test_city_country_population() 的测试,核实可以使用类似于
's... |
214f5b112c81efed5de997dd92b72e35383da87d | eMUQI/Python-study | /python_book/basics/chapter03_list/03-08.py | 352 | 4.125 | 4 | list_of_place = ['hangzhou','shanghai','meizhou','xian','beijing']
#1
print(list_of_place)
print(sorted(list_of_place))
print(list_of_place)
print(sorted(list_of_place,reverse = True))
print(list_of_place)
list_of_place.reverse()
print(list_of_place)
list_of_place.sort()
print(list_of_place)
list_of_place.sort(reve... |
f328a30f3b006c192cdd7fa608acc1350d1d9de7 | eMUQI/Python-study | /python_book/basics/chapter09_class/09-05.py | 1,446 | 4.03125 | 4 | '''
9-5 尝试登录次数:在为完成练习 9-3 而编写的 User 类中,添加一个名为
login_attempts 的属性。编写一个名为 increment_login_attempts() 的方法,它将属性
login_attempts 的值加 1。再编写一个名为 reset_login_attempts() 的方法,它将属性
login_attempts 的值重置为 0。
根据 User 类创建一个实例,再调用方法 increment_login_attempts() 多次。打印属
性 login_attempts 的值,确认它被正确地递增;然后,调用方法 reset_login_attempts() ,
并再次打印属性 ... |
d697f885000bdbad371849ed2113ecc79a77190e | eMUQI/Python-study | /python_book/basics/chapter11_testing/11-03/test_Employee.py | 1,014 | 3.984375 | 4 | '''
11-3 雇员:编写一个名为 Employee 的类,其方法 __init__() 接受名、姓和年薪,并
将它们都存储在属性中。编写一个名为 give_raise() 的方法,它默认将年薪增加 5000
美元,但也能够接受其他的年薪增加量。
为 Employee 编写一个测试用例,其中包含两个测试方法: test_give_default_
raise() 和 test_give_custom_raise() 。使用方法 setUp() ,以免在每个测试方法中都创
建新的雇员实例。运行这个测试用例,确认两个测试都通过了。
'''
import unittest
from Employee import Employee
... |
506b600010b3515d85c10d8112ceffc2e5f44f61 | eMUQI/Python-study | /old/python-01_基础/11-break_contiune.py | 235 | 3.703125 | 4 | i=1
j=1
while i<=5:
while j<=i:
if i==3:
break
print(j,end="")
j+=1
print()
j=1
i+=1
print(10*"-")
i=0
while i<5:
i+=1
if i==3:
continue
print(i)
print(10*"-")
|
6dc97b4c549ebe0b22a56ab71268e6437ad0a545 | eMUQI/Python-study | /mooc/week1_BasicSyntaxeElements/exercises/1.py | 335 | 3.796875 | 4 | s = input()
temp = float(s[:-1])
if s[-1].upper() == "C":
result = temp*1.8+32
# print(str(round(result,2))+"F")
print("%.2fF"%float(round(result,2)))
elif s[-1].upper() == "F":
result = (temp-32)/1.8
# print(str(round(result,2))+"C")
print("%.2fC"%float(round(result,2)))
else:
print("输入格式错误... |
ef433d27a26cb0e66c291fb18dd15a5473137a66 | eMUQI/Python-study | /python_book/basics/chapter06_dictionary/06-09.py | 252 | 4 | 4 | favorite_places = {"Jack": ["Beijing", "Paris"],
"Mark": "Shanghai",
"Mary": ["Guangzhou", "Princeton"],
}
for name, place in favorite_places.items():
print(name + " love "+str(place)[1:-1])
|
a13ebde49f60836a16fc894cc9c1ab245cd93a5c | eMUQI/Python-study | /python_book/basics/chapter03_list/03-06.py | 560 | 4.0625 | 4 | def invite(templist):
for temp in templist:
print("Dear " + temp + ",可以和我一起共进午餐吗?")
list_of_person = ["Person A", "Person B", "Person C"]
invite(list_of_person)
print()
print(list_of_person[-1] + " won't come, so sad.")
print("list update\n")
list_of_person[-1] = "Person D"
invite(list_of_person)
print(... |
6f149fe9c1657eb018bd14cbee85b3b24c057a27 | eMUQI/Python-study | /python_book/basics/chapter10_files_and_exceptions/10-05.py | 332 | 3.78125 | 4 | '''
10-5 关于编程的调查:编写一个 while 循环,询问用户为何喜欢编程。每当用户输
入一个原因后,都将其添加到一个存储所有原因的文件中。
'''
with open("reasons.txt","a")as file:
i=3
while i>0:
i -= 1
file.write(input("The reason you like python:")+"\n")
|
b6995d632da9836081489cdc5117e8a29542cb15 | eMUQI/Python-study | /old/cases/video_case07_4s店.py | 782 | 3.515625 | 4 | class CarStore(object):
def __init__(self):
self.factory = Factory()
def order(self,car_type):
k = self.factory
f = k.select_car_by_type(car_type)
return f
class Factory(object):
def select_car_by_type(self,car_type):
if car_type == "suonata":
return Suo... |
48257aad2cf8143c5c25ff969cec0743bb049d26 | eMUQI/Python-study | /mooc/week2_BasicGraphicsDrawing/exercises/1.py | 498 | 3.953125 | 4 | '''使用turtle库,绘制一个蟒蛇形状的图形。'''
import turtle
# initialize pen settings
turtle.setup(650, 350, 200, 200)
turtle.ht()
turtle.penup()
turtle.fd(-250)
turtle.pendown()
# draw the snake's body
turtle.pensize(25)
turtle.pencolor("green")
turtle.seth(-40)
for i in range(4):
turtle.circle(40, 80)
turtle.circle(-40, 8... |
8cc94edbe41ae017b7593618b5df0b4e20da16d4 | eMUQI/Python-study | /python_book/basics/chapter04_list_operation/04-01.py | 132 | 3.84375 | 4 | list_of_pizza = ["pizza1","pizza2","pizza3"]
for pizza in list_of_pizza:
print("I like %s"%pizza)
print("I really love pizza!") |
1fbc3924bab14f9234a656b8f29a9bcb4e0fff63 | eMUQI/Python-study | /old/python-04_面向对象、异常、模块/10-继承.py | 442 | 3.5625 | 4 | class Animal:
def eat(self):
print("eating...")
def drink(self):
print("drinking...")
def sleep(self):
print("sleeping...")
def run(self):
print("runing...")
class Dog(Animal):
def bark(self):
print("wang...")
class XD(Dog):
def fly(self):
print(... |
6bd531db3a89d8b2b611888731ae8564df7cad65 | kerriop/python_things | /BuzzFizz.py | 281 | 3.84375 | 4 | def checkio(number):
if number%5 == 0 and number%3 == 0:
return "Fizz Buzz"
elif number%5 != 0 and number%3 == 0:
return "Fizz"
elif number%5 == 0 and number%3 != 0:
return "Buzz"
else:
return str(number)
print(checkio(15))
print()
|
d89e02c0b0288ccd99217bc50701e2f108135782 | nickciliberto/python-codewars | /count-smileys.py | 876 | 4.0625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 22 17:02:26 2020
@author: nicholas
"""
def count_smileys(arr):
'''
input: a list of characters
output: the number of valid smiley faces in the input list
'''
validEyes = [':', ';']
validNose = ['-', '~']
validMouth = [')... |
2d3a83330bdaeca9a430793d4a2c36c28e20d955 | nickciliberto/python-codewars | /letters-of-natac.py | 396 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 5 10:19:52 2020
@author: nicholas
"""
def play_if_enough(hand, play):
newHand = hand[:]
for letter in play:
if letter not in newHand:
return (False, hand)
else:
index = newHand.index(letter)
... |
be2844559aa5202e31f03a324a1df6189ae3e3df | nickciliberto/python-codewars | /two-sum.py | 391 | 3.875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 15 10:21:59 2020
@author: nicholas
"""
def two_sum(numbers, target):
for i in range(len(numbers)):
for j in range(i+1, len(numbers)):
if numbers[i] + numbers[j] == target:
return (i,j)
print(two_sum([1,2,3],... |
78917c37bc9cda71369e9cf44b22f3d8af878cbc | nickciliberto/python-codewars | /all-star-code-challenge.py | 598 | 3.90625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 18 17:19:11 2020
@author: nicholas
"""
def slogan_maker(array):
import itertools
words = list(set(array))
slogans = []
for slogan in itertools.permutations(words,len(words)):
slogans.append(slogan)
result = []
for sl... |
dc672b4679e34fee91816eb5d425a4188e29468f | nickciliberto/python-codewars | /highest-rank-number-in-array.py | 515 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 15 10:21:59 2020
@author: nicholas
"""
def highest_rank(arr):
s = set(arr)
highest_count = 0
most_freq = min(arr)-1
for num in s:
count = arr.count(num)
if count >= highest_count and num > most_freq:
high... |
53f01d090b6a9b818272de5a0202f791a35943af | nickciliberto/python-codewars | /detect-panagram.py | 448 | 3.96875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 15 10:21:59 2020
@author: nicholas
"""
import string
def is_pangram(s):
s = s.lower()
counter = 0
for i in string.ascii_lowercase:
if i in s:
counter += 1
if counter == len(string.ascii_lowercase):
retu... |
6b53d00c540b88832a0c0cc4b924d7271e0f3ff9 | adamcristi/OthelloIA | /Alpha_Beta_Pruning.py | 3,547 | 3.53125 | 4 | from Heuristic_Evaluation import heuristic_evaluation_function
import numpy as np
import math
computer_piece = 2
def add_piece_to_board(board, row, column, current_piece):
from Board_Representation import isValidMove
pieces_to_flip = isValidMove(board, row, column, current_piece)
if len(pieces_to_flip)... |
858729b4e53fa645fea655fd3d7f1f60a2b6ae71 | gscheck/FlappyBird | /Pipe.py | 1,762 | 3.59375 | 4 | import pygame
#Mister Pipe
class Pipe(pygame.sprite.Sprite):
#TODO - Add default constructor
#Returns an image of the pipe when givin a color
def get_image(self, color):
return pygame.image.load("pipe-" + color + ".png").convert_alpha()
#Constructor
def __init__(self, left, y, velocity, ... |
c431b2411aec3b03e73e021f8dc234d9a44e8f96 | sagarm4224/python | /PycharmProjects/First/exception.py | 510 | 4.03125 | 4 | try:
file = open("foo2.txt","r")
file.write("this is an exception hadling example")
except IOError:
print("the file can't be open for the writing")
else:
print("content written succesfully")
finally:
print("end of the operation")
# Define a function here.
def temp_convert(var):
tr... |
a1ba2026687b109cdd7c72113cc222d4cffdd804 | cassandraingram/PythonBasics | /calculator.py | 1,427 | 4.1875 | 4 | # calculator.py
# Cassie Ingram (cji3)
# Jan 22, 2020
# add function adds two inputs
def add(x, y):
z = x + y
return z
#subtract function subtracts two inputs
def subtract(x, y):
z = x - y
return z
# multiply function multiplies two inputs
def multiply(x, y):
z = x * y
return z
# divide function divides two ... |
9cbef5e0a44dc31d50bb3d06e7b02ac7dd2e46e1 | dynotw/Leetcode-Lintcode | /LeetCode/26. Remove Duplicates from Sorted Array.py | 1,182 | 3.6875 | 4 | Question:
Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Answer:
class Solution:
def removeDuplicates(self,... |
4e3e6ecbf46cbe05385579acda69305de4c20df6 | dynotw/Leetcode-Lintcode | /LeetCode/53. Maximum Subarray.py | 3,180 | 3.890625 | 4 | # Question:
# Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
# Example:
# Input: [-2,1,-3,4,-1,2,1,-5,4],
# Output: 6
# Explanation: [4,-1,2,1] has the largest sum = 6.
# Follow up:
# If you have figured out the O(n) solution, t... |
f975b11cacb95ac617d88a4fd1b56650d943fd4a | tittuvmathew/pyRiemannProblem | /wave.py | 1,348 | 4.03125 | 4 | class Wave(object):
"""A single wave that makes up part of the solution to a Riemann problem"""
subwaves = [] # If the wave is compound it may be made of waves
def __init__(self, model, start, end, left, right, xi = [], data = []):
"""Define by the start and end of the wave in characteristic
... |
5b367a209665084ead95dfc4beed4f9c24e40cc2 | qmcgilvery/Dashboard | /USD/Algorithms on Graphs/week4_paths2/1_dijkstra/dijkstra.py | 1,246 | 3.5 | 4 | #Uses python3
import sys
import queue
class Dijkstra(object):
def __init__(self):
self.n = len(adj)
self.dis = [999999999999 for i in range(self.n)]
def distance(self, adj, cost, s, t):
q = {}
self.dis[s] = 0
for i in range(len(self.dis)):
q[i] = (self.d... |
bc0e3df4478df8a48f76fdbcbcddc8aa90ba8db6 | qmcgilvery/Dashboard | /USD/Algorithms on Graphs/week2_decomposition2/2_toposort/toposort.py | 1,716 | 3.5 | 4 | # Uses python3
import sys
# from typing import List
class Vertex(object):
def __init__(self):
self.n = len(adj)
self.color = ['white' for i in range(self.n)]
# self.d = [0 for i in range(self.n)]
# self.f = [0 for i in range(self.n)]
# self.time = 0
self.order = [... |
b6a4b388ede2e0f9ce2dfbb908f4e43519c0fb56 | qmcgilvery/Dashboard | /USD/Algorithmic Toolbox/Algorithmic Warm Up/Fibonacci Number Again/fibonacci_number_again.py | 1,270 | 3.875 | 4 | # python3
def fibonacci_number_again_naive(n, m):
assert 0 <= n <= 10 ** 18 and 2 <= m <= 10 ** 3
if n <= 1:
return n
previous, current = 0, 1
for _ in range(n - 1):
previous, current = current, (previous + current) % m
return current
def pp(m):
previous, current = 0, 1
... |
f7d5661810efcd0f9394f3450c6e483ded6eeef1 | AbuBakkar32/Python-Essential-Practice | /DataCamp Practice/Intermadiate to Importing Data in Python/1-importing-data-from-the-internet/performing-http-requests-in-python-using-urllib.py | 388 | 3.609375 | 4 | # Import packages
from urllib.request import urlopen, Request
# Specify the url
url = "http://www.datacamp.com/teach/documentation"
# This packages the request: request
request = Request(url)
# Sends the request and catches the response: response
response = urlopen(request)
# Print the datatype of response
print(ty... |
fe755badd933ef984adfac6e51feec14ee23211e | AbuBakkar32/Python-Essential-Practice | /DataCamp Practice/Data Manipulating Python With Pandas/01-extracting-and-transforming-data/01-index-orrdering.py | 620 | 3.6875 | 4 | '''
Index ordering
In this exercise, the DataFrame election is provided for you. It contains the 2012 US election results for the state of Pennsylvania with county names as row indices. Your job is to select 'Bedford' county and the'winner' column. Which method is the preferred way?
Feel free to explore the DataFrame... |
7e1f9d5de9088ea871b3c50926242268e1496ccb | AbuBakkar32/Python-Essential-Practice | /DataCamp Practice/Data Manipulating Python With Pandas/05-putting-it-all-together/01-grouping-and-aggregating.py | 923 | 3.984375 | 4 | '''
Grouping and aggregating
The Olympic medal data for the following exercises comes from The Guardian. It comprises records of all events held at the Olympic games between 1896 and 2012.
Suppose you have loaded the data into a DataFrame medals. You now want to find the total number of medals awarded to the USA per ... |
1a2f3a7254c700ec0b7b966dbe51622edbba48da | AbuBakkar32/Python-Essential-Practice | /Machine_Learning/Linear Regression.py | 478 | 3.609375 | 4 | import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
df = pd.read_csv('home_prices.csv')
# plt.scatter(df['area'], df['price'], marker='*', color='red', label='Data Area')
# plt.legend()
# plt.xlabel('Area measure')
# plt.ylabel('Price of Area')
# plt.title('Home Pri... |
70fbe0607e7d3a24f73f0e2485d2726eefb93cbf | AbuBakkar32/Python-Essential-Practice | /WebScraping/testScraping.py | 12,831 | 3.703125 | 4 | import requests
from bs4 import BeautifulSoup
"""url = requests.get('https://www.prothomalo.com/')
soup = BeautifulSoup(url.text, 'html.parser')
result = soup.find_all('span', attrs={'class': 'tab_list_title'})
print(result)
for i in result:
link = i.find('a')['href']
span = i.find('span').text
print(link)... |
1b3e97898049796df37ed3d592815b06ca699f92 | minsooyeo/NeuroKit | /neurokit2/complexity/fractal_dfa.py | 21,245 | 3.609375 | 4 | # -*- coding: utf-8 -*-
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from ..misc import expspace
def fractal_dfa(
signal,
windows="default",
overlap=True,
integrate=True,
order=1,
multifractal=False,
q="default",
show=False,
**kwargs,
):... |
c2563154f3b65aa61e963a98577df316696a2a86 | patfov/numeric-matrix-processor | /Problems/Running average/main.py | 243 | 3.9375 | 4 | n = input()
list_numbers = []
for char in enumerate(n):
list_numbers.append(int(n[char]))
moving_average = []
for char in range(len(n) - 1):
moving_average.append((list_numbers[char] + list_numbers[char + 1]) / 2)
print(moving_average) |
2609942adf242ef101610119418623f57b654bd7 | patfov/numeric-matrix-processor | /Numeric Matrix Processor/task/processor/processor.py | 3,536 | 3.96875 | 4 | import numpy as np
def list_to_array(list):
for n in range(len(list)):
for m in range(len(list[0])):
list[n][m] = float(list[n][m])
return np.array(list)
def print_result(array):
print('The result is:')
for n in range(len(array)):
row = ''
for m in range(len(array... |
9b1f1235c847b4954ecf7c512bc0db11a2cdc478 | vansh-kapila/DSA_Class_Codes | /python/mergeSort.py | 881 | 3.890625 | 4 | def merge(arr,mid,l,r):
n1=mid-l+1
n2=r-mid
a,b=[0]*n1,[0]*n2
for i in range(n1):
a[i]=arr[l+i]
for i in range(n2):
b[i]=arr[mid+i+1]
i,j,k=0,0,l
while i<n1 and j<n2:
if a[i]>b[j]:
arr[k]=b[j]
j+=1
k+=1
else:
... |
b08036972c8a10ef1a70fc58e498d196c8f24f5f | vansh-kapila/DSA_Class_Codes | /python/queue.py | 707 | 4.0625 | 4 | class queue:
def __init__(self,size):
self.size=size
self.arr=[]
def enqueue(self,data):
if len(self.arr)==self.size:
print("Queue overflow error")
return
self.arr.append(data)
print("Successfully enqueued",data)
def dequeue(self):
if... |
9527efcef31dba3ca25ec33f2115ebfc5ec1d53a | snowpuppy/linux_201 | /python_examples/example1/guessnum.py | 855 | 4.21875 | 4 | #!/usr/bin/env python
#Here we import the modules we need.
import random
random.seed() #We need to seed the randomizer
number = random.randint(0,100) #and pull a number from it.
trys = 10 #We're only giving them 10 tries.
guess = -1 #And we need a base guess.
while guess != number and trys != 0: #So, we need to let... |
7d054aafcf999dcbb23bb557e6ffb026802b5711 | IstvanPn/Tasks- | /Data Science, Algorithms and Advanced Software Engineering P2/Poly.py | 1,919 | 3.59375 | 4 | import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
# Training set
x_train = [[2006],[2007],[2008],[2009],[2010],[2011],[2012],[2013],[2014],[2015],[2016],[2017],[2018],[2019],[2022],[2021],[2022],[2023]]
y_t... |
6cdce3313af74d6cb2cab2bc7a1b8fb08803c359 | kin7274/Dugeundugeun-Python | /5장/축구 게임.py | 267 | 3.765625 | 4 | import random
options=["왼쪽", "중앙", "오른쪽"]
com_choice=random.choice(options)
user_choice=input("어디를 수비하시겠어요?(왼쪽, 중앙, 오른쪽)")
if com_choice ==user_choice:
print("수비 성공")
else:
print("패널티킥 성공")
|
fec406e19d41cd5f8e4cc42297a7400696c67d70 | kin7274/Dugeundugeun-Python | /5장/연습문제3.py | 115 | 3.578125 | 4 | temp=int(input("현재 온도 : "))
if temp>=25:
print("반바지 추천")
else:
print("긴바지 추천")
|
09753129029fc9ea17bb4458040bde68b654cab3 | kin7274/Dugeundugeun-Python | /3장/연습문제6.py | 263 | 3.578125 | 4 | # 거북이 출발
import turtle
t=turtle.Turtle()
x1=int(input("x1 : "))
y1=int(input("y1 : "))
x2=int(input("x2 : "))
y2=int(input("y2 : "))
t.up()
t.goto(x1,y1)
t.down()
t.goto(x2,y2)
t.write("두 점 사이 거리 = " + (str)(((x1-x2)**2+(y1-y2)**2)**0.5))
|
9354fb18c327c0ef40f21ccf4f52e23e32a4c4c9 | kin7274/Dugeundugeun-Python | /3장/다각형그리기.py | 158 | 3.671875 | 4 | import turtle
t=turtle.Turtle()
t.shape("turtle")
n=int(input("몇각형을 그리시겠어요?(3-6) : "))
for i in range(n) :
t.fd(100)
t.lt(360//n)
|
5644870dd93e703853dc049cc3d432d82289738b | indianwebmaster/learning | /python/pygame/fgames/apps/roll_dice_do_where.py | 1,024 | 3.5 | 4 | from fgames.libs import FDice
class FDiceDoWhere:
def __init__(self):
self.do_list = ["Kiss", "Lick", "Suck", "Nibble", "Tickle", "Massage"]
self.where_list = ["My Chest", "Intimate parts", "My Back", "On Legs", "On Neck", "Face"]
self.prompt = "Enter Q to quit, anything else to Roll: "
... |
6ca5be0e46fcfed12e771cf4f9847e127a46a79d | indianwebmaster/learning | /python/basics/0032_binary_tree.py | 1,348 | 4.03125 | 4 | #python2
# left <= root < right
class Node:
def __init__(self, value):
self.parent = None
self.value = value
self.left_child = None
self.right_child = None
class Tree:
def __init__(self):
self.root = None
self.height = 0
def add_node(self,value,parent=None):... |
3d366fff37dbcafa9f0a32ff9f4d6e8339b26019 | indianwebmaster/learning | /python/pygame/fgames/libs/FDice.py | 589 | 3.59375 | 4 | import random
class FDice:
def __init__(self, faces):
random.seed()
self.faces = range(1, faces + 1)
self.rolled = False
def __str__(self):
dice_string = "A " + str(max(self.faces)) + "-sided dice."
if self.rolled:
return dice_string + " You rolled " + str(s... |
c01e09cf4f1b3552408c9b5ebc4e233f48677905 | indianwebmaster/learning | /python/basics/0031_tree_2.py | 3,051 | 4.125 | 4 | #python2
class Node:
def __init__(self, value):
self.parent = None
self.value = value
self.children = []
class Tree:
def __init__(self):
self.root = None
self.height = 0
def add_node(self,value,parent=None):
node = Node(value)
if (parent == None):
... |
779dcf2af0bdd669aef4d933e7fbf08b36613134 | RafaelGoncalves8/MIT_6.00sc_problem_sets | /notes/ex04.py | 2,185 | 3.890625 | 4 | # # # 04 - Debugging
# # Floats - Binary:
#0.1 = decimal: 1*10^-1 | binary: ~ 0.0001100110011001100110011...
#x = 0.0
#numItens = 100000
#for i in range(numItens):
#x += 0.1
#print x #binary aproximation
#print repr(x) #real binary value
#print 10.0*x == numItens
#def close(x, y, epsilon = 0.00001):
#return(x-y) ... |
a7d9a04aee157a4dc402a02f0a65fb8877e74442 | RafaelGoncalves8/MIT_6.00sc_problem_sets | /ps00/ps0.py | 245 | 3.828125 | 4 |
#Problem Set 0
#-------------------------------------------------------------------------------
date=raw_input('Right your date of birth')
name=raw_input('Put your name')
print('your name is ' + name + ' and your date of birth is ' + date)
|
cb736714ff1ec23ef912b6e09a167489d9a04123 | Ademvp9/Lab-111 | /Práctica 2/Ejercicio 3.py | 302 | 3.640625 | 4 | h=int(input("Ingrese las horas:"))
m=int(input("Ingrese las minutos:"))
s=int(input("Ingrese las segundos:"))
s=s+1
if s>59:
m=m+1
s=0
if m>59:
h=h+1
m=0
if h>23:
h=0
else:
pass
print(h,"Horas")
print(m,"Minutos")
print(s,"Segundos")
|
3b18f38d05066caca211146a666253cf11bb75d7 | kevfallon97/first-year-assignments | /first_semester/triangular_stars.py | 1,480 | 4 | 4 | # Triangular Stars
# A “star number”, s, is a number defined by the formula: s = 6n(n-1) + 1 where n is the index of the star number.
# Thus the star numbers are: 1, 13, 37, 73, 121, 181, 253, …
# A “triangle number”, t, is the sum of the numbers from 1 to n: t = 1 + 2 + … + (n-1) + n.
# Thus the triangle number... |
c90e74eb318ad878ed1fb2d381809b3f14b7f895 | kevfallon97/first-year-assignments | /first_semester/square_ages.py | 1,814 | 3.765625 | 4 | # Square Ages
# The mathematician Augustus De Morgan was aged 43 in the year 1849AD. This is interesting because 43 squared is 1849, ie, in 1849 his age was the square root of the year.
# Given that no person has ever lived longer than 123 years (and assuming that no one ever will), write a Java application that will ... |
90012b2ed5f40a87e8b710e24d0ff824e72fbb5d | programadorpython/LendoGravadoArquivoCsv | /main.py | 1,087 | 3.5625 | 4 | import csv
import requests
import pandas as pd
from config import URL, ARQUIVO_CSV
# Requisição para o Link do arquivo .csv
response = requests.get(URL)
# print(response.content)
# Criando um arquivo chamado 'covid19.csv' e salvando no pc local
with open('covid19.csv', 'w', newline='\n') as novo_arquivo:
writer ... |
b991489dd3532656e6635cf3edd89f26291bd748 | Sasszem/cryptopals-solutions | /set3/03_break_fixed_nonce.py | 2,644 | 3.65625 | 4 | import string
"""
Problem: upper/lowercase letters
If all characters are letters, upper/lowercase is 1 bitt difference
so we can't be sure if we got it right
"""
"""
This scoring is not perfect
but kinda works
"""
def score(text):
return 2*sum(chr(x) in string.printable for x in text) - sum(chr(x) in string.punct... |
d554a1e73e00cc1e4fce9d8b71401a6083d88e93 | Sasszem/cryptopals-solutions | /set1/06_break_repeating.py | 3,061 | 3.578125 | 4 | import itertools
import string
"""
Damn these challanges get hard FAST
"""
def hamming(first, second):
assert len(first)==len(second), f"hamming called with diffing length inputs: {first}, {second}!"
diff = bytes(a^b for a,b in zip(first, second))
return sum(sum((a>>i)&1 for i in range(8)) for a in diff... |
75a8cd97b20810b2dee28e1444569a4ed4a778f6 | SaiGomathi2000/LETSUPGRADE-DAY3 | /ASIGNMENT2(D3).py | 158 | 3.953125 | 4 | for num in range(1,201):
if num >1:
for i in range(2,num):
if(num%i==0):
break
else:
print("The prime numbers are:",num)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.