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 |
|---|---|---|---|---|---|---|
40fd4aee03aaa67d0811ad9f362c103fb40fb50f | twaun95/Algorithm | /그리디/곱하기혹은더하기.py | 193 | 3.609375 | 4 | data = list(map(int,input()))
result = data[0]
for i in range(1,len(data)):
num = data[i]
if result<=1 or num<=1:
result += num
else:
result *= num
print(result)
|
a7f97299c2c26925c66034bbdfbc5ceafdfad854 | saurabhpsabnis/PythonSnippets | /backtracking.py | 774 | 3.65625 | 4 | '''
Created on May 10, 2016
@author: amolsaurabh
'''
def generateNbitStrings(n):
'''Generate all n bit binary strings for given n'''
if n == 0:
return []
if n == 1:
return ["0","1"]
return ["0" + x for x in generateNbitStrings(n-1)] + ["1" + x for x in generateNbitStrings(n-1)]
def... |
7aed9dbe1fca35c551cd6fe42feb2eedc9392d64 | Ashebir07/icpc-solution | /lastfactorial.py | 202 | 3.53125 | 4 | def fact(n):
if n==1:
return 1
return (n*fact(n-1))
a=int(input())
for i in range(a):
b=int(input())
if fact(b%10)>10:
print(0)
else:
print(fact(b%10))
|
989a6d7ca162987d02ae1f88f212e408c27edb07 | Ashebir07/icpc-solution | /planina.py | 59 | 3.578125 | 4 | x=2
for i in range(eval(input())):
x=2*x-1
print(x**2)
|
2989739805dac78138ec75bb65b536d02b290ff0 | Ashebir07/icpc-solution | /where.py | 183 | 3.5625 | 4 | n=int(input())
l=[]
for i in range(n):
t=int(input())
for i in range(t):
x=input()
l.append(set(x))
j=set(int(len(l)) for i in range(t))
print(j)
|
d01b9d736bb38bbbab5c1ba48137fdcc5b9ff9b2 | Ashebir07/icpc-solution | /lubricant.py | 308 | 3.6875 | 4 | n=int(input())
print("Lumberjacks:")
y=[]
yy=[]
for i in range(n):
l=[int(i) for i in input().split()]
l.sort()
y=l.sort(reverse=True)
for i in range(len(l)):
if l[i]<l[i+1]:
print("Ordered")
elif y[i]>y[i+1]:
print("Ordered")
else:
print("Unordered")
|
6389de3a76620a9c8d5097fa8f4455967932bf65 | Ashebir07/icpc-solution | /cute.py | 77 | 3.625 | 4 | v1,v2=(int (i) for i in input().split())
v=(2*v1*v2)/(v1+v2)
print("%.5f"%v)
|
3df0cf25150d812035182c53ce0eaa0b64b9d489 | janepeng/diary | /helper.py | 443 | 3.796875 | 4 |
def is_int(val):
try:
val = int(val)
return True
except (ValueError, TypeError):
return False
def format_date(date):
date = str(date)
if len(date) == 1:
date = '0' + date
return date
def print_dictionary(d):
print '{'
for date in d:
print date, ': '
for k in d[date]:
if ... |
b4f271e3a902188ce99905547ebcf43d52261f50 | niloy-biswas/OOP-Data-structure-Algorithm | /oop.py | 2,673 | 4.15625 | 4 | class Person:
def __init__(self, name: str, age: int, birth_year: int, gender=None):
self.name = name # Person has a name // has a relation with instance
self.__age = age
self.__birth_year = birth_year # Private variable / Data encapsulation
self.gender = gender
def get_name(s... |
6d55d7a3a5e2830825f12102666e40424c47ceee | ngilles/adventofcode-2017 | /day-03/spiral_memory.py | 1,261 | 3.65625 | 4 |
import math
def spiral_position(n):
ring = math.ceil((math.sqrt(n) - 1)/2)
side = 2 * ring + 1
max_value = side ** 2
v = n * 4 // max_value % 4
if n < max_value - 3 * (side - 1):
return (ring, n - (max_value - ring - 3 * 2 * ring))
elif n < max_value - 2 * (side - 1):
return ... |
c5eb6785b7e2a7175363a53e50d221d910344097 | Dimas4/Algorithms-Python | /Dynamic programming/max_sequence_in_2_arrays.py | 412 | 3.625 | 4 | def max_sequence(A1, A2):
F = [[0 for _ in range(len(A2)+1)] for _ in range(len(A1)+1)]
for i in range(1, len(A1)+1):
for j in range(1, len(A2)+1):
if A1[i-1] == A2[j-1]:
F[i][j] = 1 + F[i-1][j-1]
else:
F[i][j] = max(F[i-1][j], F[i][j-1])
retur... |
2819afd9f57e0f47f463f46ae062e83debb36495 | Dimas4/Algorithms-Python | /Sorting algorithms/bubble_sort_1.py | 947 | 4.0625 | 4 | import unittest
def bubble_sort(array):
"""
It compares 2 elements in an array and moves them if it's needed
"""
n = len(array)
for i in range(n):
for j in range(n - i - 1):
if array[j] > array[j + 1]:
array[j], array[j + 1] = array[j + 1], array[j]
class Test... |
314aec8f7c4240004929eedf68216f98b7f5d289 | FlorianRoudaut/BetQuotes | /DataModel/bet.py | 339 | 3.5625 | 4 | """Module of the bet class"""
class Bet:
"""Domain model for a type of bet, on a specific game"""
def __init__(self, game, event):
self.betid = -1
self.game = game
self.event = event
def to_string(self):
"""Domain model for a type of bet"""
return self.game.toStrin... |
2c758cd5b6825ae199112690ac55dc7e229f782d | ritopa08/Data-Structure | /array_rev.py | 867 | 4.375 | 4 | '''-----Arrays - DS: An array is a type of data structure that stores elements of the same type in a contiguous block of memory. In an array, , of size , each memory location has some unique index, (where ), that can be referenced as (you may also see it written as ).
Given an array, , of integers, print each ele... |
c88143eec87a374f9b504a7c08299b8d0a6ec1b6 | 10-15-5/TrainingAttendance | /attendance.py | 685 | 3.6875 | 4 | import csv
from tkinter import *
import tkinter.messagebox as tm
import os
root = Tk()
def welcomescreen():
root.title('Welcome!')
fr = Frame(root)
message = "Welcome the hurling attendance program!\nThis program is still under construction but please" \
" enjoy it in it's current state.\n... |
1bbdc7e6b9122bb96c9465535306c279c3601a77 | mithleshkr/testprime | /primenumber.py | 278 | 3.90625 | 4 | a=int(input("Enter start number "))
b=int(input("Enter last number "))
prime=[]
for num in range(a,b+1):
fact=0
for c in range(2,num):
if num %c==0:
fact=1
break
if fact==0:
prime.append(num)
print("prime numbers are ",prime)
|
0039dcb880b9574fad5526960d516ced50d48da2 | matchallenges/Portfolio | /2021/PythonScripts/intro.py | 183 | 3.875 | 4 | #for loop
for i in range(10):
print("Wow")
'''
multi-line
comment
'''
country = "Canada"
if(country == "Canada"):
print("Hello, Canada")
else:
print("Hello, America") |
b2eccf1a8b26d9242ea2d0d993f5c4f4bbb0babd | matchallenges/Portfolio | /2021/PythonScripts/inheritance.py | 472 | 3.890625 | 4 | class Adult():
def __init__(self, name, height, weight, eye_color):
self.name = name
self.height = height
self.weight = weight
self.eye_color = eye_color
def print_name(self):
print(self.name)
class Kid(Adult):
def add(self, x, y):
return x + y
a... |
3e0c54798996388e56ff161fb7023a022777de1b | manojkumar0405/pyhton-assignment-letsupgrade | /Day-6 ASSIGNMENT.py | 315 | 3.59375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[26]:
alist = [1,2,3,4,5,6,7,8]
blist = ["a","b","c","d","e"]
print (list(zip(alist,blist)))
# In[25]:
alist=[0,1,2,10,4,1,0,56,2,0,1,3,0,56,0,4]
alist.sort(key=,reverse=56)
print(alist)
# In[10]:
alist
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
|
f3309b629cee48cee3a17c8e9c8c11c609c89975 | chaubeau/Python | /Study/2day/cal.py | 1,502 | 3.59375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#
# Date: 2014-03-12 09:34:27
#
# Copyright 2014 chaubeau <chaubeau01@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either versio... |
f49de136755b368bef89b13037fd9aa3119a544e | tarasssov/python-learning | /lesson4_easy.py | 1,437 | 3.703125 | 4 | # Все задачи текущего блока решите с помощью генераторов списков!
# Задание-1:
# Дан список, заполненный произвольными целыми числами.
# Получить новый список, элементы которого будут
# квадратами элементов исходного списка
# [1, 2, 4, 0] --> [1, 4, 16, 0]
a = [1,2,3,4]
b = [_ ** 2 for _ in a]
print(b)
# Задание-2:
... |
c7c11df614d2ea7e58c3e30cd30ce0ca24149d5b | tarasssov/python-learning | /lesson2_hard.py | 4,882 | 3.875 | 4 | # Задание-1: уравнение прямой вида y = kx + b задано в виде строки.
# Определить координату y точки с заданной координатой x.
equation = 'y = -12x + 11111140.2121'
x = 2.5
# вычислите и выведите y
result = -12 * float(x) + 11111140.2121
print('при х = ', x, 'уравнение:', equation, '=', result)
# Задание-2: Дата... |
4c96b0fb13c9675631b3e8b10f015dac606d15ea | jmontara/Purchase-Guidance-from-Quickbooks-report | /functions/itemStatsFxns.py | 10,427 | 3.53125 | 4 | # itemStatsFxns.py
import datetime
import classes.itemStats
def total(transactions, dateStart, dateEnd):
"""
returns the sum of quantities in transactions that
occur on dateStart, on dateEnd, and between
dateStart and dateEnd.
Inputs:
transactions - list, list of transaction objects
dateStart - datetime.dat... |
4e003805486ab37a91cfe62cc6b86519f7d70e5d | Sept23/LeetCode_python | /Easy/35_searchInsertPosition.py | 315 | 3.640625 | 4 | def searchInsert(nums=[1,3,5,6], target=2):
key = None
if target in nums:
key = nums.index(target)
else:
for k, v in enumerate(nums):
if target < v:
key = k
break
if key == None:
key = len(nums)
return key
print(searchInsert()) |
6d30ea6b16928b1c59bb67beae358d1e6526eac0 | Sept23/LeetCode_python | /Easy/88_MergeSortedArray.py | 364 | 3.890625 | 4 | def merge(nums1=[1,2,3,0,0,0], m=3, nums2=[2,5,6], n=3):
"""
Do not return anything, modify nums1 in-place instead.
"""
L=nums1[:m]+nums2
L.sort()
for i in range(m+n):
nums1[i]=L[i]
# for i in range(m, m + n):
# nums1[i] = nums2[i - m]
# nums1 = nums1[:m + n]
# nums1... |
17fe4092766a15ed20c100c9ed66a2b9487341c3 | Sept23/LeetCode_python | /Easy/283_moveZeroes.py | 372 | 3.671875 | 4 | def moveZeroes(nums=[0,1,0,3,12]):
"""
Do not return anything, modify nums in-place instead.
"""
for i in range(len(nums)-1):
if nums[i] == 0:
for j in range(i + 1, len(nums)):
if nums[j]!=0:
nums[i]=nums[j]
nums[j]=0
... |
a87621ac4cb9c506b514ee5c6f69796330c92237 | pratibashan/Day4_Assignments | /factorial.py | 261 | 4.25 | 4 |
#Finding a factorial of a given no.
user_number =int(input("Enter a number to find the factorial value: "))
factorial = 1
for index in range(1,(user_number+1)):
factorial *= index
print (f"The factorial value of a given number is {factorial}") |
7bf3f58d0dd2cb9688ae24218c294a404838e933 | Hernandezjose2000/PARCIAL_FINAL_ALGORITMOS_1 | /107411 - Hernandez, Jose - E1.py | 6,729 | 3.875 | 4 | import csv
def menu() ->int:
opciones = ["Procesar archivos","Agregar o eliminar un gasto al archivo gasto.csv",
"Cantidad de dinero recaudado","Top 3 productos mas comprados",
"Reporte de porcentaje por de cada gasto sobre el total", "Incidencia en porcentaje de cada articulo"]
... |
82b6d1f999bc334e0f39277c4b2b1bc76e49e566 | ppbarros/Prova1 | /Questão 4.py | 330 | 3.65625 | 4 | m2 = float(input('Qla a área (m²) a ser pintada? '))
preco = 80
cobertura = 3 * 18
qnt = None
if m2 % cobertura == 0:
qnt = m2 // cobertura
else:
qnt = (m2 // cobertura) + 1
print(f'''Você precisará de {qnt} latas de tinta para cobrir uma área de {m2}m².
O custo total da compra será de R$ {(preco * qnt):.2f}''... |
91ba52102754411fdc4746c88f0c6f51ff6ab5a0 | milanll/python | /py_code/test/compute_E.py | 301 | 3.984375 | 4 | # -*- coding: UTF-8 -*-
import sys
import math
def factorial_(n):
a = 1
for n in range(1, n + 1):
a *= n
return a
for n in range(1, int(sys.argv[1])):
a = 1/n
b = 1 + a
c = b ** n
print (c)
m = int(sys.argv[2])
print(m," factorial is ",factorial_(m))
la = [1, 2, 3]
la[1] = 1
print(la)
|
f8e304d994f16939c6df1921ffd01e21b71eb0d2 | Sean-Kimchi/Python-2-Tesla-Stock-APL-2020-Spring | /Practice for pandas plotting.py | 1,068 | 3.875 | 4 | import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import matplotlib.dates as mdates
from matplotlib.ticker import (MultipleLocator)
'''Making a dataframe and plotting dummy integer data by converting the data
with pandas dataframe'''
##
##data= {'Date': [5, 10, 15, 20],
## 'Price': [10, 1... |
e9b8c15882e6e1c7c26201e4f4e2e065a43c235a | the-vampiire/google_foobar | /level_2/lovely_lucky_LAMBS.py | 7,386 | 3.515625 | 4 | def answer(total_lambs):
if total_lambs < 10 or total_lambs > 1000000000: return 0 # Because Googal lied to me :[
def distributor(generous):
henchman_minus_2_payout = 1
henchman_minus_1_payout = 2 if generous else 1
paid_henchman_count = 2
remaining_LAMBs = total_lambs - henchman_minus_2_payout - he... |
fa80200026d438f2575f4adcceb56d250e86d4f6 | StGalya/prog_Stupnikova | /черепашка/prog9.py | 321 | 3.953125 | 4 | import turtle
turtle.shape('turtle')
n=3
x=15
turtle.left(30)
for i in range (10):
for j in range (n):
turtle.right(360/n)
turtle.forward(x)
turtle.penup()
turtle.right(180/n)
turtle.forward(5)
turtle.pendown()
n=n+1
x=x+10
turtle.left(180-180/n)... |
35b6e1380999fc48bcaa69194fdd0dcf5195c22e | jacprez/developers.institute | /Week 4/Day 1/Exercise XP/xp.py | 438 | 4.03125 | 4 | # Exercise 1
print("Hello world\n" * 5)
# Exercise 2
print((99^3) * 8)
# Exercise 3
name = "Jackie"
age = 24
shoe_size = 9
info = "My name is " + name + " and I am " + str(age) + " years old with a size " + str(shoe_size) + " shoe."
print(info)
# Exercise 4
computer = 'mac'
print("My computer is a " + computer)... |
4038d2dc54db044cb9af82dc56bd1719f2af916e | jacprez/developers.institute | /Week 4/Day 2/Exercise XP Gold/xpgold.py | 1,236 | 4.09375 | 4 | # Exercise 1
# Take three numbers from the user and print the greatest number.
# number1 = float(input("Enter your first number: "))
# number2 = float(input("Enter your second number: "))
# number3 = float(input("Enter your third number: "))
# if (number1 > number2) and (number1 > number3):
# largest = number1
# e... |
6fdbb097525acbcb0397a79f1e4fbdf0dc09c569 | wccgoog/pass | /python/time_exercise.py | 968 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 25 19:23:24 2018
@author: wccgo
"""
import datetime
def get_weekday():
t=datetime.datetime.now()
print('今天是',t.strftime('%A'))
#get_weekday()
def get_age():
byear=int(input('输入年份'))
bmon=int(input('月份'))
bday=int(input('日'))
birth=datetime.... |
749ee70b6299dc89f02a41903e3dd4dbe61679fa | wccgoog/pass | /python/printover.py | 118 | 3.921875 | 4 | from is_tri import is_tri
fin=open('words.txt')
for line in fin:
word=line.strip()
if is_tri(word):
print(word) |
80a3bc2e57aa3646506b821e8b1f979e7ea418e5 | wccgoog/pass | /python/eval_loop.py | 182 | 4 | 4 | import math
def eval_loop():
print('如果要终止请输入done')
while True:
x=input('输入算式')
if x=='done':
print('已结束')
break
print(eval(x))
eval_loop() |
2f22b0d983274ab8f9ec329f8b2c7c97988f4fc1 | wccgoog/pass | /python/binomial.py | 243 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 28 16:12:16 2018
@author: wccgo
"""
d={}
def binomial_coeff(n,k):
if k==0:
return 1
return 0 if n==0 else binomial_coeff(n-1,k)+binomial_coeff(n-1,k-1)
print(binomial_coeff(3,2)) |
90c45b7457e3faefe0800c2805879f1c0ce1e692 | wccgoog/pass | /python/learn_threading.py | 1,557 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 11 14:53:08 2018
@author: wccgo
"""
#import threading,time
#count=0
#class Counter(threading.Thread):
# def __init__(self,lock,threadName):
# super(Counter,self).__init__(name=threadName)
# self.lock=lock
# def run(self):
# global count
# ... |
df2530786f8b833d84fc2bcdcb3e345634f25705 | AfkZa4aem/snake_game | /score.py | 692 | 3.640625 | 4 | from turtle import Turtle
ALIGNMENT = "center"
FONT = ("Courier", 14, "normal")
class Score(Turtle):
def __init__(self):
super().__init__()
self.color("white")
self.speed("fastest")
self.penup()
self.ht()
self.goto(0, 280)
self.current_score =... |
7ca2e7df05ff4b356476d4355c2d025826dff1f7 | lesliehwu/scaling-chainsaw | /dic_tuple.py | 271 | 3.625 | 4 | def dic_tuple(dic):
my_list = []
for keys,peeles in dic.iteritems():
my_list.append(tuple([keys] + [peeles]))
print my_list
my_dict = {
"Speros": "(555) 555-5555",
"Michael": "(999) 999-9999",
"Jay": "(777) 777-7777"
}
dic_tuple(my_dict)
|
6671ca404f704cf143d719c60f030eddf9a48b8d | vasudhanapa/Assignment-2 | /assignment 2.py | 750 | 4.40625 | 4 | #!/usr/bin/env python
# coding: utf-8
# 1. Write a program which accepts a sequence of comma-separated numbers from console and generate a list.
# 1. Create the below pattern using nested for loop in Python.
# *
# * *
# * * *
# * * * *
# * * * * *
# * * * *
# * * *
# * *
# *
#
# In[1]:
num1 = 1
num2 = ... |
9709680af1eeef88c1b8472142c5f85b9003114c | AmitAps/advance-python | /generators/generator7.py | 860 | 4.5 | 4 | """
Understanding the Python Yield Statement.
"""
def multi_yield():
yield_str = "This will print the first string"
yield yield_str
yield_str = "This will print the second string"
yield yield_str
multi_obj = iter(multi_yield())
while True:
try:
prt = next(multi_obj)
print(prt)
... |
9f311f33adbc0a2fb31ffc1adb014bb66de0fb2b | AmitAps/advance-python | /oop/class2.py | 337 | 4.15625 | 4 | class Dog:
#class attribute
species = 'Canis familiaris'
def __init__(self, name, age):
self.name = name
self.age = age
"""
Use class attributes to define properties that should have the same value for every class instance. Use instance attributes for properties that vary from one
instance... |
42f8e41488f1de16d53ced9f76053374fe5ce4a3 | AmitAps/advance-python | /instance_class_and_static_method/fourth_class.py | 1,073 | 4.15625 | 4 | import math
class Pizza:
def __init__(self, radius, ingredients):
self.radius = radius
self.ingredients = ingredients
def __repr__(self):
return (f'Pizza({self.radius!r}, '
f'{self.ingredients!r})')
def area(self):
return self.circle_area(self.radius)
... |
a4a9466ca29261aff4264cd4d2c565df7c19a0fa | AmitAps/advance-python | /dog-park-example.py | 703 | 4.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 22 09:25:55 2020
@author: aps
"""
class Dog:
species = "Canis familiaris"
def __init__(self, name, age, breed):
self.name = name
self.age = age
self.breed = breed
# Another instance method
def speak(se... |
7bf88c9c4c7e46de1f6994ae21071625a1afc957 | AmitAps/advance-python | /instance_class_and_static_method/first_example.py | 3,327 | 4.25 | 4 | class MyClass:
def method(self):
return 'instance method called', self
@classmethod
def classmethod(cls):
return 'class method called', cls
@staticmethod
def staticmethod():
return 'static method called'
"""
//Instance Methods
Through the self parameter, instance methods ... |
5e7563c7118bcf9e680da9f74ffca3db71245f5f | AmitAps/advance-python | /generators/generator1.py | 242 | 3.984375 | 4 | """
Building Generators With Generator Expressions
"""
nums_squared_lc = [num ** 2 for num in range(5)] #list comprehension
nums_squared_gc = (num ** 2 for num in range(5)) #generator expression
print(nums_squared_lc)
print(nums_squared_gc)
|
11925d4a5c3e11e6f84e4ef7cffdd03fe7d9146b | AmitAps/advance-python | /time_example.py | 188 | 3.71875 | 4 | import time
start = time.time()
for i in range(20):
print(i)
time.sleep(1) #Sleep for 1 second
end = time.time()
print(f"Time needed to excuted this code is {end - start} seconds!")
|
734b35ffe9322cfdd903c69c4a87a0933611f33c | AlexeyLz/BSUIR-PYTHON-2020 | /Solutions/Task2/class_vector.py | 4,707 | 3.625 | 4 |
class Vector(object):
def __init__(self, size, *user_coordinates):
self.size = int(size)
self.coordinates = []
for index in range(size):
self.coordinates.append(int(user_coordinates[0][index]))
def __add__(self, other):
sum_coordinates = []
for ind... |
cc454d3df76cec4560bd8bde67f70ebabbfe1ef4 | Ayselin/python | /restaurant.py | 1,586 | 4.0625 | 4 | class Restaurant:
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.served_customers = 0
def describe_restaurant(self):
print(f"{self.restaurant_name} is {self.cuisine_type} restaurant!")
... |
c977f10079c4c36333dfc1b33635945b2e469c29 | Ayselin/python | /candy_store.py | 1,014 | 4.125 | 4 | candies = {
'gummy worms': 30,
'gum': 40,
'chocolate bars': 50,
'licorice': 60,
'lollipops': 20,
}
message = input("Enter the number of the option you want to check?: \n1. To check the stock. \n2. How many candies have you sold? \n3. Shipment of new stock.")
if message == '1':
for candy, ... |
ee7b4538572736d597f645980ae114c19a3e55e9 | Ayselin/python | /dictionary.py | 2,304 | 3.78125 | 4 | # admin = {
# 'first_name': 'Kevin',
# 'last_name': 'Olu',
# 'age': 20,
# 'cily': 'London',
# }
# admin_name = admin['first_name']
# print(admin_name)
# favorite_numbers = {
# 'alice': 3,
# 'nick': 4,
# 'jeff': 8,
# }
# number = favorite_numbers['nick']
# print(f"Nick's favorite number ... |
772111b2c01f8bb109176bf9980275f359b33632 | Ayselin/python | /die.py | 813 | 3.796875 | 4 | from random import randint
class Die:
def __init__(self, sides):
self.sides = sides
def roll_die(self):
return randint(1,self.sides)
# append 1 side randomly, 10 times
def roll(sides):
die = Die(sides) # initializes Die with a number of sides
# results = [] # empty list to ... |
49efddfae97fc592a956e3061f3e6dbdf1ed5e5c | alfi1998/Kita-Data | /kak_sarah/custom.py | 5,912 | 3.578125 | 4 | from random import randint,sample,random
import numpy
class Board:
def __init__(self, rows, columns):
self.rows = rows
self.columns = columns
self.squares = [['00'] * columns for i in range(rows)]
def __repr__(self):
print('Step di papan : ')
for i in range(self.rows):
print(self.squares[i])
class T... |
db9458a583e814f45227c0befb35ea86efdd1b4c | BelovVladimirO/tms-python-z14-onl | /src/task_1_5.py | 239 | 4.03125 | 4 | #Даны катеты прямоугольного треугольника. Найти его гипотенузу и
#площадь.
import math
a = 8
b = 15
d = (a * a) + (b * b)
sqrt = math.sqrt(d)
s = a * b // 2
print(int(sqrt), s)
|
f163e2237ef880da4a7e215de93a16bc4e5d46f9 | twilio/twilio-python | /twilio/base/values.py | 280 | 3.8125 | 4 | from typing import Dict
unset = object()
def of(d: Dict[str, object]) -> Dict[str, object]:
"""
Remove unset values from a dict.
:param d: A dict to strip.
:return A dict with unset values removed.
"""
return {k: v for k, v in d.items() if v != unset}
|
39c75c9097f0181b97baba9373fcdb6c74e0f6c2 | schaffer2013/Smart_rockets | /rocket.py | 4,526 | 4.25 | 4 | import numpy as np
class Vector:
""" implementation of Eucledian vector"""
def __init__(self, x=0.0, y=0.0):
self.x = x
self.y = y
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Vector(x, y)
def __str__(self):
return "(" + ... |
6bb125d7a5dc19ea920103b2164e59a44cc3093e | gavinrbrown1/algorithm_scratchpad | /binary_search.py | 268 | 3.75 | 4 | def binary_search(A, x):
A.sort()
lo = 0
hi = len(A) - 1
while hi >= lo:
guess = (lo + hi) // 2
if A[guess] == x:
return(guess)
elif A[guess] > x:
hi = guess - 1
else:
lo = guess + 1
|
0aa22e10cd0e400ed807803c1ad939ec5890640a | SadSack963/day-17-quiz | /quiz_brain.py | 1,118 | 3.75 | 4 | class QuizBrain:
def __init__(self, q_list):
self.question_number = 0
self.question_list = q_list
self.score = 0
def next_question(self):
current_question = self.question_list[self.question_number] # Get the current question
self.question_number += 1 # Get ready for th... |
a7845ce6cd67a95ae8069bb5d06be44fcd82afad | shivaniofficial/hello-git | /Assignment-4.py | 1,431 | 4.09375 | 4 | # Assignment-4
from collections import Counter
# tuple with different data types
tpl_1 = ("Python", True, 3.8, 5)
#length of tuple :
print(len(tpl_1))
#maximum element of tuple
print(max(tpl_1))
#minimum elememt of tuple
print(min(tpl_1))
#product of tuple
tpl_2 = (5,8,6.2,8,7)
result = 1
for x in tpl_2:
result ... |
1788d7fb0349eebc05ab37f91754b18e6ce66b3f | SeshaSusmitha/Data-Structures-and-Algorithms-in-Python | /SelectionSort/selection-sort.py | 423 | 4.3125 | 4 | def insertionSort(array1,length):
for i in range(0, length ):
min_pos = i;
for j in range(i+1, length):
if array1[j] < array1[min_pos]:
min_pos = j;
temp = array1[i];
array1[i] = array1[min_pos];
array1[min_pos] = temp;
array1 = [2, 7, 4, 1, 5, 3];
print "Array before Selection sort"
print(array1);... |
ede9bebe83e749f417919cd127c8c39490747b35 | freugit/project1 | /OOP/04.py | 654 | 3.703125 | 4 | #构造函数的概念
class Animal():
pass
class PaxingAni(Animal):
def __init__(self):
print("PaXing DongWu")
class Dog(PaxingAni):
#__init__就是构造函数
#每次实例化的时候,第一个被自动的调用
#因为主要工作是进行初始化,所以得名
def __init__(self):
print("I am init a dog")
class Cat(PaxingAni):
pass
#实例化的时候,自动调用了Dog的构造函数
#因为找到了... |
0ed3a7365b821bf9d1ad642bd80c4350cdcc7222 | freugit/project1 | /spider/v4.py | 1,425 | 3.671875 | 4 | """
利用parse模块模拟post请求
分析百度词典
分析步骤:
1.打开F12
2.尝试输入单词girl,发现每敲一个字母都有请求
3.请求地址是http://fanyi.baidu.com/sug
4.利用NetWrok-All-Headers,查看发现FormData的值是:kw:girl
5.检查返回内容格式,发现返回的是json格式内容==>需要用到json包
...
"""
from urllib import request,parse
import json
"""
大致流程是:
1.利用data构造内容,然后urlopen打开
2.返回一个json格式的结构
3.结果就应该是girl的释义
"""
baseu... |
e20c174a2573c3c3ff163a70205f6d861c36ecd8 | awassbu/lab6-1 | /skeleton_habituationGWR.py | 2,927 | 3.734375 | 4 | # Based on Tom Anastasio's habituationGWR.m
# this script sets up a very simple simulation of habituation
# of the Aplysia gill withdrawal reflex
#
# Modified for BU's RISE Practicum Comp Neuro lab by mbezaire@bu.edu
###############################
# import libraries with special
# functions needed in ... |
bda9f8852bc4023da711d7375337f0fe6d3359aa | naitisb/MobileAttentionManifold | /unzipFile.py | 992 | 3.71875 | 4 | from zipfile import ZipFile
from urllib.request import urlopen
import pandas as pd
import os
def download_url(url, save_path):
with urlopen(url) as dl_file:
with open(save_path, 'wb') as out_file:
out_file.write(dl_file.read())
URL = 'https://datasets.d2.mpi-inf.mpg.de/MobileHCI2018/MPIIMobile... |
a0e592c0c4816d5ae930ea94aa4d097473674876 | litao-Albert/spider | /学神1809/lianxi/Deom01.py | 1,180 | 3.609375 | 4 | # def in_fo(a):
# if type(a)==int:
# print(a+1)
# if type(a)==str:
# print(a+'1')
# if type(a)==list:
# a.append(1)
# return a
#
# print(in_fo([1,2]))
# total=0
# def sum (arg1,arg2):
# total=arg1+arg2
# print('函数内是局部变量',total)
# return total
# #globals(total)
# s... |
5a986256a2c6c243ce0ad9e3074304c792e965e4 | litao-Albert/spider | /学神1809/MD5加密/Test01.py | 860 | 3.875 | 4 | import hashlib
user = {
"username":"admin",
"password":"123456"
}
name = input("请输入用户;")
print(user["username"]== name)
print(user["password"])
# class Test_login(object):
#
# def __init__(self ,username,password):
# self.username = username
# self.password = password
# def login(self):
... |
63acc30a81446b5cd7d648c974971d8e3e359aad | litao-Albert/spider | /学神1809/异常/Test1.py | 1,039 | 3.640625 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
# author:黎涛
# datetime:2018/10/16 22:34
# software:PyCharm Community Edition
class MyException(Exception):
def __init__(self,length,atleast):
super().__init__()
self.length = length
self.atleast = atleast
try:
nam = 10
# open('1.txt','r',... |
7b894a68f9368e2f0e318cc3fce947d22048117f | litao-Albert/spider | /学神1809/lianxi/基础练习.py | 2,012 | 3.546875 | 4 | #打印九九乘法表
# for i in range(1,10):
# for j in range(1,i+1):
# print('%d * %d=%d\t'%(j,i,j*i),end='')
# print('\n')
# for i in range(0,10,3):
# print(i)
#水仙花树
"""for i in range(100,1000):
a=i%10
b=i//10%10
c=i//100)
if a**3+b**3+c**3==i:
print(i)
"""
#排序
li=[3,65,22,102,4]
# li.... |
580d2e7abead3862dae17143c1e36fbe288e89eb | litao-Albert/spider | /学神1809/作业/study.py | 8,579 | 4.15625 | 4 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
# author:黎涛
# datetime:2018/10/19 10:20
# software:PyCharm Community Edition
#1. 编程实现对一个元素全为数字的列表,求最大值、最小值
# 1.编程实现对一个元素全为数字的列表,求最大值、最小值
class Dister(object):
def __init__(self,list1):
self.list1=list1
def Max(self):
max = self.list1[0]
for i ... |
95d0466dc9606760166f6d5c5126bb4b2a263d4d | litao-Albert/spider | /2017_10_11_线程通信/_thread_/Dome01.py | 1,535 | 3.671875 | 4 |
# def loop():
# print('thread %s is runing...'%(threading.current_thread().name))
# for i in range(5):
# print('thread %s >>>%s'%(threading.current_thread().name,i))
# print('thread %s is runing...'%threading.current_thread().name)
# t=threading.Thread(target=loop)
# t.start()
... |
08b4ce27209260274f5f89c2d728d6ad8fe2ab3b | litao-Albert/spider | /学神1809/lianxi/D.py | 1,955 | 3.75 | 4 | # 1.有一对兔子从出生后3月起一个月生一对小兔子,小兔子长到
# 第三个月后每个月又生一对兔子,假如兔子都不死,问每个月
# 的兔子总数是多少
# class Rb:
# month=1
# def group(self): #兔子的年龄,每调用一次
# self.month+=1
# def bir(self,a):#每调用一次就让当前这对兔子生小兔子
# a.append(Rb())
# class count():
# list=[Rb()] #生成一个笼子,并放入一对兔子
# def add_num(self):
# for i in ... |
4b414735cbd1563ac59a6598279f7a4863723828 | zaidITpro/PythonPrograms | /inseritonanddeletionlinklist.py | 1,106 | 4.15625 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def insert(self,data):
if(self.head==None):
self.head=Node(data)
else:
current=self.head
while(current.next!=None):
current=current.next
current.next=Node(data)
d... |
c331146f00f42f2182254e5ab7e09a01421cf0ec | riguee/movie_diversity | /outputcsv.py | 6,247 | 3.59375 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import pylab
import sys
country = sys.argv[1] #look into a country's folder
input_file = int(sys.argv[2]) #most recent your to start from
rangepup = int(sys.argv[3]) #looks through the number of files that's input
list = ("white", "black", "hispanic", ... |
8c8fbf39da5aa6c0e269e1396b4a3bda441e9e85 | CristinaMelicio/AIDS | /Projeto2/biblio.py | 10,109 | 4 | 4 | connectors = ['not','and','or','=>','<=>']
import sys
# ------------------------------------------------------------
# This part is relevant to work with sentences not yet converted to
# CNF format
def IsSentenceValid(sentence):
""" Check if sentence is valid, still needs to be improved"""
# if sentence h... |
c21695503b37f35c76a49c2f090b5818c13315b6 | Qui-Gon-Jin/Archivist | /resizer.py | 525 | 3.5625 | 4 | from PIL import Image
import os
def Resize(file, path):
file_path = path + "/" + file
print(file_path)
image = Image.open(file_path)
image = image.convert('RGB')
image = image.save(path + "/" + file.split(".")[0] + ".jpg", quality=80)
if file.split(".")[1] != "jpg":
os.remove(file_path)
#
#image.... |
4d01a87c54c37c0953c3d1b0677db4ad1ed9f314 | RSerzh/python_algorithms | /БыстраяСортировка.py | 1,063 | 3.796875 | 4 | from random import *
from time import time
import myFunc as myF
# Быстрая сортировка Хоара
def quick_sort( ms ):
if len(ms)>1:
pv = choice(ms)
left = [ x for x in ms if x < pv]
mid = [ x for x in ms if x == pv]
right = [ x for x in ms if x > pv]
return quick_sort(left) + mid... |
f63bdb1938b5e7811d1786e53c8ca799b40a3d43 | DavidHan008/lockdpwn | /python_archive/140611.py | 1,014 | 3.78125 | 4 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
'''
python ==>
'''
class Account(object):
num_accounts = 0
def __init__(self,name,balance):
self.name = name
self.balance = balance
Account.num_accounts += 1
def __del__(self):
Account.num_accounts -= 1
... |
8ae73c2432219386a1d3b270407ed0b1ede02b95 | Karin-Wang/test1 | /test.py | 669 | 3.515625 | 4 | # /Users/Kaering/PycharmProjects/test
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
led = 7
print("start....")
GPIO.setup(led, GPIO.OUT)
# GPIO.setup(led, GPIO.IN)
try:
while True:
GPIO.output(led, 1)
time.sleep(50)
# GPIO.output(led, 0)
# time.sleep(0.00001)
... |
54b83a023bcaa586e9ae79871966687184d79da1 | Catrina-Barth/go-team-livexpress | /liveexpress/blog/utils/filters.py | 412 | 3.75 | 4 | import re
def filter_hashtags(iterable):
# Filter strings from iterable and return only letters and numbers
# ignore other Chars
res = []
for string in iterable:
filter_string = "".join(re.split("[^a-zA-Z0-9]*", string))
res.append(filter_string)
return res
if __name__ == "__main_... |
88d351110e828bb6d093daecf7aaf032047dc307 | pjbautista/algorithms-python | /knapsack.py | 940 | 3.921875 | 4 | """
Solves the Knapsack problem
"""
def main():
""" Main function """
# Retrieves the items
items = []
f_input = open('knapsack_big.txt')
knapsack_size, _ = [int(x) for x in f_input.readline().strip().split()]
for line in f_input:
value, weight = [int(x) for x in line.strip().split... |
6b314c4169ed0c9c5e24bfa0a2aa1b8aee9d7b62 | Rrrapture/python-the-hard-way | /ex/ex11.py | 441 | 3.609375 | 4 | # exercise 11: Asking Questions
print "How old are you?",
age = raw_input()
print "How tall are you?",
height = raw_input()
print "How much do you weigh?",
weight = raw_input()
print "So, you're %r old, %r tall and %r heavy." %(
age, height, weight)
# Study drills:
# 1. research raw_input
# 2. What are other ways to... |
64ae84094c031ea4b449b8fb3529eed1332d75fb | Charles1990/awesome-practice | /think_python_price/c15.py | 505 | 3.90625 | 4 | # def sumall(*t):
# return sum(t)
# print(sumall(1,2,3,4,6))
import random
def sort_by_length(words):
t = []
for word in words:
t.append((len(word), random.random(), word))
t.sort(reverse=True)
res = []
for length, _, word in t:
res.append(word)
return res
... |
8c7baf32d06cae9adc49acf0bcbf932327527a49 | Charles1990/awesome-practice | /think_python_price/c3.py | 835 | 4.09375 | 4 | # def a(x):
# if x%2==0:
# print('x is even')
# else:
# print('x is odd')
# def a(x,y):
# if x==y:
# print ('他们相等')
# else:
# if x<y:
# print('X小于y')
# else:
# print('x大于y')
# a(3,3)
# def a(x):
# if 0<x:
# if x<10:
# ... |
e30118f55b1411f5a90d6b6be3843bb3c42aad0c | humyrx/Python-COP4045 | /A8/a8_chowdhuryh2016.py | 4,441 | 3.953125 | 4 | import math
# Driver program for A8 - COP 4045
class Shape(object):
def __init__(self, shape='Shape'):
self.shape = shape
self.perimeter = None
self.area = None
def __str__(self):
return "{} || Perimeter: {}\tArea: {}".format(self.shape, self.perimeter, self.area)
class Circ... |
f4f5d22648246c6d967a515238d119ece426f41e | fourBaekjoon/baekjoon | /src/taehoon/1717/1717.py | 637 | 3.609375 | 4 | n,m = input().split()
n,m = int(n),int(m)
union_set = []
for i in range(n+1):
union_set.append(i)
def find(idx):
if union_set[idx] == idx:
return idx
else:
union_set[idx] = find(union_set[idx])
return union_set[idx]
def union(a,b) :
a_temp = find(a)
b_temp = find(b)
if ... |
3deb9351f98b5bf2d62e7d48567a4ac1fb7276cb | JosephHughes14/pyWav | /Tools/good_code.py | 1,014 | 3.953125 | 4 | #This is an example of good code structure, dont worry if you dont understand all of it
#now, you will !
import time
from random import randint
class GenRandomNumber(object):
''' Random number generator class '''
def __init__(self, rand_range):
#initilisation class
self.min = ran... |
4f555e053d644d114fcc113c7deec2c476f9a053 | hatiferenc1/feltetelesutasitas | /utasitas2.py | 431 | 3.828125 | 4 | '''2 Készíts egy programot, ami bekér egy számot a felhasználótól, majd kiírja, hogy a megadott szám páros-e vagy páratlan!
[Tipp] A maradékos osztás segít! Mennyivel is kell elosztanod a számot maradékosan, hogy kiderüljön páros-e? Ebben az esetben mennyi lesz a maradék? '''
i = int(input('Adjon meg egy számot! '))
i... |
ad300bcfe400d0ed2ced74e064893bd2cdc4d5a8 | luiscarlossf/grafos | /Algoritmo de Dijkstra/filaprioritaria.py | 2,034 | 3.859375 | 4 | #File name: filaprioritaria.py
#Author: Luis Carlos <luiscarlos.sf@outlook.com>
class PriorityQueue:
def __init__(self):
self.fila = [(0,0)]
self.tamanho = 0
def getTamanho(self):
return self.tamanho
def find_min(self):
if self.tamanho != 0:
re... |
c239eddac5bd840e8c73c44e1da8e3c5e6e794ea | dxn19950918/dxn | /demo2.py | 542 | 4.125 | 4 | #循环语句:有规律切重复操作的语句
#列表
# a = [1,2,3,4]
# for i in a : # for 中的in不是判断
# print(i)
# #元组
# b = ("123",1,3,4)
# for i in b:
# print(i)
# #字符串变量
# c = "儿童节快乐"
# for i in c:
# print(i)
#字典
d = {"username":"张三","password":"123456"}
for i in d:
print(i) #i 第一次循环是username
#print(d[i]) #下标key值方式取值
prin... |
cbe8c49dc185902be53cb32a3a5166f29113fcea | kauttoj/text_classification | /Project/three_example_models_quid.py | 5,007 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
https://quid.com/feed/how-quid-uses-deep-learning-with-small-data
Created on Sat Oct 21 15:40:02 2017
@author: Jannek
"""
from sklearn.pipeline import FeatureUnion,Pipeline
def plot_vectors(data):
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
ts = TS... |
bcba01e9d34ba4f8ffda2a0663e892df10fc3f3d | leavesgreen/zi_cube | /lib/utils/udate.py | 6,072 | 3.5625 | 4 | # -*- coding: utf-8 -*-
import time,datetime
from dateutil import relativedelta
import ustr
#待处理
def is_date(str1):
try:
datetime.datetime.strptime(str1,'%Y-%m-%d')
return true
except Exception,e:
return false
def date_to_str(d1,fmt='%Y-%m-%d %H:%M:%S'):
str1 = "1900-01-01 00:00... |
203c81d28bdc6153e0ea7faf6a0730191ffaf1ed | BruceBannerr/Mcd_spil | /BoardGame.py | 10,205 | 3.640625 | 4 | """ McD-Game """
import arcade
import sys
import time
import random
SPRITE_SCALING = 0.5
SCREEN_WIDTH = 780
SCREEN_HEIGHT = 700
SCREEN_TITLE = "McD-Game"
MOVEMENT_SPEED = 5
TILE_SCALING = 0.5
COIN_SCALING = 0.5
PLAYER_SCALING = 0.3
WORKER_SCALING = 0.5
TABLE_SCALING = 1
EXIT_SCALING = 0.4
#BRUH
class Player... |
f350074a43aff2dbf487fd11e0261f3bd094d020 | Thomascript/Questoes---URI---Python | /2397.py | 969 | 3.546875 | 4 | A, B, C = map(int, input().split())
if(A < B and A < C and B < C):
a = C
b = B
c = A
elif(A < B and A < C and C < B):
a = B
b = C
c = A
elif(B < A and B < C and A < C):
a = C
b = A
c = B
elif(B < A and B < C and C < A):
a = A
b = C
c = B
elif(C < A and C < B and ... |
d792a413d799474cb718b10d772762bce06fdc85 | Thomascript/Questoes---URI---Python | /1546.py | 345 | 3.5 | 4 | k = int(input())
for i in range(k):
feed = int(input())
for j in range(feed):
feedbacks = int(input())
if(feedbacks == 1):
print("Rolien")
elif(feedbacks == 2):
print("Naej")
elif(feedbacks == 3):
print("Elehcim")
else:
... |
23ecb04726243da8aaee6833047d4983bb37d111 | Thomascript/Questoes---URI---Python | /1079.py | 194 | 3.6875 | 4 | n = int(input())
for i in range(n):
media = 0.0
num1, num2, num3 = map(float, input().split())
media = (num1 * 2 + num2 * 3 + num3 * 5) / 10.0
print("{0:.1f}".format(media)) |
a2ec1f57c9434991c56ac8fd96963854ac7cfb7b | Thomascript/Questoes---URI---Python | /1028.py | 237 | 3.6875 | 4 | def euclides(a, b):
if(b == 0):
return a
else:
return euclides(b, a % b)
N = int(input())
for i in range(N):
a, b = input().split()
a = int(a)
b = int(b)
print("{}".format(euclides(a, b))) |
730e407bab0de9a0fe50c1fc6c31057832c92486 | Thomascript/Questoes---URI---Python | /1279.py | 701 | 3.75 | 4 | pula = 0
while(1):
try:
ano = int(input())
b = 0
ord = 1
if(pula):
print("")
pula = 1
if(ano % 4 == 0 and ano % 100 != 0 or ano % 400 == 0):
print("This is leap year.")
b = 1
o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.