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 |
|---|---|---|---|---|---|---|
4a98b19419c953a3b12a1df262c3674a6b3a8967 | kahuroA/Python_Practice | /holiday.py | 1,167 | 4.53125 | 5 | """#Assuming you have a list containing holidays
holidays=['february 14', 'may 1', 'june 1', 'october 20']
#initialized a list with holiday names that match the holidays list
holiday_name=['Valentines', 'Labour Day', 'Mashujaa']
#prompt user to enter month and date
month_date=input('enter month name and date')
#check i... |
1e5f9a0e5180307e0428fec4dfb6c990e3c58cdb | aoancea/ud120-projects | /outliers/outlier_cleaner.py | 999 | 3.796875 | 4 | #!/usr/bin/python
def outlierCleaner(predictions, ages, net_worths):
"""
Clean away the 10% of points that have the largest
residual errors (difference between the prediction
and the actual net worth).
Return a list of tuples named cleaned_data where
each tuple is of the ... |
e28538a493be285eb2b7cb2cba63ad18efcca923 | Alianger18/IBM-Data-Science-Professional-Certificate | /08-Data Visualization with Python/08-Dash_Interactivity_4.7.py | 2,658 | 3.5 | 4 | # Import required libraries
import pandas as pd
import plotly.graph_objects as go
import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output
# Read the airline data into pandas dataframe
airline_data = pd.read_csv('httpscf-courses-data.s3.us.cloud-ob... |
af3d0c86488a7699274dd0af1060460de8231c93 | Lisprez/compiler-5 | /check.py | 1,026 | 4.0625 | 4 | def parenthes_brace_Check(file_input):
# It checks whether the number of open and close parentheses or braces are equal or not
line_number = 1
comma_counter = 0
brace_counter = 0
tmp_token = ''
for line in file_input:
for token in line.replace('\t',' ').split(' '):
if token.s... |
cb22cfda8ffc66e32b480faf614814338cf1d3ed | gary7/AIND-projects-1 | /AIND-Sudoku/solution.py | 7,216 | 3.8125 | 4 | assignments = []
rows = 'ABCDEFGHI'
cols = '123456789'
def cross(A, B):
"Cross product of elements in A and elements in B."
return [a+b for a in A for b in B]
boxes = cross(rows, cols)
row_units = [cross(r, cols) for r in rows]
col_units = [cross(rows, c) for c in cols]
square_units = [cross(r, c) for r in ('... |
8a0f51790c3063891e6f6b421011566a6bec6907 | VANSHDEEP15577/CLASS-127 | /LCM.py | 251 | 4.03125 | 4 | num1=int(input("ENTER THE FIRST NUMBER:"))
num2=int(input("ENTER THE SECOND NUMBER:"))
if num1>num2:
lcm=num1
else:
lcm=num2
while True:
if lcm%num1==0 and lcm%num2==0:
break
else:
lcm+=1
print("LCM IS ",lcm) |
d01393a87f1f967f17f2d4d989e80df070eb3364 | ChristopherNugent/FrequencyMap | /freqmap/FrequencyMap.py | 2,445 | 3.890625 | 4 | from collections import Counter # Used for the inner map
from random import randrange # Used for random probalistic retrieval
class FrequencyMap:
"""A structure designed for mapping hashable types to other hashable types,
to be used for implementing n-grams, Markov chains, and other similiar,
f... |
295da187b5080a12db6a3b79b4e7f99196ab831a | szhua/PythonLearn | /Unit2/Lesson8.py | 362 | 3.625 | 4 |
#枚举
from enum import Enum ,unique
"""
value属性则是自动赋给成员的int常量,默认从1开始计数。
"""
leilei =Enum("Leilei",("szhua","szhua2"))
for x in leilei:
print(x)
print(leilei.__members__.items())
@unique
class Weekday(Enum):
SUN=0
MON=1
TUE=2
WED=3
TUR=4
FRI=5
SAT=6
print(Weekday.SUN.name)
|
349ce370fde4a6903901f7fabf5dfc52a70315a4 | szhua/PythonLearn | /Unit1/Review1Args.py | 3,236 | 3.921875 | 4 | #复习一下函数的参数
#位置参数
def power(x):
return x*x
#print(power(222))
#默认参数
def power(x,n=2):
result =1
while True :
result = result * x
n = n - 1
if(n<1):
return result ;
print(power(9,1))
def power(x, n=2):
s =1
while n>0:
s*=x
n-=1
return s
print(p... |
6f910131944698122ee5d6a4040ea432f2ecca40 | szhua/PythonLearn | /Unit3/Lesson2.py | 1,722 | 3.984375 | 4 |
#从本章开始学习一下python内置的模块
from datetime import datetime
#打印当前时间
now =datetime.now()
print(now)
print(type(now))
#指定日期:时间
time =datetime(year=2017,month=11,day=11)
print(time)
#时间戳的问题---打印时间戳
print(time.timestamp())
timestamp =datetime.now().timestamp()
#时间戳转换城日期:
print(datetime.fromtimestamp(timestamp))
#datetime也可... |
b53f116d97b9c953149ec57e6335c87dc431c574 | szhua/PythonLearn | /Unit2/Review.py | 1,012 | 3.78125 | 4 |
class Student(object):
#先进行set的方法
@property
def score(self):
return self._score
#然后写set的方法;
@score.setter
def score(self,value):
self._score =value
s =Student()
s.score=10
print(s.score)
class Screen(object):
@property
def width(self):
return self._width... |
16342f440ec69754348c8226ba712c52bafc087f | szhua/PythonLearn | /Unit2/Lesson7.py | 1,314 | 3.90625 | 4 |
#
"""
定制函数
"""
class Student(object):
def __init__(self, name):
self.name = name
def __str__(self):
return 'Student object (name=%s)' % self.name
leilei =Student('leilei')
print(leilei)
class Fib(object):
def __init__(self) -> None:
self.a,self.b =1,1
def __iter__(self):
... |
45abb976b17c64e9c0f27c6fc128acb97251f485 | d0coat01/three-point-lines | /three-lines.py | 4,334 | 3.71875 | 4 | import csv
class CsvCoordinates:
def __init__(self):
return
def extract_points(self, filename):
points = []
with open(filename) as csvfile:
fieldnames = ['x', 'y']
reader = csv.DictReader(csvfile, fieldnames=fieldnames)
for row in reader:
... |
96c5d57708223bf13c34bc0c215af353a0b73aec | limsehui/likelionstudy | /8,9일차/forrange.py | 596 | 3.734375 | 4 | for i in range(5):
print(1)
names =['철수','영희', '바둑이', '귀도', '비단뱀']
for i in range(len(names))
name =names[i]
print('{}번: {}'.format(i + 1, name))
for i, name in enumerate(names):
print('{}번: {}'.format(i + 1, name))
for ii in range(11172):
print(chr((44032 + i), end ='')
'''range : 순회할 횟수가 정해져 있을 때
list... |
3987d9b65bb9e9e5555e92c42bcdde97b3464e18 | linxiaoru/python-in-action | /examples/basic/function_default.py | 435 | 4.21875 | 4 | """
⚠️
只有那些位于参数列表末尾的参数才能被赋予默认参数值,意即在函数的参数列表中拥有默认参数值的参数不能位于没有默认参数值的参数之前。
这是因为值是按参数所处的位置依次分配的。举例来说,def func(a, b=5) 是有效的,但 def func(a=5, b) 是无效的。
"""
def say(message, times=1):
print(message * times)
say('Hello')
say('World', 5) |
d907f7128959dd5f915ebef10db8a6f078eb4312 | japrietov/Workshop2 | /DES_implementation.py | 14,015 | 3.6875 | 4 | # -*- coding: iso-8859-1 -*-
# Authors: Jeisson Andres Prieto Velandia
# David Santiago Barrera
# Supplementary Material DES.
# https://en.wikipedia.org/wiki/DES_supplementary_material
## -*- coding: latin-1 -*-
from itertools import repeat
import math
import re
import random
def fill_to8(string_to_expa... |
ec3010b56ca544f4910d38d6bf5c5dc8e61ff30e | l-ejs-l/Python-Bootcamp-Udemy | /Lambdas/filter.py | 883 | 4.15625 | 4 | # filter(function, iterable)
# returns a filter object of the original collection
# can be turned into a iterator
num_list = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, num_list))
print(evens)
users = [
{"username": "Samuel", "tweets": ["IO love cake", "IO love cookies"]},
{"username": "Kat... |
c804c5d05f53dfc7f90521a9a79f05b5464dca5b | l-ejs-l/Python-Bootcamp-Udemy | /Lambdas/lambdas.py | 132 | 3.75 | 4 | def square(num): return num * num
square2 = lambda num: num * num
add = lambda a, b: a + b
print(square2(7))
print(add(3, 10))
|
c59e167d00e927e6ca41268b9490b3eb6722ad3d | l-ejs-l/Python-Bootcamp-Udemy | /Iterators-Generators/generator.py | 410 | 4.1875 | 4 | # A generator is returned by a generator function
# Instead of return it yields (return | yield)
# Can be return multiple times, not just 1 like in a normal function
def count_up_to(max_val):
count = 1
while count <= max_val:
yield count
count += 1
# counter now is a generator and i can call... |
d3b10c9fdd390fdf8068c1e343da8c334c034437 | l-ejs-l/Python-Bootcamp-Udemy | /Lambdas/zip.py | 437 | 4.4375 | 4 | # zip(iterable, iterable)
# Make an iterator that agregate elements from each of the iterables.
# Returns an iterator of tuples, where the i'th tuple contains the i'th element from each of the of the argument
# sequences or iterables.
# The iterator stops when the shortest input iterable is exhausted
first_zip = zip([... |
ec84882bca29348f1d291a87573c98e390ec4043 | l-ejs-l/Python-Bootcamp-Udemy | /Lambdas/all.py | 551 | 3.953125 | 4 | # all(iterable)
# returns True if all elements of the iterable are truthy (or if the iterable is empty)
all([0, 1, 2, 3]) # False, 0 is a Falsy value
# THERE'S NO NEED TO USE LIST COMPREHENSION, JUST GENERATOR EXPRESSION
all([char for char in 'eio' if char in "aeiou"]) # True every character is inside 'aeiou'
all(... |
74e0cdcdf5b7d6c141295e055200eadec3a8619c | victoorraphael/wppchatbot | /maisOpção_Joao.py | 1,401 | 4.1875 | 4 | def saudacao():
print('Olá, digite seu nome: ')
nome = input()
while(True):
print('{}, digite o numero referente a opção desejada:'.format(nome))
print('\n')
print('1 - Novo pedido')
print('2 - Alteração de pedido')
print('3 - Mais opções')
op = int(i... |
29813ff5310858f981663f25957d789a904a8939 | amenson1983/Python_couses | /Chapter 3 (2).py | 714 | 3.984375 | 4 | a1 = float(input("Введите длину первого прямоугольника: "))
b1 = float(input("Введите ширину первого прямоугольника: "))
a2 = float(input("Введите длину второго прямоугольника: "))
b2 = float(input("Введите ширину второго прямоугольника: "))
c1 = a1*b1
c2 = a2*b2
if c1 > c2:
print("Площадь первого прямоугольника бо... |
a521c6c539485688fcdc273ce3202168025926e6 | amenson1983/Python_couses | /Chapter 2 Distance.py | 277 | 3.84375 | 4 | speed = 70
time_6 = 6
time_10 = 10
time_15 = 15
dist_6 = speed*time_6
dist_10 = speed*time_10
dist_15 = speed*time_15
print("During 6 hours the distance will be: ", dist_6,"\nDuring 10 hours the distance will be: ", dist_10, "\nDuring 15 hours the distance will be: ", dist_15) |
1ab33843014c69df4f8aeb7d35f80a2190507420 | amenson1983/Python_couses | /Chapter 3 (1).py | 381 | 3.953125 | 4 | n = int(input("Please input a figure from 1 to 7"))
if n >= 1 and n <= 7:
n_ch = True
else: print("Not correct")
if n==1:
print("Monday")
elif n==2:
print("Tuesday")
elif n==3:
print("Wednesday")
elif n==4:
print("Thursday")
elif n==5:
print("Friday")
elif n==6:
print("Saturday")
elif n==7:
... |
6d2c63dc221d72ffcc2431d696988f33d6a18119 | amenson1983/Python_couses | /Chapter 3 (13).py | 286 | 3.921875 | 4 | mass = int(input("Please point the weight of your parcel (grams): "))
rate = 0
if mass<=200:
rate = 150
elif mass>200 and mass<=600:
rate = 300
elif mass>600 and mass<=1000:
rate = 400
elif mass>1000:
rate = 475
cost = rate*float(mass/100)
print("Amount to pay: ", cost) |
7c72be4c8267600763ec26e46d0913333ed39def | del0ff/IIS | /graph.py | 3,967 | 3.515625 | 4 | from __future__ import annotations
from collections.abc import Iterable, Iterator
from typing import Any, List
from queue import Queue
class GraphIterator(Iterator):
_position: int = None
def __init__(self, collection: TopCollection) -> None:
self._collection = collection
self._pos... |
448784979c9edc5a47e210b51f3eb317f81dad70 | rajeshpandey2053/Python_assignment_3 | /merge_sort.py | 939 | 4.1875 | 4 | def merge(left, right, arr):
i = 0
j =0
k = 0
while ( i < len(left) and j < len(right)):
if (left[i] <= right[j]):
arr[k] = left[i]
i = i + 1
else:
arr[k] = right[j]
j = j + 1
k = k + 1
# if remaining in left
while(i ... |
565ed1283b607e22ee16bee98826cce32368f271 | jacquesw12/Advent-of-code-2020 | /day7/day7.py | 1,930 | 3.546875 | 4 | #!/usr/bin/env python3
def contains_shiny(rules, bag):
if rules[bag][0] == '':
return False
if 'shiny gold' in rules[bag]:
return True
else:
res = False
for elt in rules[bag]:
res = res or contains_shiny(rules, elt)
return res
def bag_contains(rules, bag... |
4a44c18329b410b041cb06f6e9f890f3042feea6 | jacquesw12/Advent-of-code-2020 | /day4/day4.py | 2,595 | 3.625 | 4 | #!/usr/bin/env python3
import re
def read_entries(file):
list_entries = []
cur_map = {}
for line in file:
if line.strip():
entries = line.strip().split(' ')
for entry in entries:
key, value = entry.split(':')
cur_map[key] = value
else... |
a6a2047f7c3eb5d70312055311310b46a8d5a818 | Victormbg/Python | /Programas com pygame/Pong-master/ball.py | 3,314 | 3.875 | 4 | from paddle import *
from constants import *
from math import cos, sin
import random
from resources import *
"""
Desc file:
Contains Ball class witch inherits for the Paddle: a ball has a shape a color
a quantity of movement, it cans move from top down and collide with walls.
With... |
6c8c406974da3ed35898f343a63f90d5b3c094ca | AnanyaRao/Python | /tryp13.py | 198 | 4.0625 | 4 | def right_shift(num,n):
flag=num>>n;
return flag;
num=int(input('Enter the num:'))
n=int(input('Enter the n:'))
flag=right_shift(num,n);
print("The right shifted value is:",flag); |
b6c2661624d37fd6e7104a904e56486d15b921c0 | AnanyaRao/Python | /tryp12.py | 575 | 3.96875 | 4 | def check_amicable_numbers(num1, num2):
flag=False;
i=1;
j=1;
sum1=0;
sum2=0;
for i in range(i,num1):
if(num1%i==0):
sum1+=i;
for j in range(j,num2):
if(num2%j==0):
sum2+=j;
#print(sum1,sum2,num1,num2);
if(num1==sum2 and num2... |
fae187d17f928d0791df8d0f4f7d5f678d09c5cd | AnanyaRao/Python | /tryp10.py | 224 | 4.28125 | 4 | def factorial(num):
fact=1;
i=1;
for i in range(i,num+1):
fact=fact*i;
return fact;
num=int(input('Enter the number:'))
fact=factorial(num);
print('The factorial of the number is:',fact) |
6f1149877e0a3f9959f4b62806fe73a170c88ce3 | AnanyaRao/Python | /tryp24.py | 118 | 3.9375 | 4 | str1="The count is999 what we find here";
list_a=str1.split();
print("The number of words are:"+str(len(list_a))); |
bf5ca4a2000a7d1ffa895ec758308b80ef1cb93a | calwoo/ppl-notes | /wengert/basic.py | 1,831 | 4.25 | 4 | """
Really basic implementation of a Wengert list
"""
# Wengert lists are lists of tuples (z, g, (y1,...)) where
# z = output argument
# g = operation
# (y1,...) = input arguments
test = [
("z1", "add", ["x1", "x1"]),
("z2", "add", ["z1", "x2"]),
("f", "square", ["z2"])]
# Hash table to... |
2c9b757e2ec6c6c1f87f4ba68c041a052669b5ee | LeslieKuo/ANC-experiment | /test_interpolate.py | 1,253 | 3.546875 | 4 | # !/usr/bin/env python
# -*-coding:utf-8 -*-
import numpy as np
from scipy import interpolate
import pylab as pl
x = np.linspace(0, 10, 11)
print(type(x))
m = np.arange(8)
print(type(m))
# x=[ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.]
y = np.sin(x)
xnew = np.linspace(0, 10, 101)
pl.plot(x, y, "ro")
for k... |
d807d317dc96a5cbe3fe8a2917fb026f6d212831 | stamhe/bitcointalk_forum_scraper | /import_json.py | 1,702 | 3.546875 | 4 | import pymongo
import sys
import json
from comment_parser import parse_comment
def import_json(filename):
"""Reads a JSON file and inserts each element into the database
"""
mongo = pymongo.MongoClient()
database = mongo["bitcoin_rest"]
users = database.users
comments = database.comments
... |
977e974ee479c6af87f05a987a8adb8f03c14c78 | eggee/LPTHW | /ex24-PracticeEverything.py | 1,272 | 4.09375 | 4 | print "Let's practice everything."
#escapes '\' are needed to use hyphenation that might otherwise be confused as an end-of-string character
print 'You\'d need to know \'bout excapes with \\ that do \n newlines and \t tabs.'
#this is a lonnnnng string using 'escapes' for newlines and tabs
poem = """
\tThe lovely world... |
65dc28a631094879e2e41ac29e62bbe8242582f0 | sergiigladchuk/courses | /python/ExtraData/palindromExtractor.py | 1,399 | 3.5625 | 4 | #!/usr/bin/python3
import argparse
import sys
usage = '''This program extracts palindromic sequences from given fasta file and two parameters'''
parser = argparse.ArgumentParser(description=usage)
parser.add_argument('-v','--version',
action='version',
version='%(prog)s 1.0')
parser.add_argument('-s','--... |
726a9ec2206dbb868da9cdc6c211085accae2531 | sergiigladchuk/courses | /python/options2.py | 926 | 4.03125 | 4 | #!/usr/bin/python3
import argparse
import sys
usage = '''This program counts the total number of characters in a file
(including newlines) or in a number of lines in the files'''
parser = argparse.ArgumentParser(description=usage)
parser.add_argument('-v','--version',
action='version',
version='%(prog)s... |
af50326911f8ab7817ee2dd4c454b7e5b17bfc71 | isaacramiez00/ca-scrabble-pro | /scrabble.py | 1,933 | 3.703125 | 4 | # ca-scrabble-pro
#two lists
letters = ["A", "B", "C", "d", "E", "F", "G", "H", "I",
"J", "K", "L", "M", "N", "O", "P", "q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z"]
points = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 4, 1, 3,
10, 1, 1, 1, 1, 4, 4, 8, 4, 10]
#zip dict{}
letters_to_points = {letter.upper():poin... |
052a08212326fbe28e281a21af4364bf58d51e5e | mathead/pycrypt | /pycrypt/translators/substitutiontranslator.py | 916 | 3.5 | 4 | import translator
from .. import utils
from collections import OrderedDict
class SubstitutionTranslator(translator.Translator):
"""Basic substitution, default key reversed alphabet"""
def __init__(self, key=utils.alphabet[::-1]):
self.setKey(key)
def setKey(self, key):
if (type(key) in (dict, OrderedDict)):
... |
ea4c0e7adb7d2e75021ba01e152737c468b61916 | Nawan743/skribbl | /server/round.py | 1,772 | 3.5 | 4 | """
Represents a round of the game, storing things like word,
time, skips, drawing player and other stuffs
"""
import time
from _thread import *
from chat import Chat
class Round:
def __init__(self, word, player_drawing, players):
self.word = word
self.player_drawing = player_drawing
s... |
f6eaadfbc02240af09b8d1f10b7dcd62aab34f60 | kopperatom/python-2020-project. | /guessing gane.py | 3,329 | 4.15625 | 4 | ## Kian Johnson
#9/20
# guess my number 1.0
import random
#intro
print ("\twelcome to 'guess my number' ! ")
question = input ("what difficulty would you like easy, medium, hard" )
if (" Ea " in question) or ("ea" in question) : #e or E puestion
diff = 1
maxrange = 10
trys = 3
elif (" M " in questio... |
6a49e82ec807c79cbc5a036abfd7d585a06542a4 | LucioFex/The-Weird-Way | /TheWeirdBBDD.py | 1,845 | 3.59375 | 4 | import pickle
class Memoria:
"""
Almacenamiento de los niveles superados y
estrellas recolectadas en partida.
"""
def __init__(self):
"""Genera el archivo de guardado binario en caso de que no exista,
si existe, le entrega a la variable 'contenido'."""
with open("the_weird... |
71efc819db238b25e17f2afd1fb1f80b1a4956b2 | jackarendt/casino | /src/blackjack/actor.py | 3,199 | 3.59375 | 4 | from card import *
from constants import *
from hand import *
class Actor(object):
"""
Base class for interacting with the environment. Allows humans or AIs to use
the same API.
"""
def __init__(self, chip_count=0):
self.chip_count = chip_count
self.hands = [Hand()]
self.bet = 0
self.took_ins... |
87e331826daaefe9b7fd3acb7db0f464d357519e | devejs/Algorithm | /baekjoon/bj_2822_python.py | 631 | 3.640625 | 4 | """
2822. 점수 계산
210202 Solution
1. 문제 번호를 기억하기 위해 인덱스와 점수를 튜플로 같이 저장
2. 튜플의 두번째 요소인 점수를 기준으로 내림차순 정렬
3. 앞에서부터 5개 돌면서 합 구하고 추가 리스트에 각 문제 번호 저장
4. 문제 번호는 오름차순으로 정렬
"""
scores = []
sum = 0
strList = []
for i in range(8):
score = int(input())
scores.append((i,score))
scores.sort(key=lambda x:x[1], reverse=True)
fo... |
e843b5290f21a923a0a456416a313798a73d3a0a | bigboateng/robosoc_eurobot_2017 | /src/PrimaryRobot/PythonAstar/map_generator.py | 1,042 | 3.53125 | 4 | from PIL import Image
"""
This program will generate a sequence of 1's and 0's from image pixels:
Just specify the image path, the new width and height of the string
WARNING: this program is buggy when dealing with images smaller than the speficied height and width
You can pipe the result of this pro... |
2d4d22d0c2128ee775904c114c761c4fc24dfe90 | bigboateng/robosoc_eurobot_2017 | /src/PythonAstar/map.py | 10,641 | 3.53125 | 4 | from astar import AStar, AStarNode
from exception import *
from math import sqrt
import time
"""
This class contains higher level representation of the map.
It contains the obstacles as well as the locations of points of interest, e.g. location of cylinders, base, etc.
It also provides a path finding algorithm
"""
cla... |
d2321e22449b260fb832b295daedf41fc23c1bd2 | bigboateng/robosoc_eurobot_2017 | /src/SecondaryRobot/PythonAstar/map_loader.py | 1,609 | 3.96875 | 4 | # -*- coding: utf-8 -*-
from map import Map
from math import sqrt
"""
This class serves to load the map before the start of the competition
call load_map which returns Map object
"""
class MapLoader(object):
"""
file path points to the file where the 0's and 1's representation of the map is stored
"""
def __in... |
34c63d9de4d1ae434289c7cab6cb6489238e5b6a | neerajrao/interview-prep | /data-structures/linkedList/python/SinglyLinkedList.py | 4,184 | 3.5625 | 4 | class SinglyLinkedList:
def __init__(self):
self.head = None
self.tail = None
self.count = 0
def insert(self, node):
''' insert at head '''
if(self.isEmpty()):
self.head = node
self.tail = node
else:
node.setNext(self.head)
... |
cbe52a4c9bf047de882273ef2154f40794c754db | Handauru/pysocket | /udp_server.py | 935 | 3.796875 | 4 | #This is a gadget for sending UDP
# 1. Send UDP
# 2. configure the data size
# 3. configure the send interval
# 4. configure the dst addr
# 4.1 Unicast
# 4.2 Broadcast
# 4.3 Multicast
#---------------------------------
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Originated from https://github.com/michaelliao/learn... |
8bf474eb7cb4c7a20e28091486f107dd489edf74 | lowell1/Algorithms | /rock_paper_scissors/rps.py | 1,463 | 3.65625 | 4 | #!/usr/bin/python
import sys
# def recurse(n, idx):
# new_combos = []
# if idx == n - 1:
# arr = ["rock"] * n
# for text in ["rock", "paper", "scissors"]:
# new_combos.append(arr[:-1] + [text])
# else:
# print(idx)
# last_combos = recurse(n, idx + 1)
# for combo in last_combos:
# ... |
1bc5682b37a9397490f5c54e893c204d6e4f3e47 | wolfblunt/DataStructure-and-Algorithms | /heap.py | 659 | 3.859375 | 4 | def heapify(arr , n,i):
largest = i
leftChild = 2*i + 1
rightChild = 2*i + 2
if leftChild < n and arr[i] < arr[leftChild]:
largest = leftChild
if rightChild < n and arr[largest] < arr[rightChild]:
largest = rightChild
if largest != i:
arr[i] , arr[largest] = arr[largest] , arr[i]
heapify(arr , n , la... |
21c0da1e7b864c040519456ea60f6ca95e7d8bf7 | wolfblunt/DataStructure-and-Algorithms | /Sorting/QuickSort.py | 595 | 3.765625 | 4 | def quick_sort(nums , low , high):
if low >= high:
return
pivot_index = partition(nums, low, high)
quick_sort(nums, low, pivot_index-1)
quick_sort(nums, pivot_index+1, high)
def partition(nums, low, high):
pivot_index = (low + high)//2
swap(nums, pivot_index, high)
i = low
for j in range(low, high,1):
... |
dff5d06a52d72b122dae1d3f9cff595cd1283ce7 | wolfblunt/DataStructure-and-Algorithms | /Sorting/InsertionSort.py | 320 | 4.0625 | 4 | def insertion_sort(nums):
for i in range(len(nums)):
j = i
while j>0 and nums[j-1] > nums[j]:
swap(nums,j,j-1)
j= j-1
return nums
def swap(nums,i,j):
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
if __name__ == '__main__':
nums = [2,4,-1,-2,0,9,78,45,98,-4]
insertion_sort(nums)
print(nums) |
d3b6d836f217cfc764986f9873ab9d2dd92deb4c | wolfblunt/DataStructure-and-Algorithms | /Sorting/BubbleSort.py | 336 | 4.125 | 4 | def bubble_sort(nums):
for i in range(len(nums)-1):
for j in range(0,nums-1-i,1):
if nums[j] > nums[j+1]:
swap(nums, j ,j+1)
return nums
def swap(nums, i ,j):
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
if __name__ == '__main__':
nums = [12,34,23,1,5,0,56,22,-1,-56,-34,88,97,57]
bubble_sort(nu... |
56007489a13ff4b5be158899a0155aa562c6749c | Feliscatus84/file_watcher | /file_watcher/file_list.py | 1,113 | 3.859375 | 4 | import abc
import pickle
from typing import List
class FileSaver(abc.ABC):
@abc.abstractmethod
def save_file_list(self, file_list):
pass
@abc.abstractmethod
def get_file_list(self) -> List:
pass
class SimpleTextFileSaver(FileSaver):
def __init__(self, path):
self._path ... |
b43fa882a78c6df3a58963140449d48b23f06e16 | staiber/counter_salary | /counter_salary.py | 5,517 | 3.765625 | 4 | import pickle
import csv
class Rates:
period_result = 0
rates = "set.dat"
with open(rates, "rb") as file:
hourly_rate = pickle.load(file)
overtime_rate = pickle.load(file)
def __init__(self, hour, over):
self.hourly_rate = hour
self.overtime_rate = over
with... |
9630ca3dba6da9caee780ce534289340de497daa | z-sector/otus_algorithms | /src/hw4/priority_queue.py | 740 | 3.921875 | 4 | class Node:
def __init__(self, info, priority):
self.info = info
self.priority = priority
class PriorityQueue:
def __init__(self):
self.queue = list()
def insert(self, node):
if self.size() == 0:
self.queue.append(node)
else:
for x in range(0, self.size()):
if ... |
936ce5e1d8181e03d394ba350ef26c10ee575bb6 | sonias747/Python-Exercises | /Pizza-Combinations.py | 1,614 | 4.15625 | 4 | '''
On any given day, a pizza company offers the choice of a certain
number of toppings for its pizzas. Depending on the day, it provides
a fixed number of toppings with its standard pizzas.
Write a program that prompts the user (the manager) for the number of
possible toppings and the number of toppings offered on th... |
b8a846eed6f71d3dc9f45d7000c7582378507931 | NeymarCA/Project-4 | /main.py | 1,660 | 3.984375 | 4 | def main():
print("Please select one of the following destinations.", '\n', "1. Hawaii ", '\n', '2. Bahamas', '\n', '3. Cancun')
destinations = input()
if destinations == "1"or "Hawaii":
carrier(destinations)
elif destinations == '2' or 'Bahamas':
carrier(destinations)
elif destinations == '3' or "Ca... |
1cb28e20e5c5ce15052fa3e1f31a77b36115416a | CARLOSC10/T08_LIZA.DAMIAN_ROJAS.CUBAS | /ROJAS_CUBAS/iteracion.py | 3,523 | 4 | 4 | #ITERACIÓN DE CADENAS
#ejercicio 1
print("EJERCICIO 1")
cadena="LENGUAJE C++"
#ITERAR LA CADENA
for letra in cadena:
print(letra)
#fin_for
print("")
#ejercicio 2
print("EJERCICIO 2")
cadena="COMPUTADORAS Y LAPTOS"
#ITERAR LA CADENA Y CONTAR LA CANTIDA DE CARACTERES QUE TIENE
contador=0
for letra in cadena:
co... |
02a910acef85ef388668f2574792b9408b41f009 | CARLOSC10/T08_LIZA.DAMIAN_ROJAS.CUBAS | /LIZA DAMIAN CARLOS/3. COMPARACION.py | 6,006 | 4.03125 | 4 | #OPERACION CON CADENAS COMPARACION
print("EJERCICIO NRO 01")
#COMPARACION
cadena01="HOLA MUNDO DE LA PROGRAMACION EN PYTHON" #asignacion de la cadena carlos
cadena02="FRANK" #asiganacion de la cadena frank
verifica=(cadena01 == cadena02) #verifica si las cadenas son iguales
print("cadena01 == cadena02:",verifica) #im... |
0b6a5afc782a03fffefa7d3434272175bbebeb93 | LucasCorssac/mlp2 | /OOP/lists.py | 467 | 3.71875 | 4 | # funções uteis para listas
empty = []
def first(one_list):
return one_list[0]
def second(one_list):
return one_list[1]
def rest(one_list):
return one_list[1:]
def is_empty(one_list):
if len(one_list) == 0:
return True
else:
return False
def con... |
7a901428030be14e1aea86cd7480086c76c592ef | gmsIgor/igorgomespereira_P1 | /Q3.py | 367 | 3.5 | 4 | #questao 3
def pi():
anterior = 0
prox_imp = 1
pi = 4*(1/prox_imp)
anterior = -1000000
while abs(pi-anterior) > (5*pow(10,-8)):
anterior = pi
if(prox_imp < 0):
prox_imp = (abs(prox_imp) + 2)
else:
prox_imp = -(prox_imp + 2)
pi... |
055de414cf3bd3b54b3ae050ec0acbbe1d863683 | OsvaldoAmorim/Solves_hackerrank | /Diagonal_Difference.py | 621 | 3.984375 | 4 | #https://www.hackerrank.com/challenges/diagonal-difference/problem
#By: Osvaldo Amorim
#_________________________________________________________________
def diagonalDifference(arr):
# Write your code here
n = len(arr)
count = 0
j = n - 1
diagonalP = 0
diagonalS = 0
while count < n:
diagonalP += ... |
62021b456a4f6fbaeed24422fa09429698a7459d | ethanschreur/python-syntax | /words.py | 346 | 4.34375 | 4 | def print_upper_words(my_list, must_start_with):
'''for every string in my_list, print that string in all uppercase letters'''
for word in my_list:
word = word.upper()
if word[0] in must_start_with or word[0].lower() in must_start_with:
print(word)
print_upper_words(['ello', 'hey', '... |
312fa7f8b220070f3ba4dee8c1bef5c96ef022f5 | ndymion3217/library_manager | /도서관 관리 프로그램.py | 23,287 | 3.6875 | 4 | class Account:#ID, Password, 이름, 계정타입, 생년월일, 전화번호, 대여중인 책 목록
r = open('건드리지 마시오.txt','r')
r.seek(0)
id = r.readline().split()
password=r.readline().split()
name=r.readline().split()
type=r.readline().split()
birth=r.readline().split()
phone_num=r.readline().split()
books=[]
for i... |
95c466cec6fed05cedafb9ca19f7f10a9f4cc679 | Rashandeep/python-for-everybody-specialization-coursera-solutions | /course2/week3/2.7.2.py | 372 | 3.546875 | 4 | fname=input("enter file name")
try:
fh=open(fname)
except:
print("file doesnot exist")
quit()
count=0
sum=0
for line in fh:
line=line.strip()
if not line.startswith("X-DSPAM-Confidence:"):
continue
count=count+1
num=line.find(':')
val=line[num+1:]
fval=float(val)
sum=su... |
45c0d75d0d8365197a9a308328302a0fd6add08b | salnuraqidah/basic-python-batch4 | /Tugas-1/soal-3.py | 463 | 3.953125 | 4 | nilai_minimum = 70
teori = float(input("Nilai ujian teori : "))
praktek = float(input("Nilai ujian praktek : "))
if teori>=nilai_minimum and praktek>=nilai_minimum:
print("Selamat, anda lulus!")
elif teori>=nilai_minimum and praktek<nilai_minimum:
print("Anda harus mengulang ujian praktek")
elif teori<nilai_mi... |
ba83bd39ded8a760a464826957c4ba022249f0ec | hossamasaad/Console-Projects | /Probability Calculator/prob_calculator.py | 1,463 | 3.65625 | 4 | import copy
import random
# Consider using the modules imported above.
class Hat:
# constructor
def __init__(self, **no_of_balls):
# add balls to contents
self.contents = []
for k, v in no_of_balls.items():
for i in range(v):
self.contents.append(k)
de... |
b257b7b470331cf6a6968d16a96ba8fda13ec23e | tolgatc/PythonAdvancedMay2021 | /2_tuples_and_sets/5.py | 305 | 3.703125 | 4 | n = int(input())
all_guests = set()
for _ in range(n):
all_guests.add(input())
ticket = input()
arrived = set()
while not ticket == "END":
arrived.add(ticket)
ticket = input()
print(len(all_guests.difference(arrived)))
print(all_guests.difference(arrived))
# TODO print first VIP tickets |
0aebac4e26e6ab5e342b69db52cad354e07a85cc | tolgatc/PythonAdvancedMay2021 | /error_handling/3.py | 257 | 3.71875 | 4 | text = input()
number = input()
try:
number = int(number)
except ValueError:
print("Variable times must be an integer")
except SyntaxError:
print("Some syntax error")
else:
print(text * number)
finally:
print("Printed no matter what")
|
f98c04bb6bfbc4a524c13860a52674977ea75a50 | EddyArellanes/Python | /Scripts/RandomPath/Drunk.py | 2,368 | 3.5625 | 4 | # Also known as Camino de los Borrachos
import random
class Drunk:
def __init__(self, name):
self.name = name
class CommonDrunk(Drunk):
def __init__(self, name):
super().__init__(name)
def walk(self):
return random.choice([(0, 1), (0, -1), (1, 0), (-1, 0)]) #Options that would happen with the same ... |
f1197d2b20f47fa02a3f3d4370180962552d0bf6 | recroot89/exercism | /python/raindrops/raindrops.py | 250 | 3.6875 | 4 | def convert(number):
acc = ''
if number % 7 == 0:
acc = f'Plong{acc}'
if number % 5 == 0:
acc = f'Plang{acc}'
if number % 3 == 0:
acc = f'Pling{acc}'
if acc == '':
return str(number)
return acc
|
b0af56e83d834105190d4df02cf35918d73317ab | recroot89/exercism | /python/sum-of-multiples/sum_of_multiples.py | 284 | 3.796875 | 4 | def sum_of_multiples(limit, multiples):
return sum([x for x in range(1, limit) if has_multiply(x, multiples)])
def has_multiply(value, multiples):
for x in multiples:
if x == 0:
pass
elif value % x == 0:
return True
return False
|
f7fd118e928d0800d4a6c74be63e67cf8fc46be4 | recroot89/exercism | /python/armstrong-numbers/armstrong_numbers.py | 141 | 3.5 | 4 | def is_armstrong_number(number):
str_number = str(number)
return sum(map(lambda x: int(x) ** len(str_number), str_number)) == number
|
5bd6dcc6fe966a8034ec0ddee3b6f33a7736d515 | vincentluciani/python-playground | /design_patterns/full_factory_pattern/source_readers/abstract_parser.py | 319 | 3.6875 | 4 | from abc import ABC, abstractmethod
class AbstractParser(ABC):
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
@abstractmethod
def read(self, input_string):
pass
@abstractmethod
def display(self):
pass |
682cefecf41aa810f4158aa5d488b28c8b76ee55 | TejasNichat/Python-Projects | /Password Generator/main.py | 1,127 | 4 | 4 | # Password Generator Project
import random
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', ... |
f5b8c0d6665920b8a5c2913f54f45c2a6559c9d3 | rafaelgoncalvesmatos/estudandopython | /Programas/programa12.py | 450 | 3.796875 | 4 | #!/usr/bin/python
# -*- coding: latin1 -*-
import string
# Importando modulo string
print 'Importando modulo string - import string.'
print 'O alfabeto'
a = string.ascii_letters
print '\nConteudo da variavel a - a = string.ascii_letters'
print a
print '\nRodando o alfabeto um caractere para a esquerda.'
b = a[1:]+... |
63f4ccb9bbd91e0df9bce5d9b463aa8995ef94a1 | rafaelgoncalvesmatos/estudandopython | /Curiosidade/curiosidade07.py | 149 | 3.59375 | 4 | #!/usr/bin/python
# Fucando em condicoes dentro de variaveis
print 'Numeros pares'
for x in range(2,50,2):
print 'Valor de x e igual',x
# FIM
|
fd3f09e49d7dfce44464ac3e665e7442401c5f49 | rafaelgoncalvesmatos/estudandopython | /CBTNuggets/Range_number.py | 333 | 4.03125 | 4 | #!/usr/bin/python
# *-* coding:latin1 *-*
from __future__ import print_function
# Define range variable
numbers = range(5,50)
print(numbers)
for number in range(5,50,10) :
print(number)
# OR
print("-----------------------------------")
numbers1 = range(5,50,10)
print("numbers1")
for number1 in numbers1 :
p... |
3a657098da9e5064e211d3830ea78bb676a76399 | rafaelgoncalvesmatos/estudandopython | /Curiosidade/curiosidade16.py | 603 | 3.71875 | 4 | #!/usr/bin/python
# -*- coding: latin1 -*-
import string
print 'Brincando com string'
b = 'Trabalhando com texto'
a = string.hexdigits
print 'Trabalhando com formatacao de texto'
print '{:^30}'.format(b),'centralizado'
print '{:<30}'.format(b),'30 a esquerda'
print '{:>30}'.format(b),'30 a direita'
print '{:>40}'.f... |
32d6d454bbfa496bff66186894e10ef535416bfb | rafaelgoncalvesmatos/estudandopython | /Programas/programa06.py | 178 | 3.609375 | 4 | #!/usr/bin/python
# Trabalhando com loop
print 'Soma de 0 a 99'
s = 0
x = 1
while x < 100 :
s = s + x
x = x + 1
print "Repeticao numero.",x,"\nValor das somas",s
|
230b8f8ec3351f2b9b0615494deafc52aacb366c | rafaelgoncalvesmatos/estudandopython | /Curiosidade/curiosidade11.py | 249 | 3.96875 | 4 | #!/usr/bin/python
print 'Alterando conteudo da variavel para interiro'
a = float(raw_input('Digite um numero flutuante'))
print "Seu numero flutuante e: ", a
print "Convertendo isso para inteiro: ", int(a)
print "Flutuante novamente: ", float(a)
|
7bbfcb79f14e92c7abaa57bfd13a6d1a0bc9b626 | tackyattack/ML_learning | /linear_regression_relearn.py | 5,239 | 3.859375 | 4 | import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
path = os.path.normpath(os.getcwd() + os.sep + os.pardir + "/data/ex1data1.txt")
data = pd.read_csv(path, header=None, names=['Population', 'Profit'])
data.head()
print(data.describe())
# LEARNING AREA
# -------------------
# output =... |
b5887edb1d489421105fe45ca7032fb136c479df | KenMatsumoto-Spark/100-days-python | /day-19-start/main.py | 1,614 | 4.28125 | 4 | from turtle import Turtle, Screen
import random
screen = Screen()
#
# def move_forwards():
# tim.forward(10)
#
#
# def move_backwards():
# tim.backward(10)
#
#
# def rotate_clockwise():
# tim.right(10)
#
#
# def rotate_c_clockwise():
# tim.left(10)
#
#
# def clear():
# tim.penup()
# tim.clear(... |
712f1919ff6f178994fdb3986b0402820e5b8e76 | KenMatsumoto-Spark/100-days-python | /turtle-crossing-start/car_manager.py | 919 | 3.859375 | 4 | from turtle import Turtle
import random
COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 10
cars = []
class CarManager():
def __init__(self):
self.cars = []
def generate_car(self, current_level):
new_car = Turtle()
new_car.lev... |
21db6cba4a85bb50c2dcd2a244df81a7c5309495 | GrimReaperSam/Cini-OCR | /ciniocr/utils/md5.py | 722 | 3.59375 | 4 | import hashlib
import binascii
def md5sum(path, blocksize=65536):
"""
Generates the md5 of a file.
(Inspired from http://stackoverflow.com/questions/3431825/generating-an-md5-checksum-of-a-file)
:param path:
:param blocksize:
:return:
"""
hasher = hashlib.md5()
with open(path, 'rb'... |
756ff0bdf97f3ddd741327a02cee70a9980060dc | ARSimmons/IntroToPython | /Students/salim/session01/draw_box.py | 1,726 | 3.8125 | 4 | def print_grid(size, boxes):
# adjust wrong inputs
size, boxes = adjust_inputs(size, boxes)
# rows of grid
row_count = 0
for i in range(size):
# if row is a solid line
if row_count % (size / boxes) == 0:
print_row(width=size, row_type='solid', boxes=boxes)
# ... |
e39b0644bfc4e2398846ecd583fb12bf49fd4adb | ARSimmons/IntroToPython | /Solutions/Session04/get_langs.py | 554 | 3.828125 | 4 | #!/usr/bin/env python
"""
script to determine what programming languages students came to this clas iwth
"""
file_path = '../../Examples/Session01/students.txt'
all_langs = set() # use a set to ensure unique values
f = open(file_path) # default read text mode
f.readline() # read and toss the header
for line in f:... |
d3145d494d82b2757f415946e7240c3171d39dcb | ARSimmons/IntroToPython | /Students/SSchwafel/session01/grid.py | 2,264 | 4.28125 | 4 | #!/usr/bin/python
#characters_wide_tall = input('How many characters wide/tall do you want your box to be?: ')
##
## This code Works! - Commented to debug
##
#def print_grid(box_dimensions):
#
# box_dimensions = int(box_dimensions)
#
# box_dimensions = (box_dimensions - 3)/2
#
# print box_dimensions
#
# ... |
1c7d035b0f99f28e085e132e0ce7f9b0baee24c4 | ARSimmons/IntroToPython | /Students/lascoli/session03/unfinished_mailroom_4.py | 3,392 | 3.859375 | 4 | #Create a data structure with 2 elements (Name, Dollar Amount Donated)
donor_db = []
donor_db.append( ("Jimmy Page", [653772.32, 12.17]) )
donor_db.append( ("Robert Plant", [877.33]) )
donor_db.append( ("Roger Daltry", [663.23, 43.87, 1.32]) )
donor_db.append( ("Pete Townsend", [1663.23, 4300.87, 10432.0]) )
donor_db.... |
f2a07bb3055a4a6080aa523d1b31749c61df2536 | ARSimmons/IntroToPython | /Students/ebuer/session_03/mailroom.py | 5,607 | 3.515625 | 4 | #mailroom program to break the monotony
#this may be a bad idea but we will see
#a list of tuples for donors and donations
client_list = [
(('Askew', 'Anne'), (87.50, 100, 200)),
(('Bocher', 'Joan'), (25, 43.27)),
(('Clarkson', 'Jeremy'), (10.03,)),
(('Hamont', 'Matthew'), (1000, 250, 5)),
(('May',... |
11a8783eb1369de76d00aa4c76bd2465eaef4cee | ARSimmons/IntroToPython | /Students/Lottsfeldt_Erik/Session01/sum_double.py | 158 | 3.9375 | 4 | def sum_double(a, b):
# Store the sum in a local variable
sum = a + b
# Double it if a and b are the same
if a == b:
sum = sum * 2
return sum |
48517479b07bcb159045902b53a54763aacda282 | ARSimmons/IntroToPython | /Students/ASimmons/Session02/ack.py | 727 | 3.625 | 4 | __author__ = 'Ari'
class ackerman:
def ack(m,n):
"""Return a non-negative integer based on the Ackerman function
Definition of Ackerman: http://en.wikipedia.org/wiki/Ackermann_function
m, n: non-negative integers"""
# validate that m is NOT a negative number
if m < 0:
... |
f9aa2c4dc6d885a474be97d8e4220c5b8e9319ac | ARSimmons/IntroToPython | /Students/michel/session01/grid.py | 675 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
def grid(nbCol, nbRow, size):
''' Draws a grid nbCol wide and nbRow tall
nbCol and nbRow are integers > 0 and < 10
size is the width of a cell
size is an integer > 2
the function returns nothing'''
horLine = '... |
34ee45d78a702fe01e3a66228a6d3e1dfab19abd | ARSimmons/IntroToPython | /Solutions/Session03/rot13.py | 4,307 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
## the above line is so I can use Unicode in the source
## only there for the µ charactor in the timings report...
"""
A simple function to compute rot13 encoding
ROT13 encryption
Applying ROT13 to a piece of text merely requires examining its alphabetic
characters and r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.