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
8c7251c948f82ae3fc650ed8d51ad159168636b1
nibnait/PyTest
/3-高级特性/3.2-迭代.py
646
3.828125
4
# coding=utf-8 # dict:for循环默认key d = {'a':1, 'b':2, 'c':3} for key in d: print key, print # 迭代value: for value in d.itervalues(): print value, print '' # 同时迭代key和value for k,v in d.iteritems(): print k,v print #Q1:如何判断一个对象是否可迭代? from collections import Iterable l = [1,2,3,4] print isinstance(l, Iterable) ...
f82bb3cf963ef6abd55663f032aaeaf98708aa5a
nibnait/PyTest
/3-高级特性/3.1-切片.py
239
3.640625
4
# coding=utf-8 # list、tuple都可以进行切片操作 l = range(100) print l[0:3] print l[:3] print l[1:3] print l[-3:] # 前10个数 每2个取一个: print l[0:10:2] # start,end,step # 所有数 每5个娶一个 print l[::5]
2c5569c99d54e1fa5aa523b6071862f237bc6334
DemondLove/Python-Programming
/CodeFights/28. alphabetShift.py
951
4.3125
4
''' Given a string, your task is to replace each of its characters by the next one in the English alphabet; i.e. replace a with b, replace b with c, etc (z would be replaced by a). Example For inputString = "crazy", the output should be alphabeticShift(inputString) = "dsbaz". Input/Output [execution time limit] 4 s...
004282825cb9fe328bc041717fc0dc840b5d367e
DemondLove/Python-Programming
/Leetcode/LeetCode - 1119. Remove Vowels from a String.py
520
3.796875
4
/* Given a string S, remove the vowels 'a', 'e', 'i', 'o', and 'u' from it, and return the new string. Example 1: Input: "leetcodeisacommunityforcoders" Output: "ltcdscmmntyfrcdrs" Example 2: Input: "aeiou" Output: "" Note: S consists of lowercase English letters only. 1 <= S.length <= 1000 */ class Solution...
e092d0fd578167e1a9ce807063426a1e148a6d4a
DemondLove/Python-Programming
/Leetcode/Leetcode - 1108. Defanging an IP Address.py
839
3.90625
4
''' Given a valid (IPv4) IP address, return a defanged version of that IP address. A defanged IP address replaces every period "." with "[.]". Example 1: Input: address = "1.1.1.1" Output: "1[.]1[.]1[.]1" Example 2: Input: address = "255.100.50.0" Output: "255[.]100[.]50[.]0" Constraints: The given address i...
fc2a2ca8d11b1c90f35118263132230e1b544ebb
DemondLove/Python-Programming
/CodeFights/42. Bishop and Pawn.py
1,450
4.125
4
''' Given the positions of a white bishop and a black pawn on the standard chess board, determine whether the bishop can capture the pawn in one move. The bishop has no restrictions in distance for each move, but is limited to diagonal movement. Check out the example below to see how it can move: Example For bishop...
9f33e74a5c3aac486f9e89ccaf5281a5ac87db0b
jtapias-lsv/movies
/movies_app/tests/test_bouncy.py
2,746
4
4
from unittest import TestCase import time def en_lista(num:int) -> list: """ function to make a list whit a number's digits Args: num: number to be separated in its digits Returns: a list with parameter number's digits example: 234 -> [2,3,4] """ try: result = list(map(int, s...
860d6eef378bb7e7c3b1b70b0f0366d215e48e82
NJRena/RN_JY_Project
/Project.py
673
3.71875
4
import pandas as pd import matplotlib.pyplot as plt countries = pd.read_excel('IMVA.xlsx') print(countries) country = countries['Periods'].str.split(expand = True) countries = countries.assign(country_year=pd.to_numeric(country[0])) countrylist = countries[(countries['country_year'] >= 1988) & (countries['country_yea...
621d36d3dea03fc4e0092b98d4cde06f8b36a1f8
erik-hedlund/AdventOfCode
/2019/src/day13.py
3,606
3.703125
4
from enum import Enum from intcode_computer import IntcodeComputer from util import read_input def get_program(): program = list() for line in read_input('input13.txt'): program.extend(line.split(",")) return [int(i) for i in program] X = 0 Y = 1 DATA = 2 class Game(object): ...
9de8a41ce410fcc4334cdf4ecaa910bce000ea1a
esadckova/hello-world
/Задача1.py
200
3.953125
4
name = input("Введите имя") a = int(input("Введите ваш вес в кг")) d = a * 33 print(f"{name},вам необходимо выпивать {d: d} мл воды день")
a05f6bbb98563d606fd1fe5e9c58942b75466f99
hbalasu1/computer-pointer-controller
/src/input_feeder.py
2,170
3.703125
4
""" This class can be used to feed input from an image, webcam, or video to your model. Sample usage: feed=InputFeeder(input_type='video', input_file='video.mp4') feed.load_data() for batch in feed.next_batch(): do_something(batch) feed.close() """ import cv2 from numpy import ndarray class Im...
7954c9f8c2fcfcda19320508d46b11cdc3a74b08
HaukeBu/SmartChair
/src/hal/pi/helper.py
562
3.71875
4
import re def uppercase_to_camelcase(text): temp = text.lower().split('_') return temp[0] + "".join(map(str.capitalize, temp[1:])) def camelcase_to_uppercase(name): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).upper() def list_to_json_string(lst):...
0c1a5a8de1dd2f64ecba2e74302e6a1681990cbc
Tiresiasel/intro-to-Python-SMM692
/_3/basic_array_methods.py
2,213
3.890625
4
#/usr/env/bin python3 # -*- encoding utf-8 -*- """ ----------------------------------------------------------------------------- basic_array_methods.py | ndarray, the fundamental NumPy object ----------------------------------------------------------------------------- Auhor : simone.santoni.1@city.ac.uk Agen...
b01d6c6d2949acf9e4169ca916a349ff8fc436f6
joepeak/BeiJingSubwayFlows
/datetime_helper.py
5,586
3.5
4
""" 时间处理函数 """ import time from datetime import timedelta, datetime, date FORMAT_DATE = '%Y-%m-%d' FORMAT_DATE_CHINA = "%-m月%-d日" FORMAT_DATE_CHINA_FULL = "%Y年%m月%d日" COMPACT_DATE = "%Y%m%d" DOT_DATE = "%Y.%m.%d" COMPACT_TIME = "%H%M%S" FORMAT_DATETIME = '%Y-%m-%d %H:%M:%S' FORMAT_ONLY_TIME = "%H:%M" COMPACT_DATE...
16d00f1a6d17003a6df8b762fd2e3ab75f9e83ba
sinasezza/airport_management-python-master-
/Airliner.py
605
3.5625
4
from Airplane import Airplane; class Airliner(Airplane): #default constructor: def __init__(self,id,capacity) -> None: super().__init__(id) self.__Capacity = capacity; # -------------------------------------- def SetCapacity(self,cap): self.__Capacity = cap; # -----...
8cd584ed94690af9dfc2d5ccbf426685628e8214
jrmullen/cse233
/problem9/problem9.py
532
3.625
4
__author__ = 'Jeremy' def main(): try: random_numbers = open('numbers.txt', 'r') number = 0 total = 0 average = 0 print("List of numbers:") for line in random_numbers.readlines(): print(line) total = total+int(line) number +...
025296e1bd8ab9ffcf995d50f7132eb71581446f
ShimantoBhowmik/A-simple-calculator-GUI-
/calculator.py
3,595
4.21875
4
from tkinter import * #creating the window: root = Tk() root.title("Simple Calculator") e = Entry(root, width = 35 , borderwidth =5) e.grid(row = 0 , column =0 , columnspan = 3, padx = 10 , pady = 10) def button_click(number): current = e.get() e.delete(0, END) #deleting whats inside the box e.inser...
ca3344cd64a904d74a2bab95d4c053b320377e06
kaurharminder96/first
/excp.py
182
4
4
try: a=int(input("Enter the value of A")) b=int(input("enter the value of B")) print(a+b) print(a/b) except ArithmeticError: print("No. is divisible by 0");
ac0124ee0d5d20bee6d45ba7f256f50bd7016e5f
msabbir007/Introduction-to-Python
/Assignment(Round3)/ruutu_2.py
567
3.9375
4
# Johdatus ohjelmointiin # Print a box with input checking def print_box(a,b,c): for i in range(0, b): for j in range(0, a): print(c, end="") print() def read_input(x): y = int(input(x)) while True: if y<0: y = int(input(x)) elif y==0: y...
2e70057acd03f9e147b4f71c0cd6210af61914ae
msabbir007/Introduction-to-Python
/Assignment(Round 6)/Encrypt_whole_msg.py
1,213
4.0625
4
def encrypt(alphabet): regular_chars = ["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"] encrypted_chars = ["n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y...
dc7fdadfcb5d8c59a98f2b961e6b979ca5f46989
msabbir007/Introduction-to-Python
/Assignment(Round 6)/rot13.py
976
4.09375
4
# TIE-02100 Johdatus ohjelmointiin # TIE-02106 Introduction to Programming # Task: ROT13, program code template def encrypt(alphabet): regular_chars = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", ...
678366727bf2440b014bc9ccb79743e0c5caaf8a
msabbir007/Introduction-to-Python
/Assignment(Round 6)/longest_substring_in_order.py
253
3.8125
4
def longest_substring_in_order(x): substring_value=0 longest_substring='' lc=[0 for k in range(len(x)+1)] result=0 for i in range(len(x)+1): if i==0: lc[i]=0 elif: x[i-1]== return longest_substring
4e25fe1a14919f0a94436f55cf8369a91c6a23fe
msabbir007/Introduction-to-Python
/Assignment(Round2)/WhileLoop2.py
379
4.03125
4
a=str(input("Answer Y or N: ")) if a=='Y' or a=='N': print('You answered ', a) elif a== 'y' or a=='n': print('You answered ', a) else: while a!='Y' or a!='N' or a!= 'y' or a!='n': print('Incorrect entry.') a = str(input("Please retry: ")) if a=='Y' or a=='N' or a== 'y' or a=='n':...
7621c114d74e45065f5d94f0595fd07ec6162c4d
jgalloway42/MS-Applied-Mathematics-Projects
/MATH 7203 Numerical Analysis 1/Project 1/CommandLineScript/RunMe.py
2,136
3.515625
4
''' Description: Runs program to demonstrate the level detection algorithm created by modifying the standard Canny Edge Detection Algorithm Input: none Output: Marked up Video of Level Draining From a Jug as algorithm draws a line at the water level for each frame Uses: Math 7203 Mini Project 1 Video ( 1 mi...
1f79314ab2d8a6154ad94119859dcef247a35840
mtophir/Machine_Learning
/pytorch_3-layer-nn.py
995
3.703125
4
#3-layer-nn using pytorch import torch def sigmoid(x, deriv=False): if (deriv==True): return x*(1-x) return 1/(1+torch.exp(-x)) #input tensor X = torch.Tensor([[0,0,1],[0,1,0],[0,1,1],[1,0,0]]) #expected output (supervised learning) y = torch.Tensor([[0],[1],[1],[0]]) torch.manual_seed(1) # randoml...
328368504b4985d5dbe78d84651cf061ed3b090d
gwenchee/CD
/scripts/input.py
644
3.515625
4
import jinja2 def load_template(in_template): """ Returns a jinja2 template from file. Parameters --------- in_template: str path and name of jinja2 template Returns ------- output_template: jinja template object """ with open(in_template, 'r') as default: output_t...
7a6f3c545c9b9c0b011c54ce1af7c2b24ebd9b92
kaveri-nachu/kaveri
/Recursive.py
329
3.78125
4
import turtle def tree(branchLen,r): if branchLen > 5: r.forward(branchLen) r.right(20) tree(branchLen-15,r) r.left(40) tree(branchLen-15,r) r.right(20) r.backward(branchLen) def main(): r = turtle.Turtle() myWin = turtle.Screen() r.left(90) r.up() r.backward(100) r.down() r.color("green") tree(75,r) myWin.exitonclick(...
54ba52223eb9e67154a4f2e4fe08b4010c972d00
Jongwook-Seong/Practice-List
/Algorithm/LeetCode/20 - Valid Parentheses.py
559
3.65625
4
class Solution: def isValid(self, s: str) -> bool: l = len(s) stack = [] o = ['(', '{', '['] c = [')', '}', ']'] if l == 0: return True elif l % 2 != 0: return False elif s[0] in c: return False elif s[l-1] in o: return False for p in s: ...
852f3068b5aefbbc2780397e8386581ca313938b
veratsurkis/enjoy_sleeping
/lab_2_1/ex4.py
138
3.859375
4
import turtle as tr tr.shape('turtle') def circle(n): turn = 360/n for i in range(n): tr.forward(3) tr.right(turn) p = 100 circle(p)
694ccf14ab1fd174eafdfbc3d5c25ff5b5461644
veratsurkis/enjoy_sleeping
/ex10_1.py
201
3.765625
4
import turtle as tr tr.shape('turtle') tr.speed(0) def circle(n): turn = 360/n for i in range(n): tr.forward(1) tr.right(turn) p=400 for i in range(6): circle(p) tr.right(60)
9010311882cbfb3237bca7bb508d502bc9ae0315
aggo/jku-dl
/dl_a1_e3/ex_5_k1557854_impl.py
6,153
3.78125
4
import numpy as np def softmax(z): m = z.max(1)[:, None] # improves numerical stability of softmax e = np.exp(z - m) return e / e.sum(1)[:, None] def forward_pass(w0, b0, w1, b1, w2, b2, x): ''' Calculate the output of a network with 2 hidden layers with tanh hidden and softmax output activ...
e0d0696bc9f6bd9516893ffbfae606b70bcea6ab
EpicRowan/ShrimplytheBest-shopping-site
/user.py
943
3.875
4
class User(object): def __init__(self, user_id, email, password, ): self.user_id = user_id self.email = email self.password = password def __repr__(self): """Convenience method to show information about user in console.""" return "<User: {}, {}, {}>".format(self.user_id, self.email) def ...
ce389515649fc3224a7175abeb1ed89ff8b5743e
makassigithub/core-python
/Book/chapter6.py
2,867
4.25
4
#6.1 Écrivez un programme qui convertisse en mètres par seconde et en km/h une vitesse fournie #par l’utilisateur en miles/heure. (Rappel : 1 mile = 1609 mètres) #mp = float(input("enter speed :\n")) #print("the equivalent in km/h is: ", (mp*1609)/1000) #print("the equivalent in m/ is: ", ((mp*1609)/1000)*1000/3600)...
7f14ace1ea158c7e55a0c7eb982a836ce346a560
makassigithub/core-python
/OOP/ex_12_2.py
615
3.875
4
class CompteBancaire(): "Incarne les caracteristiques d,un compte bancaire" def __init__(self,nom='Dupont', solde=1000): self.nom = nom self.solde =solde def depot(self,somme): self.solde += somme def retrait(self,somme): self.solde -= somme def affiche(self): ...
846dc2a18ea03e6bb034a5db63f18481e48e351e
makassigithub/core-python
/OOP/oop_intro.py
399
3.796875
4
class Point(): "Le pint est definie par 2 coordonnes spaciales" def calculer_distance(A,B): " etant donné point A et B, cette function calcul la distance qui les separe et la retourne " return ((B.x - A.x)**2 + (B.y - A.y)**2)**1/2 p1 = Point() p1.x , p1.y = 2.0, 3.0 p2 = Point() p2.x , p2.y = 4.0, 2.0 ...
08cc42adae9c5077db60e1f49607b7a8c0fb9ddf
jaredscarr/data-structures
/linked_list.py
2,235
4.125
4
# -*- coding: utf-8 -*- class Node(object): """Construct Node object.""" def __init__(self, val): """Initialize node object.""" self.val = val self.next = None class LinkedList(object): """Handle creation of a linked list.""" def __init__(self, iterable=None): """In...
e1a8722c83b4b3cab7c75f05e45bc7526d2a3ad1
jaredscarr/data-structures
/test_linked_list.py
2,856
3.5
4
# -*- coding: utf-8 -*- import pytest @pytest.fixture() def linked_list(): """Test fixture for linked list tests.""" from linked_list import LinkedList ll = LinkedList() ll.insert('a') ll.insert('b') ll.insert('c') return ll def test_node_class(): """Test Node.""" from linked_lis...
3785da3094cd267a733f69a3014e96850c2530b7
cornell-cup/r2-chatbot
/r2_chatterbot/util/face_recognition.py
2,815
3.890625
4
import utils import re import nlp_util import live_streaming import os def isFaceRecognition(text): """ Determines whether a string is a facial recongnition command. The different types of facial recognition commands include greetings, such as "hi," "hello," or "wave," the make new friends command in t...
ebc8bdf05cf2dccaf52283154b8bd5c6f6214edc
Arczibald89/Speedway
/rider.py
3,261
3.734375
4
class Rider(object): """ Representation of speedway rider.""" def __init__(self, name, surname, total_skills, visible=False, match_runs=0, match_points=0, match_falls=0, match_defects=0): self.name = name self.surname = surname self.total_skills = total_skills se...
921ae2b647a89ac4cf81d28c5bd3aa083924de77
AlexandervVugt/DarkTimesMississippi
/gui/main.py
1,488
3.890625
4
import inputScreen, event, dice, turn, popup_modify, popup_confirm, victorious import logic.Game as Game import logic.GameController as GameController global currentScene, scenes, game, gameController def setup(): global currentScene, scenes # currentScene is used like a stack # to nest a scene, use ...
a739fe27bebb091de3bf49387d98eb236d0dfc63
wxke/python_new
/多线程/threading_Daemon守护线程_线程锁.py
665
3.546875
4
#!/usr/bin/env python # -*- coding:UTF-8 -*- import threading import time def run(): lock.acquire() #线程锁 关闭 global n n += 1 print(n) lock.release() #线程锁 释放 n = 0 lock = threading.Lock() #线程锁 #threading.RLock() 递归锁 #semaphore = threading.Bound...
44e86e3083c540e6387ae5cbdc7877c7edff5de8
wxke/python_new
/Atm/atm/core/shop_main.py
762
3.84375
4
#!/usr/bin/env python shop_product = { 'python':500, 'mac':400, 'iphone':300 } shop_car={} def shopping(func): def wap(*args): print("q退出 or 继续") for i in range(1000): a =input() if a is not 'q': func(a) else: print("qq...
7d8943b9e1affec42259274e1c88ff2f9935c41d
wxke/python_new
/多线程/threading_test.py
644
3.9375
4
#!/usr/bin/env python # -*- coding:UTF-8 -*- import threading import time #主线程是程序本身 一下都是在本线程的“子线程” def run(n): print("start:---",n) time.sleep(2) print("end:-----",n) list = [] start_time = time.time() for i in range(50): t = threading.Thread(target=run,args=("----%s" %i ,)) t.start() list....
145ff8544b53d73a2e29444aef3977e97403ec20
wxke/python_new
/反射/反射.py
439
3.671875
4
#!/usr/bin/env python # -*- coding:UTF-8 -*- def talk(self): print("%s talking!!!!!!!!!" %self.name) class dog(object): def __init__(self,name): self.name = name def walk(self): print('%s walking!!!!!!!!'%self.name) d = dog("啦啦啦") d.walk() chioce = input(">>>>:") if hasattr(d,chioce): ...
b4ef5f188aa84d8a71146285fabd9fbbbbe14f7a
wxke/python_new
/装饰器/列表生成器.py
159
3.765625
4
#!/usr/bin/env python # -*- coding:UTF-8 -*- a = [ i+2 for i in range(10)]#列表生成式 print(a) b = ( i+2 for i in range(10))#列表 生成器 print(b)
0f5c3cd40b211687732caa78d79f62344ad9b217
Raajesh12/YouFood
/yelp_data_loading/test_weekly_transactions.py
1,065
3.609375
4
from credentials import USER, PASSWORD, DATABASE, HOST import psycopg2 import json from pprint import pprint from datetime import datetime #Connect with psycopg2 to server conn = psycopg2.connect(dbname=DATABASE, user=USER, password=PASSWORD, host=HOST) cur = conn.cursor() #Get the current time, replace this with wha...
8e07990242db635d4333f14162ab072fec562a69
kyungjaeson/project2wchad
/main.py
1,620
3.734375
4
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns cryptoDF = pd.read_csv('crypto-markets.csv') #"Test data exists" # print(cryptoDF.head()) #print(cryptoDF.info()) #convert to datetime cryptoDF['date'] = pd.to_datetime(cryptoDF['date'], format = "%Y-%m-%d") #presets oldest_cryptoDF = pd.Data...
e3c870a1069eee7c09d0d2c66f7e1d7a04f8127c
jiangyu718/pythonstudy
/base/integrative.py
509
4.15625
4
listone = [2, 3, 4] listtwo = [2*i for i in listone if i > 2] print(listtwo) def powersum(power, *args): '''Return the sum of each argument raised to specified power.''' total = 0 for i in args: total += pow(i, power) return total exec('print(powersum(2,3,4))') exec('print(powersum(2,10))') eva...
c57e57dc68adb7cb290ffbfa7a0a3679fca23a1c
Hugal31/Sensei
/ressources/encode.py
99
3.609375
4
#!/usr/bin/env python3 for char in range(12353, 12438): print(chr(char), char, '0x%x' % char)
8882d77b88d9d5adce2afeab7d45f684887b22d4
Dipon12/Basic-OOP-
/Basic8(DuckTyping).py
719
3.671875
4
class PyCharm: def execute(self): print("Compiled...") print("Executed...") class VStudio: def execute(self): print("Spell Check...") print("Convention Check...") print("Compiled...") print("Executed...") class Laptop: def code(sel...
5deebe1339e5288232f0b0c121f98846a9fa625c
ankitha253/20A91A0597_Ankitha_CSE-B
/pp-11.py
303
3.890625
4
#To find reverse of a number using while loop. num=int(input()) rev=0 while(num>0): reminder=num%10 rev=(rev*10)+reminder num=num//10 print('reversed number is %d'%rev) '''expected output 13579 reversed number is 97531''' '''actual output 13579 reversed number is 97531'''
f2c4c52e992824e46ee2fd96ef48de9e57429287
booji/Exercism
/python/collatz-conjecture/collatz_conjecture.py
299
3.9375
4
def collatz_steps(number): if number < 1 or number is None: raise ValueError("Number has to be postivie value") count = 0 while True: if number == 1: break number = int(number/2) if number%2==0 else int(number*3+1) count += 1 return count
e37bd32f3a7692b162e3d4ea9a5d7d3b1a304dc6
booji/Exercism
/python/simple-cipher/simple_cipher.py
1,756
3.515625
4
import secrets from collections import deque import string class Cipher(object): def __init__(self, key=None): if key == None: self.key = ''.join([secrets.choice(string.ascii_lowercase) for i in range(100)]) else: self.key = key def encode(self, text): result = ...
3ceab3ad04a845fcf81f46c24b4b612c7d7e3dc9
booji/Exercism
/python/prime-factors/prime_factors.py
707
4.28125
4
import math def prime_factors(natural_number): factors = [] i = 2 # Find all prime '2' the remainder will be odd. while natural_number%i == 0: natural_number = natural_number // i factors.append(i) # Go up to sqrt(natural_number) as prime*prime cannot be greater then # natural_...
039b8ca6ac6b608c8d20bc2b2cf8be7c4e271bda
booji/Exercism
/python/perfect-numbers/perfect_numbers.py
677
3.703125
4
def classify(number: int) -> str: perfect = "perfect" abundant = "abundant" deficient = "deficient" if number < 1: raise ValueError('Invalid number') elif number == 1: return deficient divider = 2 listing = set([1]) while True: if number == divider: br...
5c5231ebc56f46a09a3963c23fab73bdb43508ab
JihongZ/python_learning
/wordgame2.py
880
3.890625
4
import random print("------这是一个文字游戏2--------") temp = input("请你猜一个我心中的数字:") guess = int(temp) secret = random.randint(1, 10) # first guess if guess == secret: print("你猜中啦!正确答案是" + str(secret) + "!!!!") print("猜中了也没有奖励啦~~") else: if guess > secret: print("大了") else: print("小了")...
8506aa21f24c614e70fdc3058dca15b973a5f4d8
SampleUser0001/dict_list_inPython
/app/src/app.py
375
3.984375
4
# -*- coding: utf-8 -*- def loop_dict(items): for key in items: print(items[key]) def loop_list(items): for i in range(len(items)): print(items[i]) if __name__ == '__main__': tmp_list = ['a','b','c'] tmp_dict = { 'key01': 'hoge', 'key02': 'piyo'} loop_dict(tmp_dict) loop_list(tmp_l...
ebe2cb67deccd11150cba66d8684b314ab6ac8c2
fxrcode/Udacity-Data-Engineering
/Class/4-Data-Lake-Spark/spark/sparkForML/3_creating_features_quiz.py
3,388
4
4
#!/usr/bin/env python # coding: utf-8 # # Creating Features Quiz # Use this Jupyter notebook to find the answers to the quiz in the previous section. There is an answer key in the next part of the lesson. # In[22]: from pyspark.sql import SparkSession from pyspark.ml.feature import RegexTokenizer, CountVectorizer, ...
790d11daed36af486c57a4cb4a017798b1a9dcc4
SimonCCooke/CodeWars
/SmallestInteger.py
446
4.1875
4
"""Given an array of integers your solution should find the smallest integer. For example: Given [34, 15, 88, 2] your solution will return 2 Given [34, -345, -1, 100] your solution will return -345 You can assume, for the purpose of this kata, that the supplied array will not be empty.""" def findSmallestInt(arr): ...
86b7beeaca264703c09472e1b6918152ee16f8a3
dougsoa/Cursoemvideo
/teste 03.py
212
3.859375
4
n01 = int(input('escolha um número: ')) n02 = int(input('escolha outro número: ')) s = n01 + n02 print('somando sua primeira escolha {} com a sua segunda escolha {}. O valor será de: {}'.format(n01, n02, s))
0b069781c497413c893c6eb35e7ac7efad7e621a
dougsoa/Cursoemvideo
/teste38.py
286
4.0625
4
n1 = float(input('escolha o 1° número: ')) n2 = float(input('escolha o 2° número: ')) if n1 > n2: print('O primeiro número é maior que o segundo!') elif n1 == n2: print('Os dois números são iguais!') else: print('O segundo número é maior que o primeiro!')
2844669bbae7499a36ea2e82e90f4db7f4bc2e82
urkang/graphgen
/graphgen/two_community_block_model.py
3,990
3.65625
4
""" Generates weighted or unweighted graphs using a block model. """ import networkx as nx def unweighted_two_community_graph(random_state, N, mu, avg_degree): """ To create the graph we generate a poisson distributed number of edges for each group pair where the mean is w_rs (1/2 w_rs when r=s). Then...
45d29a7a22088dab15040b1251e98cc49a25448b
VIDHI3030/c103
/bar.py
171
3.546875
4
import pandas as pd import plotly.express as px dataFile=pd.read_csv("data.csv") graph=px.bar(dataFile,x="Country",y="InternetUsers",title="incomeChart") graph.show()
1e5b7e296da9f7f15c881b10e0aa9aac3b23ee52
iwonabanas/pp1
/02-ControlStructures/36.py
435
3.515625
4
# 36 # liczba podzielna przez 7, przy dzieleniu przez 2,3,4,5,6 daje reszte 1 liczba = 0 flag = False while flag != True: if liczba % 7 == 0 and liczba % 6 == 1 and liczba % 5 == 1 and liczba % 4 == 1 and liczba % 3 == 1 and liczba % 2 == 1: flag = True else: flag = False liczba +...
1322d291ba322efb1f62b7d4cdae0d05abc52990
iwonabanas/pp1
/01-TypesAndVariables/zadanie.25.py
510
3.921875
4
# zad.25. Numer rachunku bankowego składa się z 26 cyfr. Napisz program, który odczyta numer rachunku z klawiatury # (wprowadzane tylko cyfry), a następnie wyświetli go w formacie jak poniżej (wraz z odstępami). number = input("Podaj numer rachunku bankowego: ") output = " " temp = " " try: int(number) print(f...
4ed397217d4b22e31f2a50885370b5344e0c5ba7
iwonabanas/pp1
/02-ControlStructures/zadanie11.py
460
3.625
4
# zad.11. System komputerowy zawiera konto użytkownika o identyfikatorze (login) „marek” i haśle „m-123”. # Napisz program, który sprawdzi, czy wprowadzony login i hasło są zgodne z danymi konta użytkownika. login = "marek" password = "m-123" user_login = input("Podaj login: ") user_pass = input("Podaj hasło: ") if ...
cb9c1049aad7673f34927554a940636e9578c2ef
iwonabanas/pp1
/02-ControlStructures/zadanie13.py
1,089
3.90625
4
# zad. 13. Niech x i y oznaczają współrzędne punktu na płaszczyźnie. # Napisz program, który określi, w której ćwiartce układu współrzędnych znajduje się punkt P(x,y) # lub na której z osi jest on położony lub też że znajduje się on w początku układu współrzędnych. # !!! POPRAWIĆ try: x = float(input('Podaj liczb...
5efc06ab1637db6054bdb88b0b62e5c6b78b6e54
iwonabanas/pp1
/02-ControlStructures/zadanie15.py
345
3.703125
4
# zad.15. Napisz program, który utworzy tabliczkę mnożenia w zakresie od 1 do 10, dla dowolnej liczby wprowadzonej przez użytkownika. try: x = float(input("Podaj liczbę: ")) for i in range (1,11): print("{0:g} x {1} = {2:g}".format(x,i,x*i)) except ValueError: print("Podana wartość nie jest li...
745fa4696928cb53c8f0dcfe35a5ce4650e2563b
jeb482/examples
/grammarian/grammarian.py
2,920
3.8125
4
import argparse from typing import Dict, Set, Iterable import nltk from nltk.corpus import words sample_spell_list = \ [ "Eldritch Blast", "Green Flame Blade", "Prestidigitation", "Bless", "Mage Armor", "Distort Value", "Earth bind", "Find Familiar", "Hold Per...
213ad3e8142536daa5789411d9e8a6dbf45056cd
satishkhanna/feature_engineering_project
/q03_skewness_sqrt/build.py
323
3.53125
4
# Default imports from scipy.stats import skew import pandas as pd import numpy as np ny_housing = pd.read_csv('data/train.csv') def skewness_sqrt (data): sp = np.sqrt(data['SalePrice']) val1 = skew(sp) gla = np.sqrt(data['GrLivArea']) val2 = skew(gla) return val2, val1 # Write your Solution Her...
b56945528aebd8e24b8bf88610f4e1b7f3706f10
Stompke/cs-module-project-hash-tables
/hashtable/hashtable.py
8,922
3.984375
4
class Node: def __init__(self, value): self.value = value self.next = None class LinkedList: def __init__(self): self.head = None def insert_at_head(self, node): node.next = self.head self.head = node def find(self, value): cur = self.head ...
a50b7abafd88ec624247b71075f6a886c2e634f7
girisandeep/Assignments
/anagram.py
327
3.71875
4
#!/usr/bin/python import fileinput for line in fileinput.input(): words = line.split() sortedword ={} for word in words: key = "".join(sorted(word.lower())) if not sortedword.has_key(key): sortedword[key] = [] sortedword[key].append(word) for key in sortedword: print sortedword...
8938d075f1b326e07214198881df479ea9eaf9de
kwaper/iti0102-2018
/kt4/exam.py
2,520
3.953125
4
"""KT4.""" def two_digits_into_list(nr: int) -> list: """ Return list of digits of 2-digit number. two_digits_into_list(11) => [1, 1] two_digits_into_list(71) => [7, 1] :param nr: 2-digit number :return: list of length 2 """ return [int(a) for a in list(str(nr))] pass def fizzbu...
263698ba009eb8555c08d620fe065045d223f2fd
kwaper/iti0102-2018
/pr14_exam/exam.py
6,082
4.4375
4
"""Test.""" def segment_number(first_number, last_number): """ Return list with elements dividable by 5 but not dividable by 3 between (inclusive) two arguments. Return list of numbers where only numbers between first_number and last_number (both inclusive) which divide by 5 but do not divide by 3 ...
3ce0dfaa573f5b0c705df722f06347ca7046d0aa
kwaper/iti0102-2018
/pr13_transportation/transportation.py
1,770
3.703125
4
"""Retrieve stops and departures info from REST service.""" import requests API_BASE = "https://public-transport-api.herokuapp.com" REGION = "tallinn" def get_nearby_stops(api_base, lat, lng): """ Get nearby stops. :param api_base: Base URL that the endpoint gets appended to :param lat: Latitude ...
38f7f4defa13ac0cc35d78a54b90d7764f9e6116
kwaper/iti0102-2018
/pr08_testing/shortest_way_back.py
1,586
4.25
4
"""Find the shortest way back in a taxicab geometry.""" def shortest_way_back(path: str) -> str: """ Find the shortest way back in a taxicab geometry. :param path: string of moves, where moves are encoded as follows:. N - north - (1, 0) S - south - (-1, 0) E - east - (0, 1) W - west ...
8559956f07bc53fd2f8299abf2dd2a1ffdca0c35
r-harini/Code
/Dynamic_Programming/howSum.py
353
3.703125
4
target= int(input('Enter target: ')) arr=[] n=int(input('Enter num of elements: ')) for i in range(n): a=int(input('Enter ele: ')) arr.append(a) def how(target, arr): if target==0: return [] elif target<0: return None for num in arr: remainder= target-num newa...
2d8d3c86d6c48ba00c0052fc7e50f710ad9a52db
r-harini/Code
/DSA_Practice/Python_programs/Exception_handling.py
212
3.578125
4
import math import sys lines=[] try: while (True): line=input("Enter the sentence:") lines.append(line) except SyntaxError: for i in range(len(lines)): print(lines[-1-i])
5b7775ec15638c8e3815887d7d4f53ae139fd028
r-harini/Code
/Dynamic_Programming/fib.py
366
3.578125
4
n=int(input("Enter n: ")) def fib(n, memo): if n in memo.keys(): return memo[n] elif n<=2: return 1 else: memo[n]=fib(n-1, memo)+ fib(n-2,memo) return memo[n] def opt(n): if n<=2: return 1 i=2 a,b=1,1 while i<n: a,b=b,a+b i+=1 ret...
69aea8910bf9c0f04b3b5d2c46c930398de81e4b
r-harini/Code
/DSA_Practice/Python_programs/Ll.py
5,373
4.03125
4
class LinkedList(): class _Node(): def __init__(self,element,next): self._element=element self._next=next def __init__(self,max): self._head=None self._tail=None self._size=0 self._maxsize=max def __len__(self): return self._size ...
9be798cdab5851b8e8622dd043ca3bccea20180f
r-harini/Code
/Machine_Learning/Deep_Learning/CNN/CNN.py
835
3.84375
4
#Building the CNN from keras.models import Sequential from keras.layers import Convolution2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense #Initialising the CNN classifier=Sequential() #Step 1: Convolution classifier.add(Convolution2D(32, 3, 3, input_shape=(64,6...
04ec308573556b4c9e216035cc5f2d65a9eaeb97
SaifAlsaad/simplecalculator
/My-first-simple-calculator.py
1,036
4.46875
4
print("Welcome to Saif's calculator") num1=input("Enter any number: ") op=input("Choose any symbole + - * ** / % // == != < > <= >= = : ") num2=input("last step to see the results: ") num1=float(num1) num2=float(num2) if op=="+": pls=num1 + num2 print(pls) elif op=="-": sub=num1-num2 print(sub) elif op=...
b0d6a9a10a7b20cdf39fdfba029bb5f4fd319c77
RaneemQaddoura/EvoNP
/src/NP.py
18,425
3.734375
4
from treelib import Tree import sys import numpy as np import random def NP(points_, sortedDistancesTree_, k_, initialPointsIndices_, randomPointsIndices_, pointsNearestIndices_, pointsNearestDistances_): """ This is the implementation of the NP clustering technique Parameters ...
979e0dc8cbd715255ca482d7e4bbd2c457d55931
annakuchko/DataEngineering
/Python-Basics/HW7/3.py
4,601
3.65625
4
# 3. Реализовать программу работы с органическими клетками. Необходимо создать # класс Клетка. В его конструкторе инициализировать параметр, соответствующий # количеству клеток (целое число). В классе должны быть реализованы методы # перегрузки арифметических операторов: сложение (__add__()), # вычитание (__sub__(...
a6aeb3abf0eb6ec38987f2fe21c39a68c4da5d97
annakuchko/DataEngineering
/Python-Basics/HW5/5.py
543
4.03125
4
# 5. Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных # пробелами. Программа должна подсчитывать сумму чисел в файле и выводить ее на экран. with open('numbers.txt', 'w+') as f: f.write(input('Введите набор чисел через пробел: ')) f.flush() f.seek(0) l = f...
136c43e8b88fcf1125699eca394c1f022e9b0974
xor-ia/Lonely_project
/main.py
791
3.59375
4
import random,time from playsound import playsound filename="sound.mp3" debugmode=False# if true will print current random number def rater(): rate=float(input("enter rate(1-100 higher=slower) : ")) rate=rate/10 return rate try: rate=rater() while rate>10.0: print("Rlly?",rate,"s delay???...
a815fbd1f0e796376e5166473e85e4fe751cf25d
caiotorrez/URI
/Ad-Hoc (URI)/Jogo do Maior.py
445
3.609375
4
def jogo_do_maior(fichas): p1 = 0 p2 = 0 while fichas > 0: jogada = raw_input().split() if int(jogada[0]) > int(jogada[1]): p1 += 1 elif int(jogada[0]) < int(jogada[1]): p2 += 1 fichas -= 1 return "%d %d" %(p1,p2) while...
19813faf4614a61b4fd8d3fba4116eb1d932ea7e
caiotorrez/URI
/Estruturas e Bibliotecas(URI)/Eu Posso Adivinhar a Estrutura de Dados!.py
1,447
3.703125
4
while True: try: stack = 0 queue = 0 priority = 0 lista = [] comandos = 0 st = -1 fila = 0 impossivel = False for i in xrange(int(raw_input())): comando,value = raw_input().split() value = int(value) if coma...
3ba5d92334af9b35173d23c1d62d55569cc34171
caiotorrez/URI
/Ad-Hoc (URI)/Tudo o que Você Precisa é Amor.py
648
3.75
4
entrada = int(raw_input()) par = 1 while entrada > 0: S = int(raw_input(),2) L = int(raw_input(),2) if S%2 == 0 and L%2 == 0: print "Pair #%d: All you need is love!" %(par) elif S%3 == 0 and L%3 == 0: print "Pair #%d: All you need is love!" %(par) elif S%5 == 0 and L%5 == 0: ...
173cb350e3a176b139290a860bf34d0443a96af3
caiotorrez/URI
/Ad-Hoc (URI)/Getline Two - Frutas.py
414
3.5625
4
dias = int(raw_input()) total = 0 resultado = [] variedade = 0.0 for i in range(dias): valor = float(raw_input()) frutas = raw_input().split() resultado.append(len(frutas)) total += valor variedade += len(frutas) for j in range(len(resultado)): print 'day %d: %s kg' %(j+1,resultado[j]) prin...
c74e63703ba5ff88039440f1595c211354e93a95
iliasmachairas/MSc_Thesis_Drought_Scripts
/Functions/Applying_variable_thres_function.py
4,689
3.53125
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: import numpy as np import pandas as pd def df_droughts_var_T(df,column,threshold,column2, removed_period): #variable threshold #The function loses 1 time step in case it starts with a drought # Removed_period arguement is just an integer number, not a string nei...
b6860d96e8ddd33de6787b4cb728bcdde38497f2
amandeep1991/data_science
/learnings/notes/PythonGyanLessons/demo/DebuggingFile.py
260
3.59375
4
for i in range(15): if i > 10: break if i < 5: continue print(i) hello_world_1 = 10 hello_world_2 = 10 hello_world_3 = 10 hello_world_4 = 10 hello_world_5 = 10 hello_world_6 = 10 hello_world_7 = 10 hello_world_7 print("Amandeep")
917c5e91e5c9fdc6fe802f299404b20ad7393d3c
Cozy-Ho/python_study
/gui_basic/7_radiobutton.py
1,053
3.671875
4
from tkinter import * root = Tk() root.title("cozy-ho") root.geometry("640x480") # 가로 * 세로 Label(root, text="select menu").pack() burger_var = IntVar() # int 형으로 값을 저장 btn_burger1 = Radiobutton(root, text="hamberger", value=1, variable=burger_var) btn_burger2 = Radiobutton(root, text="chicken-hamberger", value=2, va...
d863722da86150e9bf04e34ca28f71689f452a70
clopez13/CPSC230ParlettPelleriti
/Classwork/Functions_17.py
3,538
4
4
# Class Activities + Review (Class 17) # Together------------------------------------------------ # 0. Questions? # 1. How can we tell whether an object will remain changes AFTER # a function is done running? # 2. What type of object does a f(x) need to return to do MA? # Classwork-----------------------------------...
f8276627c5f78c46b6b447b6f95716c1101b874c
Lucas-Frey/Time_Series_Modeler
/Utils/ParallelPrinter.py
8,406
3.671875
4
import datetime import numpy as np import pandas as pd from itertools import repeat class ParallelPrinter: program_started = False def __init__(self, total_procs, proc_job_dict): """ Constructor method to initialize the parallel printer. It will initialize the printing format based o...
d1a6f5c16099b6b0d87946d9551681ed6a422a76
kamperh/bucktsong_eskmeans
/segmentation/utils/dp_align.py
6,600
3.609375
4
""" Functions and classes for aligning two lists using dynamic programming. The algorithm is based on on a slight variation of the method given at: http://www.avatar.se/molbioinfo2001/dynprog/adv_dynamic.html. By default NIST insertion, deletion and substitution penalties are used. Author: Herman Kamper Contact: kamp...
439d1481fcc7a1f7b31f96765a5efae3c8c97930
Suheel/Programming210CT
/Question 11 Week 5.py
351
3.875
4
#Question 11 #Week 5 # Based on the Python code or the C++ code provided in class as a starting point, implement #the double linked list node delete function. def remove(self,n): if prev = None: prev.next = n.next else: self.head = n.next if next = None: n.next.prev = n.prev el...
933ff881390dfd9555ffe8b9e03bc5b01145d157
Suheel/Programming210CT
/Question 3 Week 2.py
381
3.875
4
#Question 3 #Week 2 #Write the pseudocode for a function which returns the highest perfect square which is less or #equal to its parameter (a positive integer). def highestperfectsquare(inputval): highestsquare=1 2ndhighestsquare=4 index=1 while 2ndhighestsquare>=inputval: highestsquare=indext*2 index=index ...
17f70272ddf81483bcf5b5c36377659a43174a8d
amiraHag/Python-Basic
/basic datatypes/variables.py
584
4.4375
4
#print any text using print function print("Hello World!") """store value in variables""" x=5 y=6 z= x+y print(z) """ know the type of the variable by using type()""" print(type(z)) #make operations on numbers x= 3+4*5 print(x) # arithmatic operators four basic - + * / # ** power ()parenthesis- use to identify whi...
e89fd0c0c049d19d8d2d124f5c58b8307ca55bfe
digitalix-ai/PythonChallenges
/MoreOfIt.py
99
3.640625
4
inp = input('Give me a digit: ') a = inp*2 b = inp*3 c = a*2 print(int(inp)+int(a)+int(b)+int(c))