blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
3d20a5e1db42d71cb75d997f5d9035b0630da2e8 | vish9568/BestEnlist | /Day 10/que5.py | 68 | 3.546875 | 4 | import re
string = "VISHAL MANIKRAO Jadhav"
print(*re.findall(r"[A-Z]+",string)) |
89c55f71816227423147789f1536c59c02ca83a9 | vish9568/BestEnlist | /Day 8/que2.py | 777 | 4.15625 | 4 | try:
n1,n2,operator = int(input("Enter First Number: ")), int(input("Enter Second Number: ")), input("Enter Arithmetic Operator: ")
if operator == '+':
print(n1,"+",n2,"=",n1+n2)
elif operator == '-':
print(n1,"-",n2,"=",n1-n2)
elif operator == '... |
45d0b0e55e0c761e272e11e39a2d853100d05317 | MinuteSheep/MS-Python | /Python进阶/#4/9.py | 454 | 3.96875 | 4 | class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def eat(self):
print('{0} eat cat'.format(self.name))
class Cat(Animal):
def eat(self):
print('{0} eat mouse'.format(self.name))
class Mouse(Animal):
def eat(self):
print('{0} eat {0}'.forma... |
c284ae8e743d999ec8ef260e6a877f4398043091 | MinuteSheep/MS-Python | /Python进阶/#4/4.py | 600 | 3.796875 | 4 | class Animal:
'''
所有动物的超类
'''
def eat(self):
print('动物都会吃饭')
def talk(self):
print('动物都会叫')
class Dog(Animal):
'''
继承Animal
'''
def smell(self):
print('狗的嗅觉灵敏')
class Cat(Animal):
'''
继承Animal
'''
def tree(self):
print('猫会爬树')
... |
98aaa54d1517b4c8b6dc5e5590d1046d900bfd16 | MinuteSheep/MS-Python | /Python基础/#7/many-order.py | 166 | 3.984375 | 4 | num = 20
if num > 30:
print('>30')
elif num > 20:
print('>20')
elif num > 10:
print('>10')
else:
print('<=10')
sss = 10 if 1 > 2 else 20
print(sss)
|
ba0e09876bcc1a021e30e3a51766c1199e4bdc94 | shepshook/python-labs | /task2.py | 323 | 3.640625 | 4 | text = input()
dic = {}
words = text.split()
for word in words:
if dic.get(word) is None:
dic[word] = 1
else:
dic[word] += 1
sorted_words = [k for k, _ in sorted(dic.items(), key=lambda item: item[1], reverse=True)]
for i in range(min(len(sorted_words), 10)):
print(sorted_words[i], end=" ... |
e8b90b91e9249a3a893efb3cd2a658b69790e35e | fuxiaoshuai/repo1 | /class1.py | 394 | 3.671875 | 4 | #!/usr/bin/python
# -*- coding=utf-8 -*-
class suan():
def __init__(self,passx,passy):
self.x = passx
self.y = passy
def num(self):
print("%s + %s = %s" %(self.x,self.y,self.x + self.y))
def nux(self):
return ("%s - %s = %s" %(self.x,self.y,self.x - self.y))
if __name__ == '... |
76fadef4221e3afa8442147f284ff8d93845268d | fuxiaoshuai/repo1 | /1.py | 313 | 3.703125 | 4 | #!/usr/bin/python
# -*- coding=utf-8 -*-
class a():
def __init__(self,name,age):
self.aa = name
self.bb = age
def ss(self):
print("name is %s,age is %s" %(self.aa,self.bb))
class b(a):
def ss(self):
pass
def qw(obj):
obj.ss()
c = b('12',12)
qw(c)
print(c) |
f790254e37c25f4dd03eca209e1bb018b4a26621 | shriasannuthi/python | /tictactoegame.py | 3,426 | 4.3125 | 4 | #PYTHON 3 CODE FOR TIC-TAC-TOE
from os import system
print("\n=~=~=~=~=~=~=~= TIC-TAC-TOE =~=~=~=~=~=~=~=\n")
print("> HOW TO PLAY :")
print("--> Enter a digt from the check below.")
print("--> Each player is given a unique character.")
print("--> The first player to fill the checks either")
print(" horizon... |
525baa0f42ac7290da4d5656625343a6e766554d | PriveSylvain/BestStrat | /Tools/objects.py | 5,739 | 3.765625 | 4 | #!/usr/bin/env python
import argparse
import random
import sys, os, time, itertools
class Carte(object):
"""une valeur et une couleur"""
def __init__(self,value,color) :
"""constructeur"""
self.value = value
self.color = color
def __str__(self) :
return '%s de %s' %(self.value,self.color)
de... |
24376eb61a336459373a2aecfba74dd147e24c54 | 1sdc0d3r/cs-sprint-challenge-hash-tables | /hashtables/ex4/ex4.py | 352 | 3.6875 | 4 | def has_negatives(a):
result = []
# Your code here
cache = {}
for n in a:
if n not in cache:
cache[n] = n*-1
if cache[n] in cache and n != 0:
result.append(abs(cache[n]))
# print(cache)
return result
if __name__ == "__main__":
print(has_negat... |
10619026a53bb476ea825b54ea8f381e1dab0ce5 | kvin15/descriptive_statistics_project | /q02_plot/build.py | 808 | 3.65625 | 4 | # Default Imports
import pandas as pd
import matplotlib.pyplot as plt
from greyatomlib.descriptive_stats.q01_calculate_statistics.build import calculate_statistics
dataframe = pd.read_csv('data/house_prices_multivariate.csv')
sale_price = dataframe.loc[:, 'SalePrice']
# Draw the plot for the mean, median and mode fo... |
533bd43af9652553186dff897fb38b5b7cde8b09 | kaustubhvkhairnar/PythonPrograms | /FileIO/Assignment5.py | 812 | 4.03125 | 4 | # 5. Accept file name and one string from user and return the frequency of that string from file.
import os;
from sys import *;
def read(file, str):
cnt = 0;
if os.path.exists(file):
fobj = open(file, "r");
zip = list(fobj.read().split(" "))
for i in range(len(zip)):
... |
c7029d2c47f8fc320b50c8cee82e2ba2573fde76 | kaustubhvkhairnar/PythonPrograms | /Lambda Functions/Assignment4.py | 845 | 4.03125 | 4 | #4.Write a program which contains filter(), map() and reduce() in it. Python application which
#contains one list of numbers. List contains the numbers which are accepted from user. Filter
#should filter out all such numbers which are even. Map function will calculate its square.
#Reduce will return addition of all ... |
6c5c57d64d3ac76773f3faaa8d7abdea6fdf5599 | kaustubhvkhairnar/PythonPrograms | /Lambda Functions/Assignment1.py | 267 | 4.0625 | 4 | #1.Write a program which contains one lambda function which accepts one parameter and return power of two.
def main():
value=input("Enter number : ")
ret=fp(value);
print(ret)
fp=lambda no : int(no) **2;
if __name__=="__main__":
main();
|
0e1663c6c04820822122cd2f4c4792296e2aa7c9 | kaustubhvkhairnar/PythonPrograms | /List/Assignment4.py | 778 | 4.15625 | 4 | #4.Write a program which accept N numbers from user and store it into List. Accept one another
#number from user and return frequency of that number from List.
def main():
num = int(input("Enter number of elements : "))
fun(num);
def fun(no):
print("Enter", no, "Element/s");
arr = [];
fo... |
54cfe5cb59a9391960b285b05f0840887c18b056 | kaustubhvkhairnar/PythonPrograms | /Recursion/Assignment5.py | 336 | 4.25 | 4 | #5. Write a recursive program which accept number from user and return its
#factorial.
def main():
value=input("Enter number : ")
fact=factorial(int(value))
print(fact)
def factorial(no):
if no == 1:
return 1
else:
return no * factorial(no-1)
if __name__ == "__main__... |
e66c24e535135c05ac8b146dd87657d449eab6bd | kaustubhvkhairnar/PythonPrograms | /Recursion/Assignment1.py | 310 | 4.25 | 4 | #1. Write a recursive program which display below pattern.
#Input : 5
#Output : * * * * *
def main():
value=input("Enter number : ")
rec1(int(value));
def rec1(no):
if(no!=0):
print("*",end=' ');
no=no-1;
rec1(no);
if __name__ == "__main__":
main();
|
193c2b243e184809a5056fd53daa7a24467cfb05 | kaustubhvkhairnar/PythonPrograms | /Automation Scripts/Assignment8.py | 1,351 | 3.8125 | 4 | #8. Design automation script which accept two directory names and one file extension. Copy all
#files with the specified extension from first directory into second directory. Second directory
#should be created at run time.
import os;
from sys import *;
import shutil;
def CopyFileS(path, dst,ext):
flag... |
4f74ba17b17c29b34d0f8bd9963ecff0f419baa2 | hafeeskazhunkilhameeth/skripsiku | /binfile/rabin.py | 3,847 | 3.671875 | 4 | def sanitize(text):
import re
text = text.lower().strip()
text = re.sub(r'[^\w|\s]', '', text)
text = re.sub(r'\n+', ' ', text)
text = re.sub(r'\r+', ' ', text)
text = text.split(" ")
return text
def sanitize_grams(text):
import re
p = re.compile(r'\w', re.UNICODE)
def f(c):
... |
7335ad143f5e71cc1fbed243e0d3d77b42799e8f | frvannes16/Cops-Robbers-Coding-Challenge | /src/competition_code/cops_controller.py | 3,464 | 3.828125 | 4 | TEAM_CODE = 'qtksg' # My cops. TODO: clear before distributing.
TIME_BETWEEN_MOVES = 0.5 # seconds. Minimum of 0.3 seconds
# DIRECTIONS
UP = 'up'
DOWN = 'down'
LEFT = 'left'
RIGHT = 'right'
STAY = 'stay'
# Helper function
def get_column_row(coordinate):
col, row = map(int, coordinate.split(':'))
... |
df38bc11f80e1c455acf566e4b8f5807e1f8e484 | deannariddlespur/convert | /convert-1.0.py | 6,464 | 4.0625 | 4 | c=0 # choice number
i=39.3701 # inches per meter
f=3.28084 # feet per meter
x=1 # outer while loop
r=13.29 # pesos per dollar
l=3.785417 # liters per gallon
k=1.60934 # kilometers per mile
p=2.20462 # pounds per kilogram
s='-'*70 # seperator line
def multiply(a,b):
a=float(a)
b=f... |
a10019ef90b06f15cc488e5f805d91ab43fe12de | gsopu8065/mlcrunchProjects | /opencv/program13.py | 2,160 | 3.5625 | 4 | import matplotlib
matplotlib.use("MacOSX")
from matplotlib import pyplot as plt
import cv2
import numpy as np
def grayHistogram():
image = cv2.imread('./bill.png', cv2.IMREAD_GRAYSCALE)
cv2.imshow("Original", image)
# construct a grayscale histogram
hist = cv2.calcHist([image], [0], None, [256], [0, 25... |
368232ac1b8bc105488e659dd0965dd7d33432d4 | vicky299/praktikum-9 | /no 3.py | 101 | 3.8125 | 4 | x = input("masukkan angka :")
for i in range (x*0,5):
print(('*'*(1+2*i)).center(1+2*x))
|
b1ad60441d0a03600ec0b4d37eafc933512b1e7f | BrunoBastos97/JogoPPTCarta | /Jogadores.py | 1,222 | 3.75 | 4 | from Cartas import *
class Jogadores:
nome_dos_jogadores = []
cartas_do_jogador = []
def adicionar_jogador(self):
for i in range(0, 2):
nome = input("Digite o nome do "+ str(1 + i) +"° jogador: ")
self.nome_dos_jogadores.append(nome)
self.entregar_cartas()
def... |
de6885c7e7169769516b065a0be8902b2cb7de24 | Ralph-Wang/MyPythonCookBook | /tricks/singleton.py | 587 | 3.859375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Parent(object):
singletons = {}
def __new__(cls, *args):
key = (cls, str(args))
if key not in Parent.singletons:
Parent.singletons[key] = object.__new__(cls)
return Parent.singletons[key]
def hello(self):
prin... |
e14e201d36a9af96ce5574b1d170569fbbaa82b1 | Ralph-Wang/MyPythonCookBook | /modules/cls_static_method.py | 1,676 | 3.796875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Fruit(object):
total = 0
def __init__(self, area, category, batch):
"""docstring for __init__"""
self.area = area
self.category = category
self.batch = batch
@classmethod
def get_total(cls):
"""使用类方法来访问独立的命名空... |
a61b807c04b71b135dd48f96d13497f44822f599 | Ralph-Wang/MyPythonCookBook | /tricks/list_slice.py | 283 | 3.703125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
lst = range(20)
print lst[::2] # step 2
print lst[::3] # step 3
print lst[::-1] # reverse
# named
last_three = slice(-3, None, None) # start, stop, step
head_three = slice(3) # stop
print lst[last_three]
print lst[head_three]
|
3e295fd2685eb778b6d549212572459d936ef71b | Ralph-Wang/MyPythonCookBook | /patterns/actions/command.py | 1,020 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import abc
class CommandReceiver(object):
def start(self):
print "run start command"
def stop(self):
print "run stop command"
class Command(object):
""" 命令基类 """
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def execute(self)... |
997da3a976594ff6fa4fa060244d918a34904b21 | zigzagjie/Leetcode-using-Python | /Easy/Easy-20. Valid Parentheses.py | 2,274 | 4.03125 | 4 | """
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Exampl... |
b0b09faf8a6387f0c5da4eb236e83c978ac20b97 | Luuuuuucifer/untitled | /base/map&reduce.py | 361 | 3.71875 | 4 | # -*- coding:utf-8 -*-
from functools import reduce
def char2num(s):
return{'0': 0, '1': 1}[s]
# 这是dict的用法
def nums2num(x, y):
return(10 * x + y)
print(char2num('1'))
s = '101010101'
a = map(char2num, s)
# print(a)
a = reduce(nums2num, map(char2num, s))
print(a)
#map reduce里面的方法都不要加括号,只给一个方法名就行 |
58cadbf34da9117e77a5f51f250835e398e72cbe | Luuuuuucifer/untitled | /tkinter/tk01.py | 1,168 | 3.625 | 4 | # -*- coding:utf-8 -*-
import tkinter
window = tkinter.Tk()
window.title('my window')
window.geometry('200x200')
# 很神奇,这里就是字母x
# 窗口内容
on_hit = False
num = 0
def hit_me():
global on_hit
global num
num += 1
if on_hit is False:
on_hit = True
var.set('you hit me %d' % num)
else:
... |
4ef322433207a4575be703fc27001de9a2757b26 | Luuuuuucifer/untitled | /base/if.py | 288 | 4.1875 | 4 | # -*- coding:utf-8 -*-
#x = 1
try:
x = input('please input a number:')
intx = int(x)
except ValueError as e:
print('WTF!it is not a number')
else:
print(intx)
finally:
print('END')
#if isinstance(x, int):
# print(x)
#else:
# print('wtf,it is not a number!')
|
43a3a9dcf3593656956001229659388c03f8a116 | aa18514/workbook-solutions | /Python/challenge 23 happy_message.py | 352 | 4.15625 | 4 | mood_level = input("Rate your mood from 1 to 10 where 1 is very sad and 10 is extremely happy")
if mood_level <= 3:
print('Cheer up, tomorrow is a new day')
if mood_level > 3 and mood_level <= 7:
print('Its okay, everyone has average days')
if mood_level > 7 and mood_level <= 10:
print('Awesome, it is great... |
946fac86772db2cae095ff601b3febee84c4c3be | aa18514/workbook-solutions | /Python/challenge_6.py | 287 | 4.3125 | 4 | '''
Challenge 6:
tells a person how many more calories can he consume in a day to
maintain a healthy lifestyle
'''
print("YOUR NAME's calorie counter")
calories = int(input("How many calories have you eaten today?"))
s = 2000 - calories
print("You can eat", s, "more calories today")
|
a8b2b6f87e59990efd0cd0b5660c7bf985a71cc2 | aa18514/workbook-solutions | /Python/challenge_15.py | 277 | 3.90625 | 4 | '''
challenge 15 - addition
explore the different ways of adding two numbers
'''
# assign the variable length a value of 10
# change length by 20
length = 10
length = length + 20
# assign the variable length a value of 10
# change length by 20
length = 10
length += 20
|
45cda63b124c3804d278ece1005f594327dfa0b8 | aa18514/workbook-solutions | /Python/challenge_19.py | 368 | 4.0625 | 4 | '''
Challenge 19 - If Only...
The program asks the user to enter two numbers and compares
them
'''
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
if num1 > num2:
print(num1, "is greater than ", num2)
if num1 < num2:
print(num2, "is greater than", num1)
if num1... |
ad0892b39092df3ea2c44bc16a71db8ce46eb419 | vijayalakshmieee/python_program | /beginner level/alpht.py | 99 | 3.984375 | 4 | i=input("enter the character")
if(i>='a' and i<='z'):
print("alphabet")
else:
print("not")
|
833f6b97dc9a347b726438711ac10381e23feb81 | lichkingwulaa/Codewars | /5 kyu/5_kyu_Valid_Parentheses.py | 758 | 4.03125 | 4 | """
https://www.codewars.com/kata/valid-parentheses/train/python
"""
def valid_parentheses(string):
string = list(string)
if len(string) == 0:
return True
i = 0
while True:
if string[i] != '(' and string[i] != ')':
del string[i]
i = 0
else:
i += 1
for j in range(len(string)):
if string[j] != '('... |
f552921c9f25d358ca20fe905858ae66815092ed | lichkingwulaa/Codewars | /5 kyu/5_kyu_Directions_Reduction.py | 876 | 3.75 | 4 | """
https://www.codewars.com/kata/directions-reduction/solutions/python
"""
def dirReduc(arr):
i = 0
while True:
if i + 1 - len(arr) >= 0:
return arr
if sorted([arr[i],arr[i+1]]) in [['NORTH', 'SOUTH'] , ['EAST', 'WEST']]:
del arr[i]
del arr[i]
i = 0
else:
i += 1
a = dirReduc(['EAST', 'NORTH', '... |
f65624a1265533f1dff7280155f9a575bc501d05 | lichkingwulaa/Codewars | /5 kyu/5_kyu_ROT13.py | 533 | 3.671875 | 4 | def rot13(message):
res = ''
for x in message:
if x.isalpha():
if ord('A') <= ord(x.upper()) < ord('N'):
res += chr(ord(x) + 13)
else:
res += chr(ord(x) - 13)
else:
res += x
return res
print(rot13("This is my first ROT13 excercise!"))
# 大佬鼠
def rot13a(message):
return message.encode('rot13')
... |
8141942cbf2380e5061c5a4e27a8b608ea4a0f47 | lichkingwulaa/Codewars | /6 kyu/6_kyu_Two_Sum.py | 317 | 3.6875 | 4 | def two_sum(nums, target):
for i in range(len(nums) - 1):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
print(sorted(two_sum([1,2,3], 4)), [0,2])
print(sorted(two_sum([1234,5678,9012], 14690)), [1,2])
print(sorted(two_sum([2,2,3], 4)), [0,1]) |
d5f14c64467572d59ef1abdc9ba1d57033577581 | lichkingwulaa/Codewars | /7 kyu/7_kyu_Largest_5_digit_number_in_a_series.py | 226 | 3.65625 | 4 | """
https://www.codewars.com/kata/largest-5-digit-number-in-a-series/train/python
"""
def solution(digits):
return max([int(digits[i:i + 5]) for i in range(len(digits) - 4)])
number = "1234567898765"
print(solution(number)) |
095947c99557ede6b66dcd0fa8a51dce9164c283 | lichkingwulaa/Codewars | /6 kyu/6_kyu_Faro_Shuffle_Count.py | 533 | 3.65625 | 4 | """
https://www.codewars.com/kata/faro-shuffle-count/python
"""
def faro_cycles(deck_size):
old_num = num = [i for i in range(deck_size)]
cur = 1
while True:
c = []
for i in range(len(num) // 2):
c.extend([num[i], num[i + len(num) // 2]])
if c == old_num:
retu... |
1d1ac70becc0699dece480886f1eae2577a8e4ab | lichkingwulaa/Codewars | /4 kyu/4_kyu_Snail.py | 665 | 3.59375 | 4 | def top(a1):
return a1.pop(0) if a1 else []
def right(a2):
return [x.pop(-1) for x in a2] if a2 else []
def bottom(a3):
return a3.pop(-1)[::-1] if a3 else []
def left(a4):
return [x.pop(0) for x in a4][::-1] if a4 else []
def snail(array):
res = []
while array:
res += top(array)
res += right(array)
res... |
c16e2ae1064ece26bf794d466ea6eced36c8b618 | MadDinosaur/GoogleHashCode | /practice/practice2020_qualification.py | 2,269 | 3.546875 | 4 |
filename = "input/a_example.txt"
file = open(filename, "r")
#Read and save info from first line of file
line = file.readline().split(" ")
total_books = int(line[0])
total_libraries = int(line[1])
total_days = int(line[2])
#Read and save info of scores (each score is stored in an array, as it is a mutable data type)... |
5772cfb967cdcc033e4599f2273d3257e75e4283 | sriharigokavarapu499/PythonSessions | /List.py | 132 | 3.6875 | 4 | list_1 = [1,2,['a','b','c'],5,6,7]
print (list_1 [2][1])
list_1[2].insert(1,'d')
print (list_1)
list_1[2].remove('c')
print (list_1) |
614ff9ab318b385d01e284d638c1754f94ed18fd | erinemrath/12DayProgram | /hashtable.py | 1,609 | 3.671875 | 4 | from hash import hash
class HashTable:
def __init__(self, size=20):
self.size = size
self.data = [None] * self.size
self.slots = [None] * self.size
def __setitem__(self, key, data):
self.put(key, data)
def __getitem__(self, key):
self.get(key)
def show_slots(self):
print(self.slots)... |
055624834cab4a6027554e4711eb6227d25b885b | ivan-marozau/Euler-Project | /Problem005.py | 1,316 | 3.8125 | 4 | ## Smallest multiple
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
import time
start = time.clock()
def prime_factors(n):
lst = []
i = 2
count = 1
whil... |
873c77e277c296f7c0b8d8304de503bdd55f55c1 | ivan-marozau/Euler-Project | /Problem017.py | 1,141 | 4.03125 | 4 | ## Number letter counts
# If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
import time
start = time.clock()
def get_number_name(n):
dic = {0: '', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10:... |
e78e3143ce079213142cf37b1fe660799f516c13 | foobarna/furry-spice | /binary_search_tree.py | 3,634 | 3.890625 | 4 | __author__ = 'blink'
class Node():
"""An object representing a node in a tree. It has value, storage, left and
right leafs as properties. Value acts as a key in a dictionary and storage
as value. Same values can be added multiple times."""
def __init__(self, value, storage=None):
self._value =... |
551611807aaa103eab5ac9371ccd947b097e7ddf | furuiqi/DesignPatterns | /part4/demo01.py | 782 | 3.921875 | 4 | from abc import ABCMeta, abstractmethod
class Payment(metaclass=ABCMeta):
@abstractmethod
def pay(self, money):
pass
class Alipay(Payment):
def pay(self, money):
print("支付宝支付{}元".format(money))
class WechatPay(Payment):
def pay(self, money):
print("微信支付{}元".format(money)... |
5f21ef14d65e261292c352b734b32689cb9c2506 | Sandhya18Chettiar/Calculator | /DriveProg.py | 947 | 4.09375 | 4 | from add import add
from subtract import subtract
from multiply import multiply
from divide import divide
print("Select Any operation.")
print("a.Add")
print("b.Subtract")
print("c.Multiply")
print("d.Divide")
while True:
# Take input from the user
choice = input("Enter choice(a/b/c/d): ")
... |
f5b8344ea812d5d533c480ed0fc83785e2b1cf37 | zsegel/538riddler | /dwarves.py | 1,679 | 3.890625 | 4 | """
Riddler Classic problem found here:
https://fivethirtyeight.com/features/where-will-the-seven-dwarfs-sleep-tonight/
Each of the seven dwarfs sleeps in his own bed in a shared dormitory. Every night, they
retire to bed one at a time, always in the same sequential order, with the youngest dwarf
retiring first and... |
ef569fad2334a11010f80e09894d738ad7ac7fcd | penguincookies/GWSSComputerScience | /Python/CloserToTwo.py | 485 | 4.0625 | 4 | # showing off the while loop
# variables don't use camel style
addend = 1
power = 0
sum_total = 0
counter = 1
while sum_total < 2:
# no need for the math class in python to do exponents
power = 2**counter
power = 1.0/power
sum_total = addend + power
# can't do string addition with floats and strs ... |
77bd0983c76b74581f85b1b9f19292843db009eb | effectivemadness/ct_exercise | /모의고사/solution.py | 775 | 3.5 | 4 | def solution(answers):
answer = []
corr = []
std1 = [1,2,3,4,5]
std2 = [2, 1, 2, 3, 2, 4, 2, 5]
std3 = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]
corr_temp = 0
for i in range(len(answers)):
if std1[i%len(std1)] == answers[i]:
corr_temp += 1
corr.append(corr_temp)
corr_temp = ... |
69c43609f7286a2bab51e71586414d59fb1a1a4e | SebasLeonC/ProyectoElementos1 | /pruebaSLC.py | 1,402 | 3.859375 | 4 | def llenarlista():
listaA=[]
a=int(input('Cuantos numeros tiene el primer grupo'))
z=int(input('Cuantos numeros tiene el segundo grupo'))
w=int(input('Cuantos numeros tiene el tercer grupo'))
i=1
m=int(input("Digite un numero"))
if a>0:
if m>0 and m<11:
print(m)... |
8c7464acfe919832578b36e2a411ef65db04024b | hikarocarvalho/Blue_Module_01 | /exercicios_Aulas/Aula_12/ex03.py | 1,556 | 4.25 | 4 | #pede ao usuário uma opção
lista = list()
cont = 0
opcao = 0
while True:
#Cria dicionário para cadastrar aluno
student = dict()
#exibe o menu
option = input("""
- [1]cadastrar média e novo aluno.
- [2]visualizar media de alunos cadastrados.
- [3]Sair do systema.
""")
if opti... |
23a943935c259962d5e0833e7409294bc4394202 | hikarocarvalho/Blue_Module_01 | /exercicios_Aulas/Aula_10/ex03.py | 818 | 4.03125 | 4 | matriz = list()
soma = 0
resultado = ""
for i in range(3):
temp = list()
for g in range(3):
temp.append(int(input(f"digite o valor de [{i}] [{g}]")))
matriz.append(temp)
#realiza a soma dos valores pares
for i in range(3):
for g in range(3):
if matriz[i][g]%2==0:
soma = soma+... |
6d94da58721f759f373b6ee46c004b83ea8f7fe1 | hikarocarvalho/Blue_Module_01 | /exercicios_Aulas/Aula_10/ex04.py | 360 | 3.859375 | 4 | cadastro = list()
contador = 1
while True:
cadastro.append([input("digite seu nome: "),float(input("digite eu peso"))])
if input("deseja continuar?").lower().strip(" ").startswith("n"):
break
contador += 1
print(f"A quantidade de pessoas cadastradas é: {contador} \nO maior peso é de {max(cadastro)}\... |
a5c858ae1ee821a16d7e18d149df69a1f6e6759e | hikarocarvalho/Blue_Module_01 | /exercicios_Aulas/Aula_08/ex03.py | 359 | 3.796875 | 4 | lista = [5, 7, 2, 9, 4, 1, 3]
print(f"""
- o tamanho da lista é = {len(lista)}
- o maior valor na lista é = {max(lista)}
- o menor valor na lista é = {min(lista)}
- a soma de todos os elemento é = {sum(lista)}
- a lista em ordem crescente é = {sorted(lista)}
- a lista em ordem decrescente é = {... |
a3412236f74f50061147f56ac423181c13b2a1f6 | hikarocarvalho/Blue_Module_01 | /exercicios_Aulas/Aula_14/ex03.py | 659 | 3.65625 | 4 | #function to perform one sum from impost and the current value
def somaImposto(taxaimposto=0,custo=0):
return (custo - altera(taxaimposto,custo))
#function to perform one convertion from one percent number to perform de calculus
def altera(taxaimposto=0,custo=0):
return (taxaimposto*custo/100)
#function to have... |
613786036a391a21ee65f51ca806df233c3c3acb | hikarocarvalho/Blue_Module_01 | /exercicios_Aulas/Aula_08/ex01.py | 183 | 3.6875 | 4 | import random
tupla = tuple()
for cont in range(5):
tupla += tuple([random.randrange(1,50)])
print(tupla)
print(f"o menor valor é : {min(tupla)} o maior valor é {max(tupla)}") |
afd51a57d36060ee616b235c21cd52e07680f0b7 | hikarocarvalho/Blue_Module_01 | /exercicios_Aulas/Aula_14/ex05.py | 459 | 4.125 | 4 | #Faça um programa que calcule através de uma função o IMC de uma pessoa que tenha
#1,68 e pese 75kg.
#perform the calculus
def performIMC(weight,height):
return weight / (height**2)
#enter function - get the values from user
def main():
weight = float(input("Enter with your weight: "))
height = float(input... |
5c6bef93e3db9e46c4fa26f601feca3af0c94f6a | hikarocarvalho/Blue_Module_01 | /exercicios_Aulas/Aula_07/ex_com_while/ex03.py | 663 | 3.734375 | 4 | produtoNome = ""
produtoValor = ""
acimaDeMil = 0
baratoPreco = 0.0
baratoNome = ""
sair = False
valorTotal = 0.0
while not sair:
produtoNome = input("digite o nome do produto")
produtoValor = float(input("digite o valor do produto"))
valorTotal += produtoValor
if produtoValor > 1000:
acimaDeMil... |
81a752cd35835fc4b9f976edf0648ebcf2b9b612 | ryandeng32/LeetCode-Practice | /1029_two_city_scheduling.py | 1,600 | 3.84375 | 4 | # Goal: Assign exactly N candidate to city A & N to city B
# Minimize travel cost
''' main takeaways:
questions like this is like a sorting problem, so I should figure out what parameter should be sorted
in this case it's the difference between costs to A and B
'''
# will sorting work?
# no, because we wan... |
3f50050022c48ba7807d8dd77acb77e529d9f816 | Lgneous/AOC2020 | /Day8/solve.py | 1,310 | 3.59375 | 4 | import sys
def swap(instr):
swap = {"nop": "jmp", "jmp": "nop"}
instr[0] = swap[instr[0]]
def reset(instr):
for ins in instr:
ins[2] = False
def run(instr):
i = 0
acc = 0
while i < len(instr):
ins, n, has_ran = instr[i]
if has_ran:
return False, acc
... |
245b8fc64317641a7eb655ed73cc139f6863f7a7 | Lgneous/AOC2020 | /Day18/solve.py | 1,089 | 3.5625 | 4 | import sys
with open("sys.argv[1]) as f:
content = f.read().split('\n')
op = {
'+': lambda x,y: x+y,
'*': lambda x,y: x*y
}
def tokenizer(s):
s = s.replace('(', ' ( ').replace(')', ' ) ').split()
return list((s))
def parse(s, precedence=False):
rpn = []
operators = []
for i in s:
if i.isnumeric... |
cd651add35d15c8f43ce5115a459f915f9b5f3f7 | ashutoshsingh429/FaceRecognitionSystem | /WorkingWithImages2.py | 474 | 3.609375 | 4 | # Simple program to read and show an image using opecv
import cv2
img = cv2.imread('logo.png')
# To read an image in gray scale
gray = cv2.imread('logo.png', cv2.IMREAD_GRAYSCALE)
cv2.imshow('My Logo', img)
cv2.imshow('My Gray Logo', gray)
# waitKey species the time after which the window must be destroyed... |
b12137e36691a7d7637791c141013307daf4f641 | AbhijitEZ/PythonProgramming | /Beginner/statements.py | 949 | 3.765625 | 4 | from random import shuffle, randint
if False:
print('TRUE condition')
elif not False:
print('Else if condition')
else:
print('ELSE condition')
for item in [1, 2, 3]:
print(item)
for item in (3, 4, 5):
print(item)
# tuple unpacking
for first, second in [(6, 7), (8, 9)]:
print(f'{first}-{seco... |
a6ae52ef73427bac18f93de0a5357cf7035441d1 | Koyomin21/OOP-Tic-Tac-Toe-with-Minimax-Algorithm | /Bot.py | 4,343 | 4.03125 | 4 | import random
from Board import Board
class Bot:
def __init__(self, player_notation):
self.name = 'Bot'
self.player_notation = player_notation
self.notation = ''
if self.player_notation == 'X':
self.notation = 'O'
else:
self.notation = 'X'
def p... |
4cb888c18feff8e4a1fd8e158643f87d7808fb7f | fcasersilva/Python2-2016 | /lei-do-mundo.py | 2,313 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
SISTEMA TERRA - SOL (PG 123 e 124 APOSTILA)
"""
from math import pi, sqrt
import matplotlib.pyplot as plt
def orbita(t0, vx0, x0, vy0, y0, IT, dt, alfa):
# esse alfa eh uma correção do termo r**2
# na eq. T**3/r**2 fica
r = sqrt(x0**2 + y0**2)
t = [t0]
vx = [vx0... |
1851e658e8d794252d29fe1aef3664ddea035102 | fcasersilva/Python2-2016 | /fourier_02.py | 4,301 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
SERIES DE FOURIER
"""
import matplotlib.pyplot as plt
import numpy as np
##################################################################
# função serra em senos (fourier_01)
#def fourier(n,t,l):
# return 2*((-1)**(n+1))*np.sin(n*t)/n
#l= np.pi
#a0 = 0.0
#t = np.arange(-... |
dfaa806d28b1b3f9fc1a969945b9611455499a20 | fcasersilva/Python2-2016 | /exec_02-set_01.py | 1,063 | 3.71875 | 4 |
"""
Exercicios aula 02 - 09
x[n+1] = x[n] + (dx/dt)*h
x' = x^2 + y^2 -6
y[n+1] = y[n] + (dy/dt)*h
y' = x^2 -y
"""
import matplotlib.pyplot as plt
def solve(N, x0, y0):
#Definindo as cond inicias
a = 0.0 #t inicial
b= 20.0 #t final
h = (b-a)/N #valor do paaso
... |
8de6cd4fc7cfc5ba4c8dae0a6e13a4e02df70e09 | LDT-USF/learningPython | /functions.py | 935 | 3.8125 | 4 | #!/usr/bin/python3
def forLoop(myArray):
count = 0
for i in myArray :
print("For loop says", i)
count += 1
return count
def forRangedLoop(myArray):
for i in range(4):
print("Ranged for loop says", myArray[i])
def whileLoop(myArray):
i = 0
while(i < len(myA... |
9255f668dd0fe7434edf6f086345d4920b86def5 | Rocky108/1codesandotherstuff | /crypto.py | 1,484 | 3.75 | 4 | #transposition cipher
#original:This_is_a_secret_message_that_i_want_to_transmit
#encoded:hsi_ertmsaeta_att_rnmtti_sasce_esg_htiwn_otasi
def scramble2Encrypt(plaintext):
evenChars= ""
oddChars=""
charCount= 0
for ch in plaintext:
if charCount % 2 == 0:
evenChars=evenChars+ch
... |
254eecd0d1081513727ca8a164cad3c173a68a49 | skylerbast/TxRRC_data | /cobol_types.py | 3,884 | 3.734375 | 4 | STRIP_PIC_X = True # Set this to False if trimming PIC X causes problems.
import codecs
from array import array
# This contains functions to deal with COBOL COMP-3 compressed numbers and elementary
# items, such as PIC A, PIC 9, and PIC X.
#
# COMP-3 Binary Coded Decimals store values in binary form; each digit is on... |
2bdd0ceb947ffd6eee41cd9f12845df738084f59 | maheshmic88/opencv_learn | /test.py | 481 | 3.546875 | 4 | import numpy as np
import cv2
#Draws a black image and then draws a line from top right corner to bottom left
myImg = np.zeros((512,512,3),np.uint8)
myImg = cv2.line(myImg,(0,512),(512,0),(255,0,255),2)
myImg = cv2.rectangle(myImg,(25,25),(200,200),(255,12,200),3)
myImg = cv2.circle(myImg, (350,350), 105, (120,120,1... |
29b714b566abd5aea7da57352207ebda3763d095 | juanjotr/especialidad | /EJERCICIO5.py | 489 | 4.09375 | 4 | ''' Programa 5 '''
NUM = input("Introduce el primer numero para comparar: ")
NUM = int(NUM)
NUM2 = input("Introduce el segundo numero para comparar: ")
NUM2 = int(NUM2)
NUM3 = input("Introduce el tercer numero para comparar: ")
NUM3 = int(NUM3)
if NUM > NUM2:
if NUM > NUM3:
print("El numero A es el mayor")
... |
4d7ffe1f1b5b2397ad69457c2889bae366c83b36 | dhevanthareza/PDP-01 | /PDP_01_3.py | 253 | 3.6875 | 4 | panjang = float(input("Masukan panjang tanah pak Eko\t: "))
lebar = float(input("Masukan lebar tanah pak Eko\t: "))
luas = panjang * lebar
print("\nLuas: {} m2 \nJadi pak Joni dan pak Soni masing - masing mendapat Luas tanah {} m2".format(luas, luas/2)) |
8d7cb40703d350b582ef6d2103a1be806bf31b7b | mogubess/python_test | /nyumon/7chapter/7136PatternMatch.py | 1,003 | 3.703125 | 4 | '''
7.1.3.6 パターンの特殊文字列
'''
import string
import re
printable = string.printable
print(len(printable))
print(printable[0:50])
print(printable[50:])
#数字だけPickup
#['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
m = re.findall('\d', printable)
print(m)
#数字、英字、アンダースコア
#['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',... |
e04f6f49ebd26e117688d7c3dc24e0a806ff69bc | mogubess/python_test | /nyumon/6chapter/6151fukusyu.py | 1,634 | 4.3125 | 4 | '''
6-15 復習問題 6-1
'''
class Thing():
pass
print(Thing)
example = Thing()
print(example)
#6-2(クラス属性)
class Things2():
letters = 'abc'
print(Things2.letters)
#6-3(インスタンス属性)
class Things3():
def __init__(self):
self.letters = 'xyz'
example3 = Things3()
print(example3.letters)
#6-4
class Elemen... |
104a02884fb058a95138e2a2c99ff004800f2f33 | mogubess/python_test | /nyumon/4chapter/03functions.py | 971 | 4.03125 | 4 | '''
関数 位置引数 キーワード引数 デフォルト引数値の指定
'''
#位置引数
def menu(wine, entree, dessert):
return {'wine':wine, 'entree':entree, 'dessert':dessert}
menuA = menu('chardonnay', 'chicken', 'cake')
print(menuA)
#キーワード引数
menuB = menu(entree='beef', dessert='bage1',wine='bordeaux')
print(menuB)
#キーワード引数と位置引数の混在は可能
#*による位置引数のタプル化... |
645dbba780c1f179afdfdf23782da41fff36983b | mogubess/python_test | /nyumon/6chapter/6141NamedTuple.py | 1,119 | 4.125 | 4 | '''
名前付きタプル
'''
from collections import namedtuple
Duck = namedtuple('Duck', 'bill tail')
duck = Duck('wide ornge', 'long')
print(duck)
print(duck.bill)
print(duck.tail)
'''
辞書からも作れる
**parts のキーワード引数であることに注意
'''
parts = {'bill': 'wide orange', 'tail': 'long'}
duck2 = Duck(**parts)
#同じ意味
#duck2 = Duck(bill = 'wide o... |
94093a251fc5378d98fe2f6a0ed02e61d11b789d | mogubess/python_test | /nyumon/6chapter/69DuckTyping.py | 1,160 | 3.90625 | 4 | '''
ポリモーフィズムの緩やかな実装を持っている
クラスの種類に関わらず、異なるオブジェクトに対して、同じ操作を適用する
'''
class Quote():
def __init__(self, person, words):
self.person = person
self.words = words
def who(self):
return self.person
def says(self):
return self.words + '.'
class QuestionQuote(Quote):
def says(sel... |
e6aca215c25b32a301836c4a551100a0435e0c43 | gdelgadochaves/US-TFG-1160 | /utils/f_price_range.py | 778 | 3.609375 | 4 | def priceRange(x):
if x < 20.0:
price_range = 0.0
elif x >= 20.0 and x < 50.0:
price_range = 1.0
elif x >= 50.0 and x < 100.0:
price_range = 2.0
elif x >= 100.0 and x < 150.0:
price_range = 3.0
elif x >= 150.0 and x < 200.0:
price_range = 4.0
elif x >= 200... |
f29d190067c5f136f8a663069e77a83eecb0d46b | mtarbit/advent-of-code | /2018/d01_2.py | 561 | 3.53125 | 4 | #!/usr/bin/env python3
def run(arr):
arr = list(map(int, arr))
tot = 0
tot_seen = set([tot])
while True:
for num in arr:
tot += num
if tot in tot_seen:
return tot
tot_seen.add(tot)
if __name__ == '__main__':
assert run(['+1', '-1']) ==... |
9b1d9370cc4047719977b643fc2b33b3681d381e | mtarbit/advent-of-code | /2019/d04_1.py | 788 | 3.65625 | 4 | #!/usr/bin/env python3
def run(s):
run_length = 1
has_double = False
# print('-' * 80)
for i in range(1, len(s)):
prev = int(s[i - 1])
curr = int(s[i])
if prev > curr:
return False
if prev == curr:
run_length += 1
else:
if r... |
a543c94e7baabdb580e4aac11fe7ffa36a02c137 | mtarbit/advent-of-code | /2020/d03_1.py | 420 | 3.515625 | 4 | #!/usr/bin/env python3
from aoc import get_lines
def run(input):
n = 0
r, c = 0, 0
rows = len(input)
cols = len(input[0])
while r < (rows - 1):
r = (r + 1)
c = (c + 3) % cols
if input[r][c] == '#':
n += 1
return n
def main():
assert run(get_lines('... |
1674400b3b16a3de9c5a20b320617f0bf628f414 | litsdm/Data-Structures | /source/sorting.py | 4,173 | 3.984375 | 4 | #!python
from binarysearchtree import BinarySearchTree
from heap import MinHeap
def bubble_sort(elements):
swap = True
while swap:
swap = False
for i in xrange(len(elements) - 1):
if elements[i] > elements[i+1]:
elements[i], elements[i+1] = elements[i+1], elements[i... |
274f823592ef230089f5bff3c3e0f6c595de59d1 | SheinH/113-Project-Fall | /letter_classifier_manual.py | 6,455 | 3.5 | 4 | import os
from data_generator import HGenerator, LGenerator
class LetterClassifierManual:
""" Class is used to show and classify data """
cwd = os.getcwd()
training_h_file_name = cwd + '/Data/H Training.txt'
training_l_file_name = cwd + '/Data/L Training.txt'
def __classify(self, letter):
... |
632bb059f0f6448404a314f22c5aed0c10dd5664 | Suchit2706/pygames | /time pass game.py | 5,582 | 3.984375 | 4 | import time
options = ['Sleep', 'Watch Anime', 'Watch Movies', 'Code(anything Stupid.....like this one)', 'Watch something naughty(if you know what I mean)', 'Study']
def sleep():
r = 1
print('Do you actually feel sleepy(y,n): ')
ask = input()
if ask == 'y' or ask == 'Y':
print('T... |
1f7004e43b2c127cdf1eba27f50698a368f0e803 | MacHundt/WebIR | /assignments/03/ex7.py | 904 | 3.6875 | 4 | # -*- coding: utf-8 -*-
# Ex 7: Logging
import logging
def init_log(file_n="execution.log",
file_m="a",
lvl=logging.DEBUG,
fmt="%(asctime)s %(levelname)s: %(message)s.",
d_fmt="%d.%m.%Y %H:%M:%S"):
logging.basicConfig(filename=file_n,
... |
e249efcdb2a8ffca88685151e459a8b1afe4043a | simba263/labass1 | /q2.py | 559 | 4.1875 | 4 | #Write a Python program to count the number of characters (character frequency) in a string.
def char_frequency(str1):
... dict={}
... for s in str1:
... keys=dict.keys()
... if s in keys:
... dict[s]+=1
... else:
... dict[s]=1
... |
df24f496936a85a9603f7fda8fcf0dc2fc127866 | avieshel/python_is_easy | /snowman.py | 4,237 | 3.640625 | 4 | line_1 = ' ____'
line_2 = ' / |'
line_3 = ' ___|____|___'
line_4 = ' | * * |'
line_5 = ' \ < / \|/'
line_6 = ' .> <. W'
line_7 = ' / * \---<|'
line_8 = ' | * | |'
line_9 = ' \ * / |'
line_10 = '.....> <..... |'
snowma... |
afae4ca804c306beed139f9b8a28521b2dab8870 | anubhav-shukla/Learnpyhton | /advance_func_prac1.py | 615 | 4.09375 | 4 | # This is challenge with practice
# define a function take any no of list contaning number
# [1,2,3],[4,5,6],[7,8,9]
# return average
# (1+4+7)/3,(2,5,8)/3,(3,6,9)/3
# try to make this anobymous function in one line using lambda expression
# def average_finder(*args):
# average=[]
# for pair in ... |
154dd83602afcf50335466a622984c64fdb0eb88 | anubhav-shukla/Learnpyhton | /args_as_argument.py | 335 | 3.96875 | 4 | # when define function than it is called parametre
# when we call define funtion thanit call argument
def multiply_nums(*args):
multiply =1
print(args) #([2,3,4])
for i in args:
multiply *=i
return multiply
nums =[2,3,4]
print(multiply_nums(*nums))#using * it unpack the list ,dictiona... |
07908b235dbb8eeba822015fd720ab88b1451ffc | anubhav-shukla/Learnpyhton | /Iterative Quick Sort.py | 833 | 4 | 4 | def partition(arr, low, high):
i = (low - 1) # index of smaller element
pivot = arr[high] # pivot
for j in range(low, high):
# If current element is smaller
# than or equal to pivot
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
... |
9123ccebfa038dcd5dbf18028aaa620ff40b1df7 | anubhav-shukla/Learnpyhton | /python_debugging.py | 805 | 4.21875 | 4 | import pdb # import pdb module
#want definition and other stuff than you simply google it..
# We understand step of debugging
# 1.) set trace
# 2.) execute code line by line
# 1. you can do manually by comment program and after uncomment one by one
# using module pdb
pdb.set_trace()
name= input(... |
4c1f863e96d573aab388073cd610962754349ef8 | anubhav-shukla/Learnpyhton | /ch15_exe.py | 899 | 4.125 | 4 | # exercise:
# define generator function
# take one number as argument
# generate a sequence of evem numbers from 1 to that number
def gen_even(l):
for i in range(1,l+1):
if i%2==0:
yield(i)
for i in gen_even(5):
print(i)
for i in gen_even(5):
print(i)
fo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.