blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
2a2bc666a41dd220c7cc361efa52eaef34c89938 | blogSoul/Python_summary | /Make_Algorithm/Algorithm/tree.py | 436 | 3.765625 | 4 | class Tree(object):
def __init__(self, name = 'root', childern = None):
self.data = None
self.chilern = []
if childern is not None:
for child in childern:
self.add_child(child)
def __repr__(self):
return self.name
def add_child(self, node):
... |
23b389daa4ac03e36b78deb616ca02df063863ff | ajiehust/rosalind | /Algorithms_Heights/ms.py | 776 | 3.671875 | 4 | #!/usr/bin/env python
'''
Merge Sort
Problem Title: Merge Sort
Rosalind Armory ID: ms
URL: http://rosalind.info/problems/ms/
'''
import sys
def fr(fn):
with open(fn) as f:
n = int(f.readline().strip())
lst = map(int, f.readline().strip().split(" "))
assert len(lst) == n
return lst
... |
2751eec7008a4bdc4ce08f51e0f6d164dc67ba7e | lonesloane/Python-Snippets | /data_persistence/databases/sqlite_sample.py | 1,633 | 3.71875 | 4 | import sqlite3
def create_table():
conn = sqlite3.connect('lite.db') # creates the db file if does not exist yet
cursor = conn.cursor()
query_create = "CREATE TABLE IF NOT EXISTS store (item TEXT, quantity INTEGER, price REAL)"
cursor.execute(query_create)
conn.commit()
conn.close()
def inser... |
7700e29089050e077cb8deb2447163ddc9041e62 | desve/netology | /tasks/9/9-4.py | 429 | 3.59375 | 4 | # Диагонали: параллейные главной
print("Введите размермассива n=")
n = int( input())
a = []
a = [[0] * n for i in range(n)]
for i in range(n):
for j in range(n):
if i == j:
a[i][j] = 0
elif j > i:
a[i][j] = j - i
elif j < i:
a[i][j] = i - j
for row i... |
88106c1baf8927bc1420c7a2a3b35553d4b71b45 | hyccc/myPython | /5 练习/Craps赌博游戏.py | 1,416 | 3.953125 | 4 | '''
Craps赌博游戏
规则:玩家掷两个骰子,每个骰子点数为1-6,如果第一次点数和为7或11,则玩家胜;
如果点数和为2、3或12,则玩家输庄家胜。
若和为其他点数,则记录第一次的点数和,玩家继续掷骰子,直至点数和等于第一次掷出的点数和则玩家胜;
若掷出的点数和为7则庄家胜。
author: Ethan
'''
import random
def dice():
x = random.randint(1, 6)
y = random.randint(1, 6)
return x + y
if __name__ == '__main__':
i ... |
4bbd3e0b97efb468a3eb6f0098ee6bbab2920a97 | daodewang/learn | /learn.py | 2,122 | 3.640625 | 4 | '''
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
print(pairs)
__import__('os').system('dir')
def f(a):
a.append(1)
print(a)
f(pairs)
print(pairs)
b=7
def f(a):
print(a+b)
f(2)
print(b)
# IO-input
name = 'Liming'
print('my name is %s.' % name)
print(f... |
2582227f9093e3d1a445c49070adf28f9e5cb24b | marcelodias/documents | /python/ifelifelse_grandfinale.py | 449 | 3.75 | 4 | # Tenha certeza que the_flying_circus() retorna True
def the_flying_circus():
if 5 * 2 == 15: # Comece seu codigo aqui!
print "Comparadores" # Nao esqueca de recuar
# o codigo dentro deste bloco!
elif "Verdade" or "Falso":
print "Identificacao" # ... |
b834aae53691f239c06462f1273a290d980b6879 | TakuroKato/AOJ | /ITP1_5_B.py | 532 | 3.5625 | 4 | # -*- coding:utf-8 -*-
def frame(H,W):
for i in range(W):
print('#',end='')
print('')
for j in range(1,H-1):
for i in range(W):
if i == 0 or i == W-1:
print('#',end='')
else:
print('.',end='')
print('')
for i in range(W):
... |
30b666c1593d645fdbd044328c029d11bfd3f697 | yunzhuz/code-offer | /second/6.py | 600 | 3.578125 | 4 | class listnode():
def __init__(self,data,next=None):
self.data = data
self.next = next
def solution(p):
l = []
l.append(p.data)
while p.next:
l.append(p.next.data)
p = p.next
l = l[::-1]
nhead = listnode(l[0])
np = nhead
for i in l[1:]:
node = lis... |
5c03445a52e35c6741684fb37fd4881bb3e5fa43 | q-riku/Python3-basic2 | /01 函数式编程-匿名函数和高阶函数/test3.py | 308 | 3.828125 | 4 | #函数名 = lambda[参数列表]:表达式
def my_func(f, arg):
return f(arg) #f(5) x=5
print(my_func(lambda x: 2*x*x, 5))
#这个带有参数的;
g = lambda y:2*y
print(g(3))
#这个不带参数的写法;
gg = lambda :123
print(gg())
#可以有N个参数;
ggg = lambda x,y,z:x+y+z
print(ggg(1,2,3)) |
68e4274640efa7ab69d5959f2bf726e6a6fbb120 | MatheusBorgesKamla/MachineLearningStudy | /Regression/SimpleLinearRegression/code.py | 2,065 | 4 | 4 | import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv('Salary_Data.csv')
X = dataset.iloc[:,:-1].values
y = dataset.iloc[:,1].values
#Splitting the dataset into the Training set and Test set
#Nao precisei fazer os passos anteriores de preprocessamento pois
#... |
df78ebfcbce68fb1afb17541a9340ceaeab598f4 | xmliszt/capstone-ocr | /src/writer.py | 437 | 3.75 | 4 | import os
class Writer:
def __init__(self):
self.txt = ""
def append(self, txt):
self.txt += txt
def write(self, filename):
if not os.path.exists("output"):
os.mkdir("output")
output_path = os.path.join("output", filename)
with open(output_path, "w", ... |
b8235df3821a2cfe8b3791e31e9d6bd4fb9d39d3 | gottun510/tdd_vending-machine-4 | /tests/test_vending.py | 1,644 | 3.5 | 4 | # from unittest import TestCase
from vending_machine.hoge.coin import Coin, VendingMachine
class TestVendingMachine():
def test_check_coin(self):
machine = VendingMachine()
assert machine.check_coin(Coin(50)) == True
assert machine.check_coin(Coin(40)) == False
def test_treat_coin(se... |
86b41459e33672e4c6710f11d23468658f9c8aeb | kooshanfilm/Python | /Python_Code_Challenge/P3.py | 744 | 4.03125 | 4 | import random
theasurus = {
"weather" : ['balmy', 'summery','hot','cold'],
"cold" : ['a', 'b','c','d'],
'happy': ['e','f','g','h'],
'sad':['s','a','d','d2']
}
print ("Welcome to my app")
print ("\n Choose a word from our list")
print ("\n Here are words for you")
for key in theasurus.keys():
print... |
8a7f593a47db0ae92d6553eb83d07ce4c0a79afa | menard-noe/LeetCode | /Check If It Is a Straight Line.py | 498 | 3.703125 | 4 | from typing import List
class Solution:
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
(x1, y1), (x2, y2) = coordinates[:2]
for i in range(2, len(coordinates)):
(x, y) = coordinates[i]
if ((y2 - y1) * (x1 - x) != (y1 - y) * (x2 - x1)):
re... |
477c023f9a378c32985a18850ad49e599a8e9c88 | Wanpeng66/Python_learning | /面向对象编程/枚举类.py | 446 | 3.890625 | 4 | # 跟java枚举差不多的功能
from enum import Enum, unique
# @unique装饰器会检查枚举类中有没有重复的值
@unique
class Weekday(Enum):
Sun = 7
Mon = 1
Tue = 2
Wed = 3
Thu = 4
Fri = 5
Sat = 6
if __name__ == "__main__":
# 既可以用成员名称引用枚举常量,又可以直接根据value的值获得枚举常量。
print(Weekday.Sun)
print(Weekday(2))
print(Weekda... |
02c89757a976f76787b1f7de06d0115451413316 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/leap/bfb631919e8744bb9459e94a9042996c.py | 155 | 3.765625 | 4 | def is_leap_year (year):
if not (year % 4 == 0): return False
elif (year % 100 == 0) and not (year % 400 == 0): return False
else: return True
|
3bd877d708ec1a267ca60197d5ac53fae9da7d59 | MudretsovaSV/Python | /compare.py | 353 | 4 | 4 | num1=float(raw_input(" : "))
num2=float(raw_input(" : "))
if num1<num2:
print num1, " ", num2
if num1>num2:
print num1, " ", num2
if num1==num2:
print num1, "", num2
if num1!=num2:
print num1, " ", num2
|
144744cd9c61c7e12c2fdd50e28a4baa96099a08 | tai34tw/III_Python | /III_Homework/1_Selection/5_refund.py | 1,309 | 4 | 4 | '''5. 選擇性敘述的練習-refund
輸入在某商店購物應付金額與實付金額。
實付金額小於應付金額,則印出”金額不足”。
實付金額等於應付金額,則印出”不必找錢”。
實付金額大於應付金額,則輸出找回金額最少的鈔票數和錢幣數。
假設幣值只有1000, 500, 100元紙鈔和50, 10, 5, 1元硬幣。
說明:若買了132元的商品,付1000元,應找回一張500元,三張100元,一個50元硬幣,一個10元硬幣,一個5元硬幣和三個1元硬幣。
'''
payment = eval(input('應付金額:')); money = eval(input('實付金額:'))
if payment == money: print('不... |
dc79207c4023d82a329200227c3825bf2a42c8b5 | sumnous/Leetcode_python | /searchRotatedArray.py | 1,026 | 4 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 2013-12-11
@author: Ting Wang
'''
# Suppose a sorted array is rotated at some pivot unknown to you beforehand.
# (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
# You are given a target value to search. If found in the array return its index, otherwise ret... |
0c5d586e62b671e4ea1d0612a0e8decd6f8d0913 | InfoTech-Academy/Python_Week_4 | /Homework Ersin Öztürk/number_guessing_game.py | 1,198 | 3.796875 | 4 | import random
import time
def rand_find(a, b):
lst = [i for i in range(a, b + 1)]
chosen = random.sample(lst, 1)
return chosen[0]
def control_selection(c, p):
global t0
global t1
global count
global final
if count==0:
t0 = time.time()
if c - p < 0:
... |
119a1c0e9f51c3a54d261991c89c723d2633315e | KarashDariga/TSIS3 | /3.py | 307 | 3.828125 | 4 | def fun(n):
return lambda a: a * n
doubler = fun(2) # lambda a: a * 2
print(doubler(3))
print(doubler(6)) # in this doubler it;s lambda
triple = fun(3) # lambda a: a * 3
print(triple(3))
print(triple(6))
multiple_100 = func(100) # lambda a: a * 100
print(multiple_100(5))
print(multiple_100(6)) |
64da55f9441652a7e9499754bdf0aea827defa0a | Baidaly/datacamp-samples | /18 - Hypothesis Testing in Python/chapter 1/1 - Calculating the sample mean.py | 736 | 3.890625 | 4 | '''
The late_shipments dataset contains supply chain data on the delivery of medical supplies. Each row represents one delivery of a part. The late columns denotes whether or not the part was delivered late. A value of "Yes" means that the part was delivered late, and a value of "No" means the part was delivered on tim... |
1066477f7e1f42c807c7f8bc4d0c711e871d3945 | IgnatIvanov/Hypercar-Service-Center_JetBrains_Academy | /Topics/Queue in Python/Oral exam/main.py | 412 | 3.65625 | 4 | from collections import deque
board = deque()
exit_door = deque()
n = int(input())
while n != 0:
n -= 1
record = str(input())
if 'READY' in record:
board.append(record.split()[1])
elif 'EXTRA' in record:
board.append(board.popleft())
elif 'PASSED' in record:
# print(board.p... |
f6d6d381b7c5ff78b3577c89a25318415c2bbbc3 | leoelm/interview_training | /5.1.py | 277 | 3.671875 | 4 | from random import random, choice
A = [random() for i in range(10)]
def quicksort(l):
if len(l) <= 1:
return l
pivot = choice(l)
left = [i for i in l if i <= pivot]
right = [i for i in l if i > pivot]
return quicksort(left) + quicksort(right) |
d315521ca81c4f3ff0570b9f3c4a2cc6a19764d0 | StanLong/Python | /02爬虫/urllib.request的使用.py | 1,524 | 3.5 | 4 | # 使用xpath解析站长之家下载前十页的图片
import urllib.request
from lxml import etree
def create_request(page):
if page == 1:
url = 'https://sc.chinaz.com/tupian/qinglvtupian.html'
else:
url = 'https://sc.chinaz.com/tupian/qinglvtupian_' + str(page) + '.html'
headers = {
'User-Agent': 'Mozilla/5.0... |
e0e6ceb3add0b292a8d3e54f50b222a5d05f8253 | erickmiller/AutomatousSourceCode | /AutonomousSourceCode/data/raw/squareroot/d4622eb3-3c06-40d3-a4d9-c5d9fd988b84__newton_rhapson_sqrt.py | 839 | 4.34375 | 4 | ##print " this program computes square root of a number using"
##print "newton-rhapson method"
##
##number=float(input("Enter the number whose square root is desired "))
##
##guess_estimate = float(number/2.0)
##
##while (guess_estimate*guess_estimate != number):
##
## quotient = (number / guess_estimate)
## new_... |
e77861cc46c9b1407a84ff2c8414df2ba284911e | cgazeredo/cursopython | /mundo02/aula-12_exercicios-044-gerenciador-de-pagamentos.py | 801 | 3.703125 | 4 | preco = float(input('Qual o preço normal do produto? R$'))
condicao = str(input('A condição de pagamento será à vista ou parcelado? '))
if condicao == 'à vista':
condicao_vista = str(input('O pagamento será feito em dinheiro cheque ou cartão? '))
if condicao_vista == 'dinheiro' or condicao_vista == 'cheque':
... |
20b8936e94733a3489ac4d22ec725983cd9cbc52 | LenaSmb/geekbrains-python | /lesson08/ex05.py | 2,157 | 3.71875 | 4 | class Warehouse:
equipment = {}
quantity = {}
transfered = {}
def __init__(self):
pass
def status(self):
for key in self.equipment.keys():
print(key, self.quantity[key], end='; ')
print()
def receive(self, item):
if item.name not in self.eq... |
0c2322df5a728f12f4b855bccb96e8e8e33b2c44 | shishengjia/PythonDemos | /数据结构和算法/切片命名_P18.py | 209 | 3.796875 | 4 | """
代码中如果有很多硬编码的索引值,可读性会很差.
"""
record = '20 15.5'
COUNT = slice(0, 2)
PRICE = slice(3, 7)
total_cost = int(record[COUNT]) * float(record[PRICE])
print(total_cost)
|
d81855f5982e2b2ffb70c58c9da437620247fe80 | chaoboliu/Aircraft-Wars_pygame | /2018.1.8/8555.py | 607 | 3.515625 | 4 | '''
s = "欢迎进入个人信息管理系统"
print(s.center(65,'*'))
list = []
while True:
gongneng = int(input("请您选择功能:① 新增 ② 查询 ③ 修改 ④ 删除 请您进行选择:"))
if gongneng == 1:
name = input("请输入姓名")
years =int(input("请输入年龄"))
sex = input("请输入性别")
work = input("请输入工作")
list.append(name)
list.append(years)
list.append(sex)
list.app... |
fdc8f815d418a7b60d22c19a9e15d65825b6de3e | GitHubUPB/PreInformeConAcum | /Problema 3.py | 173 | 3.90625 | 4 | primer=0
for x in range (0,5):
num=int(input("ingrese un numero"))
if x==0:
mayor=num
else:
if num>mayor:
mayor=num
print(mayor)
|
759bf4df23c2701d534f6890db1e44751c7c7f84 | droogadulce/HackerRank | /math/handshake.py | 1,154 | 4.09375 | 4 | #!/bin/python3
"""
Handshake
Problem: At the annual meeting of Board of Directors of Acme Inc, every one starts shaking hands
with everyone else in the room. Given the fact that any two persons shake hand exactly once, Can
you tell the total count of handshakes?
Input Format
The first line contains the number of te... |
23e311f68a82acb0187c860a412e0c217b88dd9e | wulfebw/algorithms | /scripts/elementary_data_structures/revisit/m_stack.py | 443 | 3.96875 | 4 |
class Stack(object):
def __init__(self):
self.s = []
def pop(self):
return self.s.pop()
def push(self, v):
self.s.append(v)
def top(self):
if len(self.s) == 0:
return None
else:
return self.s[-1]
if __name__ == '__main__':
s = St... |
f5e83e6abc365f78607c993c56ef1946e4cbb842 | coldhair/Conda | /Try047.py | 202 | 4.125 | 4 | """
输出乘法口诀表(九九表)
Version: 0.1
Author: 吕艳朋
"""
for i in range(1, 10):
for j in range(1, i + 1):
print('{1}×{0}={2: <2d}'.format(i, j, i * j), end=' ')
print()
|
9dcfc14fb244dd00df951d34ec431527a180572b | tombiasz/exercism-python | /robot-simulator/robot_simulator.py | 1,002 | 3.6875 | 4 | NORTH = 0
EAST = 1
SOUTH = 2
WEST = 3
class Robot(object):
INSTRUCTION_TO_FUNCTION_MAP = {
'A': 'advance',
'L': 'turn_left',
'R': 'turn_right',
}
def __init__(self, bearing=NORTH, pos_x=0, pos_y=0):
self.bearing = bearing
self.pos_x = pos_x
self.pos_y = po... |
66e312103f3e0c95c4930e17257cfba881735b28 | wpy-111/python | /month01/day08/exercise03.py | 195 | 3.859375 | 4 | """
定义函数,根据时分秒计算总秒数
"""
def calculation_all_second(hour=0,minutes=0,second=0):
return hour*3600+minutes*60+second
re=calculation_all_second(2,60)
print(re)
|
3776df6b8f60fee67218565d5e3b1eb2b1c64f86 | Chris-Isherwood/Python-Game-Pile | /Chris' Python Game-Pile.py | 26,293 | 3.578125 | 4 | from tkinter import *
from random import randint
import time
import tkinter.messagebox
#Formats and sets the overarching game window
Game_Window = Tk()
Game_Window.title("Chris' Python Game-Pile")
HEIGHT = 500
WIDTH = 800
x = (Game_Window.winfo_screenwidth() // 2) - (WIDTH // 2)
y = (Game_Window.winfo_scre... |
2afe3054fe636aa8620c035ba5210c21a60d8a31 | lemonshark12/Portfolio | /Division without division.py | 2,677 | 3.96875 | 4 | def divide():
"""Divides any positive number by another positive number without using the build-in floor division or modulus operator."""
n = float (input ("please enter a positive integer you wish to divide >> "))
m = float (input ("please enter a positive inter you wish to divide by >> "))
solution = []
if m... |
555d94df09534bcd431d0e3a9ef391e5362d81df | DanaMC18/advent_of_code | /2020/day_12/navigate.py | 3,130 | 3.890625 | 4 | """Navigate module."""
import os
DIRS = ['N', 'E', 'S', 'W']
OPPS = {'N': 'S', 'S': 'N', 'W': 'E', 'E': 'W'}
INSTRUCTIONS_TXT = 'instructions.txt'
def manhattan_dist():
"""Get manhattan distance."""
instructions = _load_instructions()
curr_dir = 'E'
east_west = 0
north_south = 0
for ins in... |
178ca465befb03d29b7a8404efab3b9b0fe1214e | bovarysme/advent | /2017/day04.py | 1,254 | 3.78125 | 4 | def duplicates(passphrase):
words = set()
for word in passphrase.split():
if word in words:
return False
words.add(word)
return True
def anagrams(passphrase):
words = set()
for word in passphrase.split():
word = ''.join(sorted(word))
if word in words:
... |
d8ce865ec0ffd3f50f33679d5e2c27f0d0749607 | akotwicka/Learning_Python_Udemy | /dziedziczenie.py | 1,825 | 3.6875 | 4 | class Cake:
bakery_offer = []
def __init__(self, name, kind, taste, additives, filling):
self.name = name
self.kind = kind
self.taste = taste
self.additives = additives.copy()
self.filling = filling
self.bakery_offer.append(self)
def show_info(self):
... |
905ace7073124c7d9d330e333e8adfdf2ecad943 | nicolasfcpazos/Python-Basic-Exercises | /Aula15_Ex067.py | 509 | 4.125 | 4 | # Faça um programa que leia a tabuada de vários números, um de cada vez,
# para cada valor digitado pelo usuário. O programa será interrompido
# quando o número solicitado for negativo.
print('------- TABUADA -------')
cont = 0
while True:
num = int(input('Digite um número para ver sua tabuada: '))
print('-'... |
0077a2503c2db5b90d323bc4e79356352db31a67 | McNultyPT/Algorithms | /recipe_batches/recipe_batches.py | 1,489 | 3.90625 | 4 | #!/usr/bin/python
pizza = {
'dough': 1,
'cheese': 12,
'sauce': 5
}
ingredients = {
'dough': 1,
'cheese': 7,
'sauce': 5
}
import math
def recipe_batches(recipe, ingredients):
batches = []
recipe_values = [i for i in recipe.values()]
ingredient_values = [j for j in ingredients.values()]
fo... |
ad51e4d5ab11a292911904aa9af86f0f717e8062 | nasir-001/Core-Python-Exercise | /UpperToLower.py | 230 | 3.796875 | 4 | def main():
def getName():
user_input = input()
for a in user_input:
lower = user_input.lower()
if a == a.lower():
print(a.upper())
else:
print(a.lower())
getName()
if __name__ == "__main__":
main() |
0272aa772c17862826a80460b68039e252403cb5 | edgarduart23/poloMisiones | /estructuras.py | 1,588 | 4.125 | 4 |
nombre = "Harry"
print(nombre[0])
#LISTAS
nombres = ["Harry", "Ron", "hermione"]
print(nombres)
#agregar un elemento a la lista
nombres.append("Draco")
print(nombres)
#ordenar la lista
nombres.sort()
print(nombres)
#borar la lista
nombres.clear()
print(nombres)
#SET: no agrega elementos repetidos
conjunto = set()
#a... |
d0f2b62ae013886bac65f1492be1e17351cf192b | kranthikumar27/demo | /cspp1-practice/m5/p3/square_root_bisection.py | 645 | 4.15625 | 4 | '''# Write a python program to find the square root of the given number
# using approximation method
# testcase 1
# input: 25
# output: 4.999999999999998
# testcase 2
# input: 49
# output: 6.999999999999991
'''
def main():
''' this program is used to print the squareroot value of
the given number using bi-sec... |
21961c0cd137233b4a9c5f4ab3233bab1252ba05 | ShivaBansfore-JGEC/DataStructureAndAlgo-Python | /dynamic_programming/knapsackAtcoderbu.py | 722 | 3.515625 | 4 | import sys
sys.stdout = open('dynamic_programming/output.txt', 'w')
sys.stdin = open('dynamic_programming/input.txt', 'r')
def knapsackBottomUp(wt,price,c,n):
dp=[[0 for x in range(c+1)] for y in range(n+1)]
for i in range(n+1):
for w in range(c+1):
if i==0 or w==0:
dp[i][w]... |
8d2413570038115e7a052062ea074a4ade535fa8 | danslavov/Programming-Basics-Python-2017-MAY | /06_DrawingWithLoops/P08_Sunglasses.py | 364 | 3.984375 | 4 | n = int(input())
halfBorder = "*" * 2 * n
halfMiddle = "*" + "/" * (2 * n - 2) + "*"
border = halfBorder + " " * n + halfBorder
middle = halfMiddle + " " * n + halfMiddle
center = halfMiddle + "|" * n + halfMiddle
print(border)
for i in range(n - 2):
if i == (n - 1) // 2 - 1:
print(center)
e... |
1e48160edc852d90bd1e71eda192d01d5b5a8546 | PrakashPrabhu-M/pythonProgramsGuvi | /oddFactorsOfaNumber.py | 229 | 4.03125 | 4 | """ Given a number N, print the odd factors of the number.
Input Size : 1 <= N <= 1000
Sample Testcase :
INPUT
9
OUTPUT
1 3 9 """
n=int(input())
l=[]
for i in range(1,n+1):
if n%i==0 and i%2==1:
l.append(i)
print(*l)
|
b5c55868c0f801b4818e56c8a5964cfca904063c | SevenHanXu/python---learn | /list.py | 1,377 | 3.921875 | 4 | #!/usr/bin/env python
# coding=utf-8
list_a = [1, 2.2, "hello world", [1, 2, 3]]
list_b = ()
print "list_a = %s" % str(list_a)
print "list_b = %s" % str(list_b)
range_a = range(0, 100)
print "rang_a = %s" % str(range_a)
print type(range_a)
list_c = range(0, 5)
list_d = range(5, 10)
print "list_c = %s" % str(list_c)... |
825ffa977a5878827f757ae398e0823c0a18f4c3 | w7374520/Coursepy | /L07/prepareCouse/opp_1.py | 531 | 3.921875 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author:xp
#blog_url: http://blog.csdn.net/wuxingpu5/article/details/71209731
std1 = { 'name': 'Michael', 'score': 98 }
std2 = { 'name': 'Bob', 'score': 81 }
std3={'name':'xp','score':111}
def print_score(std):
print('%s %s'%(std['name'],std['score']))
class Student(ob... |
dceb26252c863c29044f8e98b41bf08b47526aad | winnertree/idk-htd | /1st/main.py | 16,147 | 3.71875 | 4 | #**은 ^
#//은 몫
#true false 10>3
# abs() 는 절댓값
# pow(4,2) 는 4^2
#max(a,b) , min(a,b)
# round(3.13) 반올림
# from math import *
# print(floor(4.99)) #내림
# print(ceil(3.14)) # 올림
# print(sqrt(16)) #제곱근
# from random import *
# print(random()) #0.0 ~ 1.0 사이의 임의의 값 생성
# print(random()*10) #0.0~10.0
# print(int(random()*10))
#... |
0a3f15694a600dace6b6c71f5101d2d758883ee2 | alexgarces98/Pythonprogramas | /extraEjercicios.py | 1,951 | 4.25 | 4 | #Escriba un subprograma en Python que determine si dos valores enteros dados son iguales o si su suma o diferencia es
# 5
def igualdad_a_cinco(a,b):
"""int,int --> bool
OBJ: Comprueba si dos enteros son iguales o suma o diferencia es 5"""
import math
return (a == b) or (abs(a-b) == 5) or (a+b == 5)
... |
868d227a9d76640ca8745069de3c909a44adfa18 | IBBD/IBBD.github.io | /machine-learning/yolov3-train-loss-show.py | 1,430 | 3.609375 | 4 | # -*- coding: utf-8 -*-
#
# yolov3训练误差可视化
# python3 machine-learning/yolov3-train-loss-show.py \
# --filename /tmp/yolov3-spp-loss.txt \
# --n 200
# Author: alex
# Created Time: 2019年08月22日 星期四 10时32分44秒
import re
import pandas as pd
from matplotlib import pyplot as plt
def read_data(filename):
# 1: 3983.4... |
05829e05765d45d0933c8c894ee60d693e9b47a6 | TauqeerAhmad5201/Python-OOPS | /args and kwargs1.py | 214 | 3.75 | 4 | def adder(*num): #a tuple is given otherwise converted but yes tuple
sum = 0
for n in num:
sum = sum + n
print("Sum: ",sum)
adder(5,7,4)
adder(5,7,4,6.7)
adder(5,7,4.5,76,34.454)
|
a477e6593d16e73218ce184e06c481bf6b7e2454 | Shreyas018/launchpad-assignments | /practise5.py | 151 | 3.9375 | 4 | num1=int(input("enter the number a:-"))
num2=int(input("enter the number b:-"))
temp=int()
temp=num1
num1=num2
num2=temp
print(num1)
print(num2) |
2975fcbfee0a9d980d1420275c5527dd36b3e6fa | complicatedlee/About_algorithm | /dataStru.py | 1,797 | 4.15625 | 4 | #--coding:utf-8
#linked list
class Node(object):
"""
node initialization
A node consists of data and next pointer
"""
def __init__(self, data):
self.data = data
self.next = None
class ListNode(object):
def __init__(self):
self.head = None
def length(self)... |
b0563726ef9de9e05d6c8c323e93de7b45281df3 | osmarsalesjr/SolucoesUriOnlineJudgeEmPython3 | /colecao_pokemon.py | 1,321 | 3.53125 | 4 |
def main():
n = int(input())
jgs = ["pedra", "papel", "tesoura", "lagarto", "spock"]
pls = ["rajesh", "sheldon"]
for i in range(n):
ps = [i for i in input().split()]
if ps[0] == jgs[0] and (ps[1] == jgs[2] or ps[1] == jgs[3]):
print(pls[0])
elif ps... |
19387eba9e667955c01c4fe19571af19b890c1d8 | clowe88/Code_practicePy | /simple_cipher.py | 277 | 4.15625 | 4 | phrase = input("Enter a word or phrase to be encrypted: ")
phrase_arr = []
finished_phrase = ""
for i in phrase:
phrase_arr.append(i)
for x in phrase_arr:
num = ord(x)
cipher = chr(num + 12)
finished_phrase += cipher
print (finished_phrase)
|
ade4be28e983a3183c4bbfdece18411068a7ee1b | qbarrier/Python | /D01/ex02/groceries.py | 252 | 3.765625 | 4 | f = open("groceries.txt", "a")
print("Qu'ajouter a la liste de course ?")
add = input()
f.write("%s\n" % add)
add = ""
while (add != "no") :
print("Anything else ?")
add = input()
if (add != "no") :
f.write("%s\n" % add)
f.close()
|
d74d2263ce67e723a1fb073761932d4e5d01faf7 | deepakmhr/tensorflow | /polynomial-regression/polynomial-regression.py | 1,089 | 3.8125 | 4 | # Multiple Linear Regression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
def show():
# Importing the datasets
datasets = pd.read_csv('Position_Salaries.csv')
X = datasets.ilo... |
e937069f475e950ac24c371222f744555f81f1ac | owowww/python- | /0812/untitled2.py | 459 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
請設計一個 function TRI(a,b,c),輸入三個邊長,此 function 可以判斷,
此三邊長能否組成三角形。三角形必要條件,最小兩邊加總大於第三邊。
"""
def TRI(a,b,c):
if (a + b) > c and (a + c) > b and (b + c) > a:
print("可以")
else:
print("不可以")
return
a=int(input("輸入a:"))
b=int(input("輸入b:"))
c=int(input("輸入c:... |
5eec022b393680405e7d153729ff668715d1fa4e | agrawalalisha/CS1110-Python | /programming assignments/dating.py | 377 | 4.09375 | 4 | # Alisha Agrawal (aa3se)
"""
This program prompts the user for their age
and returns the age range for people they can date
according to an old folk rule.
"""
# ask the user for their age
age = input("How old are you? ")
age = int(age)
# print the age range of people they can date
min = int(age/2)+7
max = age*2-13
pr... |
d55c62253b3bb47e5e1b7f993958bc324db2d616 | AbdullahAlsalihi/python-projects | /student_test_score.py | 843 | 4.46875 | 4 | # student grades_average
# this program will ask the user to enter the number of students and
# how many test scores each one gets according to specific number of test
# the user will enter both (student numbers and test scores) the program
# then will dispaly the average score for each specific student according
# t... |
2da9dee5892a19ef9d81f6de799056522625a3a5 | voxoblivion/Code_Wars | /List Filtering.py | 350 | 3.515625 | 4 | # https://www.codewars.com/kata/list-filtering/train/javascript
def filter_list(l):
e = []
for i in l:
if isinstance(i, str):
e.append(i)
[l.pop(l.index(i)) for i in e]
return l
def filter_list_V2(l):
return [i for i in l if not isinstance(i, str)]
print(filte... |
bde5d3c4a9c4f10f33f419f2971fd9cf3767bad4 | teaganryley/leetcode | /src/helpers/trie_node.py | 1,264 | 3.96875 | 4 | class TrieNode():
"""
Simple prefix tree (trie) implementation.
"""
def __init__(self, value: str):
self.value = value
self.children = []
#gives multiplicity of current character
self.counter = 1
def insert(root, word: str):
"""
Maps word to trie structure.... |
18add43db8abfd228f95bd0fa10a47d9f03cf24a | angersa/bitesofpy | /71/record.py | 328 | 3.75 | 4 | class RecordScore():
"""Class to track a game's maximum score"""
def __init__(self):
self._score = float('-inf')
def __call__(self, score):
self._score = max(self._score, score)
return self._score
record = RecordScore()
print(record(10))
print(record(3))
print(rec... |
7bd5f320620cf9b2c94b8b9708b121cd2b643886 | Tenzin-sama/LabExercisesPYTHON | /Lab Exercises/Lab Exercise 2/q6.py | 176 | 4.125 | 4 | # Lab Exercise 2, Question 6
"""Given an integer number,
print its last digit"""
num = input("Enter a number: ")
print(f"The last digit is {num[-1]}")
print()
input() |
610bd09a565d77007ec81ad77e922b119b1bd251 | L0ST-bit/Programming | /Practice/07/Python/module7.py | 1,475 | 3.640625 | 4 | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: User
#
# Created: 28.10.2020
# Copyright: (c) User 2020
# Licence: <your licence>
#-------------------------------------------------------------------------------
def main():
... |
e06c8dc685efe8ac8878f2a5b54ee456edb9c882 | phu-n-tran/LeetCode | /monthlyChallenge/2020-06(juneChallenge)/6_28_ReconstructItinerary.py | 3,742 | 4.3125 | 4 | # --------------------------------------------------------------------------
# Name: Reconstruct Itinerary
# Author(s): Phu Tran
# --------------------------------------------------------------------------
"""
Given a list of airline tickets represented by pairs of departure and
arrival airports [from... |
b2c3b693eaf2309308e09023310690e27306cfbd | mjrich/trimming-twitter-friends | /trimming-twitter-friends.py | 3,569 | 3.765625 | 4 |
# coding: utf-8
# In[1]:
print("Hello World")
# In[7]:
import tweepy
import pandas as pd
#Then create new twitter app: https://apps.twitter.com/
#Then set up Oauth below (filling in the empty double quotes)
# In[5]:
# == OAuth Authentication ==
#
# This mode of authentication is the new preferred way
# of aut... |
c4c76b35c9a7d30035483e93d76c5ab78d2a6014 | madeibao/PythonAlgorithm | /PartA/PyMap与Lambda匿名函数相互的结合.py | 1,251 | 4.5 | 4 |
map(function, sequence[, sequence, ...]) -> list
Return a list of the results of applying the function to the items of
the argument sequence(s). If more than one sequence is given, the
function is called with an argument list consisting of the corresponding
item of each sequence, substituting None for missing valu... |
c7502e4c07ab0af9e83033636ddacc4441e389a0 | LorenzoVaralo/ExerciciosCursoEmVideo | /Mundo 2/Ex041.py | 735 | 3.875 | 4 | # a confederação Nacional de natação precisa de um programa q leia o ano ne nascimento de um atleta e mostre sua categoria, de acordo com a idade:
# Até 9 anos: MIRIM
# Ate 14 anos: INFANTIL
# Ate 19 anos: JUNIOR
# Ate 20 anos : SENIOR
# ACIMA: MASTER
from datetime import date
presente = date.today().year
nasc... |
94a18874d8273858644f6b4366e7a4f6a52678c7 | alvinrach/28-Linear-Regression-From-Scratch | /Single-Variable Demo of LinearRegression Imitation .py | 2,654 | 3.84375 | 4 | #!/usr/bin/env python
# coding: utf-8
# **Here is the demo for the imitation model of the scikit-learn's LinearRegression**
# **This notebook presents you single-variable linear regression**
# In[1]:
from LinearReg import LinReg
# In[2]:
help(LinReg)
# In[3]:
import matplotlib.pyplot as plt
import numpy as... |
b9ca311e7752045e33d31ce55d51bb91d88aaa01 | burakhanaksoy/PythonOOP | /corey_schafer/dictionaries.py | 208 | 3.96875 | 4 | # key : value pairs
student = {'name': 'Burak', 'age': 25, 'course': ['Math', 'CS']}
for k in student:
print(f"{k}:{student.get(k)}")
print(student.keys())
print(student.values())
print(student.items())
|
1508486b8b2044f997ced5c58278dbdea2ec952c | SudoBobo/data_structures | /multi_thread.py | 1,170 | 3.53125 | 4 | from queue import PriorityQueue
procN, taskN = map(int, input().split(' '))
tasks_times = [int(task_time) for task_time in input().split(' ')]
# to store processing tasks in format [time_when_proccessing_ends, proc_idx]
pq = PriorityQueue()
# to store answer in format [proc_idx, time_when_proccessing_started]
proc_l... |
f20083301ebb7c64a6eaa53400cc8126291568ef | gmavrova/python-retrospective | /task3/solution.py | 1,056 | 3.609375 | 4 | class Person:
def __init__(self, name, birth_year, gender, mother=None, father=None):
self.name = name
self.birth_year = birth_year
self.gender = gender
self.mother = mother
self.father = father
self.list_of_children = []
for parent in [self.father, self.moth... |
201820abfdd248c92ce999875e03b243d4e2870c | ersanirem/gaih-students-repo-example | /Homeworks/HW1.py | 5,393 | 3.59375 | 4 | #Question 1; How would you define Machine Learning
The system learns its past experiences with the model it has developed using its data.
Ability to use this knowledge on new data without the need for reprogramming for future tasks.
#Question 2; What are the differences between Supervised and Unsupervised Learning? ... |
78e0dfe569c21db022dc4a3d9178edfdccc2c2ff | zhyErick/fengkuang_python | /11/11.2/extend_frame.py | 1,168 | 3.578125 | 4 | from tkinter import *
# 定义继承Frame的Application类
class Application(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
# 调用initWidgets()方法初始化界面
self.initWidgets()
def initWidgets(self):
# 创建label对象,第一个参数只当将改Label放入root内
w = Label(self)
... |
efb0e2d6ebac141d0aa0abcc467cf8e4d538b13f | mgbo/My_Exercise | /2018/My_students/6_объект_класс/0_primel.py | 667 | 3.71875 | 4 |
import random
greetings = ["'How can I help you?'", "'...'", "'Next!'"]
MOODS = ('bad', 'average', 'good')
RANKS = ('low', 'medium', 'high')
class Bureaucrat:
'''A government employee who works in the Institution.'''
def __init__(self):
self.rank = random.choice(RANKS)
self.mood = random.cho... |
09a421f964258ff2723339369e20fe3e17426a2b | Trsak/Python-sorting-algorithms | /insertion_sort.py | 464 | 4.125 | 4 | def insertion_sort(numbers_list):
list_length = len(numbers_list)
for i in range(0, list_length - 1):
j = i + 1
temp = numbers_list[j]
while j > 0 and temp < numbers_list[j - 1]:
numbers_list[j] = numbers_list[j - 1]
j -= 1
numbers_list[j] = temp
ret... |
76d4153ccf165a8934586156038f239e72204b3a | TianhaoFu/Web-crawler | /初步接触汇总/匹配电子邮件地址.py | 290 | 3.515625 | 4 | inport re
pattern = "\w+([.+-]\w+)*@\w+([.-]\w+)*\.\w+([.-]\w+)"
#字母,任意的字符 字母 出现多次 @ 字母 任意的字符 字母出现多次 任意字符 出现多次 任意的字符字母出现多次
string = "fdewfewfewfe"
result = re.research(pattern.string)
print(result) |
30c5c90f5d9b24263c1fc6ffa82a7446f72ef5cf | entirelymagic/Link_Academy | /fundamentals/ppf-ex07/knight.py | 333 | 3.625 | 4 | start = [-1, -1]
# Your code here
letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
for y in range(8):
print(y + 1, end=" ")
for x in range(8):
chr = "O"
if [x + 1, y + 1] == start:
chr = "S"
print(chr, end="")
print()
print(end=" ")
for l in letters:
print(l, end... |
6091da469453c2708499a6b356d3a5baac7bb94b | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4501/codes/1764_2390.py | 290 | 3.65625 | 4 | from numpy import *
pre = array(eval(input("Digite o numero de presentes a cada mes: ")))
falt = array(eval(input("Digite o numero de faltantes a cada mes: ")))
freq = pre - falt
mes = array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
i = 0
while(freq[i] != max(freq)):
i = i+1
print(mes[i]) |
bb26aa1621d711740cf122cb76ef64ee0fed52d6 | dvolk20/PythonScripts | /webscraping.py | 590 | 3.578125 | 4 | import requests
import csv
from bs4 import BeautifulSoup
url = "http://dataquestio.github.io/web-scraping-pages/ids_and_classes.html"
page = requests.get(url)
#print(page) #this will print the status
page_html = page.content #gets all of the page html
soup = BeautifulSoup(page_html, 'html.parser')
a = soup.prett... |
97ef49d9f5491ccd94c320a8ef7628fb73ce74dd | theTrio11/python-docs | /const.py | 254 | 3.65625 | 4 | class emp:
c=0
def _init_(s,name,role,salary):
s.name=name
s.role=role
s.salary=salary
emp.c+=1
def display(s):
print("%s,%s,%d"%(s.name,s.role,s.salary))
e1=emp("naman","ceo",99999999999)
e1.display()
|
535d0a2152703b96697441dc5651cde5f97dc2c8 | HITOfficial/College | /ASD/Sorts/selection_sort_linked_list.py | 1,865 | 4.15625 | 4 | # insertion sort algorithm on linked list
# complexity:
# - time O(n^2)
# - space O(1)
class Node():
def __init__(self, value=None, next_node=None):
self.value = value
self.next_node = next_node
def array_to_linded_list(array):
n = len(array)
# condition if array is not e... |
94750a543d63cfb04eacda77860c5a8bdcd348ef | amandakwong898/cs110-project1 | /day_of_week.py | 474 | 3.546875 | 4 | import stdio
import sys
# Get m month (int) from the command line.
m = int(sys.argv[1])
# Get d day (int) from the command line.
d = int(sys.argv[2])
# Get y year (int) from the command line.
y = int(sys.argv[3])
# Calculate and write the value of day of the week D.
y0 = y - (14 - m) // 12
x0 = y0 + y0 // 4 - y0 /... |
c63f0953dae6ba734cad29397ca20d61f45c9904 | astefano/project-Euler_leetCode_acm | /longestPref.py | 818 | 3.6875 | 4 | class Solution:
# @return a string
def longestCommonPrefix(self, strs):
ns = len(strs)
if ns == 0:
return ""
lens = [len(s) for s in strs]
minl = min(lens)
if minl == 0:
return ""
i = 0
last = strs[0][0]
pref = ""
... |
298db5630651e8655526f54053928ea67472aa5f | prbh695a/MyPrograms | /Practice/DataStructure/Queue/Circular.py | 967 | 3.765625 | 4 | class Circular:
def __init__(self):
self.items=[None]* 10
self.count=0
self.front=0
def add(self,value):
position=(self.front+self.count)%10
self.items[position]=value
self.count=self.count+1
def delete(self):
temp=self.items[self.front]
self... |
921b9835212ae29b00ba5b92b7b674cbcf23e770 | pulkitmathur10/FSBC2019 | /Day 01/string.py | 117 | 3.828125 | 4 | #String Handling
str1 = input("Enter the input string")
list1 = str1.split()
print(list1[1] + " " + list1[0])
|
cb41a985cedae18cad136aeff8152716a9c52413 | ClaytonStudent/leetcode- | /OfferPython/15_bit.py | 742 | 4.0625 | 4 | # 题目:二进制中1的个数
# 原来Python2的int类型有32位和64位一说,但到了Python3,当长度超过32位或64位之后,Python3会自动将其转为长整型,长整型理论上没有长度限制。
def bit_calculate(n):
count = 0
while n & 0xffffffff != 0: # 需要注意处理负数
count += 1
n = (n-1) & n # 减去1,再与本身做与操作,就可以去掉最右边的1
return count
def bit_(n):
if n < 0:
n = n & 0xffffffff # ... |
1f11ef4f3b71c5ed4251cdf815da21e759e4bf29 | MrHamdulay/csc3-capstone | /examples/data/Assignment_5/lnsjoh002/mymath.py | 553 | 3.890625 | 4 | # calculate number of k-permutations of n items
# bhavana harrilal
# 10 april 2014
def get_integer (x):
print("Enter", x, end="")
print(":")
n=input()
while not n.isdigit ():
print("Enter", x, end="")
print(":")
n=input()
n = eval (n)
... |
2c7eb657eb6f3732e87cc8a10b49f69528dccf3d | abhisheksahu92/Programming | /Solutions/31-Smallest subarray with sum greater than x.py | 1,216 | 4 | 4 | # Smallest subarray with sum greater than x
# Given an array of integers (A[]) and a number x, find the smallest subarray with sum greater than the given value.
# Note: The answer always exists. It is guaranteed that x doesn't exceed the summation of a[i] (from 1 to N).
# Example 1:
# Input:
# A[] = {1, 4, 45, 6,... |
122ba4bab71017dd0fd32625e4a7d14ae088d63b | yosho-18/LeetCode | /Basic_60/Group_Anagrams.py | 658 | 3.5625 | 4 | class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
two_strs = [[] for _ in range(len(strs))]
for two_part, part in zip(two_strs, strs):
two_part.append(part)
sort_part = sorted(part)
two_part.append(sort_part)
two_strs = sorted(t... |
0e4f2bdda598db25075fe4d585a10147e2488412 | charan2108/pythonprojectsNew | /Tuples/reassigningtuple.py | 142 | 3.578125 | 4 | click = (1,2,3, [6,7,8])
click[3][0] = 9
print(click)
print(type(click))
click =('H','e', 'l', 'l', 'o', 'w', 'o', 'r','l','d')
print(click)
|
0b20585b0cb88ec084442f9237f2fd993d641155 | suhaila98/basic-python-b6-b | /Tugas-1/Soal-1.py | 221 | 4.09375 | 4 | nama = input("Masukkan nama kamu :")
umur = input("Masukkan umur kamu :")
tinggi = input("Masukkan tinggi kamu :")
text = "Halo nama saya {}, umur saya {} tahun, tinggi saya {} cm".format(nama,umur,tinggi[:5])
print(text) |
a9d4b6d6975797dbc1488c04609990c28e562095 | yashcholera3074/python-practical | /exp9_iteration.py | 168 | 3.75 | 4 | abc=input("enter a string")
abc=abc.replace(" ","")
lis=list(abc)
lis2=set(lis)
for i in lis2:
if i in lis:
count=abc.count(i)
print(i,":",count) |
a6a11b707399aafdc05c49daef624e52ff9c1deb | UJHa/Codeit-Study | /(11) 알고리즘 기초 - Dynamic Programming/01) 1003 피보나치 함수/jinhwan.py | 773 | 3.8125 | 4 | # (1003) 피보나치 함수
fibo_dict = {}
def fibonacci(n):
if n == 0:
if fibo_dict.get(n) is None:
fibo_dict[n] = 0
return fibo_dict[n]
elif n == 1:
if fibo_dict.get(n) is None:
fibo_dict[n] = 1
return fibo_dict[n]
else:
if fibo_dict.get(n) is None:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.