blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
ce0d80749e9edddf3e333c7e1ed391e069aa38df | LeonXZhou/ScienceQuestTeachingPrograms | /Pong Code/step3AddingaBall.py | 7,052 | 4.125 | 4 | #By Leon Zhou
import pygame as pygame #import required modules
import random as random # note we imported random not just pygame.
# The below code shows how to add a player as just a shape without
#using objects. We build on the CreatingRectangleNonObjectPlayers.py example.
# Explanation for window code is omitted
dim... |
8c75a1a2653eb651b60f520345213f2a750aae95 | Cavalcantefilipe/cs50-web-programing | /Python/loops.py | 167 | 4.03125 | 4 | for i in range(4):
print(i)
names = ["Alice", "Bob", "Charlie"]
for name in names:
print(name)
name = "Filipe"
for caracteres in name:
print(caracteres)
|
a2c36a29c113bc3e859964619f789ca534d9c90b | everydaytimmy/data-structures-and-algorithms | /python/code_challenges/hashmap_left_join/hashmap_left_join.py | 627 | 3.703125 | 4 | from code_challenges.hashtable.hashtable import Hashtable
def hashmap_left_join(ht1, ht2):
answer = []
for bucket in ht1._bucket:
if bucket:
current = bucket.head
while current:
current_key = current.data[0]
current_value = current.data[1]
... |
8146d291bad0d0938f624ff9b7dcbf6b93a491e3 | everydaytimmy/data-structures-and-algorithms | /python/tests/test_breadth_first_graph.py | 1,272 | 3.515625 | 4 | from code_challenges.depth_first_graph.depth_first_graph import depth_traversal, Stack, Node
from code_challenges.graph.graph import Graph, Vertex
def test_depth_traversal_exists():
assert depth_traversal
def test_depth_traversal_one():
graph = Graph()
boston = graph.add_node('Boston')
seattle = grap... |
f34dda828ad84815f41a2ba1b2199410f9b4d0dc | everydaytimmy/data-structures-and-algorithms | /python/code_challenges/breadth_first/breadth_first.py | 1,750 | 3.921875 | 4 |
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinaryTree:
def __init__(self):
self.root = None
def add(self, value):
if not self.root:
self.root = Node(value)
return
def walk(root... |
73bcec6b393517af28ea6d4db20ad93c57522602 | harix1606/Word-and-letter-frequency-analyser | /finalproject.py | 9,732 | 3.75 | 4 | import string
import time
def palindrome_checker(word): #checks if word is palindrome. Returns True if palindrome, else returns False.
length= len(word)
if length==0:
return False
if length==1:
if word== "a" or word=="i":
return True
else:
retur... |
86088a8771ee8bd2bb1af643d45cda87f8b912b3 | Thaileaf/TestBench | /Data Structures/Hash Tables/HashTableClass.py | 2,961 | 4.0625 | 4 | # Hash tables have a O(1) look up time
# Disadvantages are possible high memory requirement, as excess space is usually needed
# Uses key value pairs
# Similar to dictionaries in Python
class HashTable:
# Initializes an array with four spaces
def __init__(self, length=4):
self.array = [None] * length
... |
82fa0a3e0d9c0d82f97ab3dcdf1b81129b512d58 | joanalexs/python_clases | /tarea_01/ejercicio2.py | 277 | 3.890625 | 4 | #Programa qu muestre la suma de dos numeros usando funciones
num1=int (input("Ingrese el primer numero"))
num2=int (input("Ingrese el segundo numero"))
def sumar(numero1, numero2):
suma= numero1 + numero2
print(f"La suma de los numeros es: {suma}")
sumar(num1, num2) |
3cdcd8cdc341777efff7754d2e8f131dd5eb4c65 | chenyao1226/learnPython | /oo/what_is_var.py | 1,005 | 3.921875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/5/4 10:52
# @Author : ChenYao
# @File : what_is_var.py
'''python中的对象引用
python和java中的变量本质不一样,python的变量实质上是一个指针,指针大小是固定的,无所谓类型,可以指向任何一种数据类型
'''
a = 1
a = "abc"
# 1. a贴在1上面
# 2. 先生成对象 然后贴便利贴
'''
a和b指向的是同一个对象
'''
a = [1, 2, 3]
b = a
print(id(a), id(... |
57a281e701ea461dc1debad81d6920ed6d9abd4f | chenyao1226/learnPython | /sequence_protocol/test_sequence.py | 719 | 3.703125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/5/2 22:06
# @Author : ChenYao
# @File : test_sequence.py
my_list = []
my_list.append(1)
my_list.append("a")
from collections import abc
'''
abc模块中实现了序列的基类,规定序列协议应该实现哪几种方法
'''
'''拼接一个列表四种不同的方式
1. c = a + b
2. a += b
3. a.extend()
4. ... |
f3055dbb503990eeb5242d4ba2dfc9a8af3b2cf0 | QQyukim/for-Algorithm-Zonzal | /nong님-온라인-코칭-테스트/BOJ-2902-KMP.py | 271 | 3.546875 | 4 | # KMP는 왜 KMP일까?
longWord = input()
abb = longWord[0]
for i in range(len(longWord)):
if (longWord[i] == '-'):
abb += longWord[i+1]
print(abb)
# 대문자나 하이픈(아스키코드)는 신경을 쓰지 않나?
# 신경 쓴 코드 만들어보기? |
a47bd4030e26f1c167df1976e97d79491f5fd489 | QQyukim/for-Algorithm-Zonzal | /PS 스터디 (with @mindflip)/프로그래머스-타겟 넘버.py | 318 | 3.546875 | 4 | # 두 개 이상 리스트의 모든 조합 구하기
from itertools import product
# 예시 입력
numbers = [1,1,1,1,1]
target = 3
# 로직
count = 0
items = [(ele, -ele) for ele in numbers]
combiList = list(product(*items))
for nTuple in combiList:
if sum(nTuple) == target:
count += 1
print(count) |
27d131704628d011c109f8200e6d5c821be57c83 | QQyukim/for-Algorithm-Zonzal | /PS 스터디 (with @mindflip)/프로그래머스-해시-L1-완주하지_못한_선수.py | 700 | 3.5625 | 4 | # def solution(participant, completion):
# for i in range(len(participant)):
# if participant[i] in completion:
# completion.remove(participant[i])
# participant[i] = ""
# for p in participant:
# if p != "":
# return p
# 유효성 검사 탈락
def solution(participant, c... |
53c0736c0768ad4f3fba23e0c93ee51839f07540 | QQyukim/for-Algorithm-Zonzal | /BOJ/3052-나머지.py | 183 | 3.53125 | 4 | inList = []
rList = []
count = int(0)
for i in range(10):
inList.append(int(input()))
for num in inList:
rList.append(num % 42)
count += len(list(set(rList)))
print(count) |
799980b8a3f55456bdeccd40ae63d5bfaf029303 | ramvishvas/Old_Chegg_Solution | /PYTHON/Bisection.py | 886 | 3.9375 | 4 | #use python3
def f(x):
return A*(x**3) + B*(x**2) + C*x + D
def bisection(a, b, t):
if (f(a) * f(b) >= 0):
print("\nYou have not assumed right (a, b)")
return
#get midpoint value
mid = (a+b)/2.0
# excute loop till the tollerence is more than given tollerence t
while (b-a)/2.0 > t:
#check is mid... |
ee142f5e64cd3d4000c67025bbda892e24641a49 | ramvishvas/Old_Chegg_Solution | /StudentList.py | 1,229 | 4.03125 | 4 | students = [("White", "Snow", 9, "F", 3.56),
("Sprat", "Jack", 12, "M", 2.0),
("Contrary", "Mary", 9, "F", 3.674),
("Dumpty", "Humpty", 11, "M", 2.342),
("Bunny", "Easter", 10, "M", 4.233),
("Wonderland", "Alice", 10, "F", 3.755),
("Bunyon", "Paul", 11, "M", 1.434),
("Penny", "Henny", 9, "F", 2.54),
("Hatter", "... |
e339317ef1806a17bbb65a8f9b5463d19d13324e | ramvishvas/Old_Chegg_Solution | /turtle.py | 2,498 | 4.09375 | 4 | from turtle import *
def part_one():
# asiigning value of a, b and c
a, b, c = 3, 4, 5
if a < b: #true if a if less than b
print('OK')
if c < b: #true if c is less than b
print('OK')
if a+b == c: #true if a+b is equals to c
print('OK')
if a*a + b*b == c*c: #true if a^2 + b^2 == c^2
print(... |
f80511ba16ef82faf06740fcdf6d7c32a13f9381 | haydenmlh/csc108_lectures_practicals | /Practicals/week3/week3_activity3_booleans.py | 2,269 | 3.96875 | 4 | def marathon_time(half_marathon_time: int, is_hilly: bool) -> int:
'''Returns total marathon time given the half marathon time and whether or not the marathon is hilly
>>> marathon_time(300, True)
630
>>> marathon_time(250, False)
510
>>> marathon_time(0, True)
30
'''
if is_hilly:
... |
4d39f5b89d8e925691e4e88d22be1c324808787b | haydenmlh/csc108_lectures_practicals | /Practicals/lab6/files.py | 4,162 | 4.28125 | 4 | import urllib.request
from typing import List, TextIO
# Precondition for all functions in this module: Each line of the url
# file contains the average monthly temperatures for a year (separated
# by spaces) starting with January. The file must also have 3 header
# lines.
DATA_URL = 'http://robjhyndman.com/tsdldata/... |
fd2d918c5826af8e3a4c0e292995f6082bfba677 | alexpearce/Condorcet | /Condorcet/elections.py | 5,052 | 3.6875 | 4 | #!/usr/bin/env python
"""
preferences is a list of string e.g. ['abc','cab',...]
'cab' is a preference: candidate 'c' is the favoirite, followed by 'a' and 'b' is last
"""
def getScore(preferences, candidates):
"""
Get Score using Borda method, not useful for LHCb method but useful crosscheck
"""
num_c... |
b652cfd77021b9f618cffafa687b400c11499fb7 | Sultanggg/codeabbey | /q36.py | 544 | 3.578125 | 4 | counter = 1
myarray =[]
for i in range(1,37):
myarray.append(i)
def josephus(arr,n,c=10):
global counter
for k in range(0,n):
if counter%c == 0:
arr[k]='x'
counter = counter + 1
return arr
def newarray(alist):
emptylist = []
for i in range(0,len(alist)):
... |
bc6f0d1baf6126210a5946088e4d148300bf67df | danny-moncada/nyusps_intro_python2.7 | /lesson_4/ex4.14.py | 247 | 3.8125 | 4 | #usr/bin/env python
new_set = set()
sentence = "I could; I wouldn't. I might? Might I!"
split_sentence = sentence.split()
for word in split_sentence:
new_word = word.rstrip('.!?;')
lower = new_word.lower()
new_set.add(lower)
print new_set |
8662b0f1cb802e9fb05399798e43456040b0489a | danny-moncada/nyusps_intro_python2.7 | /lesson_5/hw5.2.py | 1,196 | 4.0625 | 4 | #!/usr/bin/env python
"""
hw5.2.py -- create a dictonary that sums all Mkt-RF values per year
author: Danny Moncada
"""
mydict = {}
farma_french = open('../../python_data/F-F_Research_Data_Factors_daily.txt').readlines()[5:-2]
for line in farma_french:
line = line.split()
year = line[0][0:4]
mkt... |
fd1fd31c510ec991298f5d84c1f4eef3583e9f3e | danny-moncada/nyusps_intro_python2.7 | /lesson_10/ex10.py | 415 | 3.53125 | 4 | #!usr/bin/env python
class Sum(object):
def add(self, val):
if not hasattr(self, 'x'):
self.x = 0
self.x = self.x + val
myobj = Sum()
myobj.add(5)
myobj.add(20)
print myobj.x
exit()
from datetime import date, timedelta
dt = date(1926, 12, 30)
td = timedelta(days = 3)
dt = dt + timedelta(days = 3)
print d... |
89c8a5f620b40adb47f4d4399e79c9c0c6ea8e94 | danny-moncada/nyusps_intro_python2.7 | /lesson_9/ex9.7.py | 249 | 3.59375 | 4 | #!usr/bin/env python
def getlines(filename):
lines = open(filename).readlines()
return lines
lines = getlines('/Users/dmoncada/Documents/Introduction to Python Programming_NYU/python_data/revenue.txt')
for line in lines:
print line.rstrip()
|
4785dc0bc488f0e0a0df22222f5ac3707a8aca91 | danny-moncada/nyusps_intro_python2.7 | /lesson_6/ex6.1.py | 120 | 3.5 | 4 | #!/usr/bin/env python
numlist = [1, 13, 23, 3, 9, 16]
sorted_list = sorted(numlist, reverse = True)
print sorted_list |
ab35ea8ae198e9614f03ef9f5b4a1aad861d5ab7 | danny-moncada/nyusps_intro_python2.7 | /lesson_9/ex9.2.py | 159 | 3.90625 | 4 | #!usr/bin/env python
def printupper(string):
print string.upper()
printupper('hello')
printupper('my you are loud')
printupper('I am not lout. You are.')
|
dc0c7007fe3b1dfc77835d92ff3f8d7069827f96 | danny-moncada/nyusps_intro_python2.7 | /lesson_8/ex8.6.py | 503 | 3.796875 | 4 | #!usr/bin/env python
import os
import sys
user_input = raw_input('please enter a directory: ')
try:
test_dir = user_input
for file in os.listdir(test_dir):
full_path = os.path.join(test_dir, file)
size = os.path.getsize(full_path)
if os.path.isfile(full_path):
print '{} (file): {}'.format(file, size)
... |
ca5fa437808e1935217bc2230a062cdd1a28e7d3 | nilasissen/python-rookie | /india.py | 607 | 4.28125 | 4 | #!/usr/local/bin/python
print 'Legal age in INDIA'
driving_age=16
voting_age=18
smoking_age=19
marriage_age=21
age = int(raw_input('enter your age :) '))
def get_age(age):
"""this program will teach you about the if and else and elif statements """
if age >= marriage_age:
print 'you can get marriad,sm... |
3679e5d2092233de7fa650710660c67855774919 | mission-systems-pty-ltd/comma | /python/comma/dictionary/util.py | 5,053 | 3.71875 | 4 | '''
operations on dict and dict-like objects with string keys
made for convenience, not for performance
'''
import copy, functools, typing
def at( d, path, delimiter = '/', no_throw = False, full = False ): # todo: default=...
'''
return value at a given path in a dictionary
params
------
... |
be0f059ba551ea53b2eff35cee8d6a7cd2d5957f | codezoners-2/AgileDevelopment | /01_basic_testing/presentation/include/edge-cases.py | 148 | 3.828125 | 4 | def average(list):
"""
>>> average([1, 2, 3])
2
"""
total = 0
for i in list: total = total + i
return total / len(list)
|
1496c17e367409805481ebc32afc64d50f5449ce | JIAWea/Python_cookbook_note | /07skipping_first_part_of_an_iterable.py | 1,321 | 4.15625 | 4 | # Python cookbook学习笔记
# 4.8. Skipping the First Part of an Iterable
# You want to iterate over items in an iterable, but the first few items aren’t of interest and
# you just want to discard them.
# 假如你在读取一个开始部分是几行注释的源文件。所有你想直接跳过前几行的注释
from itertools import dropwhile
with open('/etc/passwd') as f:
for l... |
ce83346829246a0c7896a2b25855b435c2f3ca0b | JIAWea/Python_cookbook_note | /09yield_and_yield_from-2.py | 2,082 | 3.71875 | 4 | # yield 除了能生成一个生成器的作用,还能用在协程当中,当我们遇到了阻塞,如 IO 阻塞时,可以调配线程去做别的事情
# 下面有一段伪代码,如:
"""
def test():
request_google_server(data)
yield
print(data)
"""
# 去请求百度需要走很长的网络线路,三路握手,数据传递。这在 cpu 的感官里这就是等待数年的操作。我们的程序无法继续运行,
# 难道我们就这样让 cpu 等待?当然不所以调用 yield 把线程的控制权交出来,然后我们让线程去做一些其他的事情,比如再入
# 请求新浪服务器等等,一瞬间我们同时请求了 N 台... |
d5fc7d0c23127c4e7c052866a658499c71ba18a4 | chanbi-raining/algorithm-study | /0512_stackandqueue.py | 6,677 | 4.125 | 4 | # 알고리즘 시즌 2
'''
- date: 2019-05-12
- participants: @yoonjoo-pil, @cjttkfkd3941
- chapters: Stack and Queue
'''
# implementing stack in python
class StackNode():
def __init__(self, data, nextt=None):
self.data = data
self.next = nextt
class Stack():
def __init__(self):
self.size = 0
... |
1ff8c1d0e4d2c8ff72a72b36daece2ed1ee97d3c | hejia-zhang/welcome_assignments_sols | /rrt/env.py | 1,338 | 4.03125 | 4 | import matplotlib.pyplot as plt
import numpy as np
from rrt.robot import Robot, Obstacle
class World(object):
def __init__(self, w=400):
self.w = w # a world is a square with this width
self.world_map = np.zeros(shape=(self.w, self.w)) # this is used to just visualize, think it as a white board... |
c1b83c2ac9d096558fa7188d269cc55f2a25ecf1 | tolu1111/Python-Challenge | /PyBank.py | 2,088 | 4.1875 | 4 | #Import Dependencies perform certain functions in python
import os
import csv
# define where the data is located
bankcsv = os.path.join("Resources", "budget_data.csv")
# define empty lists for Date, profit/loss and profit and loss changes
Profit_loss = []
Date = []
PL_Change = []
# Read csv file
with op... |
3586071535e42f3431e3ddbacc7d6c80c8ba5497 | AlanSoldar/Artifitial-Intelligence | /8Puzzle/Sucessor.py | 1,262 | 3.546875 | 4 | import sys
def sucessor():
puzzle = str(sys.argv[1])
emptyPos = puzzle.find('_')
print(getLeft(puzzle, emptyPos), getDown(puzzle, emptyPos), getRight(puzzle, emptyPos), getUp(puzzle, emptyPos))
def getRight(puzzle, emptyPos):
if(emptyPos!=2 and emptyPos!=5 and emptyPos!=8):
newState = puzzle... |
78f8062aa223caa2d4a340b8b4719deb99d4a314 | AlanSoldar/Artifitial-Intelligence | /8Puzzle/avalia_dfs.py | 3,670 | 3.515625 | 4 | import sys
DIREITA = 'direita'
ESQUERDA = 'esquerda'
ACIMA = 'acima'
ABAIXO = 'abaixo'
EMPTY_SPACE = '0'
FINAL_STATE = '123456780'
class Node:
def __init__(self, previous, direction, cost, current):
self.previous = previous
self.direction = direction
self.cost = cost
self.current ... |
9576cd9981b4c19cb4895365a0621758a92eaf45 | anas-yousef/Asteroids-Game | /asteroid.py | 2,247 | 4.03125 | 4 | import math
TEN = 10
MINUS_FIVE = -5
class Asteroid:
def __init__(self, location, speed, life):
'''
:param location: Takes in the initial location of the asteroid
:param speed: Takes in the initial speed of the asteroid
:param life: Takes in the initial life of the asteroid
... |
4b6b08ab7cc50cfd04f423b39e64f91d46ec6fdd | Harakiri604/PGRM-1006 | /Week 2.2 - Pandas.py | 1,046 | 3.703125 | 4 | import pandas as pd
df = pd.read_csv("co2_emissions_tonnes_per_person.csv", index_col='country')
print(df.head(10))
print(df.describe())
print(df.columns)
print(df.index)
#Creating a list by columns
year19and20 = df[['1900', '2000']]
print(year19and20)
#Creating a list by rows
canadaAndchina = df.loc[... |
0b79c5643a6406e9055c69cc160136ff712d9c54 | Harakiri604/PGRM-1006 | /Week 1.3 - Anonymous Functions.py | 246 | 3.84375 | 4 | # Lambda function syntax - lambda x,y,z: x+y+z
#Sum function
x = lambda a,b:a+b
print(x(2,3))
print(x(3,5))
#Power function
y = lambda a:a**2
print(y(2))
#List comprehension
z = lambda a:a**2
a = [z(y) for y in range (20)]
print(a) |
271876e5e1d156160e0c472fe3f251725f01ac3f | dhanraj404/ADA_1BM18CS027 | /longestpalindrome.py | 412 | 3.5625 | 4 | def max(x, y):
if(x > y):
return x
return y
def lps(seq, i, j):
if (i == j):
return 1
if (seq[i] == seq[j] and i + 1 == j):
return 2
if (seq[i] == seq[j]):
return lps(seq, i + 1, j - 1) + 2
return max(lps(seq, i, j - 1),
lps(seq, i + 1, j))
if __name__ == '__main__':
seq = input("Enter t... |
7ede4feb02c69b109063273387609b7b43931927 | dhanraj404/ADA_1BM18CS027 | /q16/dijkstra.py | 1,503 | 3.78125 | 4 | def creategraph(vertices):
return [[0]*vertices for _ in range(vertices)]
def dijkstra(G, root, vertices):
def _mindistance(distance, vertices, selected):
mn = 10**8
for v in range(vertices):
if distance[v] < mn and v not in selected:
mn = distance[v]
... |
4486ff6ea00e2f7c0b9a41ddbc7c50e669690de2 | dhanraj404/ADA_1BM18CS027 | /binaryandlinear.py | 1,441 | 4.0625 | 4 | #Implement Recursive Binary search and Linear search and determine the time required to search an element. Repeat the experiment for #different values of N and plot a graph of the time taken versus N.
def binary(L,x):
L.sort()
l = 0
n = r = len(L)-1
while l <= r:
mid = int((l+r)/2)
if L... |
00646f9582bda3050984de87ef0e21f8325e9c3d | techforthepeople/NAVI-IoT-device | /setup.py | 950 | 3.625 | 4 | #Script for initial database setup
import sqlite3
from sqlite3 import Error
db = 'sensor.db'
def open_database(db):
con = None
try:
con = sqlite3.connect(db)
return con
except Error as e:
print(e)
return con
def create_table(con, sql):
try:
c = con.cursor()
... |
3ce0ea12701b7a79bb91e4d747176383682fe34d | 09ubberboy90/PythonProjects | /unit 14/pack/example5.py | 736 | 3.875 | 4 |
import tkinter
def display():
name = textVar.get()
messageLabel.configure(text="Hello "+name)
top = tkinter.Tk()
top.title("New_Title")
top.geometry("800x600")
top.configure(background = "white")
textVar = tkinter.StringVar("")
textEntry = tkinter.Entry(top,textvariable=textVar,width=12 ,bg = "white")
textEn... |
882676658b32eb43e8e56162222b1ae7549f7627 | 09ubberboy90/PythonProjects | /graph/pack/__init__.py | 333 | 3.8125 | 4 | def test():
n = 2
x = 3
y = 4
n_increase = 0
x_increase = 0
y_increase = 0
while n_increase < n :
while x_increase < x :
while y_increase < y :
print("%d "% n)
y_increase +=1
x_increase += 1
n += 1
print(n... |
789ef6d23defed8c3d6db95395ca9b8c80015f44 | AdityaM8/AMDZS | /P8.py | 124 | 4.28125 | 4 | x=int(input("enter the number"))
f=1
for i in range(1,x+1):
f= f*i
print ("The factorial is: ")
print (f)
|
4546b612b86188bd7be2bea96d3cb3a36529a28e | AdityaM8/AMDZS | /P7.py | 148 | 3.546875 | 4 | a=int(input("Enter lower limit:"))
b=int(input("Enter upper limit:"))
for n in range(a, b+1):
if((n%7==0) & (n%5!=0)):
print(n)
|
71f14e4f33f3d3c82a4fce471b679d5773c7ebe5 | bbsara/python-program | /multiptable.py | 252 | 3.828125 | 4 | n=int(input("enter the value of n"))
for i in range(1,11):
print(n,'x',i,'=',n*i)
#output
enter the value of n5
5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50 |
77c573ce31e2fefb975ade179176200cad5e5dd7 | bajpaiNikhil/dynamicProgramming | /bestSum.py | 1,494 | 4 | 4 | """given an target and array find the min len array whose sum is equall to target"""
#
# def best_sum(target_sum, numbers):
# if target_sum == 0:
# return []
# shortest_combination = None
# for num in numbers:
# remainder = target_sum - num
# if remainder >= 0:
# combinat... |
b3a5649c4111ada661cef24d1d410c8d58b49153 | vyahello/speech-recogniser | /lib/robot/robots.py | 1,608 | 3.625 | 4 | from abc import ABC, abstractmethod
from lib.robot.engines import Engine
from lib.robot.quotes import Quotes
from lib.robot.speech import Sayable, Speech
class Robot(ABC):
"""Represent abstract robot."""
@abstractmethod
def cheer_up(self) -> None:
"""Cheer up the master."""
pass
@abs... |
ec2a4d0d4d528f20f5f84ed3b4e31d004339000e | hikoyoshi/hello_python | /time_example.py | 1,556 | 3.515625 | 4 | #!-*- coding:utf-8 -*-
import time,datetime
print(time.time()) # 返回當前時間的時間戳(1970紀元後經過的浮點秒數)
print(time.altzone) # 返回與UTC時間的時間差,以秒計算
print(time.localtime()) # 返回本地時間的struct time物件格式
print(time.gmtime(time.time())) # 返回UTC時間的struct時間物件格式
print(time.asctime()) # 返回時間格式'Fri Feb 9 15:55:27 2018'
print(time.asctime(time.l... |
dbe7b53cb7768ca9794bca41d8688117830e887b | hikoyoshi/hello_python | /example_9/main.py | 542 | 3.828125 | 4 | #-*- coding:utf-8 -*-
import temperature as tp
c_or_f = input("0、離開 1、轉換為華式 2、轉換為攝式\n")
if c_or_f == "0":
print ("ByeBye~~")
sys.exit()
elif c_or_f != "1" and c_or_f !="2":
print ("沒這個選項啦~~")
sys.exit()
temp = input("請輸入溫度:\n")
if c_or_f == "0":
print ("ByeBye~~")
sys.exit()
elif c_or_f =... |
759d6ceff530708756a834632dd744e576ab5157 | hikoyoshi/hello_python | /pillow_demo/pillow_rotated.py | 454 | 3.515625 | 4 | #!-*- coding:utf-8 -*-
#載入pil模組
from PIL import Image,ImageDraw,ImageFont
#載入圖片
im = Image.open('kaeru.jpg')
#旋轉45度,可旋轉任意角度但rotate的旋轉不是整張旋轉所以會帶有黑邊
nim = im.rotate(45)
nim.save("rotated.jpg")
# transpose 為整張旋轉不會有黑邊,可上下左右翻轉,旋轉角度以90、180、270
nimt =im.transpose(Image.FLIP_LEFT_RIGHT)
nimt.save("transpose.jpg")
nim.show()
n... |
cffb4d38386a6ae750d02eda9cfc05176ef6cb44 | hikoyoshi/hello_python | /module/xmath.py | 197 | 3.75 | 4 | def max(a,b):
return a if a > b else b
def min(a,b):
return a if a < b else b
def sum(*numbers):
total = 0
for number in numbers:
total += number
return total
pi = 3.1415926
e = 2.718281 |
e89d601b7e0fa608b872065882f6b00269afa615 | senchenkoanastasiya/study | /test3.py | 200 | 4 | 4 | def sum_of_digit():
n = input("Введите трехзначное число: ")
n = int(n)
a = n % 10
b = n % 100 // 10
c = n // 100
return a + b + c
print(sum_of_digit()) |
5a73135343eaef9b00eb933ce11119d43b5c3869 | ashleygw/AI | /smallProjects/bayesianNetwork/randvar.py | 4,854 | 3.8125 | 4 | """
Make sure to fill in the following information before submitting your
assignment. Your grade may be affected if you leave it blank!
For usernames, make sure to use your Whitman usernames (i.e. exleyas).
File name: randvar.py
Author username(s): ashleygw, millersm
Date: 5/4/2018
"""
'''
randvar.py
A module contai... |
fbcd8afd885134d564c137da6c6e5e017903697e | krishna07210/com-python-core-repo | /src/main/py/07-Exceptions/Raising-Exceptions.py | 438 | 3.953125 | 4 | def main():
try:
for line in readfile('line.txt1'): print(line.strip())
except IOError as e:
print('Could not find the file: ', e)
except ValueError as e:
print('bad filename: ',e)
def readfile(filename):
if filename.endswith('.txt'):
fh = open(filename)
return... |
1073469bf7f0ae9eab2079507b655a22897eaf25 | krishna07210/com-python-core-repo | /src/main/py/05-Operators/Operators.py | 700 | 3.921875 | 4 | #!/usr/bin/python3
def main():
print('Add -', 5 + 5)
print('Multi -', 5 * 5)
print('Sub -', 5 - 3)
print(5 / 3)
print(5 // 3)
print(5 % 3)
print(divmod(5, 3))
num = 5
num += 1
print(num)
x, y = 4, 5
print(id(x), id(y))
print(x is y)
print(x is not y)
x = 5
... |
cfa342710536f41de8ec8967c38b8fc1b23a3fd6 | krishna07210/com-python-core-repo | /src/main/py/10-StringMethods/String-working.py | 850 | 4.21875 | 4 | def main():
print('This is a string')
s = 'This is a string'
print(s.upper())
print('This is a string'.upper())
print('This is a string {}'.format(42))
print('This is a string %d' % 42)
print(s.find('is'))
s1 = ' This is a string '
print(s1.strip())
print(s1.rstrip())
s2 =... |
c0ef50bb9e3c789792feb214dcbb7675100255ec | avalanchesiqi/awesome-tools | /tutorials/stationary_time_series_data.py | 3,818 | 3.5625 | 4 | """
How to Check if Time Series Data is Stationary with Python
source: https://machinelearningmastery.com/time-series-data-stationary-python/
"""
from pandas import Series
from scipy.stats import ks_2samp
from statsmodels.tsa.stattools import adfuller
import matplotlib.pyplot as plt
if __name__ == '__main__':
# ... |
1ec5b2dab936247f8792abc87c39a523175dc5ea | goofygeckos/drunken-ninja | /utils/pngconvert.py | 1,416 | 3.765625 | 4 | """Goofy utility to convert between PNG and text files.
Usage:
pngconvert.py myfile.png myfile.txt
Or:
pngconvert.py myfile.txt myfile.png [options]
"""
import optparse
import png
def convert_png_to_txt(png_file, txt_file):
r = png.Reader(png_file)
f = open(txt_file, 'w')
width, height, pixels, meta = r.r... |
728e6e0ed79d771b5448317a4f53f1429ac4cbdb | tnmoc-coderdojo/coderdojo | /python/pong/pong.py | 2,877 | 3.609375 | 4 | import pygame
from pygame.locals import *
def draw_game_screen():
screen.blit(bg,(0,0))
screen.blit(paddle1, (10, l_paddle_pos))
screen.blit(paddle2, (620, 100))
screen.blit(ball, (ball_pos_x, ball_pos_y))
# Scores
l_score_str = font.render(str(l_score), True, (0,0,0))
r_score_str = font... |
a3284a0c50e455866fdce7d59a573f14160765e0 | barweizman/SolveLinearEquations | /SolveLinearEquations.py | 11,213 | 3.640625 | 4 | # Bar Sela - 206902355
# Bar Weizman - 206492449
# ------Solve AX=b by using Gauss Elimination------
# Cond A
def CalcConditionNumber(matrix):
"""
description
calculation of the condition number by using the infinity norm
:param matrix: the matrix
:return: condition number
"""
norm_matrix =... |
df806bbd777caaebb26b0b52f7ef58b571948629 | jdfrens/polyglot-euler | /001/Python/problem001.py | 141 | 3.734375 | 4 | def sum35(n):
return sum([m for m in range(0, n+1) if interestingNumber(m)])
def interestingNumber(n):
return n % 3 == 0 or n % 5 == 0
|
629109031bfa1503c4cc1ef7035776378b2f6825 | takaolds/cryptopals-solutions | /solutions/set1/challenge3.py | 325 | 3.546875 | 4 | def main():
input_string = "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736"
input_bytes = bytearray.fromhex(input_string)
for i in range(255):
result = bytearray("", 'utf-8')
for j in range(len(input_bytes)):
result.append(input_bytes[j] ^ i)
print("... |
503e7db374872bb34b5126f33a7c28e580b96bd5 | ValeronMEN/Databases | /term1/lab1/lab1/module.py | 474 | 3.671875 | 4 | import datetime
def date_check(date):
birthday_date_array = date.split(' ')
if len(birthday_date_array) == 3:
year = int(birthday_date_array[0], 10)
if 1900 <= year <= datetime.datetime.now().year:
month = int(birthday_date_array[1], 10)
if 0 <= month <= 12:
... |
56e740d84e825a248b044f1f867ea8f5a97ee76c | Maskyoung/pj1 | /t2.py | 670 | 3.84375 | 4 | # /usr/bin/env python
# -*- coding: utf-8 -*-
# a = 7
# if a > 0:
# # raise ValueError('number must be non-negative')
# print('asd')
# else:
# print(a)
#
# # # print(a)
# s='asdga\asdgasdasd\sdg\t\t'
# print(s)
# import re
# def plural(noun):
# if re.search('[sxz]$', noun):
# return re.sub('$', ... |
317e92540d3a6e00bec3dcddb29669fe4806c7fa | Frank1963-mpoyi/REAL-PYTHON | /FOR LOOP/range_function.py | 2,163 | 4.8125 | 5 | #The range() Function
'''
a numeric range loop, in which starting and ending numeric values are specified. Although this form of for loop isn’t directly built into Python, it is easily arrived at.
For example, if you wanted to iterate through the values from 0 to 4, you could simply do this:
'''
for n in (0, 1, 2, 3... |
341071c13e042e7de021e4883ecdd8b936633afb | Frank1963-mpoyi/REAL-PYTHON | /FOR LOOP/forloop_patterns_exercises.py | 417 | 4.09375 | 4 | no_patterns= int(input("Please Enter the Number of patterns: ? "))
'''
for num in range(1,no_patterns+1):
print()
for pict in range(1, 10):
print(pict, end="")
print()
print(f"Number of iteration : {num}")# will print the number of user input for each iteration
'''
for row in range(1, no_patte... |
1eec2e1904286641b7140f572c19f7b860c3427e | Frank1963-mpoyi/REAL-PYTHON | /WHILE LOOP/whileloop_course.py | 2,036 | 4.25 | 4 | ''' Iteration means executing the same block of code over and over, potentially many times. A programming structure that implements iteration is called a loop'''
'''
In programming, there are two types of iteration, indefinite and definite:
With indefinite iteration, the number of times the loop is executed isn’t
sp... |
6fa0391f1539a982b0b11e1a38a6f1e9109a5460 | Frank1963-mpoyi/REAL-PYTHON | /MODULE_AND_PACKAGE/from_import.py | 1,639 | 4.03125 | 4 | '''
from <module_name> import <name(s)>
An alternate form of the import statement allows individual objects from
the module to be imported directly into the caller’s symbol table:
'''
#Syntax
# from <module_name> import <name(s)>
#Exemple
from mod import foo, s
print(s)
# Because this form of import places the ... |
16cd19a92c053cfe1cc9aeafac4d6484a98b308b | ngtrangtee/ngtrangtee.github.io | /python/homework2.py | 7,617 | 4.03125 | 4 | # 1. Viết chương trình yêu cầu người dùng nhập một chuỗi, và một giá trị số (index), hiển thị chuỗi được cắt từ 0 đến vị trí index
print("Nhập một chuỗi")
string = input(">")
print("Nhập một giá trị số (Index)")
index = input(">")
print(string[0:int(index)])
# 2. Viết chương trình yêu cầu người dùng nhập tên, i... |
eccf4a1f564166306f13e66bb7e89fa05738a7c6 | 425776024/Pythonic | /25mmap/1start.py | 1,221 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/5/7 13:36
# @Author : xinfa.jiang
# @Site :
# @File : 1start.py
# @Software: PyCharm
'''
mmap是一种虚拟内存映射文件的方法,即可以将一个文件或者其它对象映射到进程的地址空间,
实现文件磁盘地址和进程虚拟地址空间中一段虚拟地址的一一对映关系。
普通文件被映射到虚拟地址空间后,程序可以像操作内存一样操作文件,可以提高访问效率,适合处理超大文件
'''
import mmap
# write a s... |
bcfb966cbb69581fc67cf1b81d25220710391602 | 425776024/Pythonic | /24asyncio/2并发运行.py | 900 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/5/6 12:30
# @Author : xinfa.jiang
# @Site :
# @File : 2start.py
# @Software: PyCharm
import threading
import asyncio
import time
async def hello(n):
# 打印的currentThread是一样的,也就是自始自终就是一个线程在高
print('Hello world! (%s)' % threading.currentThrea... |
6ab468dc6d9364874608798e597e819875731892 | 425776024/Pythonic | /2.删除重复元素,保持顺序不变.py | 1,776 | 3.6875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Site :
# @File : 2.删除重复元素,保持顺序不变.py
def dedupe_iter(items):
seen = set()
for item in items:
if item not in seen:
yield item
seen.add(item)
a = [5, 5, 2, 1, 9, 1, 5, 10]
print(a)
print(list(dedupe_iter(a)))
it = dedupe_ite... |
16ac851a482a7c06c1a705cc1c73fcd8c543b555 | anudeeptreddy/ctci | /Ch4_Trees_And_Graphs/02_minimal_tree.py | 729 | 4.0625 | 4 |
def in_order(bst):
# in order traversal of a binary search tree
if not bst:
return
in_order(bst.left)
print bst.data
in_order(bst.right)
def minimal_height_bst(sorted_array):
if len(sorted_array) == 0:
return None
middle = len(sorted_array) // 2
left = minimal_height_b... |
923b8c5dcd7f3dfc8ccbb5b80fc1250edf141c84 | anudeeptreddy/ctci | /Ch3_Stacks_And_Queues/02_stack_min.py | 1,748 | 3.9375 | 4 |
class Node:
def __init__(self, value, min_val):
self.value = value
self.min_val = min_val
class MinStack:
def __init__(self):
self.items = []
self.min = None
def __str__(self):
return ' '.join([str(node.value) for node in self.items])
def push(self, item):
... |
bcdd34865c6780d422652fa822ca3ff818979217 | anudeeptreddy/ctci | /Ch2_Linked_Lists/02_kth_to_last.py | 818 | 3.875 | 4 | from LinkedList import LinkedList
def kth_element_recursion(current, position):
if current is None:
return 0, None
index, kth_value = kth_element_recursion(current.next, position)
index += 1
if index == position:
kth_value = current.value
return index, kth_value
def kth_element... |
afda6bccb0538ce637a4f94b62eb533c6a2401e3 | anudeeptreddy/ctci | /Ch2_Linked_Lists/08_loop_detection.py | 627 | 4 | 4 | from LinkedList import LinkedList
def loop_detection(ll):
fast = slow = ll.head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast is slow:
break
if fast is None or fast.next is None: # no loop
return None
slow = ll.head
while f... |
30f88d737655de27739242328675c6dd775421b3 | Nadeemk07/Python-Examples | /Arrays/rotation_sum.py | 762 | 4.03125 | 4 | '''Python program to find maximum value of Sum(i*arr[i])'''
# returns max possible value of Sum(i*arr[i])
def maxSum(arr):
# stores sum of arr[i]
arrSum = 0
# stores sum of i*arr[i]
currVal = 0
n = len(arr)
for i in range(0, n):
arrSum = arrSum + arr[i]
cu... |
9e43c6b0f91d8b46d8cb747266440460d1f4008b | Nadeemk07/Python-Examples | /Arrays/sort.py | 182 | 3.671875 | 4 | def combine_array():
arr1 = [1, 2, 3]
arr2 = [4, 5, 1]
final_array = arr1+arr2
print(final_array)
a = final_array.sort()
print(a)
combine_array()
|
855bf744bf1ad10b2cd99790bb30017ab64ae3b1 | Nadeemk07/Python-Examples | /Arrays/array_rotate.py | 546 | 3.890625 | 4 | # rotating element By d
def rotation(arr, n, d):
for i in range(0, d):
rotate_by_one(arr, n)
# rotating element one by one
def rotate_by_one(arr, n):
temp = arr[0]
for i in range(0, n-1):
arr[i] = arr[i+1]
arr[n-1] = temp
# Printing the rotated array
def rotate... |
cf38d3bf5f83a42c436e46a934f2557763ab0ff4 | utkarsht724/Pythonprograms | /Replacestring.py | 387 | 4.65625 | 5 | #program to replace USERNAME with any name in a string
import re
str= print("Hello USERNAME How are you?")
name=input("Enter the name you want to replace with USERNAME :") #taking input name from the user
str ="Hello USERNAME How are you?"
regex =re.compile("USERNAME")
str = regex.sub(name,str) #repla... |
f81f22047a6538e19c1ef847ef365609646ed2df | utkarsht724/Pythonprograms | /Harmonicno.py | 296 | 4.46875 | 4 | #program to display nth harmonic value
def Harmonic(Nth):
harmonic_no=1.00
for number in range (2,Nth+1): #iterate Nth+1 times from 2
harmonic_no += 1/number
print(harmonic_no)
#driver_code
Nth=int(input("enter the Nth term")) #to take Nth term from the user
print(Harmonic(Nth)) |
ad856fa96d1ea81585eb68df6b7398c2edec1625 | noelster/Pythonify | /111.py | 129 | 3.84375 | 4 | def pow(b, p):
y = b ** p
return y
def square(x):
a = pow(x, 2)
return a
n = 5
result = square(n)
print(result) |
5d353c9f31d56c0cca68e69d83735f2fce5190df | Manpreet-Bhatti/TicBlack | /Blackjack.py | 1,677 | 3.859375 | 4 | class Player(object):
def __init__(self, bank = 1000):
self.bank = bank
def addbet(self, bet):
self.bank += bet*2
def minusbet(self, bet):
self.bank -= bet
def __str__(self):
return "Your bank is currently at %x" %(self.bank)
game = Player()
game... |
0ac48d4f34a86f4cd2e279ac41c96d8f393a37d2 | joel99/GP_Titanic_Classifier | /primitives.py | 1,286 | 3.828125 | 4 | # Some place for primitives
# [bool, float, float] -> float
def if_then_else(input, output1, output2):
return output1 if input else output2
# [float, float] -> bool
def is_greater(input1, input2):
return input1 > input2
def is_equal_to(input1, input2):
return input1 == input2
def relu(input... |
8746ea471667d7ee618b23ffda91418bd80318b2 | ramthiagu/interviewcake | /exercise_3.py | 2,719 | 3.578125 | 4 | #!/usr/bin/env python
import unittest
import copy
def highest_product(array_of_ints):
new_array_of_ints = sort_array_of_ints(copy.deepcopy(array_of_ints))
if is_count_of_top_n_numbers_even(3,new_array_of_ints):
return reduce(lambda x,y: x * y, get_top_n_numbers(3,(new_array_of_ints)))
else:
... |
6727f7bfbdbc29109f02075fcd102ddebf658c14 | dinis-it/boilerplate-time-calculator | /time_calculator.py | 4,473 | 4 | 4 | def add_time(start, duration, startingDay = None):
splitList = start.split(':') # Aux list to store start time in tuple, time separated by hours and minutes + period
startInfo = (splitList[0], splitList[1].split()[0], splitList[1].split()[1]) # Tuple with (hours,minutes,period)
# print(startInfo)
addI... |
2ec335a44a4f6b50185252eebe8460c3d3f37c6f | KiloBravo77/python_code | /countdown_timer.py | 328 | 3.796875 | 4 | import time
timer_max = int(input("Set timer: "))
for x in range(timer_max):
print(str(timer_max - x))
time.sleep(1)
print("TIME IS UP!!!!!!!!!!!!!!!")
'''
print("5")
time.sleep(1)
print("4")
time.sleep(1)
print("3")
time.sleep(1)
print("2")
time.sleep(1)
print("1")
time.sleep(1)
print("BOOOOOOOOOOOM!!!!!!!!!!!!!... |
ceb136907c54a752da1c1be2944f25282b35b6d9 | KiloBravo77/python_code | /pig_latin.py | 741 | 3.984375 | 4 | print("Pig Latin Converter")
original = input("Enter a word: ")
if len(original) > 0 and original.isalpha():
word = original.lower()
first_letter = word[0]
second_letter = word[1]
if first_letter == 'a' or first_letter == 'e' or first_letter == 'i' or first_letter == 'o' or first_letter == 'u':
pig_word = word ... |
1ef034ef72b6b91ce392b889c10f4b7129996018 | jlat07/Python.ScientificCalculator | /calctests.py | 3,075 | 3.65625 | 4 | import unittest
from calculator import Calculator
class TestStringMethods(unittest.TestCase):
def test_add(self):
c = Calculator()
self.assertEqual(c.add(3, 3), 6)
def test_add2(self):
c = Calculator()
self.assertEqual(c.add(12, -10), 2)
def test_add3(self):
c = ... |
5b74b55cbc8f0145d125993fc7ac34702d8954f7 | rawatrs/rawatrs.github.io | /python/prob1.py | 819 | 4.15625 | 4 | sum = 0
for i in range(1,1000):
if (i % 15 == 0):
sum += i
elif (i % 3 == 0):
sum += i
elif (i % 5 == 0):
sum += i
print "Sum of all multiples of 3 or 5 below 1000 = {0}".format(sum)
'''
**** Consider using xrange rather than range:
range vs xrange
The range function creates a list containing numbers defin... |
bdf8ab8ce51fc3cc31505e0addbbf199084e8abb | kosigz/DiabetesPatientReadmissionClassifier | /classifier/znorm.py | 610 | 3.546875 | 4 | # decorator to z-normalize the input data of a functions
# input function arguments: self, X, Y
# output function arguments: self, X, Y, normalize
def znorm_dec(fn):
def znorm_fn(self, X, Y):
X, normalize = znorm(X)
return fn(self, X, Y, normalize)
return znorm_fn
# perform z-score normalizatio... |
6936a4fbce24ffa6be02883497224eb0fc6ad7e5 | nirmalshajup/Star | /Star.py | 518 | 4.5625 | 5 | # draw color filled star in turtle
import turtle
# creating turtle pen
t = turtle.Turtle()
# taking input for the side of the star
s = int(input("Enter the length of the side of the star: "))
# taking the input for the color
col = input("Enter the color name or hex value of color(# RRGGBB): ")
# set the ... |
71fb8c00547fb699029b1dae39b7cddcb5e7b2c7 | theetje/Twitter-Analyzer | /Analyzer/Classes/TweetAnalyzer.py | 841 | 3.5 | 4 | from datetime import datetime
class TweetAnalyzer(object):
"""docstring for [object Object]."""
""" Geef de datem terug vanuit een ms time. """
def getDateFromMSTime(timestamp_ms):
s = int(timestamp_ms) / 1000.0
return datetime.fromtimestamp(s)
""" Geef het sentiment van een tweet ter... |
9bf123a9cf95c8c258fef91e7a16d6cc9e639aff | jdavis24/guipw | /guipw/guipw.py | 879 | 3.8125 | 4 | #! /usr/bin/python3
from tkinter import *
root = Tk()
root.title('gui password test')
# initialize some variables needed below
namevar = StringVar()
passvar = StringVar()
displayvar = StringVar()
# create username/password labels and text boxes
label_name = Label(root, text='username:')
label_pass = Label(root, te... |
cd03b7b76bfb8c217c0a82b3d48321f8326cc017 | jnassula/calculator | /calculator.py | 1,555 | 4.3125 | 4 | def welcome():
print('Welcome to Python Calculator')
def calculate():
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for substraction
* for multiplication
/ for division
** for power
% for modulo
''')
number_1 = int... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.