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 |
|---|---|---|---|---|---|---|
70340f437b88e0d4d52384c7f0667fa05c1412f0 | anoff/aoc-2019 | /day04/python/wiedmann/solution.py | 1,133 | 3.921875 | 4 | def non_decreasing(d):
for i in range(len(d)-1):
if (d[i] > d[i+1]):
return False
return True
def contains_double(d):
for i in range(len(d)-1):
if (d[i] == d[i+1]):
return True
return False
def contains_double_no_larger_group(d):
# could be generalized s... |
8a199663c4dc2228104bbab583fd9ecaddcac34d | amitopu/ProblemSet-1 | /NonConstructibleChange/nonConstructibleChange.py | 1,728 | 4.40625 | 4 | def nonConstructibleChangePrimary(coins):
"""
Takes an arrary of coin values and find the minimum change that can't be made by the coins
available in the array.
solution complexity : O(nlogn) time complexity and O(1) space complexity
args:
-----------
coins (array): an array contains available coin values.... |
e874e83c5936a8dcd28f2f04dde6de4d604c5980 | amitopu/ProblemSet-1 | /ValidateSubsequence/validate_subsequence.py | 795 | 4.3125 | 4 | def isValidSubsequence(array, sequence):
"""
Takes one array and a sequence(another array) and checks if the sequence is the subsequence of the array.
solution complexity : O(n) time complexity and O(1) space complexity
args:
-----------
array : an array of numbers
sequence : an array of numbers
output... |
e3386a465ee38eab9b49cbcc8c2b62891fdd901c | Ramirezzz1/ROI_CAL | /WEEK3_ROI_CAL.py | 2,744 | 3.71875 | 4 | class ROI:
def __init__(self):
self.roi = {}
self.income = {}
self.expense = {}
self.cashflow = {}
self.cashoncash = {}
def display(self):
print(f'Here is your ROI {self.roi}')
def additem (self, newinput):
self.income.append(newinput... |
53c4ac424c3393dd8eaf4c1c046934dd29e07c6f | 1huangjiehua/ArithmeticPracticalTraining | /201826404105黄杰华算法实训/任务三.py | 1,724 | 3.953125 | 4 |
def QuickSort(lst):
# 此函数完成分区操作
def partition(arr, left, right):
key = left # 划分参考数索引,默认为第一个数为基准数,可优化
while left < right:
# 如果列表后边的数,比基准数大或相等,则前移一位直到有比基准数小的数出现
while left < right and arr[right] >= arr[key]:
right -= 1
# 如果列表前边的数,比基准数小或相等,则后移一... |
29e82e1945d6c7bd639b1d650e2b81bb6dfcdc52 | PascalBreno/My_Projects | /Alg_Próprios/Python/PersistenciaLista.py | 2,546 | 3.796875 | 4 | # hi, first you need to know your project's location
#The name 'nameMethod' it is name to your 'persistenciaLista'
nameMethod = input('insira o nome da entidade ou 0 para finalizar\n')
while(nameMethod!='0'):
#Here you need change to where your project is (or your folde with 'persistenciaLista')
arq = open("/h... |
f7525797742fc27d0e39b8915fc8736d660c78b3 | yucelzeynep/RBSC-based-deck-generation | /tools.py | 7,267 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 24 16:47:30 2021
@author: zeynep
"""
import numpy as np
from importlib import reload
import preferences
reload(preferences)
def get_rbsc(score1, score2):
"""
This function computes the rank biresial correlation coefficient (RBSC)
... |
bdccebebf8c857c2c483cfaefb3183fc211ea301 | shesdekha/Lab2 | /cond.py | 139 | 3.515625 | 4 | #!/usr/bin/env python3
import sys
print(len(sys.argv))
if len(sys.argv) != 10:
print('you do not have 10 arguments')
sys.exit()
|
5b407a0baa3591273020a9ed1f7303f2417aed15 | Patryk9201/CodeWars | /Python/8kyu/switch_it_up.py | 664 | 4.0625 | 4 | """
When provided with a number between 0-9, return it in words.
Input :: 1
Output :: "One".
"""
def switch_it_up(number):
switch = {
0: "Zero",
1: "One",
2: "Two",
3: "Three",
4: "Four",
5: "Five",
6: "Six",
7: "Sev... |
610395c1c0a55d4f8b7099bea152e4feb27dec23 | Patryk9201/CodeWars | /Python/6kyu/one_plus_array.py | 693 | 4.1875 | 4 | """
Given an array of integers of any length, return an array that has 1 added to the value represented by the array.
the array can't be empty
only non-negative, single digit integers are allowed
Return nil (or your language's equivalent) for invalid inputs.
Examples
For example the array [2, 3, 9] equals 239, addin... |
a03d3d86b25f8f132efb169ad8bd8174a9152ddb | Patryk9201/CodeWars | /Python/8kyu/temperature_in_bali.py | 1,092 | 4.1875 | 4 | """
So it turns out the weather in Indonesia is beautiful... but also far too hot most of the time.
Given two variables: heat (0 - 50 degrees centigrade) and humidity (scored from 0.0 - 1.0),
your job is to test whether the weather is bareable (according to my personal preferences :D)
Rules for my personal preference... |
bcb65ae85bfb738355861e848704689e2504816c | Bilal1Q1/Python-Projects | /Hello.py | 224 | 3.609375 | 4 | def cuont_list(listey):
count = 0
for i in listey:
if type(i) == list:
count += 1
return count
listey = [1,2,3,4,[5,6,7,8],9,[10],[12,13],[14]]
print(f"listey have {cuont_list(listey)} lists") |
6f8b35217c81f674022ada36ac918e381c8b4946 | tarzioo/guessing_game | /game.py | 1,038 | 4.0625 | 4 | # Put your code here
import random
rand_num = random.randint(1,2)
user = raw_input("Hey, What's your name? ")
play = 'Y'
while play.upper() == 'Y':
guesses = 1
print "Hey %s, let's play a game! Try to guess what number I'm thinking of" % user
num = int(raw_input("Hint, it's between 1 and 100: "))
try:
... |
c783ae559313167cff1e2e394960c4859816d3b0 | netteNz/PY4E | /Course 2/Week 1/strings2.py | 104 | 3.734375 | 4 | fruit = 'banana'
'n' in fruit
'm' in fruit
'nan' in fruit
if 'a' in fruit:
print('Found it')
|
7863b62d28d43700c35d6e5c3171ef8db3769c8f | netteNz/PY4E | /Week7/counting.py | 123 | 3.640625 | 4 | thing = [9, 41, 12, 3, 74, 15]
i = 0
for things in thing:
i += i
print(things)
print(len(thing))
|
5c88d84e443c4cf059a80ac137c0da40d47a4fe7 | kartikesh95/Testrep1 | /lpthw/ex13.py | 356 | 3.609375 | 4 | # Exercise 13 - Parameters, Unpacking, Variables
from sys import argv
script, first, second, third = argv
fourth = input("Provide fourth variable: ")
print("The script is called:", script)
print("Your first variable is:", first)
print("Your second variable is:", second)
print("Your third variable is:", third)
print(... |
945fd12a58d7b890e0e7d056977ca9263f33ea92 | bopopescu/python_training-1 | /vars.py | 103 | 3.78125 | 4 | a = 10
b = 20
print("a={0}, b={1}".format(a,b))
c = a
a = b
b = c
print("a={0}, b={1}".format(a,b))
|
f78250f01df49d085df8a8506df21560a77c60e0 | gsravank/ds-algo | /basics/queue_st.py | 608 | 3.828125 | 4 | class Queue:
def __init__(self):
self.push_stack = list()
self.get_stack = list()
return
def push(self, elem):
self.push_stack.append(elem)
return
def get(self):
if len(self.get_stack) == 0:
while len(self.push_stack) != 0:
self.... |
30c078166371d5310b605688ad7d904bd9315591 | gsravank/ds-algo | /codeforces/cf_550/a.py | 500 | 3.5625 | 4 | def check_diverse(s):
if len(s) == 1:
return True
if len(s) == len(set(s)):
ords = [ord(ch) for ch in s]
min_ords = min(ords)
max_ords = max(ords)
if max_ords - min_ords + 1 == len(s):
return True
else:
return False
else:
ret... |
48c40ec50fe5ed942ef94649feeed129ee6a6660 | gsravank/ds-algo | /basics/graph/level_order.py | 1,047 | 3.9375 | 4 | # Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param A : root node of tree
# @return a list of list of integers
def levelOrder(self, A):
level_order = list()
curr_le... |
761bbcf8574be550885759c597ea5cda6cafb28c | gsravank/ds-algo | /basics/polygon_angle.py | 287 | 3.65625 | 4 | """
https://codeforces.com/contest/1096/problem/C
"""
from fractions import Fraction
n = int(input())
for _ in range(n):
angle = int(input())
f = Fraction(180, angle)
if f.denominator <= f.numerator - 2:
print(f.numerator)
else:
print(2 * f.numerator)
|
60ce22fbd7cdfd7e32780d375f46b2054ea0c79b | gsravank/ds-algo | /basics/graph/cycle_undg.py | 1,171 | 3.78125 | 4 | from collections import defaultdict
def is_cycle_aux(vertex, adj_list, visited, parent):
# modified DFS to check if cycle exists
visited[vertex] = True
for neighbor in adj_list[vertex]:
if not visited[neighbor]:
if is_cycle_aux(neighbor, adj_list, visited, vertex):
ret... |
f9ef2b6e82a3703b324e58849cc73f41d26fd23a | aqiliangxue/Data-Structure-and-Algorithms-By-Python | /DataStructureAndAgrithom/Ch03_04/304Binary2Dec.py | 715 | 3.609375 | 4 | from basis.Stack import Stack
def divideBy2(number):
remStack=Stack()
while number>0:
rem=number%2
remStack.push(rem)
number=number//2
binString=""
while not remStack.isEmpty():
binString=binString+str(remStack.pop())
return binString
def baseConverter(number,base)... |
a1f70cf43b39caa2a1a34cf947b59cbd163c85eb | aqiliangxue/Data-Structure-and-Algorithms-By-Python | /DataStructureAndAgrithom/Ch09_10/Py608.py | 2,845 | 3.734375 | 4 |
# 优先队列,高优先级的数据项排在队首,低优先级的数据项排在后面
# 实现优先队列的经典方案是采用二叉堆(采用非嵌套的列表来实现)数据结构,二叉堆能够将优先队列的出队和入队的复杂度都保持在O(log n)
"""
完全二叉树:如果节点下标为p,其左子节点下标为2p,右子节点下标为2p+1,父节点下标为p//2
任何一个节点x,其父节点p中的值,均小于x中的值,根节点中的值最小
"""
class Binheap:
def __init__(self):
self.heapList=[0]
self.currentSize=0
def percUp(self,i):
... |
f8ebc3c78c7341e395a8b1ae8814c5937a3f748e | aqiliangxue/Data-Structure-and-Algorithms-By-Python | /DataStructureAndAgrithom/Ch07_08/505.py | 1,095 | 3.828125 | 4 |
# 谢尔排序:以插入排序为基础,对无序表进行“间隔”划分子列表,每个子列表进行插入排序,复杂度介于n和n*n之间
def shellSort(alist):
# 间隔设定,间隔越来越小,则子列表数量越来越少,无序表的整体越来越有序,从而减小整体比对次数
sublistcount=len(alist)//2
while sublistcount>0:
for startposition in range(sublistcount):
# 子列表排序
gapInsertionSort(alist,startposition,sublistcount... |
17c277e5ae89f873b67ae9b366d3661b59a09022 | aqiliangxue/Data-Structure-and-Algorithms-By-Python | /DataStructureAndAgrithom/Ch07_08/511.py | 159 | 3.5 | 4 |
def hash(astring,tablesize):
sum=0
for pos in range(len(astring)):
sum=sum+ord(astring[pos])
return sum%tablesize
print(hash("cat",11)) |
92db30c35fc693579a95ae420d0b3ae4e333fa8b | aqiliangxue/Data-Structure-and-Algorithms-By-Python | /DataStructureAndAgrithom/Ch07_08/507.py | 2,304 | 3.875 | 4 |
"""
快速排序:依据一个“中值”数据来吧数据表分为两半,小于中值的一半,和大于中值的一半,然后每部分分别进行快速排序(递归)
基本结束条件:数据表仅有一个数据项,自然是排好序的
缩小规模:根据中值,将数据表分为两半,最好情况是相等的两半
调用自身:将两半分别调用自身进行排序
# 运行中不需要额外的存储空间,关键点是中值的选取,选取不合适复杂度退化到O(n*n)
分裂数据表手段:
1、设置左右标
2、坐标向右移动,右标向左移动
坐标一直向右移动,碰到比中值大的就停止
右标向左移动,碰到比中值小的就停止
然后把左右标指向的数据交换
3、继续移动,直到坐标移动到右标的右侧,停止移动,这时右标所指的位置就是“中... |
a314ec3f4f965d818a3f7288cd2f611b84846fde | chandanavgermany/thesis_source_code | /MOO/Optimizer/job.py | 897 | 3.65625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 16 20:30:16 2020
@author: chandan
"""
class Job:
def __init__(self, job_id):
self._job_id = job_id
self._operations = []
self._max_sequence = 0
def set_max_sequence(self, max_sequence):
self._max_sequence = ... |
8d9f05cb1f555f836832b0c279b4746191c96462 | manhducpham/phamducmanh-fundamental-c4e21 | /session4/inclass/dic_ex1.py | 777 | 3.9375 | 4 | # bai toan tra cuu lookup
v1 = {
"lol": "laugh out loud",
'anw': "any way",
'btw': 'by the way',
'yoy': 'year over year',
'fyi': 'for your information',
'wth': 'what the hell?',
'idk': "i don't know",
}
while True:
key = input('''Enter your abbreviation, enter "exit" to quit the program:... |
5563f551b821fa8152a3ae75b9a421085ee4a4ae | manhducpham/phamducmanh-fundamental-c4e21 | /thinkcspy/chapter_3/ex_1to5.py | 620 | 4 | 4 | ### 1
# for i in range (1000):
# print("We like Python’s turtles!")
### 2
# for i in ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"):
# print("One of the months of the year is", i)
### 5
# a
# for xs in (12, 10, 32, 3, 66, 17, 42, 99, ... |
c5b402a97957d767d3aaeb9e874a0346dfff5bf5 | manhducpham/phamducmanh-fundamental-c4e21 | /session3/inclass/ex6.py | 581 | 3.859375 | 4 | fav_items = ['death note', 'netflix', 'teaching']
fav_size = len(fav_items)
print("*" * 20)
for i in range(fav_size):
print(i + 1, ". ", fav_items[i], sep = "")
print("*" * 20)
n = int(input("Which position do you want to delete? ")) - 1
if 0 <= n < fav_size:
fav_items.pop(n)
fav_size_new = len(fav_items)... |
ad611f8815a7d4d0d15f5f2983dc197834040b9d | manhducpham/phamducmanh-fundamental-c4e21 | /session4/homework/20_8_1.py | 283 | 3.6875 | 4 | letter_count = {}
sentence = input("Enter your sentence: ").lower()
for letter in sentence:
letter_count[letter] = letter_count.get(letter, 0) + 1
del letter_count[" "]
letter_items = list(letter_count.items())
letter_items.sort()
for i in letter_items:
print(*i, sep = "\t") |
c3c5c1557ed916b0e1b668e33962bee9064bd0a5 | manhducpham/phamducmanh-fundamental-c4e21 | /session3/inclass/ex5.py | 704 | 3.953125 | 4 | fav_items = ['death note', 'netflix', 'teaching']
fav_size = len(fav_items)
print("*" * 20)
for i in range(fav_size):
print(i + 1, ". ", fav_items[i], sep = "")
print("*" * 20)
# 2nd solution
# for index, item in enumerate(fav_items):
# print(index + 1, ". ", item, sep = "")
n = int(input("Which position do ... |
b66a9862ca351cc6a6d27162be30f7b6bc08c036 | manhducpham/phamducmanh-fundamental-c4e21 | /session3/homework/serious_ex2_part1to4.py | 650 | 3.75 | 4 | ### 2.1
flock_sizes = [5, 7, 300, 90, 24, 50, 75]
flock_num = len(flock_sizes)
print("Hello, my name is Manh and these are my ship sizes: ")
print(flock_sizes)
print()
### 2.2
max_size = max(flock_sizes)
print("Now my biggest sheep has size {0} let's shear it".format(max_size))
print()
### 2.3
default_size = 8
max_si... |
b7469eb425e9abaf5ddb6266fdfdf86451898708 | manhducpham/phamducmanh-fundamental-c4e21 | /session1/homework/ex44.py | 112 | 3.828125 | 4 | from turtle import *
# shape("turtle")
speed(0)
for i in range(100):
circle(100)
left(3.6)
mainloop() |
39992d965057b2156669c5252e268bb2cff20891 | Guillaume-dm/Phyton | /Test_positivité.py | 197 | 3.9375 | 4 | x=int(input("Saisir x : ")) #Test de positivité version 2.
if x>0 :
print ("x est strictement positif.")
elif x==0 :
print ("x est nul.")
else :
print ("x est strictement négatif.")
|
b2357c9ab1f333abd186b25c12bc9755b7c5d66f | natchavez/tagalog_english_identifier | /clean_dictionaries.py | 3,952 | 3.65625 | 4 | # Author: Nathaniel B. Chavez
# this was ran using Jupyter notebook, in order to clean the data of both filipino and english
# the nltk.corpus of english words are not yet in plural form, so added the list of orig corpus + the plural form
# I used inflect to get plural form of english words
import string
impor... |
a38b43657c41ca07ec4c3ea0844ad492c310d15e | ChungHaLee/BaekJoon-Problems | /BOJ 10817- Three Numbers.py | 156 | 3.515625 | 4 | import sys
numbers = sys.stdin.readline().split()
for i in range(len(numbers)):
numbers[i] = int(numbers[i])
numbers = sorted(numbers)
print(numbers[1]) |
1f12093987378f13156c85550bf961ee9677ac60 | blogSoul/Python_Challenge_Nomadcoder | /lecture_content/lab_code/section 1. Theory_code/section1to5.py | 188 | 3.59375 | 4 | def say_hello(who = "big"):
print("hello", who)
say_hello("Nicolas")
say_hello()
def plus(a, b):
print(a + b)
plus(1, 2)
def minus(a, b = 0):
print(a -b)
minus(2, 5)
minus(2) |
8af5fb4c5b64a2025be256185cf79868c0554f99 | lixu0818/leetcode | /python/70 stairs.py | 845 | 3.8125 | 4 | if n ==1:
return 1
if n ==2:
return 2
return self.climbStairs(n-1)+self.climbStairs(n-2)
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n ==1 or n==2:
return n
... |
6151cf5dbcf387ec524efa0e39cf400c69ca1ee7 | yurjeuna/teachmaskills_hw | /anketa.py | 1,580 | 4.25 | 4 | name = input("Hi! What's your name, friend? ")
year_birth = int(input("Ok, do you remember when you were born? \
Let's start with the year of birth - "))
month_birth = int(input("The month of your birth - "))
day_birth = int(input("And the day of your birth, please,- "))
experience = int(input("Have you studied pr... |
ae7dd308cde222ad835ad7c9d3490e267defe9de | DinaTaklit/Explore-Us-Bikeshare-Data | /bikeshare.py | 12,271 | 3.6875 | 4 | import time
import pandas as pd
import os
#This function is used to convert seconds to weeks, days, hours, minutes and seconds. It should be installed using: conda install humanfriendly
#Read more here https://stackoverflow.com/questions/775049/how-do-i-convert-seconds-to-hours-minutes-and-seconds/43261109#43261109
fr... |
9d569685b0d8d137b9ee7a23180289cfdd10488e | ErickaBermudez/exercises | /python/gas_station.py | 1,752 | 4.3125 | 4 | def canCompleteCircuit(gas, cost):
numberOfStations = len(gas)
# checking where it is possible to start
for currentStartStation in range(numberOfStations):
currentGas = gas[currentStartStation]
canStart = True # with the current starting point, we can reach all the points
# go thr... |
b2ee470fd49b2af6f975b9571c5f7579082da359 | mhkoehl0829/sept-19-flow-control | /Grade Program.py | 515 | 4.125 | 4 | print('Welcome to my grading program.')
print('This program will determine which letter grade you get depending on your score.')
print('What grade did you make?')
myGrade = input('')
if myGrade >= '90':
print('You made an A.')
else:
if myGrade >= '80' and myGrade < '90':
print('You get a B.')
if my... |
b403c7b589e0dea4675719a7269838ccaac11366 | k12shreyam/Tkinter | /SQL Database Application.py | 796 | 3.6875 | 4 | from tkinter import *
from tkinter import messagebox
obj=Tk()
obj.geometry("1080x600")
obj.title("GUI1")
obj['bg']="grey"
#frames on tkinter object obj
obj_frame=Frame(obj,width=900,height=400)
obj_frame.place(x=100,y=100)
#label on frames obj_Frame to print some message
obj_label=Label(obj_frame,text="SQL D... |
cbbcb84d2be44faf95bb4e30d5292deb2224f796 | adri-leiva/python_dev | /Ejercicios_bloque1/ejercicio1.py | 394 | 4.125 | 4 | """
EJERCICIO 1
- Crear variables una "pais" y otra "continente"
- Mostrar su valor por pantalla (imporimi)
- Poner un comentario poniendo el tipo de dato
"""
pais = "Argentina" #tipo de detos: cadena
continente = "Americano" #tipo de detos: cadena
""" print(pais)
print (continente)
"""
#print ("{} \n {}" . for... |
01ff723db60069304e7907fcefe1cdd3c9a09122 | michael-k-goff/map_generation | /map.py | 4,239 | 3.765625 | 4 | import png
# A single room in the map
class Room:
def __init__(self,l,r,b,t):
self.border = [l,r,b,t]
# Check for overlap
# Return True if no overlap, False if overlap
def check_conflict(self, new_room):
return self.border[0] >= new_room.border[1] or self.border[1] <= new_room.border[0]... |
7733d223e7d6347babb2fefcdba8f22559ae379f | Alleinx/Notes | /Python/Book_Learning_python/python_crash_course/part2_data_visualization/matlib.py | 281 | 3.75 | 4 | import matplotlib.pyplot as plt
x = [i for i in range(1, 6)]
y = [i**2 for i in range(1, 6)]
plt.plot(x ,y, linewidth=5)
plt.title("Square Numbers", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)
plt.tick_params(labelsize=5)
plt.show() |
c1da9852368f25180abe6f16ab2988f0e12405da | Alleinx/Notes | /Python/doc_Reads/library/d_type/collections_demo.py | 180 | 3.5 | 4 | import collections
deq = collections.deque()
deq.extend([i for i in range (10)])
print(deq)
deq.popleft()
print(deq)
deq.pop()
deq.appendleft('p')
print(deq)
deq.insert(100, -1)
|
16baa86dd0cb74ab107d331dd4735679774a3c26 | Alleinx/Notes | /Python/Book_Learning_python/fluent_python/cp7/pattern.py | 2,392 | 4.09375 | 4 | from abc import ABC, abstractmethod
class Customer:
"""Defines customer's properties"""
def __init__(self, name, fidelity):
self.name = name
self.fidelity = fidelity
class LineItem:
"""Defines item's properties"""
def __init__(self, product, quantity, price):
self.product =... |
1eee5ef4dd6b0d99a330b05c598c36cc48b1245d | Alleinx/Notes | /AI/approx_play.py | 2,225 | 3.625 | 4 | # This program tends to learn why NN can approximate any function:
# 1.Compare linear & non-linear activation function.
# 2.Use different non-linear activation function.
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import tqdm
def generate_target(... |
ec7c0d69a9e98853f063fd32ef431f4f28448d76 | Alleinx/Notes | /Python/Book_Learning_python/fluent_python/cp8/var.py | 875 | 4.5625 | 5 | # This program demonstrate the difference between shallow copy and deep copy
import copy
class Bus:
def __init__(self, passengers=None):
if passengers is None:
self.passengers = []
else:
self.passengers = list(passengers)
# Defensive programming style, won't mod... |
f59e6b21d364d84d2f4f79a87517989ff4be5d08 | Alleinx/Notes | /Python/npyscreen/code/app_manager.py | 1,557 | 3.578125 | 4 | '''
Robust framework for building large applications.
If you're displaying more than 1 screen, or running an application continuously,
this is the approach you should take.
'''
import npyscreen
class MainForm(npyscreen.Form):
'''
Instead of using the npyscreen.Form(widget, ...)
we can define our own Form ... |
75b1d9b79bf3253b2d1a5c0ff2d9bc3124c9b621 | Alleinx/Notes | /Python/Book_Learning_python/python_crash_course/part2_data_visualization/random_walk.py | 928 | 4.15625 | 4 | from random import choice
class RandomWalk():
""" A class that randomly generate data"""
def __init__(self, num_points=5000):
self.num_points = num_points
self.x = [0]
self.y = [0]
def fill_walk(self):
"""Genereate walking path"""
while len(self.x) < self.num... |
e79b41499da21469951537c4c3131eff4b8a6df8 | Alleinx/Notes | /Python/doc_Reads/howto/argparse/argparse_demo.py | 3,440 | 4.65625 | 5 | # This program demonstrates how to use argparse in python.
import argparse
parser = argparse.ArgumentParser(description='This program demonstrates how to use argparse module in python.')
# Define your args from here:
# 1.Positional argument.
# This method indicates which arg is **required** in this program.
# Actual... |
8c7c53f2c49abf69458fb1f8d121bf33ebc8a6b3 | Alleinx/Notes | /AI/pytorch/DL_w_PyTorch/sub_module.py | 912 | 3.796875 | 4 | # This program demonstrate how to build your own model, instead of using nn.Sequential()
# The Subclass need to extend nn.Module and implement at least forward() method.
import torch
import torch.nn as nn
class SubclassModel(nn.Module):
def __init__(self):
super().__init__()
self.hidden_layer = nn.... |
9b05b7aa4830e1c5fe6f1f6885199947cc01eccf | Alleinx/Notes | /Python/Book_Learning_python/fluent_python/cp7/simple_decorator.py | 989 | 3.890625 | 4 | import time
import functools
def clock(func):
def clocked(*args):
t0 = time.perf_counter()
result = func(*args)
elapsed = time.perf_counter() - t0
name = func.__name__
arg_str = ', '.join(repr(arg) for arg in args)
print('[%0.8fs] %s(%s) -> %r' % (elapsed, name, arg_... |
d8e9a5ecd2b339006d173088feaf9748ec590309 | Alleinx/Notes | /Python/Book_Learning_python/fluent_python/Misc/dict_set.py | 1,586 | 3.796875 | 4 | a = dict(one=1, two=2, three=3)
b = {'one': 1, 'two': 2, 'three': 3}
c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
assert a == b == c
# Dictcomp
codes = [
(86, 'China'),
(91, 'India'),
(1, 'US'),
(62, 'Indonesia'),
(55, 'Brazil'),
(92, 'Pakistan'),
(880, 'Bangladesh'),
(234, 'Nigeri... |
2c860c899e1864c79a48776448a6c2e3368492c7 | 023Sparrow/Projects | /Numbers/Coin_Flip_Simulation.py | 664 | 3.921875 | 4 | # Write some code that simulates flipping a single coin however many times the user decides. The code should record the outcomes and count the number of tails and heads.
# 假设出现0为反面,1为正面
import random
def coinflip(n):
coinlist = []
for i in range(1,n):
coinlist.append(random.randint(0,1))
def is_zer... |
4856b22b8653bb9343f567fe845ff98cf6725292 | 023Sparrow/Projects | /Classic_Algorithms/Sieve_of_Eratosthenes.py | 379 | 3.828125 | 4 | # Sieve of Eratosthenes
def odd_numbers():#生成一个无限序列,由3开始的奇数
i = 1
while True:
i = i + 2
yield i
def ismuti(n):
return lambda x: x % n > 0
def eratosthenes():
yield 2
it = odd_numbers()
while True:
n = next(it)
yield n
it = filter(ismuti(n), it)
for n in ... |
6fd363f6a639b159cc6594901c716fd3415a5402 | 023Sparrow/Projects | /Classic_Algorithms/Collatz_Conjecture.py | 420 | 4.28125 | 4 | #**Collatz Conjecture** - Start with a number *n > 1*. Find the number of steps it takes to reach one using the following process: If *n* is even, divide it by 2. If *n* is odd, multiply it by 3 and add 1.
def collatz(n):
k = 0
while n != 1:
if n%2 == 0:
n = n/2
else:
n ... |
278bf91ecaf8bb21d286bd21017ab26c79d1ac4f | 023Sparrow/Projects | /Text/Count_words_in_a_string.py | 267 | 3.875 | 4 | import re
def countword(s):
it = re.finditer('\s', s)
i = 1
for match in it:
i += 1
return i
print(countword('this is a test sentence:If you want to locate a match anywhere in string, use search() instead (see also search() vs. match()).'))
|
3b04d8c75bed612aef34fe423a12c15050b06100 | EduarFlo/Examne-2D-Graficacion | /examen2d.py | 1,267 | 3.84375 | 4 | '''
Examen 2D Graficacion
Alumno: Eduardo Gonzalez Flores
No Control: 17390753
Carrera: Ingenieria en Sistemas Computacionales
'''
import numpy as np
import matplotlib.pyplot as plt
plt.axis([-75, 75, -50, 50])
plt.axis('on')
plt.grid(True)
#Definimos el centro de x - y
xc = -15
yc = 0
# Dibujamos el primer rectan... |
d9ce9c80883c17132efb0972364278d4f187250e | Code-Institute-Submissions/DailyPlanner-1 | /run.py | 12,064 | 3.5625 | 4 | import gspread
from google.oauth2.service_account import Credentials
from datetime import datetime
from email_validator import validate_email
SCOPE = [
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/drive"
]
CREDS = Cred... |
8e5103a6f4fbae5ce65bcd0fed09a9ea0ad16fbe | JohnFoolish/DocumentationDemo | /src/basic_code.py | 1,426 | 4.4375 | 4 | # -*- coding: utf-8 -*-
"""
This first one is a basic function that includes the code you would need to
add two numbers together!
Why is this function useful?
----------------------------
* It can replace the '+' key!
* It can cause you to bill more hours for less work since the import takes
extra time to type!
* It... |
82d0625e5bb5253652418abbe3fe947de76d4114 | AlanStar233/Neusoft_Activity_coding | /basic.py | 402 | 4.1875 | 4 | # # Ctrl+'/'
#
# print('Hello Alan!')
#
# #int
# age = 19
#
# #string
# name = "张三"
#
# #print with var & var_type
# print(age)
# print(type(age))
#
# print(name)
# print(type(name))
# if
name = input("Please type your name:")
age = input("Please type your age:")
if int(age) >= 18:
print('{} Your age {} >= 18 !'.... |
7c0b69e41ad180b511a838a1cadb1807cb10e681 | nikmalviya/Python | /Practical 4/mutliplication.py | 140 | 3.90625 | 4 | num = int(input('Enter Number : '))
lines = int(input('Enter No of Lines : '))
for i in range(1,lines+1):
print(num,' x ',i,' = ',num*i) |
50d6af5ee5db1a764a160bd0f0bea1d3bf3fbdad | nikmalviya/Python | /Practical 6/prac6_lotto.py | 276 | 3.765625 | 4 | n = int(input('Enter No. Of Tickets : '))
from random import randint
nums = {x for x in range(1,51)}
tickets = {randint(1,50) for i in range(n) for j in range(10)}
if nums.difference(tickets):
print('All Numbers Not Covered')
else:
print('Yayy!! All Numbers Covered')
|
457b6785d7b6e812c54b323226e5fe11b4c3e1f2 | nikmalviya/Python | /Practical 4/pattern.py | 239 | 3.828125 | 4 | n = int(input('Enter Number Of Lines : '))
for i in range(1,n+1):
for j in range(n,i,-1):
print(' ',end=' ')
for k in range(i,0,-1):
print(k,end=' ')
for z in range(1,i):
print(z+1,end=' ')
print()
|
f5e712348ccfd6bdaeca45ba866571cf8d20e3ed | nikmalviya/Python | /Practical 4/baseconvertor.py | 153 | 3.921875 | 4 | def binhex(num):
print('Hex Value : {:X}'.format(num))
print('Binary Value : {:b}'.format(num))
n = int(input('Enter Number : '))
binhex(n)
|
dae75afabd045bc3443cecb61fcfd35d2ff3405b | nikmalviya/Python | /Practical 4/userapp.py | 883 | 3.75 | 4 | userlist = []
userlist.append(['nikhil',18,9909815772])
def isUserExist(name):
for user in userlist:
if(user[0] == name): return True
return False
def validate(name, age, phone):
name = name.isalpha()
if not name: print('Enter Valid User Name')
age = age.isdigit()
if not age: print('... |
069cecae1e6a534e78733abdafd2a7c9053b9c09 | nikmalviya/Python | /Practical 2/power.py | 100 | 3.625 | 4 | print('(a\tb\ta**b)')
for i in range(1,6):
a = i
b = i + 1
print(a, '\t', b, '\t', a**b) |
e6b4eb87feb52bb6c5d0fc0cbc784e6cee3b20af | RKiddle/python_reg_expressions | /Formatting_Strings/Make-this-function.py | 595 | 4.03125 | 4 | """"
To perform an operation between var1 and var2 inside a f-string, use f"{var1 * var2}".
Remember that you can use the format specifier :.nf to indicate the number n of decimals.
""""
# Include both variables and the result of dividing them
print(f"{number1} tweets were downloaded in {number2} minutes indicating ... |
057267cc84f53c5fa966d5ec4d0035d58e412045 | michaelg68/KNearestNeighbors | /main.py | 1,486 | 3.65625 | 4 | import sklearn
from sklearn.utils import shuffle
from sklearn.neighbors import KNeighborsClassifier
import pandas as pd
import numpy as np
from sklearn import linear_model, preprocessing
data = pd.read_csv("KNN/car.data")
#print(data.head()) #To check if data is loaded correctly
le = preprocessing.LabelEncoder()
buy... |
fabfb8982d91b9e9c9c15472811ee5fe3f89db82 | NotAlwaysRignt/Personal_Study | /Note and Code/编程/python/语法和python基本模块/open函数/open.py | 628 | 3.625 | 4 | #-*-coding:utf-8-*-
f=open('line.txt')
data = f.readline()
print data
print len(data)
'''
f=open('test.txt')
print f.next()
print f.next()
print f.next()
'''
'''
for line in f:
print line
'''
'''
for another_line in f:
if another_line.startswith('mark'):
print another_line
... |
5694e84e8616bbd4b069ebb05db2823bb99199ca | NotAlwaysRignt/Personal_Study | /Note and Code/编程/python/语法和python基本模块/decorator用法/Try_decorator.py | 1,194 | 3.84375 | 4 | #-*-coding:utf-8-*-
'''使用decorator'''
'''
def My_decorator(fun):
def func1(*p1,**p2):
print 'Let\'s see the rank'
return fun(*p1,**p2) #return拼错了会给fun报错,给人误导
return func1
@ My_decorator
def now(*p1,**p2):
print p1,p2
now('now',city='Beijing')
'''
def My_decorato... |
16ffc5a91c440a43d2e13ec402fc66e8d96940f7 | TommyThai-02/Python-HW | /hw08.py | 1,277 | 3.875 | 4 | #Author: Tommy Thai
#Filename: hw08.py
#Assignment: hw08
def get_vowel(content):
vowels = "aeiou"
_numofvowels = 0
for v in content:
if v.lower() in vowels:
_numofvowels += 1
return _numofvowels
def get_consonants(content):
consonants = "bcdfghj... |
bf8a718b87bd57002dfd3037c1ea6ceda4ab0261 | TommyThai-02/Python-HW | /hw04.py | 512 | 4.1875 | 4 | #Author: Tommy Thai
#Filename: hw04.py
#Assignment: hw04
#Prompt User for number of rows
rows = int(input("Enter the number of rows:"))
#input validation
while rows < 1:
#Error message
print("Number of rows must be positive.")
#Prompt again
rows = int(input("Enter the number of rows:"))
... |
ef3b8d624346cfbc6516b8d44e8cc22001e88ce9 | damodharn/Python_Week1 | /Week1_Algo/Temp_Conversion.py | 755 | 4.25 | 4 | # *********************************************************************************************
# Purpose: Program for checking if two strings are Anagram or not.
# Author: Damodhar D. Nirgude.
# ************************************************************************************************
from Week1_Algo.Utility2 ... |
99d696489a99b757533659ea9953b10c7781b447 | damodharn/Python_Week1 | /Week1_Functional/Utility.py | 3,769 | 4.09375 | 4 | # *********************************************************************************************
# Purpose: Creating Utility Class for all the static methods for Functional programs.
# Author: Damodhar D. Nirgude.
# ************************************************************************************************
import ... |
c93849ff244e494864be212fa94d97a591233291 | damodharn/Python_Week1 | /Week1_Functional/StopWatch.py | 868 | 4.28125 | 4 | # *********************************************************************************************
# Purpose: Program for measuring the time that elapses between
# the start and end clicks.
# Author: Damodhar D. Nirgude.
# ****************************************************************************************... |
80363199f79ea30e1b584b94654631d83840eb67 | kkecher/farpost | /Python. Имена с gramota.ru.py | 3,028 | 3.5625 | 4 | #!/usr/bin/env python3
'''
Собирает имена и их синонимы с gramota.ru. Сайт не отдает список имен, но позволяет искать со *, поэтому будем подставлять буквы и забирать результаты, пока не получим пустую страницу
Вход: ничего
Выход: список имен с синонимами
'''
import requests
import re
url = 'http://gramota.ru/slovar... |
0a13e4348da6273cec5a6bb0d68c441b4b260332 | kkecher/farpost | /Python. Склонения (Morpher.ru).py | 1,967 | 3.640625 | 4 | '''
Собирает склонения с сайта morpher.ru
Вход: файл «Леммы» со списком лемм
Выход: файл «Склонения» со списком склонений
Поменять: список лемм в файле «Леммы»
'''
import json, requests
url = "https://ws3.morpher.ru/russian/declension"
with open('Леммы.txt', 'r') as f: #Записываем леммы из файла в список без символо... |
a55d5f0f17b73ae27d1031db948b8c1acbbebe46 | kkecher/farpost | /Python. URL'ы из sitemap'ов.py | 996 | 3.546875 | 4 | '''
Собирает все URL'ы из sitemap'ов
Вход: URL в sitemap'ами
Выход: Файл с URL'ами из sitemap'а
'''
import urllib.request
import re
url = input('Enter sitemap ULR: ')
result = input('Enter result file: ')
url_list = []
def get_urls(url):
'''
Собирает все URL'ы из sitemap'ов
Вход: URL в sitemap'ами
Вы... |
b472b99c574bec9609ad8ffc595890031cdf50c3 | schedges/loiSearcher_pythonAnywhere | /loiSearcher.py | 2,824 | 3.5 | 4 | def loiSearch(frontierToSearch,searchTerm,caseSensitive=0):
import pickle
#For linking to LOIs
mainsite = "http://www.snowmass21.org/docs/files/summaries"
#How many results to show
nResultsToShow=20
nPreviewChars=500
#Open input file
inpFilename="/home/shedges/mysite/LOIs.pickle"
... |
a1808e94fd51c61a549a7131cf032eb3aa90c8f5 | jsimonton020/Python_Class | /lab9_lab10/lab9-10_q1.py | 642 | 4.125 | 4 | list1 = input("Enter integers between 1 and 100: ").split() # Get user input, and put is in a list
list2 = [] # Make an empty list
for i in list1: # Iterate over list1
if i not in list2: # If the element is not in list2
list2.append(i) # Add the element to list2 (so we don't have to count it again)
... |
8511c4077c835a414e36aa723529248499c0e6bb | jsimonton020/Python_Class | /lab2/lab2_q2.py | 432 | 3.921875 | 4 | amount = eval(input("Please Enter Investment Amount: "))
rate = eval(input("Please Enter Annual Interest Rate: "))
years = eval(input("Please Enter Number of Years: "))
mrate = rate / 1200
total = amount * (1 + mrate) ** (12 * years)
print("Accumulated Value is:", round(total, 2))
'''
Please Enter Investment Amount:... |
902922c5ba06d1bfd8a29d5410a5a6f23e8594d6 | jsimonton020/Python_Class | /lab2/lab2_q1.py | 234 | 3.984375 | 4 | celsius = eval(input("Please Enter a Degree in Celsius: "))
farenheit = (9 / 5) * celsius + 32
print(celsius, "Celsius is", round(farenheit, 1), "Farenheit")
'''
Please Enter a Degree in Celsius: 43
43 Celsius is 109.4 Farenheit
'''
|
6ddae283a78dec8205f97fc6f417e04eb3744b59 | ISC1606-MSW-GB-AD21/insercion | /insercion.py | 288 | 3.578125 | 4 | #Declaracion de Funciones
def insercion(A):
for i in range(len(A)):
for j in range(i,0,-1):
if(A[j-1] > A[j]):
aux=A[j]
A[j]=A[j-1]
A[j-1]=aux
#Programa Principal
A=[6,5,3,1,8,7,2,4]
print(A)
insercion(A)
print(A) |
88a8a391ffb30570db0825668058f6056ae287ec | momentum-cohort-2018-10/w1d3-palindrome-SowmyaAji | /palindrome.py | 838 | 4.0625 | 4 | your_sentence = input("What do you want to test as a palindrome?").lower()
import re
cleared_sentence = re.sub (r'[^A-Za-z]', "", your_sentence)
print(cleared_sentence)
if len(cleared_sentence) <= 1:
print("Is palindrome")
def match_alpha(cleared_sentence):
"""Each alphabet of the input is matched... |
7d4ed8cc8dd572ec0f071dc485eb6560595d8b2e | edelans/aoc2018 | /day05.py | 2,117 | 3.625 | 4 | #!/usr/bin/env python3
"""Template file to be used as boilerplate for each day puzzle."""
from aoc_utilities import Input
import aocd
import sys
# import itertools
# day must be 2 digit
DAY = '05'
"""
PART1
"""
def collapse1(input):
"""Takes a string and returns polymer after one iteration of collapsing."""
... |
2eaa68be8743767a7b4a7fd9e796b35121e6738c | alkaprog/summer_practice | /summer_practice_2020_final.py | 9,863 | 3.734375 | 4 | from math import *
from time import time
from random import randint
import tracemalloc
"""Задача о назначении минимального количества исполнителей:
Дано n исполнителей и m работ. Для каждой пары (исполнитель, работа) заданы затраты на выполнение работы wij. Имеется общий бюджет w на выполнение
всех работ. Треб... |
0dbdddafe5f0a2fad6b8778c78ec913561218eea | AndriyPolukhin/Python | /learn/ex02/pinetree.py | 1,500 | 4.21875 | 4 | '''
how tall is the tree : 5
#
###
#####
#######
#########
#
'''
# TIPS to breakdown the problem:
# I. Use 1 while loop and 3 for loops
# II. Analyse the tree rules:
# 4 spaces _ : # 1 hash
# 3 spaces _ : # 3 hashes
# 2 spaces _ : # 5 hashes
# 1 space _ : # 7 hashes
# 0 spaces _ :... |
a2b98b45cc022cabeb8dd82c582fd1c2f37356fb | AndriyPolukhin/Python | /learn/ex01/checkage.py | 805 | 4.5 | 4 | # We'll provide diferent output based on age
# 1- 18 -> Important
# 21,50, >65 -> Important
# All others -> Not Important
# List
# 1. Receive age and store in age
age = eval(input("Enter age: "))
# and: If Both are true it return true
# or : If either condition is true then it return true
# not : Convert a true cond... |
06a522784b6f26abb7be62f6bfd8486ffd425db0 | AndriyPolukhin/Python | /learn/ex01/gradeans.py | 437 | 4.15625 | 4 | # Ask fro the age
age = eval(input("Enter age: "))
# Handle if age < 5
if age < 5:
print("Too young for school")
# Special output just for age 5
elif age == 5:
print("Go to Kindergarden")
# Since a number is the result for age 6 - 17 we can check them all with 1 condition
elif (age > 5) and (age <= 17):
... |
8011705c39173efb62008992f83900ebfb92bd00 | AndriyPolukhin/Python | /hello/exercise01.py | 504 | 3.578125 | 4 | import sched
import time
s = sched.scheduler(time.time, time.sleep)
s.enter(2, 1, print, argument=('first'))
s.enter(3, 1, print, argument=('second'))
s.run()
start = '2018-08-12 7:35:15.629694'
stop = '2018-08-12 7:40:15.629694'
sc = sched.scheduler(time.time, time.sleep)
sc.enter(4, 1, print, argument=('third'... |
91edd7e455104e8ed014c691ecd468c264d3f94d | AndriyPolukhin/Python | /learn/ex07/recursive.py | 762 | 4.03125 | 4 | # RECURSIVE FUNCTION
# 1. FACTORIAL
# 3! = 3 * 2 * 1
def factorial(num):
if num <= 1:
return 1
else:
result = num * factorial(num - 1)
return result
print("4! = ", factorial(4)) # 4! = 24
# 1st: result = 4 * factorial(3) : 4 * 6
# 2nd: result = 3 * factorial(2) : 3 * 2
# 3rd: resu... |
99942ce7638643f25c9c1a572d8a91ad5e412a50 | silencerfy/myStuff | /survey.py | 3,419 | 4.0625 | 4 | #!/usr/bin/python
name = raw_input("Please enter your name: ")
answer1 = raw_input("Who are you? (e.g. software developer at iCrossing): ")
answer2 = raw_input("Do you support Open Source Software Development (A), Closed Source Software Development (B), Both (C), or Neither (D)? Please enter A, B, C, or D: ")
while 1:... |
426bdd9455ec9a3e4be23e1422a1ef628c93cfe9 | silencerfy/myStuff | /CodeChef/Life, the Universe, and Everything.py | 145 | 3.96875 | 4 | #!/usr/bin/python
#Life, the Universe, and Everything
x = int(raw_input())
while 1:
if x == 42:
break
print x
x = int(raw_input())
|
25d6aada9d0ae475343ca02fa79a5969565a4b7b | RehamDeghady/python | /task 2.py | 753 | 4.3125 | 4 | print("1.check palindrome")
print("2.check if prime")
print("3.Exit")
operation = int (input ("choose an operation:"))
if operation == 1 :
word = str(input("enter the word"))
revword = word[::-1]
print("reversed word is" ,revword)
if word == revword :
print("yes it is palindro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.