blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
6f30a7de181e48b349b3d1a15e71036df3a5bb17
zhangxinzhou/PythonLearn
/helloworld/chapter03/demo03.09.py
239
3.59375
4
total = 99 for number in range(1, 100): if number % 7 == 0: continue else: string = str(number) if string.endswith('7'): continue total -= 1 print("从1数到99共拍腿", total, "次.")
5b12efb2c92e09c14d3aad497a27916df4e82eb0
zhangxinzhou/PythonLearn
/helloworld/chapter07/demo02.04.py
804
3.75
4
class Fruit: def __init__(self, color='绿色'): Fruit.color = color def harvest(self, color): print("水果是:", color, "的!") print("水果已经收获......") print("水果原来是:", Fruit.color, '的!') class Apple(Fruit): color = '红色' def __init__(self): print("窝是苹果") super().__...
85ab73b618134d29af120bf7789b4f8ae38e6537
zhangxinzhou/PythonLearn
/helloworld/chapter05/demo01.08.py
94
3.65625
4
str = 'abc_ABC' lower = str.lower() upper = str.upper() print(str) print(lower) print(upper)
224160811a676654cbfe88c9d0ba15d89620450f
zhangxinzhou/PythonLearn
/helloworld/chapter04/demo03.02.py
235
4.1875
4
coffeename = ('蓝山', '卡布奇诺', '慢的宁') for name in coffeename: print(name, end=" ") print() tuple1 = coffeename print("原元组:", tuple1) tuple1 = tuple1 + ("哥伦比亚", "麝香猫") print("新元组:", tuple1)
ca8e6fd680ab452e8389b9d2391f1fbd1396ade1
zhangxinzhou/PythonLearn
/helloworld/chapter04/demo04.01.py
111
3.796875
4
dictionary = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'} print(dictionary) print(dictionary['key1'])
f152dfa3ca559ba75e1941d5f20ddc62ec2c4af0
zhangxinzhou/PythonLearn
/helloworld/chapter06/demo01.05.py
891
3.828125
4
def fun_bmi(height, weight, person='路人甲'): '''功能: 根据身高和体重计算BMI指数 person:姓名 height:身高,单位:米 weight:体重,单位:千克 ''' print(person + '的身高:' + str(height) + "米 \t 体重: " + str(weight) + "千克") bmi = weight / (height ** 2) print(person + "的BMI指数为:" + str(bmi)) # 判断身材是否合理 if bmi < 18.5: ...
683c50bc6524b5ecb5d03617cf25b1d0039773dd
pedrodeoliveira/raspberrypi
/leds_buttons/reaction_game.py
563
3.5625
4
from gpiozero import Button, LED from time import sleep from random import uniform from os import _exit led = LED(4) right_button = Button(14) left_button = Button(15) left_name = input('Left player name is: ') right_name = input('Right player name is: ') led.on() sleep(uniform(5, 10)) led.off() def pressed(button)...
75d0d8250eabe212a2756b555505e49669ec49a2
ChristosVlachos2000/ErgasiesPython
/maxsequence.py
791
3.5
4
from sys import maxsize # Function to find the maximum contiguous subarray # and print its starting and telos index def maxSequence(a,size): max_mexri_stigmhs = -maxsize - 1 max_teliko = 0 arxi = 0 telos = 0 s = 0 for i in range(0,size): max_teliko += a[i] ...
fba702b99cbf2056eb30c1547771153a966cb5a6
Dowfree/learning
/6_try.py
521
3.875
4
class Car: def infor(self): print("This is a car") car = Car() car.infor() isinstance(car, Car) isinstance(car, str) if 5 > 3: pass class A: def __init__(self, value1=0, value2=0): self._value1 = value1 self.__value2 = value2 def setValue(self, value1, valu...
62d0d299b8a4d069b60c39fa2f756e72d3f89fe9
cramer4/Python-Class
/Chapter_10/Homework_10-4.py
272
3.515625
4
def get_names(): with open("guest_list.txt", "a") as file_object: while True: name = input('What is your name? ("q" to quit): ') if name != "q": file_object.write(f"{name}\n") else: break get_names()
b0660d6dd630bb4d176784e020cf835899cb5f2b
cramer4/Python-Class
/Chapter_09/Homework_9-5.py
887
3.578125
4
class User: def __init__(self, first_name, last_name, age): self.f_name = first_name self.l_name = last_name self.age = age self.login_attempts = 0 def describe_user(self): print(f"\nUser info:\nFirst name: {self.f_name}\n" f"Last name: {self.l_nam...
e20be04e20b2bf15f303b4d1242f19a67d204290
cramer4/Python-Class
/Chapter_09/Homework_9-2.py
706
3.96875
4
class Restaurant: def __init__(self, name, cuisine): self.name = name self.cusine = cuisine self.open = True def describe_restaurant(self): print(f"{self.name} is a {self.cusine} restaurant.") def open_restaurant(self): if self.open == True: p...
d4a14dc2e7d3c0291e7cedc39e26d28b9a0b4c7b
cramer4/Python-Class
/Chapter_10/Homework_10-1.py
623
3.90625
4
########################################################### with open("learning_python.txt") as file: contents = file.read() print(contents.strip()) ########################################################### file = "learning_python.txt" with open("learning_python.txt") as file: for line in file: ...
cc768b15d6b6c1670ad7af181ee00a662f67c3b2
cramer4/Python-Class
/Chapter_09/Homework_9-8.py
906
3.734375
4
class User: def __init__(self, first_name, last_name, age): self.f_name = first_name self.l_name = last_name self.age = age def describe_user(self): print(f"\nUser info:\nFirst name: {self.f_name}\n" f"Last name: {self.l_name}\n" f"Age: {self...
404b6fb3b7e237e15fed1c24416226fc66fd9db5
cramer4/Python-Class
/Chapter_06/Homework_6-6.py
688
3.75
4
taken_poll = ["bill", "george", "john", "fred", "kieth"] favorite_numbers = {taken_poll[0]: 10, taken_poll[1]: 7, taken_poll[2]: 55, taken_poll[3]: 30, taken_poll[4]: 100} index = 0 for friend in taken_poll: print(f"{frien...
f43db38bbefb2552689ee6670952866672f9b074
cramer4/Python-Class
/Chapter_09/Homework_9-6.py
802
3.96875
4
class Restaurant: def __init__(self, name, cuisine): self.name = name self.cusine = cuisine self.open = True def describe_restaurant(self): print(f"{self.name} is a {self.cusine} restaurant.") def open_restaurant(self): if self.open == True: p...
bba3a41dc0fa8e14843c0618c33c54873f76c9fb
cramer4/Python-Class
/Chapter_08/Homework_8-3.py
157
3.5625
4
def make_shirt(size, color): print(f"Made shirt that is {color} and size {size.upper()}.") make_shirt('m', 'red') make_shirt(color='blue', size='l')
9b0bbfbf98829d0315af9a743ddf0a533aba7434
miles0197/edabit_challanges
/HackerRank_practices.py
2,580
3.765625
4
#Question1 #get the input of 2 numbers from the user for each a and b, #Perform a product of a X b import itertools a = [int(x) for x in input().split(',')] b = [int(x) for x in input().split(',')] print(' , '.join(str(t) for t in itertools.product(a,b))) #Question2 #get the input for 2 numbers, try integer divisio...
ccfbbf92235fd2a7d5e181ca94e002e10bbaaaeb
miles0197/edabit_challanges
/display_next_prime_number.py
364
4.09375
4
# If the number is not prime, print the next number that is prime def is_prime(num): for i in range(2,num): if num % i ==0: return False return True def next_prime(num): if not is_prime(num): n = num + 1 while not is_prime(n): n += 1 return n els...
a6949e9ec7aa2ff84e9b478aed8cd95033f5eabc
SanFranciscoSunrise/easyASCII
/easyASCII.py
8,068
4.34375
4
#!/usr/bin/python3 # # A simple python program to demonstrate writing numbers to the console # in BIG ASCII style. # import sys import os import collections import re #import getopt import argparse def setup_ascii_dictionary(dictionary_file): # Open our acii character reprentation database. # translate it into a ...
a3d3afa4be2a23ad703070380efa5c45a853bee3
lichenga2404/intro-to-computer-vision-with-python-opencv
/00 Archived Scripts/00_reading_and_showing_images.py
4,745
3.859375
4
############################################################################### # BASICS 0.0: Reading, Showing & Saving Images with OpenCV and Matplotlib # # by: Todd Farr # ############################################################################### ...
3353d43c6abc42eead880c624da5bc26c1a812f8
balckwoo/pycode2
/pybasic/编码解码.py
309
3.84375
4
# 第一个是字符串 strvar = 'admin' print(strvar) # 字节码 bytevar2 = b'admin' print(bytevar2) bytevar = b'hello' print(bytevar) # 解码(把bytes类型转换utf-8类型) decode print(bytevar.decode()) strvar = 'hello' # 编码 (把utf-8类型转化bytes类型)encode print(strvar.encode())
c4f7f9151ce3b2b86a1c4282f62f9377daddf22c
balckwoo/pycode2
/pybasic/异常处理.py
1,331
3.5
4
# var = 'gaf' # # 正常语法,代码没有错误 # try: # # 可能出错的代码 # var1 = int(var) # # 捕获我错误代码的异常并输出(如果代码的语法是没有问题的是不会走到except里面) # except BaseException as msg: # print(msg) # BaseException 是万能的错误异常类型 # try: # print(hello) # except BaseException as msg: # print('错误的异常是',msg) # else: # print('nihao') # else 语法...
b3f03122b27774e57f02e65eab863d713c55f11d
sqeezy/project_euler
/problem003.py
642
4.09375
4
import sys def prim_factors(n): result = [] if n<0: n = -n if n<2: return [n] while n%2 == 0: result.append(2) n/=2 for candidate in range(3,int(n**0.5+1),2): while(n%candidate==0): result.append(candidate) n/=candidate if n>2: ...
540a2bce95b7d3f74ea2c9314024eee32cdf6240
sqeezy/project_euler
/problem014.py
371
3.59375
4
def next(n): if n%2==0: return n/2 else: return 3*n+1 def sequence(n): seq = [n] while n!=1: n = next(n) seq.append(n) return seq maxLen = 0 maxNum = 0 for i in range(1,10**6): curLen = len(sequence(i)) if curLen>maxLen: maxLen=curLen maxNum ...
a46122503fed9b81fe6d6b28d6d701d77b45f11e
sqeezy/project_euler
/problem005.py
1,180
3.59375
4
def prim_factors(n): result = [] if n<0: n = -n if n<2: return [n] while n%2 == 0: result.append(2) n/=2 for candidate in range(3,int(n**0.5+1),2): while(n%candidate==0): result.append(candidate) n/=candidate if n>2: resu...
3f74b15f1f12c2ca70772ef22540eebf2598a12c
krinj/logkit
/logkit/utils/truncate.py
707
3.6875
4
# -*- coding: utf-8 -*- """ Truncates string or JSON data so that it fits a specific number of characters. """ __author__ = "Jakrin Juangbhanich" __email__ = "juangbhanich.k@gmail.com" def truncate(message: str, max_length: int=128, split_ratio: float=0.8) -> str: """ Truncates the message if it is longer than ...
e8463008f9b373d322264bbaadb0afddaba1978a
Twice22/VQA
/utils.py
10,254
3.5
4
import operator import numpy as np import collections from collections import Counter import csv def fillup(my_set, my_list, K): """ Args: my_set (set of strings): set of unique most used words to fill up my_list (list of strings): list of words in descending order of frequency of apparation K (int): numbe...
bd3ed4a8b2ecd34850ed439dc7a52892cf782ba7
pintotomas/simulacion
/TP1/ejercicios/TPEj6.py
601
3.96875
4
#/usr/bin/env/ python # -*- coding: utf-8 -*- import matplotlib.pyplot as plt import random #Generador de números aleatorios que provee PYTHON def aleatorio(): return random.uniform(-1,1) listaDeValores1=[] listaDeValores2=[] #Genero 1000 valores(por ejemplo) for i in range(0,10000): x = aleatorio() y = aleatori...
b3aea64f494ef54d7b165eca3aa50dd463ce8e88
Takayama2258/AI-Pacman-Project_Search
/multiagent/multiAgents.py
11,651
4.125
4
from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. Yo...
87be5bedc854bdd1d17fa548d74e6e19fcecc970
LauraRio12/coding_exercises
/Subject 5/ex13_and.py
260
4.0625
4
number_1= input ("Enter a first number") number_2= input ("Enter a second number") if float(number_1)> 10 and float(number_2)>10: print("Both numbers are greater than 10.") else: print("At least one of the numbers you entered is not greater than 10")
bc26f90037a7d05108a8fa5421803d9b40f886aa
LauraRio12/coding_exercises
/Subject 5/ex10_elif.py
399
4.03125
4
first_number= input("Enter a first number") second_number= input("Enter a second number") result= float(second_number)-float(first_number) if result>10: print("The result is greater than 10.") elif result>0: print("The result is greater than 0 but not than 10.") elif result==0: print("The result is zero.") ...
dc4cfcc11c9b26f1e27874d1b9ac84291664b33c
susanbruce707/hexatrigesimal-to-decimal-calculator
/dec_to_base36_2.py
696
4.34375
4
# -*- coding: utf-8 -*- """ Created on Fri Dec 21 23:38:34 2018 Decimal to hexatrigesimal calculator. convert decimal number to base 36 encoding; use of letters with digits. @author: susan """ def dec_to_base36(dec): """ converts decimal dec to base36 number. returns ------- sign+resu...
49272cf6c1b0a8d1c5f14e87174fd6b02ba7f184
sagarch1234/snowflake
/system_users/utilities.py
2,291
3.78125
4
''' Python imports. ''' import random import string import re from rest_framework import status def capitalize_name(input_name): """ Method to capitalize first character of name. If '.' is present in string then first character of every list element after splitting input string by '.' is capitaliz...
d1ef77588354c2667f2e31b089a9b04dd71bae55
somnath1077/statistical_rethinking
/code/ch02/s03_normal_approx.py
1,987
3.5625
4
# We first generate the posterior as in s02_grid_compute.py and then # approximate a normal distribution to the data import matplotlib.pyplot as plt import numpy as np from scipy.stats import binom, norm, beta NUM_PTS = 20 p_grid = np.linspace(start=0, stop=1, num=NUM_PTS) # Uniform prior is a special case of the Be...
bd491b4e19652cf54254c0f170c7e4e954b5927b
vedantgoyal/unary_modular_simulator
/basic_blocks.py
2,503
3.59375
4
from connector import * class LC: # Logic Circuits have names and an evaluation function defined in child # classes. They will also contain a set of inputs and outputs. def __init__(self, name): self.name = name def evaluate(self): return class Not(LC): # Inverter. Input A. O...
29adf683e283b094c85b51926e760405a9d9bc46
nkarg/Funciones
/funcioni.py
529
3.75
4
# -*- coding: utf-8 -*- def tipoNum(n): if n <= 0: print "Error ", n, " no es un numero natural" else: cant = 0 resp = "" print "El numero ", n, " tiene como divisores a: " for i in range(1, n+1): if n % i == 0: resp = resp + str(i) + "-" cant = cant + i print resp if cant == n: print " L...
197b5b82c6797daaa77fef699dae630124a05b9d
abdullahmamunv2/Futoshiki
/Node.py
2,740
3.53125
4
#import queue as Q class node(object): def __init__(self,domain,parent,row,col,value=0): self.domain=domain self.value=value self.row=row self.col=col self.unassigned=True self.parent=parent def deletFromDomain(self,item): self.domain.remove(item) def addItem(self,item): self.domain.append(item) de...
a8f8f449bc8d300428207c1507e87c636856d824
007hakan/Hackerrank-Problem-Solving-Solutions
/ElectronicsShop.py
445
3.609375
4
def getMoneySpent(keyboards, drives, b): keyboards.sort() drives.sort() result=[] for i in range(len(keyboards)): for j in range(len(drives)): if keyboards[i]+drives[j]<=b: result.append(keyboards[i]+drives[j]) elif keyboards[i]+drives[j]>b: ...
4c66b2b74aa4f16497118e44d44bfbf980000007
liux1711/myFirstPythonTest
/pythonProject/test1.py
446
3.953125
4
if True : print("执行!") if False : print("不执行!") print("不执行") print("不执行") age=30 if age> 28 : print("老大不小了") else: print("还小,还能浪") age= input("请输入年龄\n") if int(age)<18 : print(f"你年龄在{age},属于未成年不能上网") elif int(age)>30 and int(age)<60: print(f"输入年龄{age}") elif int(age)>60: print("可...
802a4136628ba08dab237ea8dbedb9b4f2d192f7
CKnight7663/college
/hw3.py
12,380
4.375
4
#!/usr/bin/env python # coding: utf-8 # Assignment 3 # ============== # # This programme will be taking some function f(x), and through various methods, calculate the Integral between a, b. We will start off with the traditional method, the same one to which integration is often introduced as a concept with the recta...
7051c253efff8d0669b0a126a1bbf2b06ba7de90
benaneesh/cluster
/value/sample_generator.py
3,619
3.5
4
""" ================================================= Demo of affinity propagation clustering algorithm ================================================= Reference: Brendan J. Frey and Delbert Dueck, "Clustering by Passing Messages Between Data Points", Science Feb. 2007 """ print __doc__ import numpy as np from skl...
eda920e11595b7bc7a2a7fb686f542cdb7802443
efbatista9/Busca_Sequencial
/busca_seq.py
982
3.640625
4
class Musica: def __init__(self, titulo, interprete, compositor, ano): self.titulo = titulo self.interprete = interprete self.compositor = compositor self.ano = ano class Buscador: def busca_por_titulo(self, playlist, titulo): for i in range(len(playlist)): ...
3b3985673bc8b03b3dbfe8ce85499f468439cea8
nss-day-cohort-13/bangazon-group-project-ebazaon
/order_test.py
750
3.578125
4
import unittest from order import * class TestOrder(unittest.TestCase): @classmethod def setUp(self): ''' Set up class in order to test core functionality associated with orders''' self.new_order = Order( 'Test Cust_Uid', 'Test Pay_Opt_Uid', ...
86f8df082e714a05f09512cc87050132a2c6f59d
Tenbatsu24/Project-Euler
/divisors.py
276
3.5
4
import math def f(n): divisors = set({1, n}) for i in range(2, math.ceil(math.sqrt(n)) + 1): if (n % i) == 0: divisors.add(i) divisors.add(n // i) return divisors if __name__ == '__main__': print(f(4001)) print(f(2689))
fb7e856928aee57359f46fd022985f9413be645e
XuHangkun/BaseAlgorithm
/BaseAlgorithm/graph/edgeweighteddigraph.py
9,953
3.59375
4
# -*- coding: utf-8 -*- """ edge weighted directed graph ~~~~~~~~~~~~~~ make a edge weighted directed graph class :copyright: (c) 2020 by Xu Hangkun. :license: LICENSE, see LICENSE for more details. :ref: [美]塞奇威克(Sedgewick, R.),[美]韦恩(Wayne,K.).算法[M].北京:人民邮电出版社,2012. """ import queue from BaseA...
0a1db902e3c0ed1b6742d9324397041b8ba4bbc6
XuHangkun/BaseAlgorithm
/BaseAlgorithm/data_structure/list.py
3,395
4.40625
4
# -*- coding: utf-8 -*- """ List ~~~~~~~~~~~~~~ make a list class. (Alought python has it's built-in list, we will achieve this data structure by ourself. We will only use some basic functions of python so we can display the details of list.) :copyright: (c) 2020 by Xu Hangkun. :lice...
d2d01b2f837b19d1d93f0f9506a82ad79b9352b2
lvybupt/PyLearn
/pytest/topsort/navive_topsort.py
355
3.765625
4
''' python 算法书 朴素的拓扑排序 page 90 ''' def navie_topsort(G, S=None ): if S == None: S = set(G) if len(S) == 1 : return list(S) v = S.pop() seq = navie_topsort(G,S) min_i = 0 for i,u in enumerate(seq): if v in G[u]: min_i =i+1 seq.insert(min_i,v) return seq if __name__ == '__main__...
c10eb6c7bcf2634bbefe79a744ffae1c8b63daf0
lvybupt/PyLearn
/Intro_To_Algorithms/find_maximum_subarray.py
1,185
3.765625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ##寻找最大子数组 def find_max_crossing_subarray(a,low,mid,high): leftsum = - float("inf") sum = 0 for i in range(mid,low-1,-1): sum = sum + a[i] if sum > leftsum : leftsum = sum maxleft = i rightsum = - float("inf") sum = 0 for j in range(mid+1,high+1,1): sum...
66ac2e219438d2be17b530c09092178d684ce748
bmartin5263/AlgorithmsPrep
/multiply.py
407
3.734375
4
def multiply(num1, num2): product = 0 num1_size = len(num1) num2_size = len(num2) for i in range(num1_size-1,-1,-1): zeros1 = (num1_size - 1) - i value1 = int(num1[i]) * (10**zeros1) for j in range(num2_size-1,-1,-1): zeros2 = (num2_size - 1) - j value2 = ...
b9778f41add3d3d14e4a9e4670299c0c9b445733
ArgeNH/basic-Python
/practice/アルゲ.py
3,475
3.703125
4
import os import math """ n = 5 while n > 0: print(f'el valor de n: {n}') n = n-1 print('\n') m = 0 while m < 4: print(f'El valor de m: {m}') m = m + 1 """ """ age = 0 while age < 100: if (age < 18): print(f'{age} menor de edad') elif (age < 70): print(f'{age} adulto') ...
e9873ee3cd6e780777e63e3772369fbe87a11074
hodycan/othello
/Othello GUI.py
2,650
3.5625
4
from tkinter import * from tkinter import messagebox from settings_menu import OthelloSettingsGUI from othello_gui_board import * import othello_game_logic WINDOW_WIDTH = 500 WINDOW_HEIGHT = 500 class OthelloGUI: """ Graphical user interface for Othello game. public attributes: playagain: bool ...
0352ddc6ce556f182a21e28aa3c20d31cb5e3f82
dys27/Data-Structures
/LinkedList/delete middle node of a linked list.py
2,579
3.921875
4
class Node(object): def __init__(self,data): self.data=data self.next_node=None def remove(self,data,previous_node): if self.data==data: previous_node.next_node=self.next_node del self.data del self.next_node else: if self...
84bc34ecd5eb5534227a9c3690ae99bb965950af
julianbjornsson/tkinter
/app.py
9,004
3.53125
4
import tkinter as tk from tkinter import * from tkinter import ttk from tkcalendar import Calendar, DateEntry from tkinter.scrolledtext import * from tkinter import messagebox # DB: import sqlite3 import csv conn = sqlite3.connect("data.db") c = conn.cursor() def crear_tabla(): c.execute('CREATE TABLE IF NOT EX...
e198e6442c237fdbbfa537a9af4a26c5708f0227
sergeykoryagin/tproger
/tasks/task21.py
155
3.640625
4
def unique(lst): return len(lst) == len(set(lst)) lst1 = [1, 2, 3, 4, 5, 6, 7] lst2 = [1, 2, 3, 4, 3, 2, 1] print(unique(lst1)) print(unique(lst2))
ec2e60e41c203c6b25be9a18fbefdac1b93a8eb2
sergeykoryagin/tproger
/tasks/task18.py
132
3.796875
4
string = 'qwertyuiopasdfghjklzxcvbnm,asdfghjkqwyeqeqrqemneiwibf' letter = input('letter is :') print(string.count(letter), 'times')
58a9223e31c487b45859dd346238ee84bb2f61c8
ao-kamal/100-days-of-code
/binarytodecimalconverter.py
1,485
4.34375
4
"""Binary to Decimal and Back Converter - Develop a converter to convert a decimal number to binary or a binary number to its decimal equivalent. """ import sys print( 'This program converts a number from Binary to Decimal or from Decimal to Binary.') def binary_to_decimal(n): print(int(str(n), 2), '\n') d...
25ee4620b7edb315355de1448216f604fc15129b
zero-big/Python-Basic
/String/2.3.12.string_etc2.py
610
3.5
4
setup = 'a duck goes into a bar...' #양쪽에 . 시퀀스를 삭제한다. print(setup.strip('.')) # 첫번째 단어를 대문자로 print(setup.capitalize()) # 모든 단어의 첫째 문자를 대문자로 print(setup.title()) # 글자를 모두 대문자 upper 함수 # 글자를 모두 소문자 lower 함수 # 대문자 -> 소문자로, 소문자 -> 대문자로 print(setup.swapcase()) # 문자를 지정한 공간에서 중앙에 배치 print(setup.center(30)) # 왼쪽 : ljus...
47702521bf85a8c3408a073fa8ac98112ac5e595
zero-big/Python-Basic
/Data/3. format.py
1,998
3.765625
4
# 데이터 값을 문자열에 끼워넣기 : format # [첫번째] 파이썬 2에서 쓰던 % n = 42; f =7.03; s = 'string cheese' print('%10.4d %10.4f %10.4s' % (n, f, s)) # 출력 : 0042 7.0300 stri # 10.4d : 10자 필드 오른쪽 정렬 및 최대 문자길이 4 # 10.4f : 10자 필드 오른쪽 정렬 및 소수점 이후 숫자길이 4 # 10.4s : 10자 필드 오른쪽 정렬 및 최대 문자길이 4 # 인자로 필드 길이 지정도 가능하다. print('%*.*d %...
9b750390731edd5a1a683067240907563877df45
zero-big/Python-Basic
/Pyscience/3. numpy.py
2,391
3.890625
4
import numpy as np # 1. 배열 만들기 : array b = np.array([2, 4, 6, 8]) print(b) # [2 4 6 8] # ndim : 랭크를 반환 print(b.ndim) # 1 # size : 배열에 있는 값의 총 개수 반환 print(b.size) # 4 # shape : 각 랭크에 있는 값의 개수 반환 print(b.shape) # (4,) a = np.arange(10) print(a) # [0 1 2 3 4 5 6 7 8 9] print(a.ndim) # 1 print(a.shape) ...
88c61ce7dca614082096064bb028161dd28c0207
zero-big/Python-Basic
/Tool/3. code_debugging.py
1,334
3.9375
4
''' 파이썬에서 디버깅하는 가장 간단한 방법은 문자열을 출력하는 것이다. - vars() : 함수의 인자값과 지역 변수값을 추출 ''' def func(*args, **kwargs): print(vars()) func(1, 2, 3) # {'args': (1, 2, 3), 'kwargs': {}} ''' 데커레이터(decorator)를 사용하면 함수 내의 코드를 수정하지 않고, 이전 혹은 이후에 코드를 호출할 수 있다. ''' def dump(func): "인자값과 결과값을 출력한다." def wrapped(*args, **kwargs)...
4b7c355bd3b395abe1537db19ceb3df7fa1ff9ec
Magdalon/Snippets
/terningkast.py
254
3.625
4
from random import randint def terningkast(): kast = int(input("Hvor mange terningkast?")) seksere = 0 for i in range(kast): if randint(1,6) == 6: seksere +=1 print("Antall seksere:") print(seksere) terningkast()
c8bc3f032fc80622faa026514638f6764988906f
moojan/Python-BEAGLE-HHM
/getShuffle.py
282
3.5625
4
import numpy as np """GETSHUFFLE provides a permutation and inverse permutation of the numbers 1:N. perm: for shuffling invPerm: for unshuffling""" def getShuffle(n): perm = np.random.permutation(n) invperm = perm[::-1] return perm #, invperm
c296dab78893f00978039d1a8edee17c8d6d6b3d
lillyfae/cse210-tc05
/puzzle.py
1,812
4.125
4
import random class Puzzle: '''The purpose of this class is to randomly select a word from the word list. Sterotyope: Game display Attributes: word_list (list): a list of words for the puzzle to choose from chosen_word (string): a random word from the word list create_...
8cd9750c60e15e79b53101fe543c5a4b01f42dd2
brandon-rhodes/python-sgp4
/sgp4/conveniences.py
3,527
3.65625
4
"""Various conveniences. Higher-level libraries like Skyfield that use this one usually have their own date and time handling. But for folks using this library by itself, native Python datetime handling could be convenient. """ import datetime as dt import sgp4 from .functions import days2mdhms, jday class _UTC(dt....
462a87b89e16e39b0bf1ad560eeda5c8cd53bd6e
fffFancy/myPython1
/chapter3/First.py
306
3.71875
4
import random def getAnswer(answerNum): if answerNum == 1: return 'It is certain' elif answerNum == 2: return 'It is decidedly so' elif answerNum == 3: return 'Yes' else: return 'Ask again later' r = random.randint(1,9) fortune = getAnswer(r) print(fortune)
0e948b831e8ba1f5ccb7aecb95ebd0ae4fb6cdda
fffFancy/myPython1
/chapter4/PracticeCode.py
1,406
3.828125
4
# 方法一,不完善,没有考虑列表嵌套 # def changeListToStr(alist): # para = str(alist[0]) # for i in range(1, len(alist)-1): # para = para + ', ' + str(alist[i]) # # para = para + ' and ' + str(alist[-1]) # # print(para) # # changeListToStr(['apples','bananas','tofu','cats']) # changeListToStr([1,2,3,4,5]) # chan...
0eabd87271acc72d1a716f09afffee2c17ae5ed7
adriansctech/Python--Basic-Exercises
/Ejercicio-12/UT5_Actividad12_AdriSC.py
2,747
3.75
4
def main(): return 0 if __name__ == '__main__': main() palabras = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","v","w","x","y","z"] print "*************************************************************" print "* UT5_ACTIVIDAD12 ...
187da656876fc244b6a7e8a8609b0b701da5ac34
prasertcbs/python_tutorial
/src/min_dhm.py
784
4.09375
4
def min_to_day_hour_minute(minutes): min_per_day = 24 * 60 # 1440 d = minutes // min_per_day h = (minutes - (d * min_per_day)) // 60 m = minutes - (d * min_per_day + h * 60) return (d, h, m) # tuple def min_to_day_hour_minute_dic(minutes): min_per_day = 24 * 60 # 1440 d = minutes // min_per...
ca851a63737efa0dbef14a3d542e64797b808cce
prasertcbs/python_tutorial
/src/while_loop.py
677
4.15625
4
def demo1(): i = 1 while i <= 10: print(i) i += 1 print("bye") def demo_for(): for i in range(1, 11): print(i) print("bye") def sum_input(): n = int(input("enter number: ")) total = 0 while n != 0: total += n n = int(input("enter...
297f36d9f45831806c3935f60ecc4764623ac62a
prasertcbs/python_tutorial
/src/demo_debug3.py
221
3.53125
4
import random def demo(): for i in range(100): d1 = random.randint(1, 6) d2 = random.randint(1, 6) d = d1 + d2 print("{:>4}: {} + {} = {:>2}".format(i + 1, d1, d2, d)) demo()
97d063a69a1b0d07b13145cbcaf48c7ae947770f
prasertcbs/python_tutorial
/src/random_demo2.py
624
3.75
4
import random # print(random.random()) # [print(random.randint(1, 6)) for i in range(10)] # [print(random.randrange(1, 7)) for i in range(10)] # [print(random.randrange(0, 20, 2)) for i in range(10)] # [print(random.choice(["rock", "paper", "scissors"])) for i in range(5)] # [print(random.choice("HT")) for i in...
93980f525adf6752437fb6de571bb1881ada359c
prasertcbs/python_tutorial
/src/remove_whitespace_demo.py
842
3.578125
4
def read_demo1(filename): with open(filename, mode="r") as f: s = f.readlines() print(s) s2 = [line.strip() for line in s] print(s2) def read_demo2(filename): with open(filename, mode="r") as f: s = [line.strip() for line in f] print(s) def read_demo3(filename): ...
fae074b5290fb36bc9e56b73bd74a99a615fd124
prasertcbs/python_tutorial
/src/namedtuple_demo.py
993
3.84375
4
from collections import namedtuple def demo1(): x = (4, 7, 8) print("x = ", x) Medal = namedtuple("Medal", ["gold", "silver", "bronze"]) th = Medal(4, 7, 8) print("th = ", th) print(th.gold) print(sum(th[:2])) def demo2(): Medal = namedtuple("Medal", ["country", "gold", "...
fc145d14d64e69b1ad72dca096a692f5354e00c0
prasertcbs/python_tutorial
/src/age_yy_mm_d.py
398
3.578125
4
from datetime import date # pip install python-dateutil from dateutil.relativedelta import relativedelta def how_old_ymd(dob): age = relativedelta(date.today(), dob) print(age) return age.years, age.months, age.days print(date.today()) # print(how_old_ymd(date(1997, 7, 10))) y, m, d = how_o...
e322ea4e9bc34545804c3683771a7c12e116e2c7
prasertcbs/python_tutorial
/src/string_method3.py
918
3.515625
4
import random def join_demo(): stations = ("HUA", "SAM", "SIL", "LUM", "KHO", "SIR", "SUK", "PET", "RAM", "CUL", "HUI", "SUT", "RAT", "LAT", "PHA", "CHA", "KAM", "BAN") print(stations) print(" -> ".join(stations)) print(" -> ".join(stations[1:4])) print(" ...
1f35eb0f2ed224fdd8bf552ad07d8537cacdf133
prasertcbs/python_tutorial
/src/vin.py
2,021
3.765625
4
# https://en.wikibooks.org/wiki/Vehicle_Identification_Numbers_(VIN_codes)/Check_digit def vin_checkdigit(vin): weight = ( 8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2 ) t = { "A": 1, "B": 2, "C": 3, "D": 4, "E": 5, "F": 6, "G": 7, "H": 8, "J": 1, "K": 2, "L": 3, "M": ...
1e8090298859aaa7df4097c052e771252f1ae8a9
prasertcbs/python_tutorial
/src/zip_demo.py
1,077
3.546875
4
# zip def demo1(): weight = [70, 60, 48] height = [170, 175, 161] bmi = [] for i in range(len(weight)): bmi.append(weight[i] / (height[i] / 100) ** 2) return bmi def demo2(): weight = [70, 60, 48] height = [170, 175, 161] bmi = [] for w, h in zip(weight, hei...
1d542e2baaefdc942aa96047ebcf3ea021caa317
prasertcbs/python_tutorial
/src/mult_table.py
312
3.796875
4
def mtable(fromN=2, toN=6): for i in range(1, 13): for j in range(fromN, toN + 1): print("{:2} x {:2} = {:3} | ".format(j, i, j * i), end="") print() if __name__ == '__main__': # fromN = int(input("from:")) # toN = int(input("to:")) # mtable(fromN, toN) mtable()
95d5668794f9de9904748c696cb5f1d1b0736071
prasertcbs/python_tutorial
/src/string_format2.py
938
3.859375
4
def demo(): print("{}{}".format("th", "Thailand")) print("{:5}|{:15}|".format("th", "Thailand")) # align left print("{:<5}|{:<15}|".format("th", "Thailand")) # align left print("{:>5}|{:>15}|".format("th", "Thailand")) # align right print("{:*>5}|{:->15}|".format("th", "Thailand")) # al...
1ddf917b2b2d1d2953eb181f7c24c179aad662f7
syamaguchijp/Others
/Python/Class.py
1,588
3.578125
4
# coding: utf-8 class User: # クラス変数(Public) className = None # コンストラクタ def __init__(self, name, age): # インスタンス変数(Public) self.name = name self.age = age # インスタンス変数(Private) self.__address = None # デストラクタ def __del__(self): print("destructor") ...
e105386bcb9851004f3243f42f385ebc39bac8b7
KAOSAIN-AKBAR/Python-Walkthrough
/casting_Python.py
404
4.25
4
x = 7 # print the value in float print(float(x)) # print the value in string format print(str(x)) # print the value in boolean format print(bool(x)) # *** in BOOLEAN data type, anything apart from 0 is TRUE. Only 0 is considered as FALSE *** # print(bool(-2)) print(bool(0)) # type casting string to integer print(i...
f64eb90364c4acd68aac163e8f76c04c86479393
KAOSAIN-AKBAR/Python-Walkthrough
/calendar_Python.py
831
4.40625
4
import calendar import time # printing header of the week, starting from Monday print(calendar.weekheader(9) + "\n") # printing calendar for the a particular month of a year along with spacing between each day print(calendar.month(2020, 4) + "\n") # printing a particular month in 2-D array mode print(calendar.monthc...
f18161063141ca4c5ca0f71ab54e491f93c17acf
shade9795/Cursos
/python/ejercicio4.py
153
3.578125
4
precio=int(input("Ingrese el precio: ")) cantidad=int(input("ingrese cantidad")) importe=precio*cantidad print("el importe total es de:") print(importe)
ddc4112ca99f04ff02838546bd3543b03e0cf3a1
shade9795/Cursos
/python/problemas/Estructura de programación secuencial/problema2.py
245
3.984375
4
num1=int(input("num 1: ")) num2=int(input("num 2: ")) num3=int(input("num 3: ")) num4=int(input("num 4: ")) suma=num1+num2 producto=num3*num4 print("el resultado de la suma es:") print(suma) print("el resultado del producto es") print(producto)
5af9931029bef4345ffc1528219484cd363fbcfa
shade9795/Cursos
/python/problemas/Condiciones compuestas con operadores lógicos/problema5.py
257
4.125
4
x=int(input("Cordenada X: ")) y=int(input("Cordenada Y: ")) if x==0 or y==0: print("Las coordenadas deben ser diferentes a 0") else: if x>0 and y>0: print("1º Cuadrante") else: if x<0 and y>0: print("2º Cuadrante")
bdbc33109f40ea9f6d0845fcb039467bbcc09d92
shade9795/Cursos
/python/ejercicio20.py
183
3.828125
4
dia=int(input("Ingrese el dia: ")) mes=int(input("Ingrese el mes: ")) año=int(input("Ingrese el año: ")) if mes==1 or mes==2 or mes==3: print("Corresponde al primer trimestre")
1bf441f93b17207eb3055dd79f647415181e7892
logstown/project-euler
/problem22.py
608
3.609375
4
def quicksort(listie): if len(listie) <= 1: return listie pivot = [listie[len(listie)/2]] listie.remove(pivot[0]) less = [] greater = [] for x in listie: if x <= pivot[0]: less.append(x) else: greater.append(x) return quicksort(less) + pivot + quicksort(greater) f = open('names.txt', 'r') bigstr...
372b542ddb42ce5ae8e0c0064e9780dbbb1baee4
DauletY/PyCode
/PythonExample/JungleCam.py
311
3.546875
4
def Primere(): sound = str(input()) t = "Tiger" s = "Snake" l = "Lion Lion" b = "Bird" i = 1 while i <= 4: i += 1 if sound == "Grr": sound = l elif sound == "Ssss": sound = s elif sound == "Rawr": sound = t elif sound == "Chirp": sound = b print(sound) Primere()
a8f4268bd6f4a6f121deeb4a1acdfd8751ecb37f
DauletY/PyCode
/PythonExample/testpy.py
112
3.90625
4
#commint here x = int(input()) y = int(input()) if x % y == 0: print('even ',x) else: print('odd',y)
f809c940240766b014b341c8c9ed5d7fc19252ce
Qing8/Chat_system-2018-
/reversegam.py
8,973
3.796875
4
import random import sys WIDTH = 8 HEIGHT = 8 def drawBoard(board): #print the board passed to this #funtion and return NONE print(" 12345678") print(" +------+") for y in range(HEIGHT): print("{0}|".format(y+1),end = "") for x in range(WIDTH): print(board[x][y],end=...
f3143b4d9a4c031ea2761f6024b64e0a8c3b8fb8
Shusmoy108/LeetCode
/Easy/strmatch.py
388
3.625
4
class Solution(object): def arrayStringsAreEqual(self, word1, word2): str1="" str2="" for i in range (0,len(word1)): str1=str1+word1[i] for i in range (0,len(word2)): str2=str2+word2[i] return str1==str2 """ :type word1: List[str] ...
2c7fb6ec98791f8bc08159ff2ed20af3a87187cc
KRaudla/Python_kursus_2015
/he_ja_she.py
338
3.90625
4
while True: try: isikukood = int(input("Sisesta isikukood")) except ValueError: print ("Isikukood on number!") continue else: break if str(isikukood)[0] in ("1","3","5"): print ("he") elif str(isikukood)[0] > "6": print ("See pole isikukood.") else: ...
09c66056d6b3187aa8fe2dbd33cfb7b34e6c7209
JonathWesley/travelingSalesman
/City.py
741
4.03125
4
class City: def __init__(self, name): self.name = name self.connectedTo = {} def distance(self, city): distance = self.connectedTo[city.name] return distance def __repr__(self): string = str(self.name) + ": (" for key, value in self.connectedTo.items...
f58222387a089bfbfb947ba2371715023e2f20f1
dennysreg/HackerRankSolutions
/funnyString.py
499
3.9375
4
# Enter your code here. Read input from STDIN. Print output to STDOUT def esPalindromo(s): n = len(s) middle = n/2 for i in range(middle): if s[i]!=s[n-i-1]: return False return True t = int(raw_input()) for _ in range(t): s = raw_input() n = len(s) ascii...
3a3fe86fea46900eb431cc1492f45e4291c8e651
lindsaysteinbach/cssi-prework-python-conditionals-lab-cssi-prework-2016
/morning.py
909
3.703125
4
#1. Waking Up def wake_up(day_of_week): if ((day_of_week.lower() == "saturday") or (day_of_week.lower() == "sunday")): return "Go back to bed" else: return "Stop hitting snooze" #2. The Commute def commute(weather, mins_until_work): if ((mins_until_work<=10) or (weather.lower()=="rainy")): ...
e5f0551b8b7a2d10da36ad6b00bd6c3ef8816930
abyingh/Algorithms-and-Data-Structures-Implementations
/Data Structures/Stack.py
771
3.953125
4
""" A stack is a linear data structure which follows a particular order in which the operations are performed. The order is last in first out(LIFO). 3 operations: push, pop, top(peak) """ class Stack: def __init__(self): self.items = [] self.head = None self.tail = None def getSize(s...
160c64e34c9ab49034feb19a21c23a05f11ccb93
TAdeJong/moire-lattice-generator
/latticegen/transformations.py
4,097
3.5625
4
"""Common code for geometrical transformations""" import numpy as np def rotation_matrix(angle): """Create a rotation matrix an array corresponding to the 2D transformation matrix of a rotation over `angle`. Parameters ---------- angle : float rotation angle in radians Returns ...
61c753b75f1bf6b1dc13b30d04f0612d62473add
florije1988/pythonlearn
/learn/learn026.py
1,307
3.953125
4
# -*- coding: utf-8 -*- __author__ = 'florije' if __name__ == '__main__': a = 1 b = 1 c = 300 d = 300 print(a == b, a is b) print(c == d, c is d) # 这种的在shell里面运行的时候就会发现是不对的。 ''' In [37]: a = 1 In [38]: b = 1 In [39]: print('a is b', bool(a is b)) ('a is b', True) ...
c24e0ec3bf20e113f19e61b97721757d08a6fede
florije1988/pythonlearn
/learn/learn003.py
852
3.53125
4
# -*- coding: utf-8 -*- __author__ = 'florije' # this is the program to test the func map and reduce # map( func, seq1[, seq2...] ) if __name__ == '__main__': print range(6) print [x % 3 for x in range(6)] print map(lambda x: x % 3, range(6)) a = [1, 2, 3] b = [4, 5, 6] zipped = zip(a, b) ...