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 |
|---|---|---|---|---|---|---|
017ffdad4b34c121499f95a5958c90d16b2f9c8c | Tajakasibo/GameOfLifeRecreation | /render_tk.py | 2,437 | 3.6875 | 4 | '''Render Game of Life boards to a TK Gui.'''
import tkinter as tk
import game_of_life
X = game_of_life.X
Y = game_of_life.Y
PIXEL = 10
class MainWindow():
def __init__(self, root):
self.root = root
self.active = False
# Divide up GUI into frames
button_frame = tk.Frame(root)
... |
ef8d22e8ab44d0a3cad96db2c94779ab98c2d11c | Catrinici/Python_OOP | /bike_assignement.py | 1,177 | 4.28125 | 4 | class Bike:
def __init__(self, price, max_speed, miles):
self.price = price
self.max_speed = max_speed
self.miles = abs(0)
def ride(self):
print("Riding!")
self.miles += 10
print(f"Total miles : {self.miles}")
return self
def reverse(self):
pr... |
459bbf3c436621c0b769c07740b44261bb84ff3d | Abeilles14/Java_exercises | /6.32_IfThenElseChallenge/IfThenElseChallenge.py | 274 | 4.15625 | 4 | #isabelle andre
#14-07/18
#if challenge
name = input("Enter your name: ")
age = int(input("Enter your age: "))
#if age >= 18 and age <= 30:
if 18 >= age <= 30:
print("Welcome to the 18-30 holiday, {}".format(name))
else:
print ("You are not eligible to enter the holiday") |
4f4715b0b81649687fe88b7baaf2047cf73d0c29 | TTopoo/Introduction-to-Data-Science | /数据科学课本资料/例题源程序-学生/2-8_9.py | 362 | 3.6875 | 4 | #导入numpy
import numpy as np
#例2-8:生成由10个随机整数组成的一维数组
print( np.random.randint(0,6,10) )
# #生成5×6的二维随机整数
rdm = np.random.randint(0, 2, size = (5,6))
print( rdm )
#例2-9:生成服从均值为0、方差为1的服从正态分布的4×5二维数组
rdm = np.random.normal( 0,1, size = (4,5) )
print( rdm )
|
491ce3830efaf77e641bb2ad2a65e59e8502661c | TTopoo/Introduction-to-Data-Science | /数据科学课本资料/例题源程序-学生/1-3.py | 282 | 3.859375 | 4 | #1.3.3 函数和方法库
#3种方式导入库
import math
print('1',math.sqrt(5))
from math import sqrt
print('2',sqrt(5) )
from math import sqrt as sq
print('3',sq(5) )
#自定义函数
def say(message, times = 1):
print(message * times)
say( 'Hello' )
say( 'World', 5 )
|
a4c28599d425c5425e1f1a9814292c37e111c98b | semihPy/Class4-PythonModule-Week6 | /a1_w6.py | 5,207 | 3.6875 | 4 | '''
#############################################################################################
#*******************************************************************************************#
# Copyright (c) 2020 pyCoder|semih Corporation;) All rights reserved. ##
# ... |
b8b7b53603155909fd0591c27928e95907fdaeab | SpyrosDellas/design-of-computer-programs | /src/Pig.py | 8,567 | 3.53125 | 4 | import random
from functools import update_wrapper
import itertools
def decorator(decor):
"""Update the wrapper of decor(function), where decor is a decorator function.
Returns a reference to the function object update_wrapper()
"""
def _decor(function):
return update_wrapper(decor(function)... |
63e1f1d27729f896e7996bfd46c222e507e25c91 | abuchireddygari/ML_Scikit | /01a_multiple_plots.py | 1,146 | 3.65625 | 4 | import numpy as np
import matplotlib.pyplot as plt
# generate some random data
normal_dist = np.random.normal(0, 0.01, 1000)
# init figure
fig = plt.figure(figsize=(10, 6))
ax = fig.add_subplot(2, 2, 1)
ax.plot(normal_dist)
ax.set_title('Line plot', size=20)
ax = fig.add_subplot(2, 2, 2)
ax.plot(normal_dist, 'o')
a... |
cee5299adbc0ed33c7fb3941080c07278916884d | JonathanRaiman/MC_Challenge | /mc_challenge/dataset.py | 4,966 | 3.578125 | 4 | import os
class Questions(object):
"""
Small class for holding question objects
from machine comprehension dataset.
Holds `question`, and a list of `answers`
as strings. Also has a `question_type` field
to store whether question is single or
multiple-choice.
"""
__slots__ = ["quest... |
630171f3a5f2be771a5138809c63457c4d4e575a | mmsamiei/Learning | /python/work_with_strings/manipulating_strings.py | 731 | 4.09375 | 4 | """ this is
multi line
comment! """
flag = "hello" in "i am hello"
print "flag is {flag}".format(flag=flag)
str = "Hello, I am Mahdi"
print str.upper()
print str.lower()
# they used to make case insensetive comparsion for example:
print("could you get units?")
answer = raw_input()
if answer.lower() == 'no':
p... |
8d69bd1f68bd1dfe19adb1909d0ed541fdef7b7c | mmsamiei/Learning | /python/dictionary_examples/create_grade_dictionary.py | 532 | 4.1875 | 4 | grades = {}
while(True):
print("Enter a name: (blank to quit):")
name = raw_input()
if name == '':
break
if name in grades:
print(' {grade} is the grade of {name} ').format(grade=grades[name],name=name)
else:
print("we have not the grade of {name}").format(name=name)
... |
9d2e16dbeeb5a50f23f543d301e174ada190b02c | heaventouch/design-pattern | /state-pattern/state-pattern.py | 9,046 | 3.828125 | 4 | import random
class GumballMachine(object):
SOLD_OUT = 0
NO_QUARTER = 1
HAS_QUARTER = 2
SOLD = 3
def __init__(self, count):
self.state = GumballMachine.SOLD_OUT
self.count = count
if count > 0:
self.state = GumballMachine.NO_QUARTER
def insertQuarter(self):
... |
bed80daaec098006ad0a4bb1b799b536fcc7f68e | RenatoArbex/AccessibilityResearch | /accessibility.py | 8,137 | 3.578125 | 4 | '''
Accessibility calculation functions.
'''
import pandas as pd
import numpy as np
def accessibility_calculation(graph_file_name, max_walk_distance, alfa, beta):
print('** Calculating accessibility for Graph file ', graph_file_name)
# -------------------------------------------------------... |
e6845a5a295ee25ee15b7e7b2ba1c7fd5b59d9af | shanoob/Anand-Python | /chapter-2/reverse.py | 62 | 3.859375 | 4 | x=[1,2,3,4,5,6,7,8,9]
def reverse():
print x[::-1]
reverse()
|
8701475db7e87aea4f99a68c45ec99437c3378c1 | shanoob/Anand-Python | /chapter-6/flattendict.py | 317 | 3.53125 | 4 | def flatten_dict(dict1,result=None,key=None):
if result==None:
result={}
if key==None:
key=[]
for k,v in dict1.items():
if isinstance(v,dict):
flatten_dict(v,result,key+[k])
else:
result['.'.join(key+[k])]=v
return result
print flatten_dict({'a': 1, 'b': {'x': 2, 'y': 3}, 'c': 4})
|
d76d351add6f1c63a982bc4c84fd0eb533fc08b8 | shanoob/Anand-Python | /chapter-2/list_slice.py | 241 | 3.53125 | 4 | def split(lis, size):
r = []
while len(lis) > size:
b = lis[:size]
r.append(b)
lis = lis[size:]
r.append(lis)
return r
x=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
print(split(x,2))
|
7d765e9d039197e04613e1e0028bb186f5ab4493 | shanoob/Anand-Python | /chapter-2/test1.py | 118 | 3.765625 | 4 | #to check the out put of the following operations
x=[0,1,[2]]
x[2][0]=3
print x
x[2].append(4)
print x
x[2]=2
print x
|
d0c3eb12095bfa5f5daa5c36d3822479e2cc744d | shanoob/Anand-Python | /chapter-2/cumulativesum.py | 99 | 3.5625 | 4 | x=[8,7,4,2,1]
print x
y=[]
def cusum(x):
z=0
for i in x:
z=z+i
y.append(z)
print y
cusum(x)
|
bc1a8569f7980a2b7282c02ace3f1b2e4a542c1e | CTEC-121-Spring-2020/mod-3-programming-assignment-tylerjjohnson64 | /Prob-2/Prob-2.py | 1,118 | 3.890625 | 4 | # Module 3
# Programming Assignment 4
# Prob-2.py
# <YOUR NAME>
'''
Your IPO comment goes here
'''
from math import *
def main():
# your code goes here
wage=0
overtimewages=0
overtime=0
regularwages=0
TotalTakeHome=0
name=input("Enter your name: ")
wage=eval(input("Enter your hou... |
205a4abbf88208faaca6bc78771e6ac12668c1c4 | Aaspyr/RectangleArea_1.0 | /RectangleArea.py | 311 | 4.03125 | 4 | print("Program calculate the area of the rectangle")
pole = False
while not pole:
a = int(input("Write length side a: "))
b = int(input("Write length side b: "))
p = a*b
if (p > 0):
print ("Area of the rectangle: ", p)
pole = True
else:
print ("Write correct data!")
|
98f1e0650b70d78b40e2556bb09cdc9492521a24 | gustavobiage/URI_Solutions | /Mathematics/1807.py | 209 | 3.875 | 4 | R = int(input())
MOD = 2**31 -1
def power(a, b, m):
if (b == 0):
return 1
half = power(a, b // 2, m)
res = half*half
if (b % 2 != 0):
res = res * a
res = res % m
return res
print(power(3, R, MOD)) |
da351f2c3071e3484e2966a88bff91e30ba3122b | riley-csp-2019-20/1-2-2-catch-a-turtle-leaderboard-Jacob78499 | /122jacobjaniakleaderboard.py | 2,711 | 3.625 | 4 | # a121_catch_a_turtle.py
#-----import statements-----
import turtle as trtl
import random
import turtle as score_writer
import turtle as counter
import leaderboard as lb
#-----game configuration----
shape = "arrow"
size = 5
color = "red"
font_setup = ("Arial", 20, "normal")
timer = 10
counter_interval = 10... |
9f3262b97340930afab510ff6ab0c01f1e569d80 | oussama-benbrahem/deep_learning_from_scratch | /DL_from_scratch.py | 11,347 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# =============================================================================
# Computational Graphs
# =============================================================================
class Operation:
"""Represents a graph node that performs a com... |
4efa40fa388f714e0b091e175127def892131fb5 | GiovannaCarvalho29/Docs | /elevador.py | 1,993 | 3.890625 | 4 | import time
import os
def Wait():
k = input("pressione enter para continuar")
def Floors(maxFloor,actualFloor, minFloor):
for i in range(maxFloor, minFloor-1, -1):
if i == actualFloor:
print("(|)", actualFloor)
else:
print(" | ", i)
def FromToUp(actualFloo... |
acb32f63ec4a6c3aa35320bf8e1cfa3ff311cb92 | keul/Cheese-Boys | /cheeseboys/character/navpoint.py | 4,129 | 3.640625 | 4 | # -*- coding: utf-8 -
from cheeseboys.vector2 import Vector2
class NavPoint(object):
"""A class for store the target of movement action of GameCharacter sprites,
and manage the path to follow.
"""
def __init__(self, character):
self._character = character
self._v = None
se... |
9ea875fc6f4ff52d735b26924ffdf34e3d844ad8 | keul/Cheese-Boys | /cheeseboys/sprites/triggers/trigger.py | 3,136 | 3.53125 | 4 | # -*- coding: utf-8 -
import pygame
from cheeseboys.pygame_extensions.sprite import GameSprite
from cheeseboys import cblocals
class Trigger(GameSprite):
"""Triggers are invisible sprites used to raise events in the game when other GameSprite
objects run over the area of the trigger itself (AKA fire the trigg... |
e85442499c943f92c3e8e0c22dd9c66a4bca46b3 | brendanlegas/python-challenge | /PyBank/main.py | 2,094 | 3.6875 | 4 | #import os
import os
#import csv
import csv
#define variables
count = 0
total = 0
difference = 0
sumDifferences = 0
lastRow = 0
changes = []
dataDict = {}
averageChange = 0
greatestIncrease = 0
greatestIncreaseMonth = ''
greatestDecrease = 0
greatestDecreaseMonth = ''
budget_csv = os.path.join("budget_data.csv")
wit... |
6a07533146042655f2780ff329ecaff3089cedd6 | ziyuanrao11/Leetcode | /Sum of 1d array.py | 2,483 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 26 14:41:32 2021
@author: rao
"""
'''Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).
Return the running sum of nums.
Example 1:
Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is o... |
6b20a2136e8449a61778778b4799211c391e4952 | pandiarajan-src/PyWorks | /Learn/ceaser_ciper.py | 2,026 | 4.1875 | 4 | '''Implement Ceaser Cipher encryption and decryption
https://en.wikipedia.org/wiki/Caesar_cipher.'''
def ceaser_ciper_encryption(input_to_encode, key_length):
"""Ceaser Encryption method"""
enc_output = chech_char = ""
for letter in input_to_encode:
if letter.isalpha():
n_uni_char = ord... |
df65fb19b440abab612cd950bfaf719a429fadfa | pandiarajan-src/PyWorks | /educative_examples/collection_chain_map_ex.py | 3,768 | 4.3125 | 4 | # Chain map
# A ChainMap is a class that provides the ability to link multiple mappings together such that they end up being a single unit.
# If you look at the documentation, you will notice that it accepts **maps*,
# which means that a ChainMap will accept any number of mappings or dictionaries and turn them into ... |
022ad95a92ed9bba03b252819a04df7b5c054ce7 | pandiarajan-src/PyWorks | /educative_examples/fun_tools_ex.py | 10,752 | 4.53125 | 5 | # functools
"""
Python comes with a fun module called functools.
The functions inside functools are considered “higher-order” functions which can act on or return other functions.
In this chapter we will be looking at the following portions of the functools package:
lru_cache
partials
singledispatch
wraps
Let’s ge... |
ee1fdb8b1af9f44ce15f191c158abebf1e4a2fbd | pandiarajan-src/PyWorks | /Learn/date.py | 1,685 | 4.3125 | 4 | '''Experiment on date, time and year fields'''
from datetime import datetime, timedelta #, date
def print_today_yesterday_lw_date():
"""Print today's date, yesterday;s date and last week this day"""
print(f"Today's date is {str(datetime.now())}")
print(f"Yesterday's date is {str(datetime.now() - time... |
1112dfc54b23dce7f09724d126fd90e05ea7e1c9 | pandiarajan-src/PyWorks | /Learn/decorator_ex.py | 674 | 4.0625 | 4 | '''learn decorator'''
from datetime import datetime
def perf_logger(func):
"""Measure performance as a logger"""
def wrapper():
before_exec_time = datetime.now()
func()
after_exec_time = datetime.now()
print(f"time taken to execute is {str(after_exec_time-before_exec_ti... |
ae9d7cc5b95c526e3e3afbe414ef1d93be6ac78c | pandiarajan-src/PyWorks | /Learn/xml_simple_parser.py | 3,991 | 3.546875 | 4 | '''Simple XML parser using ElementTree package'''
import xml.etree.ElementTree as ET
from pathlib import Path
class XMLUtility:
"""This class reads/write xml content of different files"""
def __init__(self, xml_file_name):
"""Initialze the root element class and use the data in other places"""
... |
b049d54aaf6a88ef05eab836b37ab40f56c067d1 | pandiarajan-src/PyWorks | /educative_examples/benchmarking_ex2.py | 2,026 | 4.0625 | 4 | # Benchmarking
# Use a decorator
"""
Writing your own timer is a lot of fun too, although it may not be as accurate as just using timeit depending on the use case.
Regardless, we’re going to write our own custom function timing decorator! Here’s the code:
"""
import random
import time
def timerfunc(func):
"""
... |
eb5b36fd683ead2eb4205f18ab6897eb76327aa0 | pandiarajan-src/PyWorks | /educative_examples/benchmarking_ex3.py | 1,192 | 4.15625 | 4 | # Benchmarking
# Create a Timing Context Manager
"""
Some programmers like to use context managers to time small pieces of code. So let’s create our own timer context manager class!
"""
import random
import time
class MyTimer():
def __init__(self):
self.start = time.time()
def __enter__(self):
... |
e86df3f56dc9ca95f6a2018b41e19aa3fc7f8e5b | pandiarajan-src/PyWorks | /Learn/converters_sample.py | 1,108 | 4.28125 | 4 | '''This example script shows how to convert different units - excercise for variables'''
MILES_TO_KILO_CONST = 1.609344
RESOLUTION_CONST = 2
def miles_to_kilometers(miles):
"""Convert given input miles to kilometers"""
return round((miles * MILES_TO_KILO_CONST), RESOLUTION_CONST)
def kilometers_to_miles(kilo... |
9268e5d7900146a81f2ae67e9feeef5901d07c9d | surbhimathur1210/assignment-1-prashansa29l | /p8.py | 183 | 4.125 | 4 | def thirdangle(angle1,angle2):
a3=180-(angle1+angle2)
print("thirdangle=",a3)
a1=int(input("enter the first angle"))
a2=int(input("enter the second angle"))
thirdangle(a1,a2)
|
2121f0b546b6307d7a823d1ac5dc286ef7ec0b02 | abeelashraf98/pgm-lab-abeel | /CO1Pg3a.py | 157 | 3.78125 | 4 | a=[10,20,-15,4,-7]
newlist=[x for x in a if x>0]
print("List of positive integer" )
print(newlist)
a=["hai","hello"]
n=[ord(x) for x in a]
print(n)
|
3eee62d5ae6ae392a29e06dbb688e2120c24bede | abeelashraf98/pgm-lab-abeel | /C02Pg4.py | 175 | 3.875 | 4 | from math import sqrt
a=int(input("Enter a limit greater than 1000: "))
for i in range(1000,a):
k=sqrt(i)
if(k==int(k) and i%2==0):
print(i)
|
2c90ca05dfbb14f391cef0021a22e43b527013ab | abeelashraf98/pgm-lab-abeel | /CO2pg1.py | 142 | 4.1875 | 4 | a=int(input("Enter The Number:"))
fact=1
print("Factorial Of Number{} is :".format(a))
for i in range(1,a+1):
fact=fact*i
print(fact) |
15ccd3ba7642f959d43f8461f0df50fe2f28aa85 | abeelashraf98/pgm-lab-abeel | /CO2Pg2.py | 144 | 3.671875 | 4 | a=int(input("eneter th terms"))
f1=0
f2=1
for i in range(0,a+1):
print(f1,end=",")
f3=f1+f2
f1=f2
f2=f3
|
58ef0063ab66182a98cfeb82a2173be41952ac75 | chigginss/guessing-game | /game.py | 1,870 | 4.21875 | 4 | """A number-guessing game."""
from random import randint
def guessing_game():
# pick random number
repeat = "Y"
scores = []
#Greet player and get the player name rawinput
print("Hello!")
name = raw_input("What is your name? ")
while repeat == "Y":
start = int(raw_input("Choose a star... |
51d32c4138544ed3f7751336e1cd1dc5553bdc9e | ClaudioBotelhOSB/CompetitiveProgramming | /Codeforces/Round #682 (Div. 2)/682_D2_A.py | 107 | 3.609375 | 4 | for t in range(int(input())):
x = int(input())
res= ""
for i in range(x):
res+="1 "
print(res)
|
fd6d45ba6fecb3605e025a74ed5f56abc63e6625 | slayer6409/foobar | /unsolved/solar_doomsday.py | 1,692 | 4.4375 | 4 | """
Solar Doomsday
==============
Who would've guessed? Doomsday devices take a LOT of power. Commander Lambda wants to supplement the LAMBCHOP's quantum antimatter reactor core with solar arrays, and she's tasked you with setting up the solar panels.
Due to the nature of the space station's outer paneling, all of it... |
84ae90ef20e0fb3ed6f7d337558a23f6186c7375 | ailogan/pynigma | /pynigma.py | 19,882 | 3.640625 | 4 | #!/usr/bin/python
# pynigma.py
#
# Andrew Logan - 12/21/2013
#
# Enigma simulator written in python
import sys
import argparse
import ConfigParser
#Ja, ist plugboard!
class Steckerbrett:
letters = None
def __init__(self, steckerbrett_list):
#Set up our memory
self.letters = []
sub_l... |
382e1e06abfa30c299ca0afaa5b39860a1f316e2 | zorhay/TwitterBot | /src/poebot/language_analysers/ArmenianLanguage.py | 3,046 | 3.6875 | 4 | class ArmenianSymbols:
LOWER_ALPHABET = {
'ա', 'բ', 'գ', 'դ', 'ե', 'զ', 'է', 'ը', 'թ',
'ժ', 'ի', 'լ', 'խ', 'ծ', 'կ', 'հ', 'ձ', 'ղ',
'ճ', 'մ', 'յ', 'ն', 'շ', 'ո', 'չ', 'պ', 'ջ',
'ռ', 'ս', 'վ', 'տ', 'ր', 'ց', '&', 'փ', 'ք',
'և', 'օ', 'ֆ'
}
LOWER_VOWELS = {
'ա', ... |
eb392e799c96d1648c5e19a3f78eaf9214bdb67d | quanhengwen/rock_github | /Learn/python/ab量化交易/learn 5.py | 511 | 4.03125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def function_1():
numbers = range(10)
size = len(numbers)
evens = []
i = 0
while i<size:
if i % 2 == 0:
evens.append(i)
i += 1
print (evens)
#高效 简洁方式
# []相当于数字 循环赋值
print ([i for i in range(10) if i%2==0])
def function_2():
#enumera... |
6cf7ee2dafeddf165889d6abf004e6387bda640e | SonjaZucki/Lektion12 | /absolute-difference.py | 203 | 3.734375 | 4 | def absolute_diff(num1, num2):
result = abs(num1 - num2)
return result
print(absolute_diff(10, 13))
print(absolute_diff(133, 190))
print(absolute_diff(300, 100))
print(absolute_diff(100, 300))
|
76e0da44de785f390b356484737c18044a223aad | carsonkahn-external/foreshadow | /foreshadow/smart/intent_resolving/core/secondary_featurizers/base_featurizer.py | 2,481 | 3.578125 | 4 | """Class definition for the BaseFeaturizer ABC."""
from abc import ABC, abstractmethod
from typing import List, Sequence
import pandas as pd
class BaseFeaturizer(ABC):
"""
Abstract base class to perform secondary featurization.
Attributes:
method {str}
-- Description of featurizer.
... |
a5e2dbe52597781813c29fc2a10ef1c9224564c7 | ritiksharma04/twitter-bot | /1intro.py | 291 | 3.515625 | 4 | from tkinter import *
from PIL import ImageTk,Image
root = Tk()
root.title("Calculator")
root.geometry("+300+300")
#label
l1 = Label(root,text = "hello")
l1.grid(row = 0,column = 1)
#image
b1 = Button(root,text = "clr",padx = 10,pady = 10)
b1.grid(row = 1,column = 1)
root.mainloop() |
0a06827b6f879e6279cd75f41676a6538f1e9d1f | beccacauthorn/cs-module-project-algorithms | /product_of_all_other_numbers/product_of_all_other_numbers.py | 1,728 | 4 | 4 | '''
Input: a List of integers
Returns: a List of integers
'''
def product_of_all_other_numbers(arr):
count = arr.count(0)
if count > 0:
if count == 1:
# use arr.index to find the correct position of the product
# the rest are zeros
index = arr.index(0)
#... |
e77a9e0ab70fbb5916f12e1b864f5f5b7211ba48 | gauravkunwar/PyPractice | /PyExamples/factorials.py | 248 | 4.3125 | 4 | num=int(input("Enter the value :"))
if(num<0):
print("Cannot be factorized:")
elif (num==0):
print("the factorial of 0 is 1:")
else :
for i in range(0 to num+1):
factorial=factorial*i
print"the factorial of a given number is:",factorial
|
48d1eeffbf97cdf144e0f8f1fb6305da1141b5be | gauravkunwar/PyPractice | /PyExamples/largestnum.py | 352 | 4.3125 | 4 |
num1=float(input("Enter the first num:"))
num2=float(input("Enter the second num:"))
num3=float(input("Enter the third num:"))
if:
(num1>num2) and(num1>num3)
print("largest=num1")
elif:
(num2>num3) and(num2>num1)
print("largest=num2")
else
print("largest=num3")
#print("The largest number among,"num... |
5fbb407bd5450e66d8e0fba7a0ac93e5df7cb90f | Rizwan-S/Snakegame | /snakegame.py | 4,266 | 3.515625 | 4 | import turtle
import time
import random
delay = 0.2
score = 0
high_score = 0
level = 1
colors = ["red","green","blue","orange","purple","pink","yellow", "white", "dark gray", "slate gray", "royal blue", "midnight blue", "cyan", "aquamarine", "spring green", "sea green", "gold", "dark goldenrod", "burlywood", "chocola... |
057f0e148106a1e400ffc51d5af56d4226b60f7a | helloshyreckdc/learn_python | /advanced_feature/generator.py | 335 | 3.984375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# The first line is used to designate a interpreter, second line is coding
g = (x * x for x in range(10))
for n in g:
print(n)
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return 'done'
for n in fib... |
67975d8e80e238975bbe745c46ad631acc9a974b | git-ahi/flask-api | /app/auth/v1/models/user_models.py | 783 | 3.84375 | 4 | class UserModels:
"""
Class for the user operations
"""
users = []
def __init__(self, username, email, password, confirm_password):
"""
Initialize the user models
"""
self.id = len(UserModels.users) + 1
self.username = username
self.email = email
... |
b52aa67d41d76d0ed84ca2864b11c2fb78316b1c | gitpdg/PSC | /ARIA_preparation/emissions.py | 21,570 | 3.96875 | 4 | import matplotlib.pyplot as plt
import numpy as np
import math
"""
This program is used to transform the emission data from MATsim into valid inputs for ARIA. It also allows to visualise the emissions.
It is divided like this :
- config
- preliminary functions
- emissions to dict
- emission map
- e... |
65182321bf46e2b1c297b0c9ac020d002264c51f | yyamada151/proconlib | /search/search.py | 1,343 | 3.9375 | 4 |
#Golden-section search to find the extreme of the function in the given interval
#Input Parameters:
#func - the function of interest. Must be of the type float -> float
#lo,hi: float/int. low and high intervals for the x values. the extreme value must be strictly within ]lo.hi[
#xtol: float/int. the maximum length of ... |
888455d12f292a2c476ab5056c3575faae0f47ea | mbatsi/lern2flow | /mnist_deep_tutorial/mnist_deep_tutorial.py | 3,510 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 4 10:08:24 2016
@author: atreo
"""
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
import tensorflow as tf
###########################
### MATHEMATICAL MODEL ####
# Define in- & output classes a... |
142099d3ced36cc2dcec05c060f2c739223f67d3 | josepharceneaux/baby-sitter | /family.py | 1,626 | 3.90625 | 4 | """
Class and functions for a family a baby sitter might work for
"""
# Fallback for rate
DEFAULT_MINIMUM_RATE = 20
# Earliest a baby sitter may begin work.
MINIMUM_START = 17
# Latest a baby sitter may end work. 28 = 24 + 4, e.g., 4am
MAXIMUM_END = 28
# Start times and associated rates for 3 families. E.g., Fami... |
f1ac7ce434862b7b26f5225810e65f539ec38838 | Nike0601/Python-programs | /km_cm_m.py | 322 | 4.3125 | 4 | print "Enter distance/length in km: "
l_km=float(input())
print "Do you want to convert to cm/m: "
unit=raw_input()
if unit=="cm":
l_cm=(10**5)*l_km
print "Length in cm is: "+str(l_cm)
elif unit=="m":
l_m=(10**3)*l_km
print "Length in m is: "+str(l_m)
else:
print "Invalid input. Enter only cm or m"... |
b349661df6d615517f5e0b870663621b819004dd | pessoajoao/LinkedListCircle | /ArrayListCircle.py | 2,322 | 3.84375 | 4 | class No:
def __init__(self, charge: object = None, ant: 'No' = None, prox: 'No' = None):
self.charge = charge
self.ant = ant
self.prox = prox
def __str__(self):
return str(self.charge)
class ArrayListCircle:
def __init__(self):
self.head = None
self.ta... |
10543223b52beafc4c7bfc29a4ddab100f422cb3 | nithen-ac/Algorithm_Templates | /data_structure/string_examples.py | 18,323 | 3.65625 | 4 | from itertools import groupby
from itertools import zip_longest
from functools import reduce
from collections import defaultdict
from collections import Counter
import string
import re
import operator
# [125] https://leetcode.com/problems/valid-palindrome/
# Given a string, determine if it is a palindrome, considerin... |
f104a63a96199414da32eeb718326ecea5b4df7e | nithen-ac/Algorithm_Templates | /algorithm/bit_manipulation.py | 980 | 4.15625 | 4 | # Bit manipulation is the act of algorithmically manipulating bits or other pieces of data shorter than a word.
#
# common bit-wise operation
#
# operations priority:
# {}[]() -> ** -> ~ -> -x -> *,/,% -> +,- -> <<,>> -> & -> ^ -> | -> <>!= -> is -> in -> not x -> and -> or
def bit_wise_operations(a, b):
# not
... |
2fb6ae80bc6847284d39727afe2d5f6dcd39b25a | nithen-ac/Algorithm_Templates | /algorithm/divide_conquer_examples.py | 5,467 | 3.59375 | 4 | import random
# [50] https://leetcode.com/problems/powx-n
# Implement pow(x, n), which calculates x raised to the power n
def myPow(self, x, n):
if not n:
return 1
if n < 0:
return 1 / self.myPow(x, -n)
if n % 2:
return x * self.myPow(x, n - 1)
return self.myPow(x * x, n / 2)
... |
e136a38ffee49a60503fb6cbfacaa84b86e1ef30 | nithen-ac/Algorithm_Templates | /algorithm/two_pointers.py | 3,062 | 3.921875 | 4 | # two pointers scenario, famous applications such as binary search, quick sort and sliding window.
'''
Classification:
1. old & new state: old, new = new, cur_result
2. slow & fast runner: slow-> fast->->
3. left & right boundary or index: left-> <-right
4. p1 & p2 from two sequences: p1-> p2->
5. start & end sliding ... |
fa4ce15301f717012279ced9fe5aff6e1f123bb9 | nithen-ac/Algorithm_Templates | /data_structure/binary_tree.py | 5,290 | 4.03125 | 4 | # Classification: binary tree, complete binary tree, full binary tree, binary search tree, AVL tree(self-balancing)
#
# Time: O(n)
# Space: O(h) h: height of tree
from collections import deque
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None... |
5c405ea8df91cc847ab89c3559ba99750ac9cfc3 | nithen-ac/Algorithm_Templates | /algorithm/sliding_window.py | 1,774 | 3.703125 | 4 | # Sliding windows code template is most used in substring match or maximum/minimum problems.
# It uses two-pointer as boundary of sliding window to traverse, and use a counter(dict) maintain current state,
# and a count as condition checker, update it when trigger some key changes.
#
# Time: O(n)
# Space: O(k) k = len... |
d4f0b12c6d6e9508c90f0872c3c249120a29eade | Julian0912/Book_DSA | /Chapter_8/LinkedBinaryTree.py | 5,763 | 3.703125 | 4 | # -*- coding:utf8 -*-
# Author: Julian Black
# Function:
#
from BinaryTree import BinaryTree
class LinkedBinaryTree(BinaryTree):
"""二叉树的链式存储结构"""
class Node(object):
"""非公开"""
__slots__ = 'element', 'parent', 'left', 'right'
def __init__(self, element, parent=None, left=None, right=N... |
073e62dd7605358faa87c85820aa8f0ebb19f9af | Julian0912/Book_DSA | /Chapter_8/BaseTree.py | 2,785 | 4.1875 | 4 | # -*- coding:utf8 -*-
# Author: Julian Black
# Function:
#
from abc import ABCMeta, abstractmethod
class Tree(metaclass=ABCMeta):
"""树的基类"""
class Position(metaclass=ABCMeta):
"""一个表示元素位置的基类"""
@abstractmethod
def element(self):
"""返回该位置的元素"""
@abstractmethod
... |
cdaa976a78cd259de440ecf74c97c133b6956dca | danzakhalid/100DaysCodingChallange | /snake-game__Easy/food.py | 418 | 3.515625 | 4 | from turtle import Turtle
import random
class Food(Turtle):
def __init__(self):
super().__init__()
self.shape('square')
self.penup()
self.shapesize(0.5, 0.5)
self.color('cyan')
self.speed('fastest')
self.refresh()
def refresh(self):
ran_x = ran... |
5b1b2cf0dbd3a182ce8605a29c41fd441a951ffe | Bricegnanago/elliptique_courbe | /main.py | 873 | 4.15625 | 4 | # Algorithme
# de x3+ax+b
class Point:
def __init__(self, abs=4, ord=9):
self.abs = abs
self.ord = ord
def setpoint(self, newabs, neword):
self.abs = newabs
self.ord = neword
# print(point.ord)
def elliptiquecourbe(a, b, point):
return point.ord * point.ord - (point.abs... |
c396bed704568f87e123bdbbec26ab2ee579702b | dudap/python | /crypt.py | 427 | 3.5625 | 4 | import string
import fileinput
howMany = raw_input("Podaj przesuniecie: ")
howMany = int(howMany) % 26
i = 0
tmp = ""
for line in fileinput.input():
if(int(howMany) > 0 and int(howMany) < 27):
line = line.rstrip()
length = len(line)
while(i < length):
if(ord(line[i]) > 96 and ord(line[i])<123):
c = or... |
d34e6997020b9ceff47a42b7c858a3ceb104bb84 | nehamehta2110/Dynamic-Programming | /TilingProblem.py | 869 | 3.953125 | 4 | """Tiling Problem
Given a “2 x n” board and tiles of size “2 x 1”, count the number of ways to tile the given board using
the 2 x 1 tiles. A tile can either be placed horizontally i.e., as a 1 x 2 tile or vertically i.e.,
as 2 x 1 tile
Input n = 4
Output: 5
Explanation: For a 2 x 4 board, there are 5 ways
1) All 4 vert... |
63ea63d8ebf79aa36389e44857c858480273db4d | deathstalkr/mypython | /credit card sample.py | 4,440 | 4.0625 | 4 | #importing the modules
#import numpy n-dimensional array
import numpy as np
#import sklearn python machine learning modules
import sklearn as sk
#import pandas dataframes
import pandas as pd
import unittest
#import matplotlib for plotting
import matplotlib.pyplot as plt
#import datasets and linear_model fro... |
f6e340cf74e4afc2384dc133321233044fd7193e | deathstalkr/mypython | /dgplug_prime_factor.py | 328 | 3.734375 | 4 | # Largest prime factor on a number
#Num = int(input("Enter Number: "))
Num = 600851475143
for i in range(2, Num + 1):
if(Num % i == 0):
isprime = 1
for j in range(2, (i //2)):
if(i % j == 0):
isprime = 0
break
if (isprime == 1):
k = i
p... |
bd43118323b8e8caaba171fc83d205d16c37e4e3 | LinhToan/MIT-HW-2 | /hangmanEZ.py | 4,703 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 15 11:34:29 2020
@author: Hiro
"""
# Hangman Game
import string
def is_word_guessed(secret_word, letters_guessed):
'''
secret_word: string, the word the user is guessing; assumes all letters are
lowercase
letters_guessed: list (of letters... |
2ab9f4f2fa5f9a9773072bc3d810f1f4e7d55669 | Kh-Apoorv/Loading_screen | /Loading.py | 354 | 3.59375 | 4 | import turtle
b = turtle.Turtle()
b.color("pink")
b.write("loading...", align= "right",font=("Calibri", 20, "bold"))
b.screen.bgcolor("black")
b.fillcolor("#C8A2C8")
b.pensize(5)
for i in range (400):
for f in ("violet", "indigo", "blue","green", "yellow","orange","red"):
b.color(f)
b.forward(100)
... |
a3a6978f2a353542c64bf4f2a6fcb081ea20100a | APeters97/CS-435-Project-1 | /Question 3 - Arrays of Integers.py | 712 | 4.09375 | 4 | import random;
def getRandomArray(n):
aList = [] #create new list
count = 0; #used to track how many numbers are added
while(count < n): #while tracker does not equal n
randNum = random.randint(0,100) #generate number
if(randNum not in aList): #only add to list if the number is... |
f31a2f8ae56690da86253aed017a2dfa91a83343 | okdonga/algorithms | /find_matches_both_prefix_and_suffix.py | 2,873 | 4.15625 | 4 | ################
# Given a string of characters, find a series of letters starting from the left of the string that is repeated at the end of the string.
# For example, given a string 'jablebjab', 'jab' is found at the start of the string, and the same set of characters is also found at the end of the string.
# This i... |
a9572f1c409ea5dffab4f17a8bb4918814122e59 | ne1son172/GB2-algo-and-data-structures | /HW1/task3.py | 478 | 3.984375 | 4 | # По введенным пользователем координатам двух точек вывести уравнение прямой, проходящей через эти точки.
x1 = int(input("Enter x1 >>> "))
y1 = int(input("Enter y1 >>> "))
x2 = int(input("Enter x2 >>> "))
y2 = int(input("Enter y2 >>> "))
temp1 = x1 - x2
temp2 = y1 - y2
k = temp2 / temp1
temp3 = k * x1
b = y1 - temp3... |
0a9bda6adc975f8526710ef07c49d9d9f2577759 | ne1son172/GB2-algo-and-data-structures | /HW2/task1.py | 1,813 | 4.21875 | 4 | """
Написать программу, которая будет складывать, вычитать, умножать или делить два числа.
Числа и знак операции вводятся пользователем.
После выполнения вычисления программа не должна завершаться, а должна запрашивать новые данные для вычислений.
Завершение программы должно выполняться при вводе символа '0' в качестве... |
0f0a0b1ca7078f0fc5aa188f30f5f83125a670ce | YarinBou/HangmanGame | /hangman-ex4.3.1.py | 254 | 3.90625 | 4 | user_guess = input("Guess a letter: ")
if (len(user_guess) > 1) and (not (user_guess.isalpha())):
print("E3")
elif (not (user_guess.isalpha())):
print("E2")
elif (len(user_guess) > 1):
print("E1")
else:
print(user_guess.lower())
|
a32ed4bf86abe7f1af38e4b7e373ac652683df78 | Searcher408/Basic-programming-projects | /226-InvertTree.py | 2,514 | 3.921875 | 4 | # Python3
class TreeNode:
def __init__(self, val=0, left=None, right=None) -> None:
self.val = val
self.left = left
self.right= right
# 后序遍历
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if not root:
return root
if not root.left a... |
ec637c363816a793f76ea30f659397fbb4714c03 | Searcher408/Basic-programming-projects | /83-DeleteDuplicates.py | 900 | 3.828125 | 4 | # Python3
from typing import List
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
cur = head
while cur:
... |
ef3f732f6095ccb458c04967b4349e702c3542c0 | Searcher408/Basic-programming-projects | /62-UniquePaths.py | 2,389 | 3.515625 | 4 | # Python3 动态规划 时间复杂度O(mn) 空间复杂度O(mn)
# 用 f(i, j) 表示从左上角走到 (i, j) 的路径数量,其中 i 和 j 的范围分别是 [0, m) 和 [0, n)
# 动态规划转移方程 f(i, j) = f(i-1, j) + f(i, j-1)
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp = [[0]*n for _ in range(m)]
for j in range(n):
dp[0][j] = 1
for i i... |
b359479a59a15d91c4f9a5662c4e00ae94268081 | Searcher408/Basic-programming-projects | /25-ReverseKGroup.py | 2,016 | 3.625 | 4 | # Python3
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# 递归
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
if not head or not head.next or k == 1:
return head
ret = head
for _ in range(k... |
a75f6969b2474e78ea506cb53fc18f3fda2b7b67 | Searcher408/Basic-programming-projects | /86-Partition.py | 851 | 3.765625 | 4 | # Python3
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# 时间复杂度: O(n),其中 n 是原链表的长度,对该链表进行了一次遍历。空间复杂度: O(1)。
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
dummy1 = ListNode(0)
dummy2 = ListNode(0)
node1 = ... |
b67a95fe6c7c692fe48f0c50ef2267fb87fcfe9f | Searcher408/Basic-programming-projects | /27-RemoveElement.py | 1,212 | 3.6875 | 4 | # Python3 双指针
from typing import List
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
fast = slow = 0
while fast < len(nums):
if nums[fast] != val:
nums[slow] = nums[fast]
slow += 1
fast += 1
return slow
# C... |
17285af511de33f99f3171651a09d5c9d0cb5c42 | Searcher408/Basic-programming-projects | /82-DeleteDuplicates.py | 3,900 | 3.921875 | 4 | # Python3
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# 一次遍历
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if not head:
return head
dummy = ListNode(0, head)
cur = dummy # 从哑节点开始遍历
... |
bd5a0ebf069f924b7d29b8ba2d3b08c20de182fe | AndyRewLy/HELP | /backend/place.py | 400 | 3.71875 | 4 | class Place(object):
def __init__(self, url, placeId, name, location):
self.url = url
self.placeId = placeId
self.name = name
self.location = location
def toString(self):
print "{"
print " url=" + self.url + ","
print " placeId=" + self.placeId + ","
print " na... |
6d0745071e38ee8949a6392e51d8f036faef9dcc | arnillacej/calculator | /calculator.py | 397 | 4.34375 | 4 | num1 = float(input("Please enter the first number: "))
operation = input("Please choose an arithmetical operation '+,-,*,/': ")
num2 = float(input("Please enter the second number: "))
if operation == "+":
print(num1+num2)
elif operation == "-":
print(num1-num2)
elif operation == "*":
print(num1*num2)
elif o... |
e875e550a7fcb0b8968882169337436dfabd7365 | certifiedloud/stem-and-leaf | /StemAndLeaf.py | 1,403 | 3.828125 | 4 | """
A simple stem and leaf plot class
"""
class StemAndLeafPlot:
def __init__(self, numList):
self.numList = sorted(numList)
def plot(self):
# The number of digits in the biggest number
maxDigits = len(str(self.numList[-1]))
numDict = self.constructPlotDict()
for i in ... |
8684c271753dea2dc86d7e6bbeee337803e80497 | JonathanWitman/todo-manager | /todos.py | 1,472 | 3.546875 | 4 | import manager
import item
#Each class should be in its own module which you will need to import accordingly
#how to store data in the file
#Look up the datetime module
def begin():
print("What's up?")
print("type 'help' for help")
inp = input("> ")
if inp == "help":
print(" - 'add' to add ... |
74fd1b9071853159dbed349504f704be01534532 | EricE-Freelancer/Learning-Python | /the power of two.py | 426 | 4.40625 | 4 | print("Hi! what is your name? ")
name = input()
anything = float(input("Hi " + name + ", Enter a number: "))
something = anything ** 2.0
print("nice to meet you " + name +"!")
print(anything, "to the power of 2 is", something)
#the float() function takes one argument (e.g., a string: float(string))and tries... |
17d0d0e6188ceb6aba423ea4dddaa5d39c7bca13 | clashCoder/pythonProjects | /crUpgradeCost/crExtract.py | 2,327 | 3.515625 | 4 | from lxml import html
import requests
import re
import sys
import argparse
# parse user input (should be a valid player id from the mobile game "Clash Royale")
text_description = 'Obtain Clash Royale card information for a given player ID. Results stored in files.'
parser = argparse.ArgumentParser(description=text_des... |
4e3c009c2376807b96291c2c3951086fc9d87cba | vlslav/AppliedPythonF2019 | /homeworks/homework_05_ml/simplex_method.py | 756 | 3.6875 | 4 | #!/usr/bin/env python
# coding: utf-8
import numpy as np
def simplex_method(a, b, c):
"""
Почитать про симплекс метод простым языком:
* https:// https://ru.wikibooks.org/wiki/Симплекс-метод._Простое_объяснение
Реализацию алгоритма взять тут:
* https://youtu.be/gRgsT9BB5-8 (это ссылка на 1-ое из ... |
eb4c16bd06762746ef19d057dcbd9644c185ee3c | yuzurunishimiya/python-date-and-time | /datetime-module/datetime.datetime-class.py | 568 | 3.984375 | 4 | # The datetime module has day_time class named dateclass that can contain information from both date and time objects.
from datetime import datetime
# datetime year, month, day
day = datetime(2020, 5, 2)
print(day)
# more complex
day_time = datetime(2020, 5, 1, 23, 59, 59, 999999)
print(day_time)
# get year, month, d... |
071c298e4e9913517b7d037e0b6b40daf1a15018 | kunalsaraf/Sipher | /modules/polybius_square.py | 2,822 | 3.53125 | 4 | # Python Program to implement Polybius Square cipher
# Decrypt function is to be written and 2 outputs will be shown as 'i' and 'j' have same values
lookup = {'A': '11', 'B': '12', 'C': '13', 'D': '14', 'E': '15',
'F': '21', 'G': '22', 'H': '23', 'I': '24', 'J': '24','K': '25',
'L': '31', 'M': '... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.