blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1afa39a8b92da889b5f8fc7bb7467573046b3f89 | Dython-sky/AID1908 | /study/1905/month01/code/Stage2/day16/project/dict/dict_client.py | 3,114 | 3.640625 | 4 | """
dict 客户端
功能:根据用户输入,发送请求,得到结果
结构:一级界面 --> 注册 登录 退出
二级界面 --> 差单词 历史记录 注销
"""
from socket import *
from getpass import getpass # 运行使用客户端
import sys
# 服务端地址
ADDRESS = ('127.0.0.1',8000)
# tcp套接字
s = socket()
s.connect(ADDRESS)
# 查单词
def do_query(name):
while True:
word = input("单词:")
i... |
57749dd69a5dd28e4166eaab9ee42aaf712a082f | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day07/demo01.py | 442 | 3.96875 | 4 | """
字典推导式
"""
# 1 2 3 4 5 6 7 8 9 10 --> 平方
dict01 = {}
for item in range(1, 11):
dict01[item] = item ** 2
print(dict01)
# 推导式
dict02 = {item: item ** 2 for item in range(1, 11)}
print(dict02)
# 只记录大于5的数字
dict01 = {}
for item in range(1, 11):
if item > 5:
dict01[item] = item ** 2
print(dict01)
# 推导式... |
010a22bf098de29127e22eb0edfe37b883ad2b7e | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day11/exercise04.py | 1,185 | 4.46875 | 4 | """
请以面向对象的思想,描述下列场景:
小明在招商银行取钱
"""
class Person:
def __init__(self,name,money):
self.name = name
self.money = money
@property
def name(self):
return self.__name
@name.setter
def name(self,value):
self.__name = value
@property
def money(self):
... |
2408692f1575e59d6bdb77401ee36287df0c223c | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day08/exercise10.py | 233 | 4.0625 | 4 | """
定义函数,数值相加的函数
"""
def adds(*args):
# result = 0
# for item in args:
# result += item
# return result
return sum(args)
print(adds(1,2,3,4,5,6,7,8,9,10))
print(adds(1,2,3,5,6,8,10))
|
f77d6bf0270b4e34732079b5277d8700b65c2a2a | Dython-sky/AID1908 | /study/1905/month01/code/Stage1/day12/day11_exercise/exercise02.py | 1,360 | 4.09375 | 4 | """
请用面向对象思想,描述以下场景
玩家(攻击力)攻击敌人(血量),敌人受伤(掉血),还可以死亡(掉装备,加分)
敌人(攻击力)攻击玩家(血量),玩家受伤后(掉血/碎屏)(游戏结束)
体会:类区分行为的不同
"""
class Player:
def __init__(self,hp,atk):
self.hp = hp
self.atk = atk
def attack(self,other):
# 打的逻辑
print("玩家攻击敌人")
# 通过敌人对象地址,调用实例方法
other.da... |
c6db7f404496339243dffcd303cb8e2736f12186 | Dython-sky/AID1908 | /study/1905/month01/code/Stage2/day07/fork02.py | 437 | 3.5 | 4 | """
fork02.py fork进程创建演示2
"""
import os
from time import sleep
print("=============================")
a = 1
# 创建子进程
pid = os.fork()
if pid < 0:
print("Create process failed")
# 子进程执行部分
elif pid == 0:
print("The new process")
print("a=",a)
a = 10000
# 父进程执行部分
else:
sleep(1)
print("The old proces... |
817a538c0fdc683d8547b64284133ce02b224157 | Dython-sky/AID1908 | /study/1905/month01/code/Stage2/day09/pipe.py | 749 | 3.671875 | 4 | """
pipe.py 管道通信
注意:1.multiprocessing 中管道通信只能用于亲缘关系进程中
2.管道对象在父进程中创建,子进程通过父进程获取
"""
from multiprocessing import *
# 创建管道
# False单向管道,fd1 --> recv fd2 --> send
fd1, fd2 = Pipe()
def app1():
print("启动app1,请登录")
print("请求app2授权")
fd1.send("app1 请求登录") # 写入管道
data = fd1.recv()
if dat... |
df08bd1948570e67ae2a728923f34bca4f868019 | alancastilleja/Python-Practice | /day8.py | 296 | 3.953125 | 4 | integer = int(input())
names_and_numbers = [input().split() for _ in range(integer)]
phone_book = {k: v for k, v in names_and_numbers}
for _ in range(integer):
name = str(input())
if name in phone_book:
print(name + '=' + phone_book[name])
else:
print("Not found")
|
2a8ece54e12565a7d62fe08cf1cdf9d0dcc255ea | anonimato404/playground | /others/challenges-of-my-father/logic/filter_and_get_average.py | 1,139 | 3.75 | 4 | class All:
def __init__(self, _name, _course, _grade):
self.name = _name
self.course = _course
self.grade = _grade
arr_all = [
All("Sebas", "c#", 11),
All("Tilsa", "python", 15),
All("Sebas", "javascript", 16),
All("Tilsa", "go", 13),
All("Sebas", "Ruby", 12),
All("... |
e25a76f18217ad492cc59d2d891801a79faadfae | nkhm345/c4cs-f16-rpn | /rpn.py | 756 | 4.0625 | 4 | #!/usr/bin/env python3
def calculate(string):
stack = []
for val in string.split(' '):
if val in ['-', '+', '*', '/', '^']:
op1 = stack.pop()
op2 = stack.pop()
if val=='-': result = op2 - op1
if val=='+': result = op2 + op1
if val=='*': resul... |
81e14709b32ad6863b6849315662b43bc8dc5db3 | parrt/lolviz | /lolviz.py | 41,950 | 3.71875 | 4 | """
A small set of functions that display simple data structures and
arbitrary object graphs in a reasonable manner using graphviz.
Even the call stack can be displayed well.
This is inspired by the object connectivity graphs in Pythontutor.com.
I love Pythontutor.com for interactive demos with the students,
but for e... |
897bc0f0ff227903922647e72c22414216c2c738 | AnilNITK/Pycharm | /Fibinoci_series.py | 162 | 3.625 | 4 | sum=0
n=1
v=0
for i in range(0,51):
if i==0 or i==1:
sum+=i
print(sum)
else:
sum=n+v
v=n
n=sum
print(sum)
|
2916c3ef9d6bc72320e6db7d1802ca7d61beae76 | AnilNITK/Pycharm | /insertion_sort.py | 246 | 3.890625 | 4 | def insertionsprt(arr):
for i in range(1,len(arr)):
key=arr[i]
j=i-1
while j>=0 and key<arr[j]:
arr[j+1]=arr[j]
j-=1
arr[j+1]=key
arr=[12,123,11,34,42,24]
insertionsprt(arr)
print(arr)
|
a83a7c09be99c20c9b2632116de2ada9a0496245 | vibhor-vibhav-au6/APJKalam | /week8/day04.py | 831 | 4.09375 | 4 | '''
Write a program to print sum of right diagonal of a matrix:
'''
def rtDiagonalSum(matrix):
# i = len(matrix)
n = len(matrix[0]) - 1
sum = 0
for i in range(len(matrix)):
sum += matrix[i][n-i]
return sum
m = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
# print(rtDiagonalSum(m))
'''
Write a program to print ... |
c313cd78b324de77a4d6d2d01492ce9abc87f09b | vibhor-vibhav-au6/APJKalam | /week8/assignment.py | 1,554 | 4.0625 | 4 | '''
Write a program to find the upper bound (first occurrence’s index) of
a target given by the user, that should be present in the list. Using linear
search.
'''
def linearSearchUpperBound(arr, target):
upperBound = -1
for i in range(len(arr)):
if arr[i] == target:
upperBound = i
return upperBound
''... |
1c277d5d6d25d628465b4f65246c36f41f168684 | vibhor-vibhav-au6/APJKalam | /week5/closet.py | 516 | 3.890625 | 4 | class Closet:
def __init__(self,length, breadth, max_capacity):
self.length = length
self.breadth = breadth
self.max_capacity = max_capacity
self.items = []
def store_item(self):
toAdd = input('enter the items to push: ')
self.items.append(toAdd)
def fetch_item(self):
self.items.pop(... |
7452c25adb532cdba316e3d1b36703b0791fa2b5 | vibhor-vibhav-au6/APJKalam | /week9/day03.py | 1,504 | 3.859375 | 4 | '''349. Intersection of Two Arrays'''
class Solution:
def intersection(self, nums1, nums2):
set1 = set(nums1)
set2 = set(nums2)
return list(set2 & set1)
# res = []
# for i in nums1:
# if i in nums2:
# if i not in res:
# ... |
33dbaaf613fabfc587bd477195930441471f7545 | ApichatSalee/CP3-Apichat-Salee | /Lecture53_Apichat_S.py | 168 | 3.828125 | 4 | totalPrice = int(input("totalPrice :"))
def vatCalculate(totalPrice):
result = totalPrice +(totalPrice * 7 / 100)
return result
print(vatCalculate(totalPrice)) |
387be6b7ec4afaf539197ba7e3d0b6ae792f2f3f | PiErr0r/aoc | /bak_2015/05.py | 1,276 | 3.703125 | 4 |
import math, copy
with open('5_input') as f:
data = f.read()
data = data.split()
# data = list(map(int, data.split()))
def has_vowels(string):
cnt = 0
for letter in string:
if letter in 'aeiou':
cnt += 1
if cnt == 3:
return True
return False
def has_not_bad(string):
bad_strings = ['ab', 'cd', 'pq... |
f7675f60787714ee325a4a43bb5f3d2473e7067b | PiErr0r/aoc | /bak_2015/08.py | 735 | 3.515625 | 4 |
import math, copy
with open('8_input') as f:
data = f.read()
data = data.split('\n')
# data = list(map(int, data.split()))
def part_1():
diff = 0
for asd in data:
string = asd.strip()
diff += 2
i = 0
while i < len(string) - 1:
if string[i] == '\\':
if string[i + 1] == 'x':
diff += 3
... |
d0b9066fca344e9fbc32a4c1ddac6d0fb4ba8a97 | PiErr0r/aoc | /bak_2015/20.py | 3,634 | 3.75 | 4 |
import math, copy
def find_divisors(n):
divs = []
for i in range(1, math.floor( math.sqrt(n) )):
if n % i == 0:
if n / i == i:
divs.append(i)
else:
divs += [i, n / i]
return divs
def find_next_prime(L, n):
i = n
is_prime = True
while True:
for pr in L:
if pr > math.sqrt(i):
return i
... |
a9c7263e75ec10b4e035a2a072b269d79335bc62 | krithinM/Networks-and-cryptography | /PlayFair.py | 1,636 | 3.859375 | 4 | import string
def getmat(ke): #method to create the encryption matrix
l=[ke[i] for i in range(len(ke)) if ke[i] not in ke[:i] and ke[i] != 'j'] #format the key
k=[i for i in string.ascii_lowercase if i not in l and i != 'j']
l=l+k
arr = [l[i:i+5] for i in range(0,len(l),5)]
return arr
def getpos(ar... |
57bd11362b095e384c690d23c03f23784f5dc69b | gwax/advent-of-code-2018 | /aoc2018/day2.py | 1,130 | 3.796875 | 4 | """Solution for day2 problem."""
from collections import Counter
import itertools
from typing import IO
from typing import Tuple
def check_string(instr: str) -> Tuple[bool, bool]:
"""Extract count check form a string."""
count = Counter(instr)
count_vals = count.values()
return (2 in count_vals, 3 in... |
11ee429465e19cb0a5af395bed18c520824bf508 | hudecekfilip/WorkLog | /tasks.py | 9,571 | 3.90625 | 4 | import datetime
import os
import re
import sys
class AddNewEntry:
entries = []
master_count = 0
def add_new_entry(self):
self.task_date = self.date_of_the_task()
self.task_title = self.title_of_the_task()
self.task_time = self.time_spent()
self.task_note = self.note()
... |
94936fe57087874fcad4638974cb9ea4e42d85a6 | riftcover/Quantitative | /example/2/Python2-21.py | 550 | 4.09375 | 4 | tup1 = ("book" , "desk","bag",2000,2008,2012,2015, 2018)
#使用下标索引来访问元组中的值
print ("元组中的第二个值,tup1[1]: ", tup1[1])
#使用中括号的形式截取字符
print ("元组中的第二和第五个值,tup1[1:5]: ", tup1[1:5])
#利用for循环语句来遍历元组中的值
print("利用for循环语句来遍历元组中的值")
for i in tup1:
print(i)
#连接元组
tup2 =("Python","Baidu")
# 创建一个新的元组
tup3 = tup1 + tup2
print (tup3)
#删... |
76b226109445e84cb40fbae4ae5943f6c8e7b2f8 | riftcover/Quantitative | /example/2/Python2-24.py | 338 | 4.09375 | 4 | student = {'Tom', 'Jim', 'Mary', 'Tom', 'Jack', 'Rose'}
print("输出集合,重复的元素被自动去掉: ",student)
# 成员测试
if('Rose' in student) :
print('Rose 在集合中')
else :
print('Rose 不在集合中')
if('Zhoudao' in student):
print('Zhoudao 在集合中')
else:
print('Zhoudao 不在集合中')
|
a0c8e1f410bc6428918de1d57d94abb363d70b6f | Binita72/Python1 | /First Ones.py.htm | 899 | 3.6875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
data =[1,2,3,4]
series1 = pd.Series(data)
series1
# # To Know type of Data
# In[2]:
type(series1)
# # Changing the index of a Series object
# In[3]:
series1 =pd.Series(data, index =['a', 'b','c','d'])
series1
# # To create dataframe
# In... |
72b858ec25a5617130cf1bdd74ff0233c82a3fa1 | isemona/codingchallenges | /2-Factorial.py | 244 | 3.6875 | 4 | # https://www.coderbyte.com/editor/First%20Reverse:Python#
# Difficulty - Easy
# Recursion!
def FirstFactorial(num):
if num == 1:
return 1
else:
return num * FirstFactorial(num - 1)
print FirstFactorial(raw_input())
|
6b5cd0e6320650cf20599806665a0b728a197209 | isemona/codingchallenges | /17-DashInsert.py | 747 | 4.28125 | 4 | # https://www.coderbyte.com/information/Dash%20Insert
# Difficulty Easy
# Implemented range() and if/and conditional
def DashInsert(str):
# convert the string into a list
# with each element being a single number
arr = list(str)
# loop through the list of numbers and add a dash if
# the current number an... |
d1f28403c207bd39c121021f99ecc26a02e39ba2 | isemona/codingchallenges | /5-SimpleAdding.py | 214 | 3.6875 | 4 | # https://www.coderbyte.com/editor/Simple%20Adding:Python#
# Difficulty - Easy
# Implemented sum and range methods at once!
def SimpleAdding(num):
return sum(range(1, num + 1))
print SimpleAdding(raw_input()) |
cfff55ca4c0d509eb2693374e9b182972de3fa5c | AidenCang/pythonbase | /pythonBase/advancePyton/chapter11/python_GIL_01.py | 1,177 | 3.578125 | 4 | # GIL全局终端锁 global interpreter Lock(cpython)
# python中的一个线程对应c语言中的一个线程
# GIL是的python同一时间只能有一个线程运行的cpu上执行字节码
# gil会根据执行的字节码行数以及时间片切换线程(时间片的时间),无法将多个线程映射到多个CPU上,gil遇到IO操作的情况下主动释放
# 对io操作来说,多线程和多进程效率差不多
# 共享变量和Queue
# pipy去GIL化的库
# Gil会根据执行的字节码行数以及时间片释放GIL,遇到IO操作的时候回释放GIL
# GIL在python2,Python3中的区别
# Python和Cpython的区别
# ... |
92753d6036c982668644077be2b0442a56a62926 | AidenCang/pythonbase | /pythonBase/datastruct/testenum/pythonAdvance.py | 650 | 3.78125 | 4 | # 业务逻辑开发者,不考虑封装性
# 包、类库的开发者
# 函数式编程
# 闭包 = 函数+环境变量
# 命令式编程、函数式编程
# Python支持函数式编程、并不是函数式编程
def cave_pre():
a = 25
def cave(x):
return a * x * x
return cave
f = cave_pre()
print(f)
print(f.__closure__[0].cell_contents)
print(f(2))
origin = 0
def factory(pos):
def go(step):
nonlo... |
71ec65132e360f6c0938bf1a72cca55cb8300988 | AidenCang/pythonbase | /pythonBase/advancePyton/iterableiterator09/iterableiterator.py | 694 | 3.984375 | 4 | from collections.abc import Iterable, Iterator
# 什么是迭代器和可迭代对象
class Company(object):
def __init__(self, employee):
self.employee = employee
# def __iter__(self):
# return 1 # TypeError: iter() returned non-iterator of type 'int'
# pass
def __getitem__(self, item): # TypeError: 'Compan... |
7e70b0506676ae9821da43317fd90b380ffa9d7f | jrivest2/Twitoff | /Twitoff/random_data.py | 724 | 3.578125 | 4 | import sqlite3
import random
import string
conn = sqlite3.connect("db.sqlite3")
curs = conn.cursor()
NAMES= ['Justin', 'Jacob', 'Katie', 'Jen', 'Jon','Kira']
TWEETS = []
for i in range(10):
x = random.sample(string.ascii_lowercase, k=10)
TWEETS.append(''.join(x))
def add_user(users):
for x in range(user... |
ea704dec4c73c7fc9590e39d6c40fff21f41093e | sachinpatel160/python | /p1.py | 388 | 3.75 | 4 | a=int(input("Enter value of a: "))
b=int(input("Enter value of b: "))
c=int(input("Enter value of c: "))
d=int(input("Enter value of d: "))
e=int(input("Enter value of e: "))
print "add= ",a+b+c+d+e
print "sub= ",a-b-c-d-e
print "mul= ",a*b*c*d*e
print "div= "
f=int(input("Enter first value"))
g=int(input("Enter seco... |
592ad676797bee117d6712a3cf52d3e29c8d3500 | sachinpatel160/python | /p5.py | 396 | 3.90625 | 4 | def name():
x =input("Enter your name: ")
print("Hello ",x)
a=eval(input("Enter value of feedback: "))
value(a)
def value(a):
if a==1:
print("Poor")
elif a==2:
print("It's ok!")
elif a==3:
print("Good")
elif a==4:
print("Very Good")
elif a==5:
print("Exe... |
3613a3125c9b5e2727e43c45b6bc7128bbf17ed5 | SumitMondal26/Miscelleneous_Codes | /Hangman_Game_.py | 1,535 | 3.6875 | 4 | import numpy as np
import copy
words=['apple','banana','cherry','papaya','mango','watermelon','dragonfruit','pineapple']
com_guess=list(np.random.choice(words))
com_guess_copy=copy.copy(com_guess)
guess_disp=[]
len_w=len(com_guess)
diff=int(input("enter difficulty :\n1 : easy 2 : normal\n"))
select=np.... |
a71a6dcb3308e23229a097aa06dd10af7d3b22e8 | nee10819/Practice | /Analysis of Dataframe - Missing Data.py | 641 | 4.03125 | 4 | # Data Preparation
# Data Preprocessing
# Handling Missing values
# importing libraries
import numpy as np
import pandas as pd
df = pd.DataFrame({'A':[1,2,np.nan],
'B':[3,np.nan,4],
'C':[5,6,7]})
# print(df)
df.describe()
df.info()
# Drops all rows having nulls
df.dropna()
# Dr... |
21b508bdd5ca074b3ebee1ef32796ee8a06dbedf | crincon56/Snake_Project | /scoreboard.py | 1,124 | 3.78125 | 4 | # Importa funcion Turtle de modulo turtle.
from turtle import Turtle
# Alinea texto de puntaje.
ALIGNMENT = "center"
# Letra para puntos.
FONT = ("Arial", 24, "normal")
# Crea tabla de puntajes.
class Scoreboard(Turtle):
def __init__(self):
"""
Hereda de la funcion Turtle,
creando ... |
2d7800f0b20ea4a2e1061ba04b97b5d0010552f6 | yirano/project_iterative-sorting | /src/searching/searching.py | 722 | 4.0625 | 4 | def linear_search(arr, target):
for i in range(0, len(arr)):
if arr[i] == target:
return i
return -1 # not found
# Write an iterative implementation of Binary Search
def binary_search(arr, target):
# get the middle point
# compare the value in the middle with target
start = ... |
78399f1adff5de6e6844a5880095c27b071c2b24 | Uchennaore/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/2-uniq_add.py | 412 | 3.78125 | 4 | #!/usr/bin/python3
def uniq_add(my_list=[]):
check_list = []
sum = 0
for i in my_list:
checked = 0
if not check_list:
sum += i
check_list.append(i)
else:
for j in check_list:
if j == i:
checked = 1
if... |
08ca5056bc1b547065fdb821fd4d62371c6ba400 | Uchennaore/holbertonschool-higher_level_programming | /0x02-python-import_modules/100-my_calculator.py | 614 | 3.859375 | 4 | #!/usr/bin/python3
if __name__ == "__main__":
from calculator_1 import add, sub, mul, div
from sys import argv, exit
if len(argv) - 1 != 3:
print("./100-my_calculator.py <a> <operator> <b>")
exit(1)
a = int(argv[1])
b = int(argv[3])
if argv[2] == '+':
val = add(a, b)
... |
c7807838b80f3facae1ed0e3f1ce86403b47a3d4 | PhuongBui27/python_ex | /Nested for loop.py | 699 | 3.625 | 4 | for i in range(1, 10):
print('===============')
for j in range(1, 10):
print('%2d *%2d = %2d' % (i, j, i * j))
students = [('Phuong', ['Ly', 'Hoa']), ('Hien', ['Hoa', 'Van'])]
for (name, subjects) in students:
print(name, 'take', len(subjects), 'courses')
counter = 0
for (name, subjects) in students... |
515dd184e12b412e24cee5238feaf2e824553604 | ichrislu/learning-python | /base/s5.py | 387 | 3.796875 | 4 | # 可变参数、关键字参数
def mysum(*numbers):
sum = 0;
for index in numbers:
sum += index;
return sum;
print(mysum(1, 2, 3, 4));
mynum = (1, 2, 3, 4, 5);
print(mysum(*mynum))
def myfun1(name, **others):
if 'sex' in others:
pass;
print("name:", name, ", others:", others);
print(myfun1("a"));
print(myfun1("a", b = "b")... |
0e83aec8a94caa4101b93802960a4f645e175a2e | ichrislu/learning-python | /base/s4.py | 832 | 3.796875 | 4 | # 默认参数
def gen_name(x="none"):
return 'chris ' + x;
def sum(a, b):
if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
raise TypeError("bad operand type");
return a + b;
# 定义默认参数要牢记一点:默认参数必须指向不变对象!
def app_end(list=[]):
list.append("end");
return list;
def app_end2(list=None):
if (list ... |
9be2a36839bd05899d983cc656a76fe77ce7161d | stauntn2/fall17mp1 | /sol_1.1.2.1.py | 662 | 3.859375 | 4 | import sys
def reverse_cipher(c_file, k_file, out):
with open(c_file) as c:
k = open(k_file)
o = open(out, 'w')
inverse = ['0' for i in range(26)] #initializing our array
cipher = c.read().strip()
key = k.read().strip()
for i in range(26):
inverse[ord(key[i]) - ord('A')] = chr(i + ord('A'))
... |
cc83e374d2ad856157409aeee0de4cad5ecf9d41 | Zhitkov/palet | /palet.py | 663 | 4.125 | 4 | """This class made dict where, size of pallet(size) = key, value of products(how_much) = key value
and muchs of pallets we need(pallets) = pallets"""
global pallets
def calculator(how_much, size):
if how_much > size:
pallets = how_much / size
if how_much % size != 0:
print ("in... |
1a24c76d24f4245f78fe1e102e32177e7bb59b59 | bowlesbe/BrowseFun | /bhistory.py | 4,070 | 3.5 | 4 | import re, os, sqlite3
import pandas as pd
import numpy as np
import string
class ChromeHistory(object):
def __init__(self, path):
'''
INPUT : a path to the user's chrome DB on the
server.
OUTPUT: a new pandas DF with url, title, with
duplicates removed and un... |
9854b4f79839d4a6b444b58f3099993a639207a1 | bala-gutti/Python-Training | /ArrayPairSum.py | 535 | 3.5 | 4 | #!/usr/bin/python
class ArrayPairSum(object):
def pair_sum(self,value,listNum):
if len(listNum) < 2:
return False
seen = set()
output = set()
for num in listNum:
target = value - num
if target not in seen:
see... |
f27f0cd95d853c6a397104c8df1a00b53dc41ecc | stormshadowcr7/python-sample-for-jenkins | /pyeg.py | 65 | 3.5625 | 4 |
for i in range(1,6):
print ("The loop number is: " + str(i)) |
b344b6ab65c730052db34f819e1be2cac29394fd | hacktech-2017-fresno/mixtape-dissertation | /evaluator/rhyming_api.py | 1,088 | 3.703125 | 4 | import requests
"""
Pros and cons of this script:
Pros: Fast and Accessible
Cons: Only 350 requests / hour
"""
def requestURL(word):
"""Returning Correct URL for request.
Example URL:
http://rhymebrain.com/talk?function=getRhymes&word=hello
"""
url = url = "http://rhymebrain.com/ta... |
6a24bfd59fb0b8fc7a791d8da7c0893b1cfb802e | arajitsamanta/google-dev-tech-guide | /python-basics/fundamentals/modules.py | 439 | 3.8125 | 4 |
# The Standard Library includes a number of functions and class definitions in which related components are organized into
# individual files called modules. A module is simply a Python source file containing various function and class definitions.
# These components can be used within a Python program via the import ... |
db082bfefb4e74a80a35727a40104cfdecffc96b | arajitsamanta/google-dev-tech-guide | /python-basics/collection/advance-list.py | 5,477 | 4.65625 | 5 |
import random
def addListItems():
# Create the empty list.
valueList = []
# Appending Items - New items can be appended to the end of the list using the append() method.
# Build the list of 10 random values.
for i in range(10):
valueList.append(random.random())
print("Appending to li... |
9d1c203ac994897b4e886091cdb7a91cd90916d9 | atavares75/MQP-URL_Classifier | /src/DataSet.py | 856 | 3.6875 | 4 | import numpy as np
import pandas as pd
from FeatureExtraction.FeatureExtraction import FeatureSet
class DataSet:
def __init__(self, csv_file=None, urls=None):
"""
Initialize the variables for the data set
:PARAM csv_file: the csv file containing the data
:param urls: pandas DataFr... |
e8c298c5ed64dab348a86f2667f882091c9179cd | dagamargit/ejemplos-tkinter | /ej21_canvas_move.py | 811 | 3.609375 | 4 | import tkinter as tk
class Aplicacion:
def __init__(self):
self.ventana1=tk.Tk()
self.canvas1=tk.Canvas(self.ventana1, width=600, height=400, background="black")
self.canvas1.grid(column=0, row=0)
self.cuadrado=self.canvas1.create_rectangle(150,10,200,60, fill="red")
self.ve... |
ff41172ad3eeb152f2812fac42817a75306b1f57 | dagamargit/ejemplos-tkinter | /ej04_grid.py | 513 | 3.890625 | 4 | from tkinter import Tk, Label, RAISED
root = Tk()
labels = [['1', '2', '3'],
['4', '5', '6'],
['7', '8', '9'],
['*', '0', '#']]
for r in range(4):
for c in range(3):
# crear label para fila r y columna c
label = Label(root,
relief=RAISE... |
30af029b65be916ffa49f15146dd99d35c9d0ba2 | bwebste20/raspberry.pi | /loops_and_strings.py | 89 | 3.90625 | 4 | word = input ("Enter Word :")
print(word)
for i in range(len(word)):
print(word[i])
|
68a3e8325d1504f117d665b04a5c059755fcfefb | josiahconely/python-machine-learning | /ICP1.py | 859 | 3.96875 | 4 |
#problem 2
import string
number = input(" enter a three digit number")
snum = str(number)
print(snum[::-1])
operation = input("enter an option: \n1. +\n2. -\n3. *\n4. /\n5. %\n")
a = input ("enter a number")
a = int (a)
b = input ("enter a number")
b = int (b)
if operation =="1":
print (a+b)
elif operation =... |
ffccdab4da59076033c34cde5334c176ed9dc662 | ricardopieper/horse | /pytests/for_loop.py | 62 | 3.578125 | 4 | some_list = [1,2,3,4,5]
for item in some_list:
print(item) |
ac8ac1789cdec6dbc9ff90276db22af87754096a | justien/lpthw | /ex30_ElseIf.py | 1,436 | 3.9375 | 4 | # -*- coding: utf8 -*-
# Exercise 30: Else and If
# 234567890123456789012345678901234567890123456789012345678901234567890123456789
print "========================================================================"
print "Exercise 30: Else and If"
print
print
#
print "We need to get out of here. The zombies are co... |
c562236ccc59588c892522bd1dd315fe2a186405 | justien/lpthw | /ex36_Game.py | 2,549 | 3.890625 | 4 | # -*- coding: utf8 -*-
# Exercise 35: Branches and Functions
# 234567890123456789012345678901234567890123456789012345678901234567890123456789
print "========================================================================"
print "Exercise 35: Branches and Functions"
print
print
from sys import exit
def gold_room(... |
d83225a8c0bae003c1c738857030973547abb7e3 | justien/lpthw | /ex20_FnsFiles.py | 1,446 | 3.90625 | 4 | # -*- coding: utf8 -*-
# Exercise 20: Functions and Files
# 23456789012345678901234567890123456789012345678901234567890123456789
print "=================================================="
print "Exercise 20: Functions and Files"
print
print
from sys import argv
script, input_file = argv
def print_all(f):
pri... |
419b68c638207f30b707ec68c6413046cb31ea6e | justien/lpthw | /ex13_argv.py | 1,953 | 4.03125 | 4 | # -*- coding: utf8 -*-
# Exercise 13: Parameters, Unpacking, Variables
# 23456789012345678901234567890123456789012345678901234567890123456789
print "=================================================="
print "Exercise 13: Parameters, Unpacking, Variables"
print
print
# --Importing a function from a library
# Here... |
e497e1516a43e6667d72919eedb135434f2518bb | justien/lpthw | /ex30a.py | 838 | 3.765625 | 4 | # -*- coding: utf8 -*-
# Exercise 30: Else and If
# 234567890123456789012345678901234567890123456789012345678901234567890123456789
print "========================================================================"
print "Exercise 30a: Else and If extension on errors in logic"
print
print
#
print "We're testing to ... |
9f30807e928a73ad9f8a2a76f0caa451d3a0eba2 | Davidxcr/python | /app.py | 237 | 4.28125 | 4 |
celsius = int(input("Enter an integer value for degree in celsius: "))
def fahrenheit(C):
return (float(1.8) * C + int(32))
print("The Fahrenheit equivalent of " + str(celsius) + " degree Celsius is " +str(fahrenheit(celsius))) |
14930d9f1eca909728049f8c6f891d79df5b7073 | Davidxcr/python | /student management system.py | 2,112 | 4.1875 | 4 | import os
import platform
global listStudents
listStudents = ["David", "Femi", "Jim", "Tom"]
def manageStudent():
x = "#" * 30
y = "=" * 28
print("""
Enter 1: To view Student's List
Enter 2: To Add New Student
Enter 3: To Search Student
Enter 4 : To Remove or Delete Student
... |
002c4c02fc513c386c8dbebe487aad6c82da9d4d | savva-kotov/python-intro-practise | /2-2-7.py | 402 | 4.21875 | 4 | '''
Для разминки прочитайте последовательность, как описано на предыдущем шаге, и выведите её длину. В последовательности могут быть пропуски (пустые строки).
Sample Input:
8
11
.
Sample Output:
2
'''
a = input()
c = 0
while a != '.':
a = input()
c += 1
print(c)
|
a3f71a3bc930736b988296da556da41711ecdd33 | savva-kotov/python-intro-practise | /2-1-8.py | 703 | 4.21875 | 4 | '''
Может ли шахматный король перейти из одной клетки в другу за один ход.
Координаты каждой клетки задаются двумя числами от 1 до 8. Сначала номер столбца, потом номер строки.
В качестве результата выведите "YES" или "NO" (заглавными буквами, без кавычек).
Sample Input:
8
3
7
4
Sample Output:
YES
'''
a, b, c, d = in... |
73a9a234c55e6201a80a61b27a9eedcf00768748 | savva-kotov/python-intro-practise | /1-1-11.py | 1,144 | 4 | 4 | '''
Вы открыли вклад в банке. Положили 100000 рублей под 10% годовых. Капитализация процентов происходит раз в год. Какая сумма будет у вас через несколько лет?
Напишите программу, которая вычисляет сумму денег на вашем счету. Количество лет поступит на вход.
Отбросьте копейки в результате.
Для простоты считайте, что... |
519adb06f3c535cd41081e44690dd5bb995860b7 | savva-kotov/python-intro-practise | /2-1-13.py | 570 | 4.28125 | 4 | '''
Напишите программу, которая считывает координаты двух точек и определяет лежат ли эти точки в одной координатной четверти.
В качестве результата выведите "YES" или "NO" (заглавными буквами, без кавычек).
Sample Input:
1
2
3
4.1
Sample Output:
YES
'''
a1, b1, a2, b2 = float(input()), float(input()), float(input())... |
e86e0105b689ce56bc9ec9a375803e81b816fa89 | savva-kotov/python-intro-practise | /3-1-8.py | 757 | 4.09375 | 4 | '''
Проверьте, является ли прочитанная строка палиндромом.
Палиндром -- это строка, которая читается одинаково слева направо и справа налево.
Пробелы это тоже символы, "СЕТУЙ УТЕС" это не то же самое что "СЕТУ ЙУТЕС", поэтому в этой задаче эта строка
полиндромом не является.
В качестве результата выведите "YES" или "... |
6e1a6cd98a9eedc94ad5054ade1d5afbe03060c1 | savva-kotov/python-intro-practise | /2-2-2.py | 285 | 3.515625 | 4 | '''
Посчитайте сумму квадратов первых k натуральных чисел. Число k подается на вход программы.
Sample Input:
3
Sample Output:
14
'''
a= int(input())
res = 0
while a != 0:
res += a**2
a -= 1
print(res)
|
650793ec3d2eecb66dd014bcd5b1afa30de7ea27 | janarqb/Notes_Week4 | /Wed.py | 1,311 | 3.578125 | 4 | # 30ые годы были lamda функции, в пайтон включили их в 1994 годах
# def identity(x):
# return x + 1
# lambda x:x
# lambda x:x +1
# (lambda x:x +1) (2)
# add_one = lambda x: x+1
# add_one(2)
# def fut_to_meters(num_fut):
# return f'{round(num_fut/3.2000)} meters'
# fut = [10, 15, 5, 6, 7]
# meters = lis... |
07be77c48bcdf4889df7803d2b5bc2887ec06f09 | coco-0610/Py104 | /ex15.py | 437 | 3.8125 | 4 | #-*- coding: utf-8-*-
# 获取文件名
from sys import argv
script, filename = argv
# 定义文件的变量名
txt = open (filename)
print "Here's your file %r:" % filename
# 打开文件
print txt.read()
print "Type the filename again:"
# 提示变量输入字符
file_again = raw_input(">")
# 文件的一个变量名
txt_again = open(file_again)
# 输出文件内容
print txt_again.read()
pri... |
ee8e2cded92adb17b7b4d595aceba038d95ac756 | lily28AC/CoffeeMachine.HyperSkillProyect | /CoffeeMachine.py | 3,942 | 4.03125 | 4 | def buy():
option = input('What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu: ')
if order == 'back':
return
else:
my_machine.check(option)
def fill():
water_add = int(input('Write how many ml of water do you want to add: '))
milk_add = in... |
c14b9ea6abc8f1d942df7fdc5969873606016b88 | ahitboyZBW/LearnPython | /deque_example.py | 1,284 | 3.890625 | 4 | # _*_ coding: utf-8 _*_
# 双端队列
# 两端都可插入与弹出
# from collections import deque # collections 库里有deque
# example:这里用list去模拟deque
class Deque:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def addFront(self,item):
self.items.append(item)
def addRear(... |
86b6b0d44b740a95f5edb9652b7ae96c0ff5c16c | HarmanpreetSinghGrover/COMP-598-Project | /scripts/clean_data_with_date.py | 1,807 | 3.53125 | 4 | import json
import pandas as pd
import re
import argparse
"""
This script takes a json file having one post per line, converts it into json.
OUTPUT :
saved in : ../data/post_dates.json
format : <name><tag><title><tag><coding>
"""
def contains_trump_biden(title):
trump = (re.search(r"[^\w\d... |
88daf89da074ed0a16b4e27e69aba8428b35ee83 | daxm/sierpinski_cube | /sierpinskiV2.py | 2,627 | 3.734375 | 4 | #!/usr/bin/python3
################
# Changeable Variables
serverip = '192.168.11.253'
layers = 3
x = 10
y = 10
z = 10
blockType = 46 #TNT
fillBlockType = 0 #AIR
filler = 1
################
from mcpi.minecraft import Minecraft
mc = Minecraft.create(address=serverip)
def placeblock(x,y,z,blockType):
mc.setBlock(x... |
bf0b59c52c91d87bd2e2e0e649d67c9b166371a2 | Agskvortsov/New_python_hw | /home_work_14-16.py | 3,046 | 4.15625 | 4 | # 14 Написать функцию, которая будет проверять четность некоторого числа.
#
# def pairity_check (number):
# result = number%2
# if result == 0:
# print("Number is even")
# if result != 0:
# print("Number is not even")
# return result
#
# x = pairity_check(16)
# 15 Написать функцию, к... |
861e2e45bbd97dae100d265015b445068c1789d6 | Agskvortsov/New_python_hw | /home_work_17-20.py | 2,308 | 3.5625 | 4 | # 17 Написать функцию решения квадратного уравнения.
# def quad_equation(a, b, c):
# import math
# d = b**2 - 4*a*c
#
# print("D =",d)
# if d > 0:
# x1 = (-b + math.sqrt(d)) / (2*a)
# x2 = (-b - math.sqrt(d)) /(2*a)
# return x1, x2
# elif d == 0:
# x1 = -b / (2*a)
... |
5e5f3434fe4c5644d4c27c5746ae6a52c1f62a90 | Yolocat12/index.html | /main.py | 3,186 | 4.03125 | 4 | import random
# ah you must be the guy, yes you! the guy ._.
# anyways welcome to my little program over here, the helperinator thing (we seriously ran out of ideas here?)
# to start are little adventure here, type start() into the console side, and the program will activate itself! W O A H! anyways, feel free to answ... |
c0dcb253c1becc19878ab827ac8df40ad472bea3 | 4rude/WGUPS_Delivery_Program_C950 | /dsa_2/main.py | 1,148 | 3.5 | 4 | # First Name: Matthew, Last Name: Rude, Student ID: #001260851
from CLI import *
# Press ⌃R to execute it or replace it with your code.
# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.
# Main function that runs the project
if __name__ == '__main__':
# Create a user_in... |
6718395847b73d9fe65d7038e69fc32ea92f3ca5 | U-Alberta/wned | /aggregate.py | 891 | 3.578125 | 4 | #!/usr/bin/python
import sys
def aggregateSortedFile(graphFile):
"""
We assume that the graphFile has already been sorted alphabetically.
Thus the duplicated lines are adjacent in the file.
"""
prev = ""
count = 0
fd = open(graphFile)
for line in fd:
line = line.strip()
... |
45f9ab19db6d94a51b662563a484c6a538fa8455 | GianlucaTravasci/Coding-Challenges | /Advent of Code/2019/Day 6/solution6.py | 2,342 | 3.78125 | 4 | orbits = {
'COM': {
'parent': None,
'children': [],
'count': 0
}
}
def input_reader():
with open("input.txt", 'r') as file:
line = file.readline().strip()
while line:
parent, child = line.split(")")
if parent in orbits:
orbits... |
0bdc2e1ed4811ffc771ffe2d26cb39e838be29b5 | Rune-Coder/beginner-project-solutions | /Armstrong.py | 291 | 4.03125 | 4 | num = int(input("Enter a number: "))
dig = len(str(num))#number of digits
sum = 0
copy = num
while copy > 0:
digit = copy % 10
sum += digit ** dig
copy //= 10
# display the result
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number") |
6ccf1fc76e475b51f0ffe1981e01eed2ad61bf91 | TaitLoughridge/july_2020_python_1 | /loops.py | 450 | 3.796875 | 4 | title = "Cats are Awesome"
counter = 0
# this next variable will increment
# while counter < len(title):
# if (counter % 2) == 0:
# print(title[counter])
# counter += 1
# a difert way to do every other
# while counter < len(title):
# print(title[counter])
# counter += 2
# will remove blan... |
3b2db9c6c9796528344dca40a250b00b6b16a858 | TaitLoughridge/july_2020_python_1 | /conditionals.py | 278 | 3.921875 | 4 | user_input = int(input("Guess a number: "))
magic_Number = 35
if user_input == magic_Number:
print("ARE YOU A MIND READER!?!?!?")
elif user_input > 50:
print("Guess was too High")
elif user_input < 20:
print("Guess was too low")
else:
print("Sorry. Try again.") |
b4c584b739fe9cc01371af2a1e5e389f18224e48 | novouss/python-minimum-spanning-trees | /mst.py | 2,288 | 3.5625 | 4 | class Graph:
def __init__(self, vertices):
self.vertices = vertices
self.graph = []
def addEdge(self, src, dst, wt):
# Source(src) and destination(dst) are the vertices
# Weight(wt) is the edge that connects the source and destination
# Graph = [[source, destina... |
241c8a67133074201bc082519538b3d17954769d | ImjustWritingCode/IDTech_MIT_camp | /Python/func.py | 151 | 3.71875 | 4 | def add(num):
num=num+1
return num
def add2(string):
string = string + " nice to meet you"
return string
num=0
word=""
print(add(num))
|
a9b8d9d8a398c7e770403dd32f79a2292b59a65a | ImjustWritingCode/IDTech_MIT_camp | /Python/Challenge/3-F.py | 197 | 4.1875 | 4 | print('Factor finding program\n')
num = int(input('Please input a number: '))
print('The factors of ', num, ' are: ', end='')
for x in range(1, num+1):
if(not num%x):
print(x, end=' ')
|
07fe3af9f62da6efd010ceb996d490dcc5f5850f | ImjustWritingCode/IDTech_MIT_camp | /Python/Challenge/3-D.py | 261 | 4.09375 | 4 | length = int(input('Please input the length: '))
width = int(input('Please input the width: '))
graph = input('Please input the character you want to output: ')
for x in range(0, width):
for y in range(0, length):
print(graph, end='')
print('')
|
734916f43a6db5418e206271542d28ae891b33df | ImjustWritingCode/IDTech_MIT_camp | /Python/Challenge/1-C.py | 471 | 4.1875 | 4 | import datetime
today=datetime.datetime.today().weekday() #print the day of today
string='' #and print len(today) times
if today == 0:
string = 'Monday'
if today == 1:
string ='Tuesday'
if today == 2:
string = 'Wednesday'
if today == 3:
string = 'Thursday'
if today ==... |
a85d435a4980f956f68c869e06eaea97d47747cd | em-ach/sampy | /sampy/graph/procedural.py | 7,266 | 3.640625 | 4 | from scipy.ndimage import gaussian_filter
import numpy as np
from ..pandas_xs.pandas_xs import DataFrameXS
def create_random_2d_height_map(shape, low_val, high_val, sigma, lvl=1, start_weight=0.5,
flatten=False, dict_coord_to_index=None):
"""
Create a procedural 2D map with a r... |
09d48334c30fd1fa0b8b35e42e32676bdde948c7 | kimnanhee/Flask | /login_signup/request_post.py | 824 | 3.515625 | 4 | import requests, json
while(1):
num = int(input('1.signup 2.login => '))
if num==1: # 회원가입
print(1)
url='http://localhost:5555/signup'
headers = {'Content-Type' : 'application/json; charset=utf-8'}
input_id = input('set the id : ')
input_pass = input('set the password : ')
data = {'id' : input_id, 'p... |
6c5647f28b4399862150fb298fd3235fdd7157ff | JuanParas/Computational-Thinking-with-Python | /1. Computational-Thinking-with-Python/4. Structured types, mutability, and high-level functions/dictionaries.py | 740 | 4.125 | 4 | my_dictionary = {
'David': 35,
'Erika': 32,
'Jaime': 50
}
print(my_dictionary['David'])
#Get
print(my_dictionary.get('Juan', 'Juan not found')) #Looks for Juan, and if that key doesn't exist, returns 'Juan not found'
print(my_dictionary.get('Jaime', 30))
#Reassign
my_dictionary['Jaime'] = 20
print(my_dic... |
e9f01dc7db486ae744a8c174dc502f67335b6420 | JuanParas/Computational-Thinking-with-Python | /1. Computational-Thinking-with-Python/2. Numerical programs/enumeration.py | 501 | 4.0625 | 4 | import datetime
#Getting the square root of an integer trying every number from zero
goal = int(input("Choose an integer: "))
time_0 = datetime.datetime.now()
answer = 0
while answer**2 < goal:
answer += 1
time_1 = datetime.datetime.now()
tot_time = (time_1 - time_0).microseconds / 1000
if answer**2 == goal:
... |
1bc10ac0566b21c1c1e09ce2185143964465c231 | JuanParas/Computational-Thinking-with-Python | /1. Computational-Thinking-with-Python/5. Testing/testing_no_unittest.py | 280 | 3.953125 | 4 | def sum(num_1, num_2):
return abs(num_1) + num_2
def test_sum():
num_1 = 5
num_2 = 10
resultado = sum(num_1, num_2)
if resultado == 15:
print('Test sum is ok')
else:
print('Test sum dió ' + resultado + ' y debió dar 15')
test_sum() |
06aa57b8dfc50afe1456e03cfc1757a7d16f1fd7 | JuanParas/Computational-Thinking-with-Python | /1. Computational-Thinking-with-Python/1. Objects, Loops and Conditionals/conditionals.py | 368 | 3.84375 | 4 | name_1 = input("Nombre del primer sujeto ")
name_2 = input("Nombre del segundo sujeto ")
age_1 = int(input("Edad de "+ name_1 + " "))
age_2 = int(input("Edad de "+ name_2 + " "))
if age_1 > age_2:
print(name_1 + " es más viejo que " + name_2 )
elif age_1 < age_2:
print(name_2 + " es más viejo que" + name_1 )
... |
749d3922e1bef8427599e1b55a736df9b512213c | Anjalibhardwaj1/Hackerrank-Solutions-Python | /Basics/Python_Division.py | 657 | 4.28125 | 4 | #Task
#The provided code stub reads two integers, a and b, from STDIN.
#Add logic to print two lines. The first line should contain the result
#of integer division, a//b. The second line should contain the result of float division, a/b.
#No rounding or formatting is necessary.
#------------------------------... |
f3d6b396d14ddb9b77ed2967041e51b5825dc34c | denommenator/Inverted-Pendulum | /Vector.py | 1,041 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 24 19:56:44 2020
The vector module!
@author: robertdenomme
"""
import math
import numpy as np
class vector:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __add__(self, v):
x= self.x + v.x
y ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.