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 |
|---|---|---|---|---|---|---|
a0dce69e3e623f8660fc73312bb8c8008a0972d0 | KwanchanokC/doppio-camp | /python/camp3/tid_student_grading_2.py | 747 | 3.59375 | 4 | def grading_function (g_name, g_score):
if g_score >=80:
print(g_name,": Score = ",g_score, ", Grade = A")
elif g_score >=70 and g_score <80:
print(g_name,": Score = ",g_score, ", Grade = B")
elif g_score >=60 and g_score <70:
print(g_name,": Score = ",g_score, ", Grade = C")
eli... |
b75d94bd69d150821af4c4155c934e1bfde57190 | itshmnt/LeetCode-Solutions | /Python/Serialize_and_Deserialize_BST.py | 2,762 | 4.03125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string.
"""
# Need to construc... |
bd3403a348a2f4301bfc49de9e084be7f90ad437 | sanchezmaxar/ArtifitialIntelligenceCourse05 | /Busqueda/Astar.py | 951 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 2 12:39:57 2017
@author: stan
"""
import heapq
from utils import *
from puzzle import *
from manhattan import *
class Astar:
@staticmethod
def search(origen,stop,heuristica):
agenda = []
expandidos = set()
if stop(... |
655fc8bb7014e5e7f0d0c5078b0d1dfb106c99ba | Gash7/Assignment | /coolTrackAssignment.py | 1,588 | 4.09375 | 4 | listOfTweets = []#Holds Object in to list
count = 0#Count for num of User You want to add
class Tweet:
'''Tweet is Class For User Tweets with Arguments as testcase,tweets,username,tweet_id'''
def __init__(self,testcase,tweets,username,tweet_id):#
self.testCase = testcase#Instance Obj==Self.testcae
... |
52eebfdc16f0ec5c1f95ba49da7422c3cb607f0d | kamilabarrios/lps_consci | /class_samples/nacho_buyer.py | 348 | 3.953125 | 4 | print("how much does the nacho cost?"
nacho_price = str(raw_input())
print("how much money is in your pocket?"
cash = int(raw_input())
if nacho_price > cash:
print("Sorry, no nachos for you!")
if nacho_price <= cash:
print(Woot, nachos for you!)
if nacho_price == cash:
print("That sure was lucky")
print("Thanks f... |
0123f5b84e3efefc6b686006db5912a03513e64c | lephatsr23/pythonbasic | /password_picker.py | 976 | 3.671875 | 4 | import random
import string
adjectives = ['sleep', 'slow', 'smelly',
'wet', 'fat', 'red',
'orange', 'yellow', 'green',
'blue', 'purple', 'fluffy',
'white', 'proud', 'brave']
nouns = ['apple', 'dinosaur', 'ball'
'toaster', 'goat', 'dragon'
'hammer', 'duck','panda',]
last_name = ['truo... |
bd5e3b96ef1fe2d938e74434214b62cda03ce6fd | kekscode/trumpeltier | /analytics/nltk_sentiment.py | 775 | 3.578125 | 4 | #!/usr/bin/env python3
"""
This receives text from stdin and does a sentiment analysis on each line
"""
import sys
from nltk.sentiment.vader import SentimentIntensityAnalyzer
def read_lines_stdin():
lines = []
for line in sys.stdin:
lines.append(line)
[line.replace('\n', '') for line in lines]
... |
b67f11ccb509d1a08cce31f39b934cef5fe558bc | DanielKillenberger/AdventOfCode | /2020/day2/password.py | 399 | 3.53125 | 4 | with open("input.txt", "r") as input_file:
input = input_file.read().split("\n")
passwords = list(map(lambda line: [list(map(int, line.split(" ")[0].split("-"))), line.split(" ")[1][0], line.split(" ")[2]], input))
valid = 0
for password in passwords:
count_letter = password[2].count(password[1])
if pass... |
68b3154343fc89a011544cea84417475673c36e7 | mariam-farrukh/Sorting | /src/iterative_sorting/iterative_sorting.py | 1,391 | 3.9375 | 4 | # TO-DO: Complete the selection_sort() function below
def selection_sort( arr ):
# loop through n-1 elements
for i in range(0, len(arr) - 1):
current_i = i
smallest_i = current_i
# TO-DO: find next smallest element
# (hint, can do in 3 loc)
for x in range(current_i+1, l... |
bdef1fdbd1450a8f51dfcd48d290afbf279523b7 | Deyui/Art-Rewards-Project | /Access.py | 3,426 | 3.609375 | 4 | from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
#Get your GDrive Account automatically authenticated
gauth = GoogleAuth()
# Try to load saved client credentials
gauth.LoadCredentialsFile("mycreds.txt")
if gauth.credentials is None:
# Authenticate if they're not there
gauth.LocalWebser... |
4eb02e90ea8c76369d7af1b63053d1b8cb4a5fa6 | You-NeverKnow/Cracking-the-coding-interview | /2/2.5.py | 3,609 | 4.15625 | 4 | from Node import Node
# -----------------------------------------------------------------------------|
def main():
"""
"""
_list1 = Node().init_from_list([1, 2, 3])
_list2 = Node().init_from_list([9, 9, 2, 1])
# debug
print("123 + 921 = {}".format(123 + 9921))
#
# print(reverse(add(_... |
e4df4fefd7c1dcf62687de4a7ae1d3765e9c217a | You-NeverKnow/Cracking-the-coding-interview | /4/4.3.py | 1,817 | 3.796875 | 4 | from BinNode import get_binary_tree, BinNode
# -----------------------------------------------------------------------------|
def main():
"""
"""
sorted_array = sorted([1, 2, 3, 5, 621, 81, 23])
root = get_binary_tree(sorted_array)
print(root)
print(linked_list_depth(root))
print(linked... |
34f8cde6eec29f80603504d8e4d988d1b2ecb3ea | tiendungitd/Learn-Python | /CoffeeMachine/main.py | 2,377 | 3.9375 | 4 | MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"cappuccino": {
... |
ac2cf51a5561be170c21f4235cd511107d0033b4 | arey0pushpa/modelling-cell-evolution | /python_helpers/gen.py | 556 | 3.875 | 4 | import itertools
from itertools import combinations, chain
allsubsets = lambda n: list(chain(*[combinations(range(n), ni) for ni in range(n+1)]))
def powerset(seq):
"""
Returns all the subsets of this set. This is a generator.
"""
if len(seq) <= 1:
yield seq
yield []
el... |
5a3baa172182f9cbf9f398d27763831f8662910a | hedayet13/learning-opencv | /kerasBasic.py | 1,442 | 3.5 | 4 | # try to use google colab
# google colabotary is one of the finest tool for traing your data
# remember to use keras from tensorflow
import numpy as np
from numpy import genfromtxt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
import tensorflow as tf
data = genfro... |
1032c4d3e8cc012d165da79a8cbbe269aab13d48 | rhinomikey/Python-Projects | /Session05_RobotMoving/.svn/pristine/ec/ec39047735613c1fcc0f27c1275b74a57c0595dc.svn-base | 4,833 | 4.375 | 4 | """
This module lets you practice one form of the ACCUMULATOR pattern,
namely, the "IN GRAPHICS" form which features:
-- DRAWING OBJECTS via ACCUMULATING positions and/or sizes,
as in: x = x + pixels
Authors: David Mutchler, Dave Fisher, Valerie Galluzzi, Amanda Stouder,
their colleagues and Nathan G... |
3f6fea02d38ea1c0f8b9651e037c55f1932f5be9 | rhinomikey/Python-Projects | /Session25_Test3/.svn/pristine/71/71293b5b841c96b13ef02614b54ebb4d218f2d13.svn-base | 2,564 | 3.671875 | 4 | """
Test 3, problem 3.
Authors: David Mutchler, Dave Fisher, their colleagues
and Nathan Gupta. May 2016.
""" # DONE: PUT YOUR NAME IN THE ABOVE LINE.
def main():
""" Calls the TEST functions in this module. """
test_problem3()
def test_problem3():
""" Tests the problem3 funct... |
ce143830075d4a5f56a03abf5edec8c79c7a733b | fernando-stteffen/data_visualization | /randomwalk/motion_watter.py | 898 | 3.75 | 4 | import matplotlib.pyplot as plot
from random_walk import RandomWalk
# Keep making new walks
while True:
# Make a random walk, and plot the points
rw = RandomWalk(5000)
rw.fill_walk()
# Set the size of the plotting window
plot.figure(figsize=(20,12))
point_numbers = list(range(rw.num_poi... |
971f5ec8bb222bbfc91123e24bcccdaf3caece28 | sidsharma1990/Python-OOP | /Inheritance.py | 1,519 | 4.65625 | 5 | ######### Inheritance ######
#####Single inheritance######
###### to inherit from only 1 class####
class fruits:
def __init__(self):
print ('I am a Fruit!!')
class citrus(fruits):
def __init__(self):
super().__init__()
print ('I am citrus and a part of fruit class!')
... |
4c34c56df0f99debb8a43334c7475ce6402236e1 | GP101/Python | /Python/Day03_Sort.py | 305 | 4.03125 | 4 | def Sort(list):
size = len(list)
for i in xrange(0,size-1):
for j in xrange(i+1,size):
#print list[i], list[j]
if list[i] > list[j]:
t = list[i]
list[i] = list[j]
list[j] = t
list = [ 5,1,4,2,3]
Sort(list)
print list |
c60237731d80d35a072ae97535e7902e720a5c4d | GP101/Python | /Python/Day06 class overriding.py | 243 | 3.734375 | 4 | class Base:
a = 1
def Test(self):
print 'BaseTest'
class Derived(Base):
a = 2
b = 3
def Test(self):
Base.Test(self)
print 'Derived.Print'
print Base.a, self.a, self.b
t = Derived()
t.Test() |
7e25aab395971cf2c2f924003d8fac8bb1845338 | wenwenhou/day06 | /day/day52.py | 49 | 3.515625 | 4 | list1=[1,2,3]
list2=list1.append()
print(list2)
|
b52acbc8a40196906efa7ab5e7111e402e85ea44 | wenwenhou/day06 | /day06/8.pyi | 1,314 | 3.53125 | 4 | print('请输入一个数字')
a = int(input())
print('请输入阶乘')
b = int(input())
print('结果是', a ** b)
print('请输入一个数字')
a = int(input())
print('请输入阶乘')
b = int(input())
print('结果是', a ** b)
print('请输入一个数字')
a = int(input())
print('请输入阶乘')
b = int(input())
print('结果是', a ** b)
print('请输入一个数字')
a = int(input())
print('请输入阶乘')
b = int... |
cd5d2f0a8a03321946fefa5fbd81809391eb37b9 | jasonbrackman/tower_defense | /tutorial/create_grid.py | 563 | 3.5 | 4 | import sys
import pygame
pygame.init()
size = width, height = 320, 240
screen = pygame.display.set_mode(size)
blk = 0, 0, 0
red = 195, 0, 0
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.fill(blk)
block_size = 1
for y in range(height):
... |
686e95865160a64b8bdf5b82878fd5c1e20aa709 | eneas95/Lista1---CES-22 | /q10.py | 569 | 3.546875 | 4 | #Representando complexos como Tuplas
#3 + 2i
x1 = (3,2)
#1 + 0i
x2 = (1,0)
#12 + 5i
x3 = (12,5)
#2i
x4 = (0,2)
#2 + 2i
x5 = (2,2)
#4 + 3i
x6= (4,3)
#Agora definir a soma de complexos
def SomaComplexos(z1, z2):
a = z1[0] + z2[0]
b = z1[1] + z2[1]
z3 = (a,b)
return z3
def test(pas... |
6089a14bf4400a7374ffd38f315c2d9d09d3412c | escc1122/design-pattern | /26_Flyweight/main.py | 669 | 3.546875 | 4 | import abc
class IString(abc.ABC):
def __init__(self, value):
self.__value = value
class String(IString):
def __init__(self, value):
super(String, self).__init__(value)
class StringFactory:
__temp = {}
def __init__(self):
pass
@classmethod
def get_instance(cls, ke... |
b8f441fdd7e1051ff2c23ffe334f4b0d8de77d36 | escc1122/design-pattern | /1_simple_factory/main.py | 1,297 | 3.921875 | 4 | import abc
class ISimpleFactory(abc.ABC):
def __init__(self):
self.__numberA: float
self.__numberB: float
@abc.abstractmethod
def to_do(self):
pass
@property
def numberA(self):
return self.__numberA
@numberA.setter
def numberA(self, new_data):
sel... |
9b4c5f817d8fcc43cf7e8553f429071e993ba41f | sixbo/Intermediate_Python | /Decorators/functioning_function01.py | 341 | 3.890625 | 4 | #从函数中返回函数
def hi(name='sixbo'):
print("now you are inside the hi() function")
def greet():
print("now you are inside the greet() function")
def welcome():
print("now you are inside the greet() function")
if name=='sixbo':
return greet()
else:return welcome()
x=hi()
pri... |
bf4495a3ce6f2eefe291b0502811cb09475e71c1 | y-sato19/tools | /indonesia_check/reflection.py | 2,321 | 3.546875 | 4 | #!C:\python3_6\python.exe
# coding: utf-8
# import
import csv
from pprint import pprint
import sys
##header
print("Content-Type: text/plain\n")
# print("test")
test = ["aaaa", "bbbbb"]
# pprint(test)
# csv読み込み関数
def readCsv(file, enc):
tmp = []
try:
# bom付きutf-8は、'utf-8-sig'
with open(file, ... |
be2338256235599b7973b2cb4af0fe687a6143f0 | nick3499/random_hostname_nick3499 | /random_hostname.py | 1,022 | 3.5625 | 4 | #! /bin/python3
'''`random_hostname` module contains the `rand_hostname()` method \
which generates a pseudo-random hostname.'''
from random import randrange
from subprocess import run
def rand_hostname():
'''`rand_hostname()` method generates a pseudo-random hostname.'''
# alphanumeric collection
_alph =... |
1a67bc5461602516fe1755404471d6c8d7f2bf08 | kleineG1zmo/helloworld-python | /Lesson 2/код-запара для тупого Яши.py | 922 | 3.84375 | 4 | a = int(input('LENGTH OF POOL '))
b = int(input('WIDTH OF POOL '))
c = int(input('METERS TO THE WIDE SIDE '))
d = int(input('METERS TO THE LONG SIDE '))
co = a - c
do = b - d
if c > a:
print('IT IS IMPOSSIBLE!') # cюда вставить функцию, которая обрывала бы график
if d > b:
print('IT IS IMPOSSIBLE!')
... |
d8e256138e7cb828c95c40047e97c45da09c4ece | Markbria01/Lesson2 | /cut2.py | 688 | 3.921875 | 4 | def discounted(price, discount, max_discount=80):
try:
price = abs(float(price))
discount = abs(float(discount))
max_discount = abs(int(max_discount))
if max_discount > 99:
raise ValueError('Слишком большая максимальная скидка')
if discount >= max_discount:
... |
838b0bb0ecda13f40f7e4a277509d887fb826f36 | danielvivasestevao/xgraph | /Geometry/path_length.py | 618 | 3.859375 | 4 | import networkx as nx
def is_path_length_leq_k(graph, node1, node2, k):
"""
Checks whether the shortest path length of two nodes node1 and node2
in a networkX.Graph graph is less than or equals to k.
:param graph: networkX.Graph
:param node1: node ID
:param node2: node ID
:param k: int
... |
a0dc0352f9cc4ac61a3e12aac526064ad008912d | ShelterPush/cue-generator | /cueSheet.py | 8,555 | 3.875 | 4 | #! python3
# cueSheet.py - A script to create cue sheets from a list of files
from pathlib import Path
import sys
def yesNo():
while True:
yesNoInput = str(input())
if yesNoInput.lower() == 'y' or yesNoInput.lower() == 'yes':
return 'y'
break
if yesNoInput == 'n' ... |
09aac6dccc75a0743d347622bf1d4671c81d67ff | AleksIonin/sistem | /lab3/task2.py | 711 | 3.96875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#lab3-2
# 23. Симметричны ли точки и относительно оси X или относительно оси Y?
import math
if __name__ == '__main__':
m1x = int(input("Введите значение х1 "))
m1y = int(input("Введите значение y1 "))
m2x = int(input("Введите значение х2 "))
m2y = int(in... |
e9d890339d2fcc96ecd260727cac999e5bc821c5 | AleksIonin/sistem | /lab9/tasks.py | 247 | 3.546875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
number = 5
st_num = 190393
task1 = ((math.pow(st_num, 2)) + st_num +1) % 15 + 1
print ("task 1 -", task1)
task2 = ((math.pow(st_num, 2)) + st_num +3) % 20 + 1
print ("task 2 -", task2)
|
a3408c742e217f7217cf389d0a26dbb7ce54c36b | codedsun/LearnPythonTheHardWay | /ex42.py | 434 | 3.65625 | 4 | class TheThing(object):
def __init__(self):
self.number=0
def some_function(self):
print("I got called")
def add_me_up(self,more):
self.number+=more
return self.number
a = TheThing()
b = TheThing()
a.some_function()
b.some_function()
print(a.add_me_up(20))
p... |
6ae29b08e62629d26b9b0cfe2414d121bf6a46e8 | codedsun/LearnPythonTheHardWay | /ex24.py | 795 | 3.734375 | 4 | #ex24: Practice
print("Let's do more practice")
print('You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.')
poem = """
\t This is lovely world vchaning line \n
now using tabs \t good bye."""
print(".."*10)
print(poem)
print(".."*10)
five = 10-2+3-6
print("This should print five %d"%five)
d... |
3c41155cbab16bb91e4387aa35d49e1832ce5b72 | codedsun/LearnPythonTheHardWay | /ex32.py | 525 | 4.25 | 4 | #Exercise 32: Loops and List
the_count = [1,2,3,4,5]
fruits = ['apples','oranges','pears','apricots']
change = [1,'pennies',2,'dimes',3,'quaters']
#for loop in the list
for number in the_count:
print("This is %d count"%number)
for fruit in fruits:
print("A fruit of type %s"%fruit)
for i in change:
print... |
8c3788b2fc95ce08c9dc6165b6f5de91e7d7d448 | semihyilmazz/Rock-Paper-Scissors | /Rock Paper Scissors.py | 2,933 | 4.40625 | 4 | import random
print "********************************************************"
print "Welcome to Rock Paper Scissors..."
print "The rules are simple:"
print "The computer and user choose from Rock, Paper, or Scissors."
print "Rock crushes scissors."
print "Paper covers rock."
print "and"
print "Scissors cut p... |
163cd2003b814999419d11e19b683fa12c6208d6 | songseonghun/kagglestruggle | /python3/001-050/008-len.py | 287 | 3.71875 | 4 | # the 'len ' bulit-in function
list_var = [1,2,3,4,5]
str_var = 'Hello, wolrd'
dict_var = {"a":100, "b":200}
print(len(list_var))
#5 - 리스트 안의 변수 수
print(len(str_var))
#12 = 글자 수 띄어쓰기 포함
print(len(dict_var))
#2 = 딕셔너리변수 갯수
|
021bfde82d8585447973fe5103626bde22295616 | songseonghun/kagglestruggle | /python3/151-200/175-strip.py | 202 | 3.53125 | 4 | #Remove nweline characters from
#the strings in a list
data = [
'alpha\n',
'beta\n',
'gamma\n'
]
print(data)
data = [
s.strip() for s in data
#list comprehension
]
print(data)
|
d5b19aab42a162c60f93a30dd1425982748705f1 | songseonghun/kagglestruggle | /python3/001-050/041-for-in.py | 113 | 4.0625 | 4 | #Looping over a list
#using "in"
my_list = 3, 5 , 7 , 9
for x in my_list:
print(x)
print(type(my_list))
|
24c24f5cdad234f94584732767cc9cf72c987762 | songseonghun/kagglestruggle | /python3/001-050/024-open-range.py | 131 | 4 | 4 | #Get the beginning or the end
#of a string using ranges
str = 'abcdefghijklmn'
#beginning
print(str[:5])
#end
print(str[10:])
|
8cfc569a2ede9df4f6dea5c8855e3dc8c9c2d2c8 | songseonghun/kagglestruggle | /python3/001-050/026-reverse-string.py | 92 | 4.21875 | 4 | #reverse a string and print it
str = 'Hello world!'
rev_str = str[::-1]
print(rev_str)
|
1e8470fee1fafdde8e754b135e91c36724293f70 | songseonghun/kagglestruggle | /python3/151-200/185-unicode-normalize2.py | 260 | 3.8125 | 4 | # canonical normalization
# in unicode
import unicodedata
# 'a' can be represented in two ways:
s1 = 'á'
s2 = 'a\u0301' #combining acute
print(s1 == s2) #False
s3 = unicodedata.normalize('NFC', s2)
print(s1 == s3) #True
print(s1)
print(s2)
print(s3)
|
9a6fe2ffbb280d239d50001e637783520b8d4aef | songseonghun/kagglestruggle | /python3/201-250/206-keep-vowels.py | 272 | 4.1875 | 4 | # take a strign. remove all character
# that are not vowels. keep spaces
# for clarity
import re
s = 'Hello, World! This is a string.'
# sub = substitute
s2 = re.sub(
'[^aeiouAEIOU ]+', #vowels and
# a space
'', #replace with nothing
s
)
print(s2)
|
c479c105dbb24542d5167ecc20f03fab112c12b6 | songseonghun/kagglestruggle | /python3/151-200/154-set-methods.py | 254 | 3.875 | 4 | #Methods of the "set" data type
#"difference"
set1 = {1, 2, 3, 4, 5, 6, 7}
set2 = {3, 5, 7, 9, 11, 13}
#차이점
diff1 = set1.difference(set2)
#kind of "set1 - set2"
diff2 = set2.difference(set1)
#"set2- set1"
print(diff1)
print(diff2)
import re
|
3aaad64002fc9c57b051cc0f9d6b56ebfa5a66a9 | songseonghun/kagglestruggle | /python3/001-050/025-more-ranges.py | 131 | 4.25 | 4 | #Using the third parameter
#in a range
str = 'abcdefghijklmn'
#print every second character
print(str[::2])
print(str[::3])
|
3f3f526fed40928ea90e0c26679243da1263bca5 | songseonghun/kagglestruggle | /python3/051-100/100-different-random.py | 237 | 3.625 | 4 | #generating a series
# of *different* random numbers
from random import randint
data = set()
n = 0
while n < 6:
r = randint(1,46)
if r not in data:
n += 1
data.add(r) #new number
print(len(data))
print(data)
|
a48d2676cf0d3350a2768ea2164e7b615203b0c4 | songseonghun/kagglestruggle | /python3/051-100/095-iter.py | 192 | 4.0625 | 4 | #Using iterators
#반복자
my_list = ['alpha', 'beta', 'gamma']
#make the list iterable
data = iter(my_list)
a = next(data)
print(a)
a = next(data)
print(a)
a = next(data)
print(a)
|
15bc922eef596c811d6136fe8115c45f4226def1 | songseonghun/kagglestruggle | /python3/051-100/079-factorial-2.py | 204 | 4.09375 | 4 | #Computing a factorial
#using recursion
def factorial(n):
if n > 1:
return n * factorial(n-1)
else :
return 1
print(factorial(5))
# 5 * 4 * 3 * 2 * 1 = 120
print(factorial(2)) |
909dab028b329163208d83dc5367101f59791f84 | songseonghun/kagglestruggle | /python3/101-150/119-odd-even.py | 355 | 4.0625 | 4 | #splitting data into
#odd and even numbers
#짝홀
data = [
45, 56, 67, 23, 57, 78, 67 ,454
]
odd = []
even = []
print(type(odd))
print(type(even))
for d in data:
if d % 2:
odd.append(d) #홀수 1이 나머지로 나옴으로
else:
even.append(d) #짝수
print(f'Odd numbers : {odd}')
print(f'Even numbers : {even... |
51072acb36eaf16f070aac0134fffa1bcdbb18fd | songseonghun/kagglestruggle | /python3/151-200/154-lru-cache.py | 293 | 3.875 | 4 | # Caching function return values
# when you call it with the same
# arguments(s)
from functools import lru_cache
@lru_cache(maxsize=1000)
def factorial(n):
if n <=1 :
return 1
print(f'Computing {n}!')
return n * factorial(n - 1)
print(factorial(5))
print(factorial(3))
|
0276411037c37ec0555f68da7b0122eb04cf5858 | FrancoVol/python-lab2 | /lab2ex2.py | 874 | 3.8125 | 4 | from sys import argv
tasks=[]
flag=True
file = argv[1]
txt = open(file)
for line in txt.read().splitlines():
tasks.append(line)
txt.close()
while flag==True:
print('''Choose one task:
[1. insert a new task
2. remove a task
3. show all existing tasks
4. close the program]''')
a=int(input())
if a==1:
... |
80a936ecd3b9c54376136c3d6166b638f1a2c8dd | steampunk99/Python-intro | /attack.py | 762 | 3.6875 | 4 | import random
class Enemy:
hp = 200
def __init__(self, attackLow, attackHigh):
self.attackLow = attackLow
self.attackHigh = attackHigh
def getAttack(self):
print(self.attackHigh)
def getHP(self):
print("Enemy hp is", self.hp)
enemy1 = Enemy(65, 89)
enemy1.getAttack... |
b5363f3d6c5b6e55b3d7607d055a266b215c28ab | dianamenesesg/HackerRank | /Interview_Preparation_Kit/String_manipulation.py | 2,979 | 4.28125 | 4 | """
Strings: Making Anagrams
Alice is taking a cryptography class and finding anagrams to be very useful. We consider two strings to be anagrams of each other if the first string's letters can be rearranged to form the second string. In other words, both strings must contain the same exact letters in the same exact fre... |
08cff7fa1dc806ba5e4dcde2d3848adf6c687407 | jickw/my-project | /python/lnh_learn/201811/1106/推导式.py | 210 | 3.71875 | 4 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
def add(a, b):
return a + b
def test():
for i in range(4):
yield i
g = test()
for n in [2, 10]:
g = (add(n, i) for i in g)
print(list(g)) |
0659d6467bcee36aa8c53fcafdb587d2b6b12709 | killingwolf/python_learning | /homework/Part 1/1-5-1.py | 271 | 3.6875 | 4 | #!/usr/bin/python
# coding:utf-8
def main():
"""while+print输出指定样式
"""
i = 1
while i < 7:
j = 1
while j <= i:
print j,
j = j + 1
i = i + 1
print
if __name__ == "__main__":
main()
|
426f6942460d751fb490fa148f1a4c348ee96860 | killingwolf/python_learning | /homework/Part 2/2-18.py | 485 | 3.578125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: killingwolf
# Email: killingwolf@qq.com
def main():
""" dict join
"""
dict1 = {
'key1': "value1",
'key2': "value2"
}
dict2 = {
'key2': "value2",
'key3': "value3"
}
tmp_dict = {}
for (k, v) in dict... |
83c4e7b948aacd261a7b7e7a35d6fa1bfeb82088 | killingwolf/python_learning | /book_code/test.py | 743 | 3.8125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: killingwolf
# Email: killingwolf@qq.com
""" This is a test module
"""
x = 10
class MyClass(object):
"""docstring for MyClass"""
a = [1]
def b(self):
self.a[0] += 1
print self.a[0]
class C(object):
"A test class"
def __in... |
9a4717e17c9402156aa55df6da5beded789a82d6 | killingwolf/python_learning | /video_code/Part4/test.py | 2,996 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2015-12-07 22:25:29
# @Author : killingwolf (killingwolf@qq.com)
class Foo(object):
num = 5
def __init__(self, x, y):
self.x = x
self.y = y
def print_xy(self):
# return self.x + self.y + self.num
# return self.x ... |
067302813a98d5f79e75ecf2b15e8843e01f5949 | killingwolf/python_learning | /homework/Part 4/13-11.py | 3,715 | 3.875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2015-12-13 01:07:49
# @Author : killingwolf (killingwolf@qq.com)
class User(object):
"""用户类"""
def __init__(self, car_name):
self.__cars = {} # 购物车名对应一个购物车
self.__cars.update({car_name: Cart(car_name)})
def add_car(self, car_n... |
518ce083e3a0a162b0fd63f43a921bd4d87c0d74 | xuguangmin/Programming-for-study | /manual_python/build-in-function/delattr.py | 186 | 3.703125 | 4 | #!/usr/bin/python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
tom = Person("Tom", 35)
dir("tom")
print tom.name
if __name__ == "__main__":
dir()
|
cc26efdbea81bed3806b76b00ed533f13286a1e8 | xuguangmin/Programming-for-study | /python_study_code/string/replace.py | 212 | 3.921875 | 4 | #!/usr/bin/python
#_*_ coding:utf-8 _*_
#字符串替换
centence = "hello world, hello Chiana"
print centence.replace("hello", "hi")
print centence.replace("hello", "hi", 1)
print centence.replace("abc", "hi")
|
f84d21df8fff22d08b2fce2784fe7c38b554bad9 | xuguangmin/Programming-for-study | /python_study_code/cusFunc/embfuc2.py | 235 | 3.71875 | 4 | #!/usr/bin/python
#_*_ coding:utf-8 _*_
#函数定义嵌套
def func():
x =1
y = 2
m = 3
n = 4
def sum(a, b):
return a+b
def sub(a, b):
return a-b
return sum(x, y) * sub(m, n)
print func()
|
da144e258d85e46d0afdb1880f44ef4c5e45861e | krok64/exercism.io | /python/grains/grains.py | 221 | 3.59375 | 4 | def on_square(num):
if num<=0 or num>64:
raise ValueError
return 2**(num-1)
def total_after(num):
if num<=0 or num>64:
raise ValueError
return sum([on_square(x) for x in range(1, num+1)])
|
ed8c9c3f036ac374c96782bc1defc4ff56d8a02d | krok64/exercism.io | /python/nth-prime/nth_prime.py | 380 | 3.6875 | 4 | def nth_prime(num):
if num < 1:
raise ValueError
return p_list[num - 1]
def sieve(num):
is_prime = [True for x in range(num + 1)]
primes = []
for x in range(2, num + 1):
if is_prime[x]:
primes.append(x)
for i in range(x * 2, num + 1, x):
is_p... |
3009ea7f772212fa13dcaf04e97cfddf8c1dd4d4 | krok64/exercism.io | /python/run-length-encoding/run_length_encoding.py | 887 | 3.53125 | 4 | def decode(phrase):
out_str=""
num = 0
for ch in phrase:
if ch.isdigit():
num = num * 10 + int(ch)
else:
if num>0:
out_str = out_str + num * ch
num = 0
else:
out_str = out_str + ch
return out_str
def enc... |
3d25c2bb79ee26870f18254eb4ca62cec0ecdba4 | krok64/exercism.io | /python/queen-attack/queen_attack.py | 818 | 3.671875 | 4 | def can_attack(poz1, poz2):
if (not check_pozition(poz1)) or (not check_pozition(poz2)) or poz1==poz2:
raise ValueError("wrong position")
if poz1[0]==poz2[0] or poz1[1]==poz2[1] or abs(poz1[0]-poz2[0])==abs(poz1[1]-poz2[1]):
return True
return False
def check_pozition(poz):
if poz[0]<0... |
7e51e64987babd2e2031be463ef3f93c85197bc4 | jasonmyers/learning-python | /learning-python/tip_calculator/tip_calculator.py | 918 | 3.96875 | 4 | #! /usr/bin/env python
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-m", "--meal", dest="meal", help="the amount of your meal",
type="float")
parser.add_option("-t", "--tax", dest="tax", help="the tax percentage",
default="8.25",
type="float")
parser.add_option("-i", "--tip", dest="... |
4d4f055d4066bd8d69bb7864b7b0121986db1329 | Ahaiman/binary-search-tree | /is_sorted/is_sorted.py | 497 | 3.609375 | 4 | def is_sorted(self):
def sorted_rec(node, minVal, maxVal):
if node == None:
return True
if node.val < minVal or node.val > maxVal:
return False
return sorted_rec(node.left,minVal, node.val) \
... |
ce5bca3cfd73e635b7c45686d824af23ec5004ac | Ahaiman/binary-search-tree | /tester.py | 870 | 3.78125 | 4 |
#Tester for the Binary_search_tree class
#Copy this to the relevant file, or import the functions.
def test():
bin_tree = Binary_search_tree()
print("MIN ",bin_tree.minimum())
print("DEPTH ",bin_tree.depth())
print("SIZE ",bin_tree.size())
print(bin_tree)
bin_tree.insert(2,"a")
print(bin_t... |
367b84984ee3d63fd402c3be100e6d487988881c | michaelschung/bc-ds-and-a | /Unit2-Iteration/tuples-dictionaries/tuple.py | 232 | 4 | 4 | '''
Mr. Chung
3/15: Tuples
'''
lst = ['hello', 'goodbye', 'yo']
lst[1] = 'what is up'
print(lst[1])
print('hello' in lst)
# Tuples are like lists, but immutable
tup = ('hello', 'goodbye', 'yo')
print(tup[1])
print('hello' in tup)
|
c5d1e2535e6e8d9ac0218f06a44e437b3358049b | michaelschung/bc-ds-and-a | /Unit1-Python/hw1-lists-loops/picky-words-SOLUTION.py | 543 | 4.3125 | 4 | '''
Create a list of words of varying lengths. Then, count the number of words that are 3 letters long *and* begin with the letter 'c'. The count should be printed at the end of your code.
• Example: given the list ['bat', 'car', 'cat', 'door', 'house', 'map', 'cyst', 'pear', 'can', 'spike'], there are exactly 3 qualif... |
74ce93f4bff449d5251191ede765e9deb2ad0c61 | michaelschung/bc-ds-and-a | /Unit3-Applications/ngrams/count-bigrams.py | 553 | 3.703125 | 4 | '''
Mr. Chung
4/7: Counting Bigrams
'''
words = []
with open('txt/tswift.txt', 'r') as f:
for line in f:
# Remove whitespace from the ends
stripped_line = line.strip()
# Split the line into a list of words
line_words = stripped_line.split()
# Add each word to our master lis... |
7c9e11000cbcd3a02be5ce6caff3d57cd0d10fa5 | michaelschung/bc-ds-and-a | /Unit2-Iteration/reading-files/read-dict.py | 785 | 3.71875 | 4 | '''
Mr. Chung
3/17: Reading from a one-word-per-line file
'''
import re
words = []
with open('tswift.txt', 'r') as f:
for line in f:
# Removes whitespace from ends of string
stripped_line = line.strip()
# Remove punctuation from the line
no_punc = re.sub("[,.;!?']", '', stripped_l... |
6e8862ea7847e16dab15c1035d3541c3182c3efa | michaelschung/bc-ds-and-a | /Unit3-Applications/deck-of-cards/deck.py | 548 | 3.53125 | 4 | from card import Card
import random
class Deck:
def __init__(self):
self.cards = []
for suit in ['C', 'D', 'H', 'S']:
for val in range(1, 14):
self.cards.append(Card(val, suit))
def shuffle(self):
random.shuffle(self.cards)
def print_deck(self):
... |
4adf09b63ba68ba2f186cbefe102c62a0a7a6cd7 | michaelschung/bc-ds-and-a | /Unit3-Applications/random/randomness.py | 762 | 3.921875 | 4 | '''
Mr. Chung
4/19: Using randomness
'''
import random
# =====Integer values=====
# Random int in range [0, stop)
print(random.randrange(10))
# Random int in range [start, stop)
print(random.randrange(5, 10))
# Random int in range [start, stop, step)
print(random.randrange(10, 20, 2))
# Random int in range [start, s... |
56011d66ae90fd4c4c5a26cb98a148514d78ded3 | yangju2011/udacity-coursework | /Programming-Foundations-with-Python/check_profanity.py | 1,248 | 4 | 4 | import urllib
# standard procedure to read a file
# content = open(path).read()
# open(path).close()
# for website content
# content = urllib.urlopen(url).read()
def read_text():
sourcefile = open (r"D:\Dropbox\Career\Coding\IntroToPython\movie_quotes.txt") #take address and filename, open it
# ... |
0a8f0a70453580a385c76b00a9ebc7a00771f62e | yangju2011/udacity-coursework | /Intro-to-Computer-Science/elementary cellular automaton.py | 6,303 | 3.703125 | 4 | # THREE GOLD STARS
# Question 3-star: Elementary Cellular Automaton
# Please see the video for additional explanation.
# A one-dimensional cellular automata takes in a string, which in our
# case, consists of the characters '.' and 'x', and changes it according
# to some predetermined rules. The rules consid... |
c9a7bdeb85a94afc6b17c2b6ddf3be0d78de6206 | yangju2011/udacity-coursework | /Programming-Foundations-with-Python/turtle/squares_drawing.py | 755 | 4.21875 | 4 | import turtle
def draw_square(some_turtle):
i = 0
while i<4: # repeat for squares
some_turtle.forward(100)
some_turtle.right(90)
i=i+1
def draw_shape():#n stands for the number of edge
windows = turtle.Screen()#create the background screen for the drawing
w... |
e1c8b1a08fb0471430c3a8acc932882e491967cd | yangju2011/udacity-coursework | /Intro-to-Computer-Science/fibonacci.py | 602 | 4.09375 | 4 | def fibonacci(n):
if n == 0:
return 0
if n == 1:
return 1
else:
return fibonacci(n-1)+fibonacci(n-2)
def fast_fibonacci(n):
if n == 0:
return 0
if n == 1:
return 1
else:
pre = 0
post = 1
i = 1
while i < n:
... |
cee1aa38a4abe5ede83e213797c771b4ce75a5be | yangju2011/udacity-coursework | /Design-of-Computer-Programs/optimize-strategy/play_pig.py | 3,768 | 4.34375 | 4 | # -----------------
# User Instructions
#
# Write a function, play_pig, that takes two strategy functions as input,
# plays a game of pig between the two strategies, and returns the winning
# strategy. Enter your code at line 41.
#
# You may want to borrow from the random module to help generate die rolls.
i... |
900a8d209c728fe5dea9eb3ea385a708958ffd6e | yangju2011/udacity-coursework | /Programming-Foundations-with-Python/turtle/draw_flower.py | 637 | 4.0625 | 4 | import turtle
def draw_diamond(some_turtle):
for i in range (0,2):
some_turtle.forward(100)
some_turtle.right(40)
some_turtle.forward(100)
some_turtle.right(140)
def draw_flower():
#create screen with turtle.Screen
windows = turtle.Screen()
windows.bgcolor... |
283ca9a6a75ca05af4784021c1ad042b0af3e9ee | yangju2011/udacity-coursework | /Design-of-Computer-Programs/word-game/anchor.py | 4,285 | 3.921875 | 4 | # anchor is set, row is list
class anchor(set):
" An anchor is where a new workd can be replaced; has a set of allowable letter. "
# class has a content body, which here is empty
LETTERS = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
ANY = anchor(LETTERS) # an anchor can be any letter
mnx = anchor('MNX')
moab = ... |
875aa070d469d788beca5f1ede780c79dc3f7a74 | aasupak/python_homework | /lesson3.py | 848 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Feb 8 12:03:49 2018
@author: aasup
"""
#def thing():
# print("hey")
# print("everybody")
#thing()
#big = max('hello world')
#print(big)
#def greet(lang):
# if lang=="es":
# print("hola ")
# elif lang=="fr":
# print("bon jour ... |
f9d09e441b505ede8d4c97a0aabe75f33a1b8b7c | misstbn101/1433finalpaper | /data_cleaning_script_2011.py | 7,933 | 3.71875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 13 11:28:18 2020
@author: temanwana
"""
import pandas as pd, math, numpy as np
def add_totals(school_codes, grade):
"""
Parameters
----------
school_codes : array of strings
list of all the school codes
grade : string
... |
be29ba7f3fa55fb76f0478096a3ddef083089939 | CheRayLiu/LeetCode | /medium/combination_sum_iv.py | 581 | 3.671875 | 4 | """
Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
Time: O(NlogN)
Space: O(N)
"""
class Solution:
def combinationSum4(self, nums: List[int], target: int) -> int:
"""
Similar to coin change
... |
b7b0198d9280c40f4f74decd9b79ce0892bc9144 | CheRayLiu/LeetCode | /medium/collect_leaves.py | 1,231 | 3.984375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findLeaves(self, root: TreeNode) -> List[List[int]]:
"""
Height of node is leave to root, bottom up approach
... |
426937fb58e28923ddb00f3295308d9da6a9da28 | LokiSharp/Learn-Python-The-Hard-Way | /ex31.py | 1,120 | 3.890625 | 4 | # -*- coding: utf-8 -*-
print "你进入的一个黑暗的房间,边上有两扇门。你想进入哪一扇 #1 或者 #2?"
door = raw_input("> ")
if door == "1":
print "这里有一只正吃着起司蛋糕的大熊。你想干什么?"
print "1. 拿走蛋糕。"
print "2. 朝着大熊大吼。"
bear = raw_input("> ")
if bear == "1":
print "大熊吃了你的脸。干得好!"
elif bear == "2":
print "大熊吃了你的胳膊。干得好!"... |
bb8c0e83efcfa540f6231eaf72a3febc6f6e3d7f | Jeff-Hutchins/python-exercises | /4.6.1_matplotlib_exercises.py | 2,808 | 3.625 | 4 | import matplotlib.pyplot as plt
import math
import random
import numpy as np
x = list(range(150))
plt.plot(x)
plt.show()
plt.plot(x)
plt.xlim(-20, 200)
plt.ylim(-5, 160)
plt.show()
plt.plot(x, c='red')
plt.show()
from random import randint
# Some random data
x1 = [randint(-5, 25) + n for n in range(150)]
x2 = [x ... |
faf983bbf5a2644741f4e84eb5db67b81e115c55 | Jeff-Hutchins/python-exercises | /pandas_dataframes.py | 6,560 | 4.40625 | 4 | import pandas as pd
import numpy as np
np.random.seed(123)
students = ['Sally', 'Jane', 'Suzie', 'Billy', 'Ada', 'John', 'Thomas',
'Marie', 'Albert', 'Richard', 'Isaac', 'Alan']
# randomly generate scores for each student for each subject
# note that all the values need to have the same length here
math_... |
1484599ce09b75d9d835d88ea827af1024eb68c1 | origersh/Server-Client-Implementation | /Exercises/ex3/ex3_server.py | 861 | 3.90625 | 4 | """ Server, receiving data from a client and sending back a response """
import socket
server_socket = socket.socket()
server_socket.bind(('127.0.0.1', 8820)) # like socket.connect, on the server side we use the 'bind' function to specify connection "line"
server_socket.listen(1) # listening on the given IP and port ... |
c129eb83c7814eb0b11a4ca3a7364a826f36b07c | rjiang9/PythonNotes | /Hadoop/Assignment1/Q1/mapper.py | 346 | 3.796875 | 4 | #!/usr/bin/env python
import sys
import re
def convertToListOfWords(sentence):
sentence = sentence.lower()
words = re.split('\W', sentence)
words = [word for word in words if len(word)>0]
return words
for line in sys.stdin:
words = convertToListOfWords(line)
bigrams = zip(words, words[1:])
for gram in bigra... |
ea34741f8866856bdee9702bc20184f57cf65271 | onursevindik/GlobalAIHubPythonCourse | /Homework/HW2/HW2-Day3.py | 843 | 4.15625 | 4 | d = {"admin":"admin"}
print("Welcome!")
username = input("Enter your username: ")
password = input("Enter your password: ")
for k,v in d.items():
if (k != username and v == password):
print(" ")
print("xxXxx Wrong username! xxXxx")
elif(k == username and v != password):
print(" ")
... |
1bb3d699d6d1e7ef8ea39a5cdc7d55f79ac4ed3d | theelk801/pydev-psets | /pset_lists/list_manipulation/p5.py | 608 | 4.25 | 4 | """
Merge Lists with Duplicates
"""
# Use the two lists below to solve this problem. Print out the result from each section as you go along.
list1, list2 = [2, 8, 6], [10, 4, 12]
# Double the items in list1 and assign them to list3.
list3 = None
# Combine the two given lists and assign them to list4.
list4 = No... |
d7aa917a00b2f582c7b15c8b40de0462ca274a66 | theelk801/pydev-psets | /pset_classes/fromagerie/p6.py | 1,200 | 4.125 | 4 | """
Fromagerie VI - Record Sales
"""
# Add an instance method called "record_sale" to the Cheese class. Hint: You will need to add instance attributes for profits_to_date and sales (i.e. number of items sold) to the __init__() method in your Cheese class definition BEFORE writing the instance method.
# The record_sa... |
1859b100bd9711dfa564f8d3a697202bc42d96c2 | theelk801/pydev-psets | /pset_conditionals/random_nums/p2.py | 314 | 4.28125 | 4 | """
Generate Phone Number w/Area Code
"""
# import python randomint package
import random
# generate a random phone number of the form:
# 1-718-786-2825
# This should be a string
# Valid Area Codes are: 646, 718, 212
# if phone number doesn't have [646, 718, 212]
# as area code, pick one of the above at random
|
ebcc56833a3d587d18debf25e2dbcf822cd31c4f | theelk801/pydev-psets | /pset_classes/fromagerie/solutions/p6.py | 3,315 | 4.1875 | 4 | """
Fromagerie VI - Record Sales
"""
# Add an instance method called "record_sale" to the Cheese class. Hint: You will need to add instance attributes for profits_to_date and sales (i.e. number of items sold) to the __init__() method in your Cheese class definition BEFORE writing the instance method.
# The record_sa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.