blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
b216bbcbb8d3d1c854b2ce54d89474f44d4759fa | milton96/practicas | /python/diccionario.py | 132 | 3.9375 | 4 | info = {"city": "Tepic", "name": "Juan", "age": 20}
for i,v in info.items():
print(i,v)
print(info.keys())
print(info.values())
|
9899d3a53e7e588e65fcd1cf9fd498572a8bb05f | infosel-it/Machine-Learning-Examples | /regression/linearregression.py | 1,168 | 4 | 4 | import matplotlib.pyplot as plt
import pandas as pd
from sklearn import linear_model
weeksalesdata = {'week': [1,2,3,4,5],
'sales': [1.2,1.8,2.6,3.2,3.8] }
df = pd.DataFrame(weeksalesdata,columns=['week','sales'])
plt.scatter(df['week'], df['sales'], color='green')
plt.title("Week and Sales in Th... |
eb4bfe8ea7e725f36c1b619ba5e7cd2853f91d78 | Spokesk/number-guess | /neoplatonist-solution.py | 2,396 | 3.96875 | 4 | import sys
from random import randint
level_difficulty = {
"Easy": {
'max_number': 10,
'tries': 3
},
"Medium": {
'max_number': 50,
'tries': 5
},
"Hard": {
'max_number': 100,
'tries': 5
},
"Extreme": {
'max_number': 1000,
'tries... |
ac1320db4244a8a91ce92d2484176daa5a56be3f | chooper/watchman | /example.py | 795 | 3.515625 | 4 | #!/usr/bin/env python
"""This example triggers a callback whenever randint(0,5) returns 2. The
callback simply prints the metric history to the screen.
"""
if __name__ == '__main__':
import sys
from random import randint
from watchman import Watchman
collector = randint
def filter_func(history):... |
ca12e72cf57d71c025bf071317ffafe712722849 | nishant-v/learning_python | /Chapter_1/Reinforcement/R-1.3.py | 308 | 3.84375 | 4 | def minmax(k):
min = k[0]
max = k[0]
for i in range(len(k)):
if k[i] < min:
min = k[i]
if max < k[i]:
max = k[i]
return min,max
num_list = [2,1,4,11,44,3]
min, max = minmax(num_list)
print ("Max ={}, Min = {}".format(min, max))
|
4edc8dc6f710a99c6112d3e6e4d706ee5be6424b | jkfer/Codewars | /Reversed_Words.py | 348 | 3.9375 | 4 |
str = "The greatest victory is that which requires no battle"
def reverseWords(str):
output = ""
L = str.split()
for i, word in enumerate(L):
if i == len(L) - 1:
output = word + output
else:
output = ' ' + word + output
return output
x = reverseWords(... |
05bf4280a7750cf207609ae63ed15f1cee96843f | jkfer/Codewars | /logical_calculator.py | 1,602 | 4.40625 | 4 | """
Your task is to calculate logical value of boolean array. Test arrays are one-dimensional and their size is in the range 1-50.
Links referring to logical operations: AND, OR and XOR.
You should begin at the first value, and repeatedly apply the logical operation across the remaining elements in the array sequenti... |
b3a0608ad6899ac13e9798ecf4e66c597f688bd1 | jkfer/Codewars | /valid_paranthesis.py | 1,071 | 4.3125 | 4 | """
Write a function called that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return true if the string is valid, and false if it's invalid.
Examples
"()" => true
")(()))" => false
"(" => false
"(())((()())())" => t... |
93a165b24f06df488bca642497b4e2ebb942eab8 | jkfer/Codewars | /disemvowel.py | 550 | 4.03125 | 4 |
"""
Your task is to write a function that takes a string and return a new string with all vowels removed.
"""
def disemvowel(string):
vowels = list('aeiouAEIOU')
L = list(string)
for i, lett in enumerate(L):
if lett in vowels:
L.pop(i)
return ''.join(L)
def disemv... |
bcd9ddaeab60580eeb2e4f92eeef8998af50aeb0 | chelseah/LCFIT | /primitive_lcfit_scripts/plot_system.py | 9,274 | 3.90625 | 4 | import os
import sys
import functions
import fitting_functions
from numpy import *
import matplotlib.pyplot as plt
from scipy import optimize
def smooth(x,window_len=11,window='flat'):
"""smooth the data using a window with requested size.
This method is based on the convolution of a scaled window with th... |
4c38f277bb27d7c9f4d5a45eed8cc6bf3d22597f | jangboolee/codility_solutions | /lessons/04c_missing_integer.py | 607 | 3.5625 | 4 | def solution(A):
# Create a unique set of the values in A
unique_A = set(A)
# Return 1 if none of the values are greater than 0
if max(unique_A) < 0:
return 1
else:
# Initialize a dictionary of all of the numbers that should be found
counter = {num: 0 for num ... |
6dda597623faba6a40b3ef7f3592b1a3f350f413 | CitizenOfRome/My-Python-LAB | /Gild_SOPA.py | 359 | 3.703125 | 4 | #!/usr/bin/python
import sys
file = open(sys.argv[1], "r")
def shift(c, d):
if "A"<=c<="Z": k = 65
elif "a"<=c<="z": k = 97
else: return c
l = k+25
n = ord(c)
r = n+d
while r>l: r-=25
while r<k: r+=25
return chr(r)
d = int(file.readline()[:-1])
for st in file:
print "".joi... |
ad16030fe65ac0005b1d07d56957fb66737f5d72 | yvlian/algorithm | /python/继承.py | 1,460 | 4.40625 | 4 | '''
继承的优点:提升代码的复用程度,避免重复操作。
继承的特点:
1、 同时支持单继承与多继承,当只有一个父类时为单继承,当存在多个父类时为多继承。
2、子类会继承父类所有的属性和方法,子类也可以覆盖父类同名的变量和方法。
3、在继承中基类的构造(__init__()方法)不会被自动调用,它需要在其派生类的构造中亲自专门调用。有别于C#
4、在调用基类的方法时,需要加上基类的类名前缀,且需要带上self参数变量。区别于在类中调用普通函数时并不需要带上self参数
5、Python总是首先查找对应类型的方法,如果它不能在派生类中找到对应的方法,它才开始到基类中逐个查找。
(先在本类中查找调用的方法,找不到才去基类中找)。
... |
5ed60d790881836b77e097154a8079317fbd87f7 | yvlian/algorithm | /t.py | 961 | 3.5625 | 4 | # import time
# x = 8
# L = [i for i in range(10**x)]
# begin = time.time()
# del L[:]
# end = time.time()
# print(end-begin)
# #最大递归层数
# def func(i):
# print(i)
# func(i+1)
# func(1)
#
# from threading import Thread,RLock
# import time
# num = 0
# class MyThread(Thread):
# _thread_rlock = RLock()
# de... |
dd7f5b528411e31aeabad2bb00168a8f7145c1d9 | yvlian/algorithm | /算法/神奇的位运算.py | 315 | 3.5625 | 4 | '''
给定x,取两个整数,使得x^a^b取得最大值。
求符合要求的a,b中,满足|a-b|最小的方案个数。
x,a,b均大于0小于2**31
'''
# x = int(input())
x = 100
print('----------------------')
num = 0
while x:
if x & 1:
num += 1
x >>= 1
print(2**(num+1))
print('aAAA'.isupper()) |
c70b83e5fadac95d54ad67811b337b65b8924e15 | yvlian/algorithm | /python/设计模式/单例模式.py | 3,853 | 3.859375 | 4 | #装饰器实现
def Singleton(cls):
_instance = {}
def _singleton(*args, **kargs):
if cls not in _instance:
_instance[cls] = cls(*args, **kargs)
return _instance[cls]
return _singleton
@Singleton
class A(object):
a = 1
def __init__(self, x=0):
self.x = x
a1 = A(2)
a2... |
90bbc1315126c8ce4d51597b4faee986bfcd25cc | yvlian/algorithm | /python/协程.py | 2,521 | 3.609375 | 4 | #什么是协程(微线程、纤程):协程是一种伪多线程,其开销远小于线程的开销。
# Python有一个GIL(Global Interpreter Lock)机制
# 任何线程在运行之前必须获取这个全局锁才能执行
# 每当执行完100条字节码,全局锁才会释放,切换到其他线程执行。
# 在python GIL之下,同一时刻只能有一个线程在运行,python只能使用到1个核
# 对于CPU计算密集的程序来说,线程之间的切换开销就成了拖累,
# 而以I/O为瓶颈的程序正是协程所擅长的
# 协程的发展:
# 1)最初的生成器变形yield/send
# 2)引入@asyncio.coroutine和yield from
# 3)在最近的Pyt... |
4f1cb40f6d9f159884725b3f383989c77888a6bc | metchel/COMP424 | /Assignment1/6-Puzzle.py | 300 | 3.515625 | 4 | init_state = [[1,4,2], [5,3,0]]
goal_state = [[0,1,2], [5,4,3]]
def index2d(list2d, value):
return next((i, j) for i, lst in enumerate(list2d)
for j, x in enumerate(lst) if x == value)
def get_zero(state):
return index2d(state, 0)
zero = get_zero(init_state)
print(zero)
|
41a9afe8cb834ffe37f1e153b9e84c3eb4b1bb6c | ben-bicakci/automate-the-boring-stuff-projects | /picture-grid.py | 788 | 3.5 | 4 | # picture-grid.py
# By Ben Bicakci
# Source: Automate the Boring Stuff with Python by Al Sweigart
grid = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O... |
8d60531dc8267cb9e2eaa9ca229b771e0a961431 | nh2/staticfetcher | /staticfetcher.py | 3,343 | 3.625 | 4 | #!/usr/bin/env python
"""
Fetches static files.
Runs on Python 2.7 and >= 3.2.
Example:
from staticfetcher import Staticfetcher
STATICS = {
'jquery/jquery.js': 'http://code.jquery.com/jquery.min.js',
'underscore.js': 'http://documentcloud.github.com/underscore/underscore.js',
}
Staticfetcher(STATICS, roo... |
498a12db5f44138b53d948354946e8abf366215f | HouChiaWei/ycsh_python_course | /L08/factorial_sum.py | 81 | 3.703125 | 4 | sum=1
n=int(input())
x=1
for i in range(1,n+1):
x*=i
sum+=x
print(sum)
|
dddd098e4cc42f7e6e7de356190280bdbb10c6d9 | HouChiaWei/ycsh_python_course | /final exam/sort3.py | 158 | 4.03125 | 4 | a = []
for i in range(3):
i=int(input('請輸入第'+str(i+1)+'個數字:'))
a.append(i)
a.sort()
a.reverse()
for x in range(0,3):
print(a[x])
|
c978ad451e40b288c04fa60c61b79223e5382a80 | HouChiaWei/ycsh_python_course | /L09/list_append.py | 107 | 3.65625 | 4 | a = []
for i in range(5):
i=int(input('請輸入第'+str(i+1)+'個數字:'))
a.append(i)
print(a) |
d337b32e177cca99d8f5239e5c5088cc3e3f54ec | HouChiaWei/ycsh_python_course | /final exam/odd_or_even.py | 97 | 3.90625 | 4 | x=int(input("請輸入數字: "))
if x%2 ==0 :
print("是偶數")
else :
print("是奇數")
|
5bcddce37c5ea0539401837a65b3d6ab13914420 | pBouillon/PasswordGenerator | /generator.py | 2,489 | 3.828125 | 4 | import random
from random import choice
from random import shuffle
from random import sample
import generationException
from generationException import LengthException
SHUFFLE_LIM = 75
MIN_SIZE = 8
MAX_SIZE = 64
class Generator():
"""References the generator
Attributes:
__length : password size... |
77f85be63c9516d56f72df5fd0e96127098460b2 | rusydi16/digibraille | /konversi_braille.py | 5,446 | 3.765625 | 4 | import string
def insert_angka(h, word):
if h != 0:
kata = word[:h]+'#'+word[h:]
return kata
else:
kata = '#' + word[h:]
return kata
def insert_hurufBesar(h, word):
if h != 0:
kata = word[:h]+'~'+word[h:]
return kata
else:
kata = '~' + word[h:]
return kata
def kembali_huruf(h, word):
kata = word... |
0eeae8d60791e1259484cc73491050d355f772d2 | brennuck/Data-Structures-2 | /lru_cache/lru_cache.py | 2,629 | 3.953125 | 4 | from doubly_linked_list import DoublyLinkedList
class LRUCache:
"""
Our LRUCache class keeps track of the max number of nodes it
can hold, the current number of nodes it is holding, a doubly-
linked list that holds the key-value entries in the correct
order, as well as a storage dict that provides ... |
5ecebd3892753c671a0bc770d39b278c6f15add6 | Thennavanmohan/18RoyalmechD12018 | /lab58.py | 142 | 3.71875 | 4 | import random
while True:
a=input("press 'r' to roll the die:")
if(a=='r'):
r=random.randint(1,6)
print(r)
else:
exit() |
190f66bebdc1cd718f9bc0be4a61aacd462f8c43 | Thennavanmohan/18RoyalmechD12018 | /graphline.py | 152 | 3.5625 | 4 | #graph
import matplotlib.pypolt as plt
x=[1,2,3,4]
y=[1,4,5,6]
plt.plot(x,y)
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.title('My Graph')
plt.show() |
098c776586e98e92b950579833876b3ce4e27311 | swanandbagve/advanced_linear_regression | /q01_load_data/build.py | 454 | 3.5 | 4 | # Default imports
import pandas as pd
from sklearn.model_selection import train_test_split
path = 'data/house_prices_multivariate.csv'
# Write your solution here
def load_data(path,test_size=0.33,randomstate=9):
df = pd.read_csv(path,index_col=None)
X=df.iloc[:,:-1]
y=df['SalePrice']
X_train, X_test... |
b68d6abc56dde7ffa957b67b8c5ab9e0efec3481 | abhis2007/Quadratic-equation-solutions | /sq.root.py | 894 | 3.921875 | 4 | from math import sqrt
print("Please provide cofficient of your desired equation in form of a*x^2+b*x+c")
print("ENTER a,b,c")
a=input()
b=input()
c=input()
d=(int(b)*int(b)-4*int(a)*int(c))
if d<0:
print("oops! your roots'r imaginary")
print("Discriminant of your desired equation=",d)
v=sqrt(int(-d));
pr... |
79b9e96fe29ce5d001d3e747eea4b0f304155c81 | VedantWankhade/Bike-Ride | /bike_ride.py | 367 | 3.71875 | 4 | def findHill(list):
hill_count = 0
for i in range(1,len(list)-1):
if list[i]>list[i-1] and list[i]>list[i+1]:
hill_count += 1
return hill_count
tests = int(input())
for j in range(tests):
n = int(input())
list = [int(x) for x in input().split()]
hill_count = findHill(list)
... |
430f6a56343b3bd7f2e57af5e3ae7f68359a7520 | JianGsHanz/PythonStudy | /module1.py | 2,926 | 3.96875 | 4 | # 创建和使用对象
from abc import ABCMeta, abstractmethod
from time import sleep, localtime, time
from types import MethodType
# (object)继承
class Person(object, metaclass=ABCMeta):
def __init__(self, name, age):
self.name = name
self.age = age
@abstractmethod
def eat(self):
print("吃饭")
... |
da88cd5960d8aeb8fd8a0717714cf88dcd5b707a | Mario97popov/Python-Advanced | /Tuples and Sets excercise/Battle_of_Names.py | 858 | 4.125 | 4 | n = int(input())
even__numbers_set = set()
odd_numbers_set = set()
for current_iteration_count in range(1, n+1):
name = input()
current_sum = sum([ord(el) for el in name]) // current_iteration_count
if current_sum % 2 == 0:
even__numbers_set.add(current_sum)
else:
odd_numbers_se... |
0a91e4cb76ed244bc549aec2c126241cb426385e | wihoho/LearningPython | /src/Syntax/10) ReturnGradeFunction.py | 301 | 3.90625 | 4 | def getGrade(score):
if score >= 90.0:
return 'A'
elif score >= 80.0:
return 'B'
elif score >= 70.0:
return 'C'
elif score >= 60.0:
return 'D'
else:
return 'F'
score = eval(input("Enter a score: "))
print(getGrade(score))
|
509ca6f8455135eba1e9b6b1209f887da6185b85 | wihoho/LearningPython | /src/Syntax/13) MultipleReturnValueDemo.py | 194 | 3.921875 | 4 | def sort(number1, number2):
if number1 < number2:
return number1, number2
else:
return number2,number1
n1,n2 = sort(453,23)
print("n1 is", n1)
print("n2 is", n2) |
38ad9dd6fd359024bc2f60034dab59d45a98d5d7 | wihoho/LearningPython | /src/Syntax/5) ChineseZodiac.py | 177 | 3.859375 | 4 | year = eval(input("Enter a year?"))
zodiacYear = year % 12
if zodiacYear == 0:
print("monkey")
elif zodiacYear == 1:
print("rooster")
else:
print("nothing") |
f6d7508e322f3248106378483dd377e9ee7ac9e8 | YaserMarey/algos_catalog | /dynamic_programming/count_factors_sets.py | 1,410 | 4.15625 | 4 | # Given a number 'n'
# Count how many possible ways there are to express 'n' as the sum of 1, 3, or 4.
# Notice that {1,2} and {2,1} are two methods and not counted as one
# Pattern Fibonacci Number
def CFS(Number):
dp = [0 for _ in range(Number + 1)]
dp[0] = 1 # if number = 0 then there is only set ... |
024b743a77b9aa548812f9314f2dc71a7a9826cf | YaserMarey/algos_catalog | /divide_and_conqure/binary_search_for_closest_match.py | 2,280 | 4 | 4 | # Modified Binary Search to find closest integer for an element in an array
# time complexity is O(nlogn)
import math
from divide_and_conqure.merge_sort import merge_sort
def Find_Closest(A, B):
# We are looking into B therefore we sort it
# A is just a sequence of numbers that we will search he c... |
250296598a5f435e20b59fb569a7e07a72841bd7 | YaserMarey/algos_catalog | /dynamic_programming/minimum_count_of_coins.py | 3,087 | 3.609375 | 4 | # Given an infinite supply of 'n' coin denominations and a total money amount,
# we are asked to find the minimum number of coins needed to make up that amount.
# Unbounded Knapsack Pattern
import math
def minimum_count_of_coins(Coins, Total):
dp = [[math.inf for _ in range(Total + 1)] for _ in range(len... |
5871c7a813bddf1480a681d08b2ee5d1d76c52d7 | YaserMarey/algos_catalog | /dynamic_programming/count_of_possible_way_to_climb_stairs.py | 1,035 | 4.1875 | 4 | # Given a stair with ‘n’ steps, implement a method to count how many
# possible ways are there to reach the top of the staircase,
# given that, at every step you can either take 1 step, 2 steps, or 3 steps.
# Fib Pattern
def CS(S):
T = [0 for i in range(S + 1)]
T[0] = 1
T[1] = 1
T[2] = 2
... |
360cfd97ecfe8ae72563657fc6a00446307130e3 | Drakulix/knex | /backend/api/helper/images.py | 2,047 | 3.53125 | 4 | from PIL import Image, ImageDraw
from hashlib import md5
GRID_SIZE = 7
BORDER_SIZE = 8
SQUARE_SIZE = 8
class Identicon(object):
def __init__(self, str_, background='#ffffff'):
"""
str_ is the string used to generate the identicon
background is the background of the identicon
"""
... |
50f0da15a7e0ccacb2677292da82fa11aa7ce593 | burnbrigther/py_practice | /ex13_3.py | 321 | 3.59375 | 4 | from sys import argv
script, second = argv
print "This only repeats the script name:", script
print ("Script name: %s" % str(sys.argv[0]))
print "And this prints the second argument of the input", second
print_back = raw_input("Now, here is your opportunity to give input:")
print "Here is your input %r" % (print_back... |
5d671a339e350f8a3c039ed153667496f6f5850c | burnbrigther/py_practice | /ex15_2.py | 687 | 4.46875 | 4 | # imports the argv feature from the sys package
from sys import argv
# Takes input values from argv and squishes them together (these are the two command line items)
# then unpacks two arguments sent to argv and assigns them to script and filename
script, filename = argv
# Takes the value from the command line argumen... |
6861a6ffe23f399bd84a72bee56204700e7319af | ikbalghozali/tugas | /rekursif/mylibrary.py | 1,432 | 3.515625 | 4 | import os, sys
#1
def add_rec(num1,num2):
if num1 == 0 :
hasil = num2
else :
hasil = 1 + add_rec((num1-1), num2)
return hasil
#2
def subs_rec(num1,num2):
if num2 == 0 :
hasil = num1
else :
hasil = subs_rec(num1, (num2-1)) - 1
return hasil
#3
def mu... |
6eac022f98ab339036775e73c86d1b8dde9c073d | Mariacagi/ML_project | /src/utils/mining_data_tb.py | 532 | 3.84375 | 4 | #FUNCIÓN PARA AÑADIR DOBLE BARRA A UNA RUTA
def funcion_para_añadir_una_barra(string):
result = string.replace("\\", r"\\")
print(result)
return result
#FUNCIÓN PARA SEPARAR UNA COLUMNA EN DOS
def split_columna(df, columna, objeto_separacion, numero_veces):
separado = df[columna].str.split(objeto_sep... |
899a18fadfcb3932a6662bf4a5e299d1916b6bae | CharlotteGenius/Niuke | /acsii与数字的转换.py | 721 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 20 18:06:30 2018
@author: xiangyinyu
"""
# 编写一个函数,计算字符串中含有的不同字符的个数。
# 字符在ACSII码范围内(0~127)。不在范围内的不作统计。
# =============================================================================
# # Get the ASCII number of a character:
# number = ord(char)
#
... |
22b898fe70011d23d1d7fe7d472e3498cf68fbb0 | enderphan94/Project | /server.py | 2,326 | 3.640625 | 4 | #EnderPhan
# import Raspberry Pi GPIO support into Python environment
import RPi.GPIO as GPIO
# import a sleep function from time module
from time import sleep
led = 18 # GPIO number where the led is connected
blue = 27
red = 10
green = 22
# Tell the GPIO module to use GPIO numbering used by processor
GPIO.setmode(... |
487e3fdbd918be5c7d57f6afc3053d942ee7751e | TomR1-1/TowerOfHanoi | /TOH.py | 374 | 3.84375 | 4 | def ringNumber():
global rings
while(1):
try:
rings = int(input("Number of rings: "))
if rings < 0:
print("Please input a postive number of rings.")
if rings > 0:
return rings
except ValueError:
print("Please input a... |
9b6e4d8ae94e35ecb27ed219292502c348b8ea13 | suguoju/pythoncode | /停车场/Park.py | 816 | 3.578125 | 4 | #停车厂类
class Park:
#car_list列表为存放车辆的所有心理
car_list = []
park_name = '智慧停车场'
#车型1收费5元
park_prize1 = 5
#车型2收费10元
park_prize2 = 10
def __init__(self,car,record,order):
self.car = car
self.record = record
self.order = order
#车主进车的动作同... |
8876f19fd5557bd864cc4bd226598e9f5c4bf5b9 | CS207ProjectGroup8/cs207-FinalProject | /hotAD/hotAD/ElementaryFunctions.py | 46,894 | 3.6875 | 4 | ##This class is used to define the behavior of elementary functions
import numpy as np
import warnings
warnings.simplefilter("error", RuntimeWarning)
from hotAD.AutoDiffObject import AutoDiff
class ElementaryFunctions():
''' Create objects that support elementary functions on AutoDiff objects and return AutoDiff ... |
7a9f80a7b9b7abc88b046e4526dba71bfb345b7a | RubixDev/BrainAge | /BrainAge.py | 2,340 | 3.703125 | 4 | from random import randint as rn
import time
empty = ''
for line in range(100):
empty += '\n'
tasks = []
solutions = {}
correct = 0
def generate():
possible = False
operation = rn(0, 1)
first_num = 0
second_num = 0
task = ''
solution = 0
while not possible:
first_num = rn(2... |
c554e2e9bc994976b0f84325076eea17c719854c | saranya258/python | /66.py | 113 | 3.71875 | 4 | rt=int(input())
for ii in range(2,rt):
if rt%ii==0:
print("no")
break
else:
print("yes")
|
4c547afe2d87df5134db08952d846d96cffcf89a | saranya258/python | /62.py | 77 | 3.578125 | 4 | stin=input()
x=set(stin)
if(x=={"1","0"}):
print("yes")
else:
print("no")
|
0b8c31ce44f126c335479358ce9a4866c97e5cf1 | saranya258/python | /8.py | 74 | 3.546875 | 4 | nat=int(input())
sum=0
while(nat>0):
sum=sum+nat
nat=nat-1
print(sum)
|
f65244692ce1cdcb5357529ee11fb9bb344f4ae9 | saranya258/python | /3.py | 250 | 4.1875 | 4 | char=input()
if char.isalpha():
if(char=='A'or char=='E'or char=='I'or char=='O'or char=='U'or char=='a'or char=='e'or char=='i'or char=='o'or char=='u'):
print("Vowel")
else:
print("Consonant")
else:
print("invalid")
|
90627373aee7a09347713a99fcd72325eb288bb9 | zhouyuyang0601/Shiyanlou-Python-- | /Tax_calculator/old/Challenge-2/challenge-2.py | 885 | 3.671875 | 4 | #initiate
import sys
salary_dict={}
#input
try:
for arg in sys.argv[1:]:
salary_dict[int(arg.split(':')[0])]=int(arg.split(':')[1])
except ValueError:
print('Parameter Error')
#
#function
#
def tax_calc(salary):
ins_rate=0.165
taxinc=salary*(1-ins_rate)-3500
if taxinc <=0:
tax=0
elif taxinc<=1500:
tax=taxin... |
7ceb3c2fa2d1f5de5e8e4ea574a3e56f766fb344 | zhouyuyang0601/Shiyanlou-Python-- | /Tax_calculator/Challenge 3/Calculator(not work).py | 4,699 | 3.5 | 4 | #coding=utf-8
"""
首先定义四个class,分别实例化然后在主函数中调用
class(Args)
class(Config)
class(userdata)
class(tax_calc)
"""
import sys
import csv
import os
from collections import namedtuple
tax_start_point=3500.00
tax_table_item = namedtuple('tax_table_item',['salary_bound','rate','quick_subtractor'])
tax_table=[
... |
d77d2cf9440f7a26941c8579170832cce7ae5e2f | decocereus/The-Forge | /mario.py | 329 | 4.09375 | 4 | while True:
try:
h = int(input('Height: '))
if h<1 or h>8:
continue
except:
print('Need a valid input.')
continue
def pyramid():
for j in range(0, h):
for r in range(0, j + 1):
print('# ', end='')
print()
p... |
54a7595b950e8d5bf72d40d9b0ab79004b05e037 | suheda-nura-kahraman/VSCode-Ecodation-PC-1 | /01_python_giris/0129_lab_pratikleri.py | 1,040 | 3.859375 | 4 | print("""
Leylek Uygulamasına Hoş Geldiniz!!!
Sürüş Ücreti → 0.59/dk
""")
s = int(input("sürüş için geçen süre (saat)\t : "))
d = int(input("sürüş için geçen süre (dakika)\t : "))
toplamDakika = s*60
toplamDakika += d
toplamTutar = 0.59 * toplamDakika
print(f"Sürüş için geçen süre (saat)\t: {s}")
print(f"Sürüş ... |
f262b66df79a9ea00c577c53cf1a30adb1b3fe8a | suheda-nura-kahraman/VSCode-Ecodation-PC-1 | /05_fonksiyonlar/0509_optional_arguments.py | 851 | 3.953125 | 4 | # region optional_arguments_default_value
"""
Namı diğer → değişken sayıda parametre gönderimi
Fonksiyonu tanımlama anında argümanlarına default değer atayabiliriz
Bu sayede, değişken sayıda argüman gönderebiliriz
a= zorunlu
b = zorunlu
c = opsiyonel
def topla(a, b, c=5):
print(f"{a} + {b} + {c} = {a+b+c}")
top... |
ee321dee412b22b5bf28b86060754f5fc39dbf34 | agcrs/beamsearch | /SolucionesIA/solución_05.py | 19,149 | 3.84375 | 4 | import math
import random
# Esta prctica tiene dos partes:
# - En la primera parte vamos a implementar en Python el algoritmo de clustering
# conocido como de K-medias
# - En la segunda parte experimentaremos la implementacin sobre un conjunto de
# datos: el conocido como iris, una base de datos en la que cada i... |
978a2fdf4c8dd6ec10b53d88591c18b452ec29ca | OluchiC/PythonLab1 | /Lab1.py | 925 | 4.21875 | 4 | sentence = 'I can’t wait to get to School_Name! Love the idea of meeting new Noun and making new Noun! I know that when Number years pass, I will be Age and I will have a degree in Profession. I hope to make my family proud! Am I done with this MadLib Yet?: Boolean.'
school_name = input('What\'s the school name?')
mee... |
46d7a4972ae83dab83e6e17a68d11bc54e083a09 | geekerisli/leetcode | /2_add_two_numbers.py | 595 | 3.59375 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
carry = 0
root = t = ListNode(0)
while l1 or l2 or carry:
s1 = s2 = 0
... |
9bf71c7546e14fcade018ff905880acd633547e9 | rainakdy1009/Prog11 | /dragon games.py | 2,525 | 4.21875 | 4 | import random
import time
def displayIntro(): #Explain the situation
print('''You are in a land full of dragons. In front of you,
you see two caves. In one cave, the dragon is friendly
and will share his treasure with you. The other dragon
is greedy and hungry, and will eat you on sight.''')
print()
... |
ce503a9b5367381fa3774fc0187a506ea0fa3dd6 | rainakdy1009/Prog11 | /Mad libs Dayoung.py | 1,528 | 4.1875 | 4 | noun1 = input("Enter a noun: ")
noun2 = input("Enter a noun: ")
adjective1 = input("Enter an adjective: ")
verb1 = input("Enter a verb: ")
plural_noun1 = input("Enter an plural noun: ")
plural_noun2 = input("Enter an plural noun: ")
number1 = input("Enter a number: ")
adjective2 = input("Enter an adjective: ")
... |
ad3f692c98438898f206119e30fae0dc5b2a1249 | LYgui/python | /simples/function/sqrt.py | 302 | 3.953125 | 4 | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import math
a = float(input('a='))
b = float(input('b='))
c = float(input('c='))
def quadratic(a, b, c):
x = float((-b+math.sqrt(b**2-4*a*c))/(2*a))
y = float((-b-math.sqrt(b**2-4*a*c))/(2*a))
return x, y
print(quadratic(a, b, c))
|
342ca3b9f92f9adf562bf6fd4b5278305e466255 | jessegtz7/Python-Learning-Files | /Strings.py | 1,018 | 4.15625 | 4 | name = 'Ivan'
age = 29
#**Concateante**
'''
print('His name is ' + name + ' and he is ' + age) -- this will result as a "TypeError: can only concatenate str (not "int") to str"
age mus be cast in to a str
'''
print('His name is ' + name + ' and he is ' + str(age))
#**String format**
#1.- Arguments by position.
print... |
76ab13972c5734bc324efb8b53482705ae990746 | irtefa/bst | /simple_bst.py | 1,142 | 4.1875 | 4 | from abstract_bst import AbstractBst
class SimpleBst(AbstractBst):
# A simple compare method for integers
# @given_val: The value we are inserting or looking for
# @current_val: Value at the current node in our traversal
# returns an integer where
# -1: given_val is less than current_val
# 1: given_val is grea... |
438f863220da86cdd6fd20c67837c4da5a5659f1 | ronen-python/complete_python_developer | /decorators/run.py | 611 | 3.53125 | 4 | # def hello(func):
# print('!!!!!!')
# greet = hello
# del hello
# print(greet())
# def hello():
# print ('hello')
# def my_decorator(func):
# def wrap_func(*args, **kwargs):
# print('rrrr')
# func(*args, **kwargs)
# print('eeeee')
# return wrap_func
# @my_decorator
# def hello(x, we='ee'):
# print(x, we... |
8055b007ba8922c14876e0b367cef405e82cae48 | romanticair/python | /basis/Boston-University-Files/AllAnswer/Assignment_1_Answer/altask0.py | 935 | 3.6875 | 4 | ########################
# Assignment 1, Task 1 #
########################
pi = [3, 1, 4, 1, 5, 9]
e = [2, 7, 1]
# First half of Puzzle:
# Creating the list [ whatNumber, whatNumber ] from pi and e
answer0 = [e[0]] + pi[-2 :]
# print(answer0)
answer1 = e[0 : 2]
# print(answer1)
answer2 = pi[-2 : : -2]
# print(answer... |
5158d818ff8fa2e3426cb85da7685856ece7f4b1 | romanticair/python | /basis/built-in-lib/struct-test.py | 4,175 | 3.609375 | 4 | """
Python 没有专门处理字节的数据类型。但由于b'str'可以表示字节,
所以字节数组=二进制str。而在C语言中,我们可以很方便地用
struct、union来处理字节,以及字节和int,float的转换
Python提供了一个struct模块来解决bytes和其他二进制数据类型的转换
struct 的 pack 函数把任意数据类型变成 bytes
"""
import struct
import base64
# 比方说要把一个32位无符号整数变成字节,也就是4个长度的bytes,你得配合位运算符这么写
n = 10240099
b1 = (n & 0xff000000) >> 24
b2 = (n & 0xff0... |
8b2897f28aaa14704a949229dd5f74c1da690fdf | romanticair/python | /basis/progr-py/System/Threads/thread_alt.py | 587 | 3.640625 | 4 | import _thread
def action(i): # 线程中运行的函数
print(i ** 32) # 3个线程都打印同一数字
class Power:
def __init__(self, i):
self.i = i
def action(self): # 线程中运行的绑定方法
print(self.i ** 32)
_thread.start_new_thre... |
620ad4500fceb0d2f58943fcaaf0b027f163ee73 | romanticair/python | /basis/recursive-demo/recursive_biggest_divisor.py | 152 | 3.5 | 4 | def gcd(m, n):
# 求最大公约数
if m % n == 0:
return n
return gcd(n, m % n)
if __name__ == '__main__':
print(gcd(48, 9))
|
059a7cdc48b4372512ee91980501c4f2b8ebf67e | romanticair/python | /basis/progr-py/Preview/make_db_file.py | 1,386 | 3.578125 | 4 | """
用自定义格式将内存数据库对象保存在文件中;
假定数据不使用'endrec.', 'endb.'和'=>';
假定数据库是字典的字典;
警告:使用 eval 可能存在危险,它会将字符串当做代码执行;
也可以使用 eval() 一次创建一条字典记录;
对于print(key, file=dbfile),也可以使用dbfile.write(key + '\n')
"""
db_file_name = 'people-file'
ENDDB = 'enddb.'
ENDREC = 'endrec.'
RECSEP = '=>'
def store_database(db, file_name=db_file_name):
... |
c2c2b56b368caddcf53665984d9a55e7d2c8a353 | romanticair/python | /basis/recursive-demo/recursive_dec_to_bin.py | 327 | 4.03125 | 4 | # Function transfer decimal value to binary
def decimalToBinary(value):
if value == 1:
return '1'
elif value == 0:
return ''
if value % 2 == 0:
return decimalToBinary(value // 2) + '0'
return decimalToBinary(value // 2) + '1'
if __name__ == '__main__':
print(decimalToBina... |
06cab040dcc63931324fc98d4382cca389e22462 | romanticair/python | /basis/Boston-University-Files/AllAnswer/猫叔的/a9task2.py | 12,678 | 3.578125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# a9task2.py
# name:
# e-mail:
"""
# 1-4题纯粹是数学知识用编程语言的实现。把相关数学知识对应的公式搞懂就能写出程序了
import numpy as np
import pandas as pd
# 1
def calc_portfolio_return(e, w):
"""
e is a matrix of expected returns for the assets
w is a matrix of portfolio weights of the asse... |
925038bddcfc020c57e86b6459a04f3875146879 | romanticair/python | /basis/math/01-sum-columns-sep-by-commas.py | 347 | 3.578125 | 4 | # Sum columns in a text file separated by commas
filename = 'data.txt' # 3, 4, 5
sums = {} # 5. 3. 9
for line in open(filename):
cols = line.split(',')
nums = [int(col) for col in cols]
for (ix, num) in enumerate(nums):
sums[ix] = nums.get(ix, 0) + num
for key in sorted(sums):
p... |
17619a6f222a159bc1519bc29cb48b6c93863d3d | romanticair/python | /basis/Boston-University-Files/AllAnswer/Assignment_3_Answer/a3_task2.py | 5,406 | 3.65625 | 4 | # Stock Returns and Statistice
# Mission 1.
def calc_returns(prices):
# Function will process a list of stock prices
# and calculate the periodic returns(1 to n).
# Assume the oldest price is in prices[0]
# and latest price in prices[-1].
# The periodic rate of return is calculate as the
# rat... |
6997a795cf5ca8f4d54735830fe224ce2da7ab25 | romanticair/python | /basis/progr-py/Gui/Tools/rad.py | 1,015 | 3.796875 | 4 | # 以动态方式重新加载回调处理程序
from tkinter import *
import radactions # 首次获取回调处理程序
from importlib import reload # 转移到Python 3.X的一个模块中
class Hello(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.make_widgets()
def make_widgets(sel... |
c1ad1d4d22f1edfe5bd439118e7c79fc67d7567d | romanticair/python | /basis/Boston-University-Files/AllAnswer/Assignment_9_Answer/a3_task1.py | 2,967 | 4.125 | 4 | # Descriptive Statistice
# Mission 1.
def mean(values):
# Take as a parameter a list of numbers, calculates4
# and returns the mean of those values
sumValues = 0
for value in values:
sumValues += value
return sumValues / len(values)
# Mission 2.
def variance(values):
# Take as a parame... |
1d06d11e5f43ba776d3e2f21d260e19b4c726941 | romanticair/python | /basis/progr-py/Internet/Other/http_getfile.py | 1,463 | 3.5625 | 4 | """
借助http.client,从一台HTTP(网络)服务器上通过套接字抓取文本;文本名参数可以是
一个完整的目录路径,也可以通过末尾的?查询参数制定一个CGI脚本,触发一个远程程序;
抓取得到文件数据或远程程序输出可以保存到本地文件,以便模拟FTP功能,或者用str.find
或html.parser模块解析;另外,http.client.request(method, url, body=None, hdrs={});
"""
import sys
import http.client
showlines = 6
try:
servername, filename = sys.argv[1:]
except:
... |
30e93f5ae4f70674ae60921f381fe2944be1cdd0 | romanticair/python | /basis/class-detail/访问类继承树.py | 574 | 3.96875 | 4 | """
Climb inheritance trees using namespace links,
displaying higher superclasses with indentation
"""
def class_tree(cls, indent):
print('.' * indent + cls.__name__)
for supercls in cls.__bases__:
class_tree(supercls, indent+3)
def instance_tree(inst):
print('Tree of %s' % inst)
class_tree(... |
60ce47e2aea40df180d29ae8c534b33f09d85db2 | mistert14/mistert-skulpt | /skulpt/python/fonction_non.py | 1,002 | 3.5625 | 4 | #
# SIMULATION DE CIRCUITS LOGIQUE
# CE CIRCUIT MONTRE UNE FONCTION LOGIQUE OUI
# VOTRE MISSION: TRANSFORMER CE CODE
# POUR CABLER UNE FONCTION LOGIQUE NON
# BON COURAGE ...
import turtle
tortue = turtle.Turtle()
#tortue.ht()
# VOUS DEVEZ ICI CHANGER L'ETAT DE L'INTERRUPTEUR
# False ou True SONT LES DEUX VALEURS ADMI... |
03be29bc14438517b54b3a67c12585965bdb3403 | Aegir9/Curso-de-introducao-python3 | /Desafios/desafio004.py | 481 | 3.703125 | 4 | n = input('Digite algo: ')
print(type(n))
print("É númerico: {}".format(n.isnumeric()))
print("É decimal: {}".format(n.isdecimal()))
print("É alfabetico: {}".format(n.isalpha()))
print("É alfanumerico: {}".format(n.isalnum()))
print("É title: {}".format(n.istitle()))
print("É tudo maiusculo: {}".format(n.isupper()))
p... |
109d1f27241c71afb0abdd3089107dc44ee71e6b | boogerburns/PyMorsels | /month.py | 266 | 3.765625 | 4 | from dataclasses import dataclass
@dataclass
class Month:
year: int
month: int
def __str__(self):
return '{self.year}-{self.month}'.format(self=self)
def __repr__(self):
return 'Month({self.year}, {self.month})'.format(self=self)
|
0d7fb18ac45047bf73f33c57ea811779f2e299a3 | ryanbrandt/py-leetcode | /palindrome_number/Solution.py | 705 | 3.8125 | 4 | import math as m
class Solution:
'''
Solutions for leetcode Palindrome Number variations
'''
def checkChar(self, strX, i, j) -> bool:
if(i >= j):
return True
if(strX[i] == strX[j]):
return self.checkChar(strX, i + 1, j - 1)
return False
def isPal... |
209cada106e9736ac643dc65e6555e5279a855d4 | KipodAfterFree/KAF-2019-DKDOS | /writeup.py | 436 | 3.703125 | 4 | import string
import itertools
def hash(password):
calculated_hash = 0
for char in password:
calculated_hash = ((calculated_hash << 2) + ord(char)) & 0xffff
return calculated_hash
def main():
chars = string.ascii_uppercase + string.digits
for item in itertools.product(chars, repeat=8):
password = ''.join(... |
a83aed260306cf34375b1fac6683996a21b0ddd3 | teknofage/Spaceman | /Spaceman.py | 8,468 | 4.15625 | 4 | import random
from pygame import mixer #found on https://stackoverflow.com/questions/20021457/playing-mp3-song-on-python
def load_word():
'''
A function that reads a text file of words and randomly selects one to use as the secret word
from the list.
Returns:
string: The secret word to ... |
ed79398c0fa30f821600bab6d3e156d6eb66760b | ThomasMGilman/ETGG1803_ConceptsOf3DGraphicsAndMath | /Labs/Lab 9/Rasterizer.py | 3,916 | 3.59375 | 4 | import math3d
import pygame
#Initilization
pygame.init()
Screen=pygame.display.set_mode((1000,600))
done=False
#This set the camera at the left hand corner of the screen
"""CameraPos=math3d.VectorN((Screen.get_width()-Screen.get_width()),(Screen.get_height()-Screen.get_height()))
#The Camera's Field of View
CameraFOV=... |
8a2edc07e5b4bdbf8d28c949fabbde770246c4c0 | ThomasMGilman/ETGG1803_ConceptsOf3DGraphicsAndMath | /Labs/Lab 5/math3d.py | 10,607 | 3.578125 | 4 | import random
import pygame
import math
class VectorN(object):
def __init__(self,*args):
self.__mData=[]
for i in args:
self.__mData.append(float(i))
self.__mDim=len(self.__mData)
#returns a string containing the vector length, followed by the list
def __str__(self):
... |
5bba7d2cf4162e8cb4be68b0eec0c2c698843073 | ivenabc/algorithm_examples | /basic/queue.py | 808 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Queue
# 先进先出队列(FIFO)
class Queue(object):
def __init__(self):
self.__list = []
# 添加一个元素
def en_queue(self, item):
self.__list.append(item)
# 删除最近添加的元素
def de_queue(self):
self.__list.pop()
def is_empty(self):
... |
bf04a809978cefdd5f3ce4a49336d578e1069e49 | harishk-97/python | /player level/program26.py | 148 | 3.671875 | 4 | a=input().split()
def display(q):
for i in range(len(q)):
if(i==0):
print(q[i],end='')
else:
print("",q[i],end='')
display(a)
|
07f094b9a394565c4c3d95b22a6918fb2474ff86 | harishk-97/python | /mycustomfunctions/listvaluessepbyspace.py | 119 | 3.609375 | 4 | def display(q):
for i in range(len(q)):
if(i==0):
print(q[i],end='')
else:
print("",q[i],end='')
|
08a79cd1b23aba0471cf9b5612d134acf4401948 | spartacoding-7th-kim/8th-examples | /week3/6-donghan.py | 585 | 4.0625 | 4 | people = [{'name': 'bob', 'age': 20},
{'name': 'carry', 'age': 38},
{'name': 'john', 'age': 7}]
# 모든 사람의 이름과 나이를 출력해봅시다.
for person in people:
print(person['name'], person['age'])
# 이번엔, 반복문과 조건문을 응용한 함수를 만들어봅시다.
# 이름을 받으면, age를 리턴해주는 함수
def get_age(myname):
for person in people:
... |
bf73ce033ddbb55e091bd7432df90ce7a8077ebb | theakozakis/ardis_code_input_files | /read_LAYERS.py | 2,950 | 3.8125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Code to extract effective altitudes and the lowest altitude temperature from a LAYERS file:
read_LAYERS(filename)
Input: LAYERS file
filename: path to LAYERS file as a string
Outputs:
Element 0: list of effective altitudes
Element 1: list ... |
c34f29ef21682bce23c223bb8ccb015cb98b0101 | JoaoAreias/Brilliant | /monte_carlo_triangle.py | 952 | 4 | 4 | """Three points are chosen uniformly at random from the
perimeter of a unit circle. Use Monte Carlo simulation
to compute the probability of the points forming an acute
triangle, what is the probability?
"""
import numpy as np
def point():
theta = 2*np.pi*np.random.rand()
x = np.cos(theta)
y = np.sin(theta)
retur... |
136eebf0b2b4b75947ecc7eb46a59b3e129c9772 | PacktPublishing/Keras-Reinforcement-Learning-Projects | /Chapter05/graph1.py | 428 | 4.03125 | 4 | graph = { "a" : ["b", "c", "d", "e", "g"],
"b" : ["c", "a"],
"c" : ["a", "b", "d"],
"d" : ["a", "c", "e"],
"e" : ["a", "d"],
"f" : ["g"],
"g" : ["a", "f"]
}
def EdgesList(graph):
edges = []
for vertex in graph:
for neighbour in g... |
f5114113998505ca2aff6ec2fbd4703eed1c1cc3 | PacktPublishing/Keras-Reinforcement-Learning-Projects | /Chapter02/MCTextGen.py | 507 | 3.625 | 4 | import markovify
with open("corpus.txt") as f:
CorpusText = f.read()
TextModel = markovify.Text(CorpusText)
print("Five randomly-generated sentences")
print("-----------------------------------")
for i in range(5):
print(TextModel.make_sentence())
print("-----------------------------------")
pr... |
aa5ee783ea1cefc38bec2f435e590764581d0a07 | PacktPublishing/Keras-Reinforcement-Learning-Projects | /Chapter03/factorial.memoized.py | 348 | 3.96875 | 4 | import time
time_start = time.clock()
storeX ={}
def factorial (x):
if x in storeX:
return storeX[x]
elif x == 0:
return 1
else:
xt = x * factorial(x-1)
storeX[x] = xt
return xt
print("Factorial of 10 is: ",factorial (10))
print("Computational time is: ",... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.