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 |
|---|---|---|---|---|---|---|
b36aaeaa9d73fe39e090b8d91f209b586880e3c6 | jennypeng/python-practice | /Tkinter/hello2.py | 610 | 3.65625 | 4 | """
Sometimes its a good idea to wrap code in one or more classes
"""
from Tkinter import *
class App:
def __init__(self, master):
frame = Frame(master) # a frame is a simple container, to hold other widgets
frame.pack() # call pack to make frame visible
self.button = Button( # fg = foreground
frame, text... |
321f1e726d75e4f7013074163ce7cfeab25dbeb8 | sunglassman/U3_L11 | /Lesson11/problem3/problem3.py | 253 | 4.1875 | 4 | print('-' * 60)
print('I am EvenOrOdd Bot')
print()
number = input('Type a number: ')
number = int(number)
if number == even:
print('Your number is even. ')
else:
print('Your number is odd. ')
print('Thank you for using the app! ')
print('-' * 60) |
3801879a40032d1e59c5d8f60d247d70137b9770 | vellankikoti/Strings_Assignment | /strings_assignment.py | 2,378 | 4.09375 | 4 | #1
st = 'Python Programming'
x = st.lower()
y = x.replace('python','Python')
print(y)
#output:Python programming
#2
txt = 'Python is powerful and easy'
words = txt.split(' ')
l = len(words)
print(l)
#optput:5
#3. What would be the output from the following Python program section?
st = ['P','y... |
b2065a382c36d84100497a77de8e1421394fdfae | brain-bzh/elu616-introtoai | /session6/lab/rl.py | 5,948 | 3.546875 | 4 | import numpy as np
import pickle
## Part 1 - Linear Model Training using SGD
# This part can be skipped unless you want to understand the details of how the linear model is being trained using Stochastic Gradient Descent.
# A starting point can be found here : https://medium.com/deeplearningschool/2-1-linear-regressi... |
160cf4e43de8ddaac5661847c16e496822a9934f | LordManchot/mini-jeux | /nombre.py | 855 | 3.8125 | 4 | from math import *
from random import *
print("Lordmanch0t présente")
yn=input('Bienvenue au jeu du nombre à deviner. Expliquer les règles ? (Y/N)')
if yn == "N":
print("Très bien. Tu dois trouver un nombre entre 0 et 1000")
elif yn == "Y":
print("Tu dois trouver un nombre entre 0 et 1000.")
print("Tu as le... |
68d6f125269ec7f72bbad302d3e62a095470b80d | dhakalshivani70/pythonproject | /function.py | 140 | 3.90625 | 4 | def add(num1,num2):
return num1+num2
'''
Add two numbers
'''
print (add(2,3))
def sub(num1,num2):
return num2-num1
print(sub(4,3)) |
4b44623b2f38775104b81a5b78316ad466e9cc91 | osavinov/huffman_py | /codes.py | 993 | 3.71875 | 4 | from typing import Tuple
class Code:
__code: int
# we initialize with value with leading 1, because codes might start with 0 bit
def __init__(self, val: int):
self.__code = 0
self.__code >>= val.bit_length()
self.__code |= val
def __len__(self) -> int:
return self.__c... |
2f0c489ff3f8cb4527b4202610e873e96a471fc9 | joshuaknight/myprograms.com | /game/passage.py | 1,262 | 3.59375 | 4 | import forest
class Passage(object):
def start(self):
print "\nAfter,Which you enter a dark passage and near a bush you find a shotgun"
print "\nYou Take the shotgun,and go along the passage"
print "\nYou are tired from walking and see a shelter"
print "\nYou Go and take rest in the Shelter,Where you meet a O... |
82db5749cc2c25bed4a61d27a586abf36dde0c32 | noblegasses/python-learning | /Variables.py | 116 | 3.8125 | 4 | # Declare a variable and initialize it
f=0;
print f
# Re-declare the variable as something else
f="abc"
print f
|
bbc717bfca847e0d266e9b008aba9a0d09dc91b9 | smv5047/Computer-Architecture | /ls8/cpu.py | 8,977 | 4 | 4 | """CPU functionality."""
# TODO
# TODO - use number of operands +1 to increment PC
import sys
class CPU:
"""Main CPU class."""
def __init__(self):
"""Construct a new CPU."""
self.is_running = True
# 256 bit memory
self.ram = [0] * 256
# temporary memory, read and writ... |
f71f74dbed26cfd47d5fffc1240a3259b372b7c7 | prizrak101950/python | /level6.py | 884 | 3.796875 | 4 | import random
guessesTaken = 0
number = random.randint(1, 50)
print("привет,друг!как тебя зовут")
myName = input()
print("я готов,начнём!Скажи мне число от 1 до 50")
while guessesTaken < 6:
print("как думаешь, что я загадал?")
guess = input()
guess = int(guess)
guessesTaken += 1
if guess ... |
73d187ce06facc86e6257cefc9edd167eab8c9a7 | vvkdby/Python-Practice | /Stack.py | 849 | 3.984375 | 4 | class Stack:
def __init__(self):
self.items = []
def push(self,item):
return self.items.append(item)
def isEmpty(self):
return self.items == []
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items) - 1]
def size(self... |
d96fbfa045f9b06f283c71ffab0744c6b145f236 | vvkdby/Python-Practice | /binarysearch.py | 1,324 | 4.03125 | 4 |
'''
recursive implementation of binary search
'''
def binarySearch(arr, l, r, x):
#check base case
if r >= l:
mid = l + (r - l)/2
#if the element is present at the middle itself
if arr[mid] == x:
return mid
#if the element is smaller than the middle element,
... |
9eb28e4d983fd03720f15f945f5c769b3e654c51 | thiruthuvarajan/FirstTask | /Counter.py | 5,123 | 3.734375 | 4 | import random
balance = waitList = waitList75 = waitList100 = ticketed = 0
waitList100Flag = waitList75Flag = False
denomination = []
print("\nWelcome to Ticket Counter!!!")
print("\nTicket Price = Rs.25\nInitial Balance = Rs." + str(balance))
highRange = int(input("\nEnter total number of people waiting in Q... |
993f90887e6022d9a97b449fee60c40623595b61 | Brymes/Learn-Python3-The-Hard-Way | /ex45/religion.py | 1,237 | 4.0625 | 4 | from sys import exit
class ReligiousPlace():
def enter(self):
print('''
So you walk into the nearest place of Worship.
You see the cleric in charge and narrate your ordeal
He ponders for a minute and allows you to stay...
.................................................
Now the pastor's son sees a ch... |
5c9f45d02e25b3b2c46f2db15770cf623a882580 | Brymes/Learn-Python3-The-Hard-Way | /ex43/bridge.py | 798 | 4 | 4 | from scene import Scene
class TheBridge(Scene):
def enter(self):
print('_' * 30)
print('''Now you're at the bridge.
Here you find another gothon,
Your only obstacle to planting the bomb.''')
print('_' * 30)
print('''There are 2 items on the floor next to you..
1. A Human Br... |
f270d476882d6676d36ebee5356e2030178b0c3d | emuhedo/pynotes | /Exercises/factorials.py | 225 | 4 | 4 | # Find factorials of a list of numbers
def factorialize(numbers):
""" Return factorials of a list of numbers.
>>> factorialize([1, 2, 3, 4, 5])
>>> [1, 2, 6, 24, 120]
"""
# your code here
|
64c55d0c99141e2e0f7350336675acbe648bf419 | emuhedo/pynotes | /Exercises/sorted_random_floats.py | 282 | 3.875 | 4 | # Sorted random floating numbers
def generate_floats(start, end, how_many):
""" Return a list of sorted random floats in the (start, end) range.
>>> generate_floats(3, 6, 5)
>>> ['4.125', '4.622', '4.835', '4.981', '5.364']
"""
# your code here
|
e9997edb2dd5df73b21e0f1c45fb9dae38b628d7 | YananJian/MapReduce | /reducer_1.1.py | 1,087 | 3.546875 | 4 | #!/usr/bin/env python
"""A more advanced Reducer, using Python iterators and generators."""
from itertools import groupby
from operator import itemgetter
import sys
import os
def format_print(atc_date, atc_total):
for atc, date_pv in atc_date.iteritems():
for date, pv in date_pv.iteritems():
p... |
ee0e317f118463d348f2a765fd161bb689ddc11e | swikot/Python3 | /ListComprehension.py | 2,162 | 4.15625 | 4 | __author__ = 'snow'
# List comprehension is an elegant
# way to define and create
# list in Python
Celsius = [39.2, 36.5, 37.3, 37.8]
Far=[((float(9)/5)*x + 32) for x in Celsius]
print("far values",Far)
odd_number=[x for x in range(1,11) if x%2]
print("odd number is: ",odd_number)
even_number=[x for x in range(1,11)... |
13f8e5d6e9648e4c88ac255fc51de82ff9f1cfd1 | swikot/Python3 | /ParameterAndArgument.py | 765 | 3.546875 | 4 | __author__ = 'snow'
def function(x):
print("x=: ",x," id=: ",id(x))
x=42
print("x=: ",x," id=: ",id(x))
p=6
print("value of p is = : ",p)
function(p)
print("now the value of p is: ",p)
def varpara(*x):
print(x)
varpara(34,34,45)
# * function call
def func(x,y,z):
print(x,y,z)
... |
cf9cedf8f05d727fe6e54a7e37b18c82b26de240 | swikot/Python3 | /OOP/PublicProtectedandPrivateAttributes.py | 2,106 | 3.65625 | 4 | __author__ = 'snow'
# We have the same classification again in object-oriented programming:
#
#
#
# 1.Private attributes should only be used by the owner,
# i.e. inside of the class definition itself.
# 2.Protected (restricted) Attributes may be used, but at your own risk.
# Essentially, this means that they should... |
1056aa97f9bd6fe7024e8b17dcbfb4e48a40e82e | swikot/Python3 | /MaxFunction.py | 518 | 4.1875 | 4 | __author__ = 'snow'
# x = eval(input("1st Number: "))
# y = eval(input("2nd Number: "))
# z = eval(input("3rd Number: "))
#
#
# maximum=max((x,y,z))
# mximum2=maximum
# print("maximum=" +str(maximum))
# print("maxumum2=",mximum2)
#
print()
number_of_values = int(input("How many values? "))
maximum = float(input("Va... |
3ddd19eb2b2c7df490718be7d1bb5a8f45e6ff50 | smithadam7/DepositoryPython | /Search.py | 1,286 | 3.5625 | 4 | # Adam Smith
# Search algorithms
arr = []
f = open('wordlist.txt', 'r')
thefile = open('nearly-sorted.txt', 'w')
for line in f.readlines():
line = line.strip('!')
line = line.strip(' ')
line = line.strip(' ')
line = line.strip(' ')
line = line.strip(' ')
line = line.strip(' '... |
a68bb3a567c611ea13074bf14ec83b9e3d52d1a0 | saadzanfal/Python | /Trigger/Trigger.py | 2,214 | 3.5 | 4 | # Enter your code for WordTrigger, TitleTrigger,
class WordTrigger(Trigger):
#take in a word as our "trigger"
def __init__(self, word):
self.word = word
def is_word_in(self, text):
#make list of words split at spaces and other punctuation
textlist = text.split(' ')
for... |
b3ac0bd2c48cb86dd742a35e7dec3a638137d94c | chenerwang/ImageShare | /homework1.py | 3,333 | 4.25 | 4 | '''
1. 开发环境搭建
多版本python安装管理:下载、安装、改名、添加环境变量
pycharm:设置解释器,连接Git
2. pycharm菜单里每个按钮的熟悉
3. pip install xxx
pip uninstall xxx
'''
'''
4. python基础语法练习
'''
# 单行注释
'''多行注释'''
"""多行注释"""
# 字符串
def demo_str():
stra = 'hello,worlD'
print(1, stra.capitalize())
print(2, stra.endswith('ld'))
print... |
7bcebf8287adc1353044af29749f6068b4241b02 | antongal/euler | /problem3.py | 537 | 3.796875 | 4 | # A naive and inefficient solution for problem 3
# Largest Prime Factor: http://projecteuler.net/problem=3
import math
#Returns the largest prime factor of n
def solve(n):
largest = 1
if isPrime(n):
return n
root = int(math.floor(math.sqrt(n)))
for i in xrange(root, 2, -1):
if n % i == 0 and isPrime(i):
... |
f1a8f0e5c6bbc524cf85aeb7fcf3e661470b93ad | ahmedaljunied/scoryst | /scorystapp/views/report_utilities.py | 3,977 | 3.5 | 4 | import __builtin__
import numpy as np
import itertools
import collections
def percentile(scores, student_score):
""" Calculates percentile for the student_score """
scores = np.array(sorted(scores))
num_scores = len(scores)
return round(sum(scores <= student_score) / float(num_scores) * 100, 2)
def mean(scor... |
8c0fff47aaf937f9767063dd2a6e25db55834d3e | isaya1910/lessons | /task_4_5.py | 985 | 3.53125 | 4 | from mytest4 import Stack
def is_scopes_balance(scopes):
stack = Stack()
for c in scopes:
if c == '(':
stack.push(c)
if c == ')':
scope = stack.pop()
if scope is None:
return False
if stack.size() > 0:
return False
return True... |
d629d861141ab3869818ff427e32693216d19c1c | isaya1910/lessons | /task_1_8.py | 491 | 3.78125 | 4 | from mytest1 import LinkedList, Node
def task1_8(linked_list_1: LinkedList, linked_list_2: LinkedList):
if linked_list_1.len() == linked_list_2.len():
ans = LinkedList()
node1 = linked_list_1.head
node2 = linked_list_2.head
while node1 is not None and node2 is not None:
... |
81efa9dfcb9c7260e4e6dd94fa142e3b556d14bf | AdiCristian/python | /index.py | 1,326 | 4.09375 | 4 | import sys
# Write Fibbonacci series up to n
def fib(n):
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a + b
# Return a list containing Fibonacci series up to n
def fib2(n):
result = []
a, b = 0, 1
while a < n:
result.append(a)
a, b = b, a + b
return... |
2922825ecd85673457086ba325bab29ccf26b7f7 | Czapelsky/Big_Data | /Exercise7 - liczby parzyste.py | 152 | 3.53125 | 4 | count = 0
print('Parzyste liczby:')
for i in range(1, 201):
if (i%2) == 0:
count+=1
print(i)
print('Liczb parzystych było ', count) |
9291707cb6b68759bf048379cad70eafbecd2389 | Czapelsky/Big_Data | /Exercise2 - kupno iphona.py | 352 | 3.65625 | 4 | import sys
iphone = 3000
print('Ile masz pieniędzy?')
try:
money = int(input())
except ValueError:
print('Wprowadzono niepoprawną kwotę')
sys.exit()
print('Aktualna cena iPhoneX = ', iphone)
if iphone > money:
print('Brakuje Ci ', iphone - money, 'aby nabyć iPhoneX')
else:
print('Stać Cię na ', ... |
c1adca5b6c673009f1823ca643bbd5c391220954 | Czapelsky/Big_Data | /Exercise18 - emotki.py | 204 | 3.859375 | 4 | data = {":)": "😃", ":(": "😞"}
def print_emoji(x):
print(data[x])
print("Podaj emotkę: ")
x = input()
if x not in data:
print('slownik nie posiada takiej emotki')
else:
print_emoji(x)
|
a99cd43cbcbd4e9c118ed18cfb9dc71a08da8948 | thisistna/Learn-Step-by-Step-Python | /Bisect/bisect2.py | 259 | 3.59375 | 4 | import bisect
ls=[1,2,3,4,5,6,7,8,9,10]
bisect.insort(ls,4) #returns sorted list after inserting number (inserts according to bisect_right rule)
print(ls)
bisect.insort_left(ls,9) #insert according to bisect_left and returns this edited list
print(ls) |
c3cd5b246cd03ba555f42fd42c8801bdfc72cd91 | isaac33/sparringPython | /sueldoIrpfPropi.py | 1,759 | 3.65625 | 4 | #Un treballador vols saber el seu salari mensual, el qual s’obté de la següent manera:
#Si el treballador treballa menys de 40 hores setmanals, se li paga 10€/hora
#Si el treballador treballa 40 o més hores setmanals, se li paga 10€/hora les 40 primeres i 15€/h les següents.
#El treballador, a més vol saber quina qu... |
efb628033c17ce121dada366c452d27ce134d8c0 | GeorgeDavila/Caesar_Cipher | /caesar_main.py | 5,624 | 3.5625 | 4 | import re
import random
alphabet_list = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
class MyCaesarCipher:
def string_cleaning(self, string1): #make the string acceptable as input for our cipher
string1 = string1.lower() #Force to lower... |
639de603bbf4502f07acfdfe29d6e048c4a89076 | rjtshrm/altan-task | /task2.py | 926 | 4.125 | 4 | # Algorithm (Merge Intervals)
# - Sort the interval by first element
# - Append the first interval to stack
# - For next interval check if it overlaps with the top interval in stack, if yes merge them
def merge_intervals(intervals):
# Sort interval by first element
sort_intervals_first_elem = sorted(intervals... |
84184aa43e9f716fab750b82593b6b4fcac75f31 | JSkophammer/python_misc | /merge_sort.py | 1,176 | 4 | 4 | import random
def merge(sorted1, sorted2):
sorted_list = []
i = j = 0
# merge into final sorted list
while (i < len(sorted1)) or (j < len(sorted2)):
# fill with only one list once the other is exhausted
if i >= len(sorted1):
sorted_list.append(sorted2[j])
j += 1... |
f71961feb4df35e573a0d05aec9a6e13e3a77e11 | JoshMooney/TheseusScripts | /web_scrapper.py | 2,780 | 3.671875 | 4 | # http://www.pythonforbeginners.com/python-on-the-web/web-scraping-with-beautifulsoup/
from bs4 import BeautifulSoup
import requests
def get_games_from_wikipedia():
url = 'https://en.wikipedia.org/wiki/2018_in_video_gaming'
r = requests.get(url)
data = r.text
soup = BeautifulSoup(data)
tables = so... |
132b54c3b4587e500e050d6be5cfadc4488f5da5 | briantsnyder/Lutron-Coding-Competiton-2018 | /move_maker.py | 1,946 | 4.4375 | 4 | """This class is the main class that should be modified to make moves in order to play the game.
"""
class MoveMaker:
def __init__(self):
"""This class is initialized when the program first runs.
All variables stored in this class will persist across moves.
Do any initialization of data y... |
2b3e68d1255e90203c3b978d5b649bcf683800cb | Wikiemol/Markov-Chain | /utils.py | 995 | 3.5625 | 4 | import random
class NGramOutOfBoundsException(Exception):
pass
class Utils:
# choices should be an array of tuples, of the form (choice, weight)
# where choice is the choice to be made, and weight is some percentage
# chance that it should be picked.
@staticmethod
def randomWeightedChoice(choic... |
017960f499a4e863a7a6b4eb628f413d6dcd3dd3 | someone735/Final-Project---CompSci | /Final Project - CompSci 30 - John T/main_menu_code.py | 3,744 | 3.890625 | 4 | from codebreaker_code import CodeBreaker
from info_slide_code import Info_slide
from border_class import border
from decrypt_class import decrypt
from encrypt_class import encrypt
with open("main_menu.txt", "r") as title:
title_list = []
title_display = ""
for x in range(12,25):
title_list.append(x... |
0fa611b3f01a4b4ae7382391c2208b02080c8040 | codingperks/werewolf | /main.py | 2,846 | 4.03125 | 4 | import random
# This function allows input of the number of players
def playercount():
while True:
try:
players = int(input("Please enter the number of players: "))
print("You have selected", players, "players")
if players < 6:
print("The minimum number o... |
982f5ae5e0ef5a2797548ae6ad214aab1450c122 | mv4z/CodePlayground | /Python/Classwork/HW10.py | 5,720 | 3.875 | 4 | from tkinter import Button, Entry, Label,Tk, TOP, LEFT, RIGHT, END
from tkinter.messagebox import showinfo
import random
class ShellGame(object):
def __init__(self,shellCount=3,winningPiece='X', losingPiece=''):
self.shellCount = shellCount
self.winningPiece = winningPiece
self.losi... |
d9fe277f0434d1ab9d483ce720f586631aafb3f5 | mv4z/CodePlayground | /Python/Classwork/HW2.py | 3,804 | 4.1875 | 4 | class Storm(object):
'a class that abstracts a storm'
xrain = 0
xwind = 0
xyear = 0
def __init__(self, rain=0, wind=0 , year=1900):
self.xrain = rain
self.xwind = wind
self.xyear = year
def getWindSpeed(self):
'get max wind speed as MPH'
retu... |
01fc2c1f9c25a7a849767e2b195a02130d800aab | pzar97/Graph-1 | /maze.py | 1,447 | 3.8125 | 4 | class Solution:
"""
TC: O(n*m)
SC: O(n+m)
where n = number of rows of maze and m = number of columns of maze
"""
def hasPath(self, maze: List[List[int]], start: List[int], destination: List[int]) -> bool:
if start[0] == destination[0] and start[1] == destination[1]:
return Tr... |
05ef349cd5b4dfe9cb4964fb0c7136068bf4b499 | ERORESRA/AlgoritmosSistemas | /ago-dic-2019/Erick O. Escarcega Rmz/PracticAss/Practica3.py | 372 | 3.6875 | 4 | k = int(input("Cuantos Dinosaurios quieres ordenar Manuelito?!\n"))
arr = list(map(str, input("Como se llaman los Dinosaurios?\n").split()))
for i in range(k):
key = i
for j in range(i, len(arr)):
if arr[j] < arr[key]:
key = j
temp = arr[i]
arr[i] = arr[key]
arr[key] = temp
... |
dccc1b902d94c091cf03777f2ac4ecd9815d650a | Mictlla/Pensamiento-Computacional | /clases.py | 2,749 | 3.984375 | 4 | def run():
# nombre = (input('¿Cual es tu nombre?: '))
# bienvenida = f'Bienvenido {nombre}'
# total_long = len(bienvenida)
# print(bienvenida)
# print(f'La longitud de la cadena es de {total_long} caracteres')
# num_1 = int(input('Escoge un numero entero: '))
# num_2 = int(input('Escoge otro nume... |
bdf5b5f3550aaceb2cc4931fc0ea2a2b8670ea45 | theweponyrebel/APCSP | /Abstraction Summaitve.py | 572 | 3.921875 | 4 | print ("Welcome to the pizza making machine")
v_pizzaorder = input("How big do you want your pizza to be?, What type of pizza sauce do you want,What type of cheese do you want?, What toppings do you want?")
def order():
openfile = open("pizza.txt", 'a')
openfile.write (str(v_pizzaorder) + '\n')
openfile.... |
12e39c272b3a3f90a09cbfeb97c661a172ba69d0 | ZackFra/Bank_example | /System.py | 487 | 3.6875 | 4 | from Errors import NoFundsSysError
# System is the real world system that our bank system is attached to
# This may be an ATM, or a whole bank, or something else.
# It keeps track of how much money that the underlying system has to dispense
class System:
def __init__(self, total):
self.__total = total
def withdr... |
927dae752bd12f1b27b5d63c3679b5eeae348e28 | djish/algorithms | /InterpolationSearch/interpolationsearch.py | 733 | 4.0625 | 4 |
def interpolation_search(arr, search, low, high):
if ( low <= high and search >= arr[low] and search <= arr[high]):
pos = low + ((high - low) // (arr[high] - arr[low]) * search - arr[low])
if arr[pos] == search:
return pos
if arr[pos] < search:
return in... |
e615c5900ba416a9dcd84b5d70d124138ffef33e | kudoyoshihiro10xx/self_project | /json_parce.py | 1,029 | 3.5 | 4 | # import json
#
# test.json
# {
# "book1": {
# "title": "Python Beginners",
# "year": 2005,
# "page": 399
# },
# "book2": {
# "title": "Python Developers",
# "year": 2006,
# "page": 650
# },
# "book3": {
# "title": "Python cookbook",
# ... |
c54cbbf7a8e0bd65caf75e12a417f97350f09369 | tikerlade/Coursera-Algorithms | /Course3(Algorithms_on_Graphs)/Week4(paths2)/3_shortest_paths.py | 1,787 | 3.796875 | 4 | #Uses python3
import sys
import queue
class Graph:
def read(self):
n, m = list(map(int, input().split()))
self.vertices = n
self.edges = m
self.adj = [[] for _ in range(self.vertices)]
self.weight = [[] for _ in range(self.vertices)]
for _ in range(m):
... |
05a88f2e88f64b0ef5f251b77a52b5a23f1ed755 | ila2003/DZ-Pyton | /DZ1/#5.py | 504 | 3.859375 | 4 | viruchka = int(input('Введите выручку'))
izderzki = int(input('Введите издержки'))
if viruchka < izderzki:
print('Фирма работает в убыток')
else:
print('Фирма работает с прибылью, рентабельность - ',(viruchka - izderzki)/viruchka*100,'%')
sotr = int(input('Введите число сотрудников'))
print('Прибыль на ... |
c7363294a807a273dce1204c1c6b0a2b167590ee | nathancmoore/code-katas | /growing_plant/plant.py | 528 | 4.34375 | 4 | """Return the number of days for a plant to grow to a certain height.
#1 Best Practices Solution by Giacomo Sorbi
from math import ceil; growing_plant=lambda u,d,h: max([ceil((h-u)/(u-d)),0])+1
"""
def growing_plant(up_speed, down_speed, desired_height):
"""Return the number of days for a plant to grow to a ce... |
a0c134ad38274134a6a34781c193c3e2a11735d8 | nathancmoore/code-katas | /sum_of_two_lowest/sum.py | 380 | 3.984375 | 4 | """Take a list of ints and return the sum of the two smallest.
#1 Best Practices Solution by danman1979 et al.
def sum_two_smallest_numbers(numbers):
return sum(sorted(numbers)[:2])
"""
def sum_two_smallest_numbers(numbers):
"""Take a list of ints and return the sum of the two smallest."""
sorted_list =... |
cb14fa65c8ed073100051b45a7994e0357c1a5b8 | zeynepCankara/Introduction-Quantum-Programming | /include/quantum.py | 1,207 | 3.78125 | 4 | import random, math
# randomly create a 2-dimensional quantum state
def random_quantum_state():
first_entry = random.randrange(101)
first_entry = first_entry/100
first_entry = first_entry**0.5
if random.randrange(2) == 0:
first_entry = -1 * first_entry
second_entry = 1 - (first_entry**2)
second_ent... |
70abb011875ae74d271abd5c873755548f6d56ad | sam-pm/practice | /Q7/Q7.py | 662 | 3.75 | 4 | class Solution:
def reverse(self, x):
str_x = str(x)
new_str = ""
# Flip the string.
for i in range(0, len(str_x)):
new_str = new_str + str_x[len(str_x)-1-i]
new_str = new_str.replace("-", "")
# If negative add sign
if x < 0:
... |
e4cf87f3828b12134fb127aed1b274607d468fb4 | VinayGb665/plague | /dataset/type_two_dump_1.py | 259 | 3.734375 | 4 | def sort(collection):
l = len(collection)
for i in range(l-1):
for j in range(l-1-i):
if collection[j] > collection[j+1]:
collection[j], collection[j+1] = collection[j+1], collection[j]
return collection
|
04667124c1b2024fee28feeea722af4132b68d3f | xuannadi/chaotic-image-encryption-1 | /python/chaosencrypt/pisarchik.py | 3,636 | 3.6875 | 4 | import numpy as np
def x_range(a):
"""
Get the valid x range (x_min,x_max) for the given [a] parameter.
"""
return (4 * a**2 - a**3) / 16, a / 4
def __test_key(key):
"""
Assert that the given key is valid.
"""
if not isinstance(key,dict) or set(key) != set(['a','n','r']):
raise ValueError("Expected key to... |
05d74783038e8fb54a016176ed14f529f2c68eb4 | Ichsandro/Ticketing-Program-with-Python | /F08.py | 1,714 | 3.5 | 4 | # Nama/NIM : Jason/16519432
# Deskripsi Program:
# F08- Menggunakan Tiket berfungsi untuk pemain dapat menggunakan tiket untuk bermain.
# Kamus
# Idwahana, Tanggal : string
# JmlTiket : integer
# IsValid : boolean
# data : array of string
def main():
if (logged_in[5] != "Admin"):
Idw... |
60f9c7e19e6735ae1f0bd313dcb84ef08cc96de4 | Ichsandro/Ticketing-Program-with-Python | /F16.py | 1,310 | 3.578125 | 4 | # Nama/NIM : Jason/16519432
# Deskripsi Program:
# F16- Exit berfungsi untuk menanyakan user apakah data ingin disimpan atau tidak dan mengeluarkan user.
# Kamus
# simpan adalah input untuk mengonfirmasi user untuk melakukan penyimpanan
# data terakhir atau tidak
def exit():
simpan = input('Apakah anda mau... |
a88f69527879bc4b3322aeba9ac71a1554d954f7 | Ichsandro/Ticketing-Program-with-Python | /F04.py | 997 | 3.734375 | 4 | # Nama/NIM : Muhammad Ichsandro D Noor/16519402
# Deskripsi Program:
# F04-Login User berfungsi untuk melakukan login pemain atau admin
# Kamus
# Username, Password : String
# IsValid : Boolean
logged_in = None
def login():
if (logged_in == None):
Username = input("Masukkan username: ")
... |
8362974abb4cb9121c869ff0d5035d7f84c8b28b | toannguyen1904/A-little-Pygame---Alien-Invasion | /ship.py | 1,464 | 3.921875 | 4 | import pygame
from pygame.sprite import Sprite
class Ship(Sprite):
def __init__(self,ai_settings,screen):
#Initialize the ship and set its starting position
super(Ship,self).__init__()
self.screen=screen
self.ai_settings=ai_settings
#Load the ship image and get its rect
self.image=pygame.image.load('... |
9c3d7acad8c4010fca3b22fcd4498b735552b6fd | suman2020/AlgorithmPractice | /linkedlist.py | 7,260 | 4.0625 | 4 | # listA = [1,2,3,4,5,6,7,8]
#
# class Node:
# def __init__(self, currentVal = None , cNodeNext = None):
# self.currentVal = currentVal
# self.cNodeNext = cNodeNext
# head = Node(listA[0])
# #1->None
#
# for value in listA[1:]:
# newNode = Node(value)
# currentNode = head
# while currentN... |
15242ac1e77ef7a5f5f8be419b3e82ec0047b9dc | petervel/adventofcode | /day6.py | 20,702 | 3.5625 | 4 |
planets = {}
class Planet:
def __init__(self, id):
self.id = id
self.parent = None
self.children = []
def addChild(self, child):
self.children.append(child)
child.setParent(self)
def setParent(self, parent):
self.parent = parent
def countChildren(self,... |
5d785bb76a0028f52d112a5d46030d40e5a87b1c | ponder2000/Paint-Lab | /drawing_app.py | 10,996 | 3.578125 | 4 | import tkinter
import tkinter.filedialog
import tkinter.colorchooser
import turtle
import xml.dom.minidom
from commands import *
class DrawingApp(tkinter.Frame):
"""
A class extended from tkinter.Frame which will add some feature to the Frame
"""
def __init__(self, master = None):
"""Creati... |
a75adc04badee66ff5ac09affa722074313b6d62 | DAP-web/Exercise02-result | /Cuenta.py | 463 | 3.671875 | 4 | class Cuenta:
def __init__(self):
self.cuenta = 0.00
def ingreso(self,ingreso):
self.cuenta+=ingreso
print(f"\nHas registrado un ingreso de ${ingreso:.2f}.")
print(f"\nTu saldo en cuenta es de ${self.cuenta:.2f}.")
def egreso(self,egreso):
... |
a3da4f3c4af90e49a0631d75c70f251efb28ca71 | abhinayrozer/python-package | /package/strmod.py | 558 | 3.890625 | 4 | def string():
all_char={} #for stroting the all characters count
name=str(raw_input('enter the string'))
spec_char=str(raw_input('enter the specific character:'))
print 'length of the string',len(name)
print '-------------------------'
print 'count of all letters is'
for i in name:
... |
1da5535be880a830ef80b17da08de54c0be39b25 | hautbli/algorithm | /baekjoon/ex1_에디터.py | 1,366 | 3.75 | 4 | # linked list
import sys
input = sys.stdin.readline
class DList:
class Node:
def __init__(self, item, prev, _next):
self.item = item
self.prev = prev
self.next = _next
def __init__(self):
self.head = self.Node(None, None, None)
self.tail = self.Nod... |
1982629b96268954c5f6d2dba3ab0f7c04e26bcb | x59272796/280201065 | /lab9/example1.py | 100 | 3.671875 | 4 | def harmonic(x) :
sum = 1/x
if x != 1 :
sum += harmonic(x-1)
return sum
print(harmonic(5)) |
240d9582ae64f1931b64c150c0dbdf66181cd062 | x59272796/280201065 | /oldfiles/cancelledQuiz.py | 507 | 3.6875 | 4 | def alphanumeric(string, n) :
non_alphanumeric = 0
if not string[n].isalnum() :
non_alphanumeric += 1
if n != len(string) - 1 :
non_alphanumeric += alphanumeric(string, n+1)
return non_alphanumeric
def popalnum(string) :
non_alphanumeric = 0
string = list(string)
if not string.pop().isalnum() :
... |
402af9c752168422502decbf6c34d22c3f111b56 | x59272796/280201065 | /lab6/example1.py | 446 | 3.96875 | 4 | adress = "ceng113@example.com"
check = str(input("insert the e-mail adress to check. "))
checkLower = check.lower()
status = False
if "@" in checkLower :
for chara in checkLower :
if status == False :
if chara == "." :
checkLower = checkLower.replace(chara , "", 1)
if chara == "@" :
st... |
54f94ae0ad6f52a578ef3b116c695a726b6c9157 | x59272796/280201065 | /homework2/example1.py | 3,062 | 3.671875 | 4 | provincesDict = {}
provincesFile = open("provinces.txt", "r", encoding = "utf-8")
vehicleDict = {"CAR": 90, "MOTORCYCLE": 80, "BICYCLE": 25}
distanceList = []
distanceDict = {}
recommendedPlaces = []
for provinces in provincesFile :
provinces = provinces.replace("\n", "").split(",")
provincesDict[provinces[0]] = (f... |
73d4c03c476e25d37b52ee3bb40832114d1cf467 | x59272796/280201065 | /lab6/example2.py | 648 | 3.9375 | 4 | #this is the code that combines excercises in slides 18 and 19
m1Weight = 30
m2Weight = 30
finalWeight = 40
studentNum = int(input("how many students are there? "))
fullList = []
AAlist = []
average = 0
allAverage = 0
grade = 0
for x in range(studentNum) :
m1 = int(input("insert midterm 1 grade. "))
m2 = int(input(... |
394cdb1df84d7fb1dff196f1e3eee5303839691a | x59272796/280201065 | /practice/1butbetter.py | 1,227 | 3.984375 | 4 | word = str(input("write the word. "))
found = []
counter = 5
spec_phrase = str(input("write the special phrase to guess the whole word. "))
while counter > 0 :
currentStatus = ""
for letter in word :
if letter in found :
currentStatus += letter
elif letter == " " :
currentStatus += " "
else ... |
0bd49dcab755b42369566e37193f5df552dcf347 | x59272796/280201065 | /lab5/example1.py | 255 | 3.96875 | 4 | a = int(input("please insert an integer from 1 to 9 (both included). "))
b = 1
while a <= 0 or a >= 10 :
a = int(input("please insert a positive integer. "))
for x in range (10) :
sum = a*b
print(str(a) + " x " + str(b) + " = " + str(sum))
b +=1 |
8a71aab73169a9aad914d6666efa5995a53a63a5 | x59272796/280201065 | /lab4/example5.py | 162 | 4.125 | 4 | factorial = int(input("insert the number. "))
sum = factorial
for x in range (factorial) :
if factorial != 1 :
factorial -= 1
sum *= factorial
print(sum) |
971629a60f0481b7458237c85a99599e496d83c3 | KyrumX/python3-dutch-pokemon-fandom-scripts | /utils/evolution_line.py | 4,219 | 3.828125 | 4 | # Copyright (c) 2020 Aaron Beetstra
# All rights reserved.
class EvolutionStep(object):
"""An step in an evolution line"""
def __init__(self,
pokemon_name: str,
ndex: str,
evo_stage: int):
self.pokemon_name = pokemon_name
self.ndex = ndex
... |
47e8094cb46eb5cc4ddc44ca2434eba82e374646 | elouahabiibrahim/elouahabi_ibrahim-atelier1_2 | /ex6a.py | 451 | 4 | 4 | # Function that Sort by insertion
def tri_selection(tab):
for i in range(len(tab)):
min = i
for j in range(i + 1, len(tab)):
if tab[min] > tab[j]:
min = j
tmp = tab[i]
tab[i] = tab[min]
tab[min] = tmp
return tab
tab = [4... |
22e5ae2277c05a2df8016e8f22f6c2a924b69ba7 | 123JACK123jack/TensorflowPractice | /DCGAN生成图片哟/network.py | 3,210 | 3.5625 | 4 | #coding:UTF-8
"""
DCGAN深层卷积的生成对抗网络
"""
import tensorflow as tf
#超参数:
EPOCHS=100#轮数
BATCH_SIZE=50
LEARNING_RATE=0.0002
BETA_1=0.5
#定义判别器的模型
def discriminator_model():
model=tf.keras.Sequential()
#添加一个卷积层
model.add(tf.keras.layers.Conv2D(
64,#64个卷积核,输出的深度
(5,5),#卷积核大小
... |
ed2666195ea5198c8b0741b553618b4be90ad7e8 | rnapier/security-right | /modaes.py | 3,524 | 4.15625 | 4 | #!/usr/bin/python
#
# Demonstrate how an attacker can modify an encrypted message without knowing
# the password
#
# Alice wants to send money to Bob. She creates a message to send to her bank
# and encrypts it with a shared secret known only to her and her bank.
#
# Eve only knows that the characters "Bob" will occur ... |
ec9b57f6cf6c09a9e3512fbdec0f51624427443c | PaviLee/yapa-python | /hw_answer_keys/Lesson14_HW_ListPart3.py | 605 | 3.578125 | 4 | # Question 1
def sum67(nums):
sum = 0
inInterval67 = False
for i in nums:
if i == 6:
inInterval67 = True
elif not inInterval67:
sum = sum + i
elif i == 7:
inInterval67 = False
return sum
####################################################... |
95861260c34b253aa321a10325f275d97fe62540 | PaviLee/yapa-python | /hw_answer_keys/Lesson6_HW_LogicalOp_NestedIf.py | 929 | 4.0625 | 4 | def cigar_party(cigars, is_weekend):
if is_weekend:
return cigars >= 40 # boolean expression: equals True or False
else:
return 40 <= cigars and cigars <= 60 # boolean expression: equals True or False
def caught_speeding(speed, is_birthday):
# If it is your birthday, subtract 5 from the ... |
d0f59bf4520f993c32505a7b3406d786a76befa9 | PaviLee/yapa-python | /in-class-code/CW22.py | 482 | 4.25 | 4 | # Key = Name
# Value = Age
# First way to make a dictionary object
database = {}
database["Frank"] = 21
database["Mary"] = 7
database["John"] = 10
print(database)
# Second way to make a dictionary object
database2 = {
"Frank": 21,
"Mary": 7,
"Jill": 10
}
print(database2)
for name, age in database2.item... |
aebc460e5c50102d7adc6871fc9d72185cd5d14c | wenjie322/final_project | /new_crawler/loc_adjv2.py | 2,051 | 3.703125 | 4 | # 本程式用於將經緯度轉換成精確的地址資料。 今晚搞定,明天睡到自然醒
from geopy.geocoders import Nominatim
import time
thefile = open("new_temple_latlng.txt", "r", encoding="utf8")
result = open("final_temple", "a", encoding="utf8")
re_search = open("temple_re_search", "a", encoding='utf8')
for line in thefile:
if "臺中" in line and "/" i... |
4818b3a987fde802f631f21faaf20b87dca0c5be | becauseofyou/contests | /codeforces/291/A.py | 189 | 3.53125 | 4 | n = input()
for i in range(len(n)):
if i == 0 and n[i] == '9':
print (9,end='')
elif n[i] < '5':
print (n[i],end='')
else:
print (9 - int(n[i]),end='')
|
35ac8d5c2d0128d6da24a30a7c908cd7cc488694 | bhering11/intro_to_CS_MIT | /01_countVowels.py | 423 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
Este é um arquivo de script temporário.
"""
# obj: count the number of vowels
# inicializar uma contagem
nvwls = 0
# um loop que vá nos elementos de s
for i in s:
# caso um dos elementos seja uma vogal, adicionar 1 ao contador
if i == "a" or i == "e" or i == "i" or i ==... |
f753437283162d87627beb1549f440e9afd62696 | kikocodYouTube/contador | /contador.py | 237 | 3.953125 | 4 | #Ejemplo de for (forense)
def ejemplo_for():
#i es una variable que toma los valores comprendidos en el rango
final=input("Hasta que numero: ")
for i in range (1,final):
print "i= ",i
ejemplo_for()
|
a7781416aceb88c7d5f7236ce9b296c6dfc785f1 | kadambkaluskar/email-parser | /test.py | 325 | 3.65625 | 4 | str_1 = "Hi, my name is Kadamb Kaluskar . I live in India."
str_2 = "Hi, my name is {{first_name}} {{last_name}} . I live in {{country_name}}."
arr_1 = str_1.split(" ")
arr_2 = str_2.split(" ")
for i in range(0,len(arr_1)) :
if arr_1[i] != arr_2[i] :
x = arr_2[i].strip('{{')
x = x.strip('}}')
print x+" :... |
c5eb434fbd894fd520d92cc743690cf110f85cf7 | DR-Ryan/ADVPY-group-project | /Old Files/FractionSolver.py | 977 | 3.953125 | 4 | import sys
import re
from fractions import Fraction
#Check for a negative from each numerator. In between each fraction, look for the sign.
patt = re.compile('([-]?[\d]+)\/([\d]+)\s?([+\-/*])\s?([-]?[\d]+)\/([\d]+)')
while True:
try:
s = input("Please provide a fractional equation to compute: ")
... |
29cae8029065539838b3c0ed267b2c248f8e7819 | amoghgaikwad/Mining-Massive-Datasets---MovieLens | /Task1/Code/spark_pairs.py | 2,291 | 3.640625 | 4 | """
Counts words in new text files created in the given directory
Usage: hdfs_wordcount.py <directory>
<directory> is the directory that Spark Streaming will use to find and read new text files.
To run this on your local machine on directory `localdir`, run this example
$ bin/spark-submit examples/src/main/p... |
8f18adc0d18cc9cd66d4719c5cca6bfad98d1756 | lucassm/cigre-montecarlo | /utilidades/Incertezas_2.py | 1,816 | 3.6875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import random
from math import log, exp
linha = input("Entre com o tipo de linha: 1 - Tronco primário; 2 - Derivação lateral; 3 - Linha secundária\n")
I = float(input("Entre com a corrente que flui no trecho: "))
ampacidade = float(input("Entre com a ampacidade do ... |
01a79301bbb2d50f36900f3375f06393b1a306b0 | bar17-meet/MEET-YL1 | /animalfile.py | 289 | 3.5625 | 4 | class Animal(object):
def __init__ (self, sound, name, "age):
self.sound=sound
self.name=name
self.age=age
def eat(self, food):
print(self.name + " is eating " + food)
def sleep(self, dream):
print("The " + self.age + " years old " + self.name + " is dreaming of " + dream)
|
8c75eccee6fa418f381d2aa0fa5460805f555554 | sgandhi101/diplomacy_lab | /process_text.py | 1,130 | 3.609375 | 4 | import spacy
from string import punctuation
# command line run: spacy download en_core_web_sm
nlp = spacy.load("en_core_web_lg")
def clean_up(text):
# Tokenize --> to break text down into sentences, words, or other units
doc = nlp(text)
token_list = [token for token in doc]
# Get rid of stop words... |
a43ece2a6fbc5cc987a3d02493ebeb52a5f145b4 | nelimalu/MyFirstRepository | /Pathfinding/AStarPathFinder.py | 13,613 | 3.9375 | 4 | import pygame # this is used to make the grid and display
from queue import PriorityQueue # this is for the pathfinding algorithm
from random import randint # this is for choosing the start and end points.
win_width = 750
win_height = 750
# define the screen
win = pygame.display.set_mode((win_height, win_width))
p... |
a3d8e9ed248c69da13e44f34320f865912612eef | Siglangf/KI_2 | /state.py | 2,561 | 3.5625 | 4 | # ------------------------------------------------------EXPLANATION-----------------------------------------------------
# DESCRIPTION:
# The GameManager implements keeps control of the current state of the game and implements state logic
# a) produces initial game states
# b) generates child states from a parent state... |
4658958638968ee183b1c663bca036ed7041fb70 | markableidinger/code-challenges | /project_euler/helpers.py | 3,106 | 4.21875 | 4 | '''
This is a module where I put all of the useful helper functions I make
for project euler problems.
'''
def is_prime(integer):
'''
For ints 25 or smaller, the number is checked against a short list of
primes. For larger ints, the function first checks if the int is divisible
by 2 or 3. If not, the f... |
4b748c96d89e99ebb80538498b3a90b9d4245419 | jie311/S3NAS | /etc_utils/base_tocsv.py | 1,468 | 3.640625 | 4 | from collections import OrderedDict
from itertools import zip_longest
import pandas as pd
class CSVMaker(object):
def __init__(self, columns):
self.columns = columns
self.data = OrderedDict()
for column in columns:
self.data[column] = []
def fill_row(self, val_list):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.