blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
6a5a673128ffdcedf4ddf30e621b103ef5b22bff | supermitch/Advent-of-Code | /2017/05/five.py | 555 | 3.671875 | 4 | def exit_count(jumps, incrementor):
count = 0
i = 0
while True:
try:
move = jumps[i]
jumps[i] += incrementor(move)
i += move
count += 1
except IndexError:
return count
def main():
with open('input.txt', 'r') as f:
jump... |
2ce379c0d27879cfc873f323da7c6de85dcdd867 | vivekaxl/LexisNexis | /ExtractFeatures/Data/sohamchakravarty/005.py | 548 | 3.515625 | 4 | from helperFunctions import *
def findSmallestMultiple(startValue,endValue):
if startValue==1: startValue+=1
numList = range(startValue,endValue+1)
primeList = SOE(endValue)
for i in primeList:
numList.remove(i)
num = product = reduce(lambda x,y:x*y, primeList)
while True:
flag=... |
c44540b6382062abdb6609363c07fc4b31513a33 | freezees/wxpython | /practice/class/super.py | 411 | 3.875 | 4 | class A():
def __init__(self):
self.n=2
def add(self,m):
print('A')
self.n=self.n+2*m
class B(A):
def __init__(self):
self.n=3
def add(self,m):
print('B')
self.n=self.n+1
class C(B):
def __init__(self):
self.n=3
def add(self,m):
super... |
35ac517024a1935a74b3e49b4a05ed81e96a8bc2 | nischal-sudo/Flask-repo | /Desktop/code/models/store.py | 959 | 3.546875 | 4 | from db import db
class StoreModel(db.Model):#creates an object which is having name and price properties #"query"
__tablename__ = "stores"
id = db.Column(db.Integer,primary_key = True)
name = db.Column(db.String(80))#'sqlalchemy.sql.column()'
items = db.relationship("ItemModel",lazy="dynamic")
d... |
f5a71aec645268beeddf0cedc22772ba11702855 | Niyuhang/read_books | /fluent_python/chapter_2/tuple_sample.py | 813 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable = line-too-long
"""
@FIle:tuple.py
~~~~~~~~~~~
:copyright: (c) 2017 by the eigen.
:license: BSD, see LICENSE for more details.
"""
# 元祖可以用来记录数据
# 可以用来进行嵌套数据的拆包
name, cc, pop, (x, y) = ('Tokyo', 'JP', 36.933, (35.689722, 139.691667))
... |
9b3cc541575097b59d98cf057bf95cf23abdd18a | EAGLE50/LearnLeetCode | /2020-07/Q209-min-sub-array-len.py | 2,364 | 3.578125 | 4 | # -*- coding:utf-8 -*-
# @Time : 2020/7/7 22:35
# @Author : bendan50
# @File : Q209-min-sub-array-len.py
# @Function : 长度最小的子数组
# 给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的子数组,
# 并返回其长度。如果不存在符合条件的子数组,返回 0。
#
# 输入:s = 7, nums = [2,3,1,2,4,3]
# 输出:2
# 解释:子数组 [4,3] 是该条件下的长度最小的子数组。
# 输入 s = 213 nums = [12, 28, 83... |
78f5874ca83b11a889034de3d07901f92a40f9bd | a2606844292/vs-code | /test2/集合和列表去重/1.py | 463 | 3.9375 | 4 | #集合和列表去重
#使用set的方法去重复
place=['Beijing','Shanghai','Hangzhou','Guangdong''Beijing','Hangzhou']
print(len(place))
unique_place=set(place)
print(unique_place)
#判断值是否在列表里面
print('London' in unique_place)
print('Shanghai' in unique_place)
place.append('London')
print(place)
#集合add()pop()
#集合添加
number={1,2... |
fd9169db18d3b5480aa56cab46eb809755762c4c | vincy0320/School_Intro_to_ML | /Project1/house-vote-84.py | 6,880 | 3.90625 | 4 | #!/usr/bin/python3
import numpy as np
import pandas as pd
import statistics as st
import naivebayes as nb
import winnow as winnow
import util as util
def normalize(column):
"""
Normalize the input feature value if it's in the range of lower bound and
upper bound.
@param feature: the feature value
... |
6c389d3548e6fdbce7aeb6bafc979ed014ce5ff6 | govindak-umd/HackerRank_Python | /text_wrap.py | 292 | 3.78125 | 4 | import textwrap
def wrap(string, max_width):
i = ""
for c in range(0, len(string), max_width):
i += string[c:c + max_width] + "\n"
return i
if __name__ == '__main__':
string, max_width = input(), int(input())
result = wrap(string, max_width)
print(result)
|
0092c7ace7c54301d4ea68c04771058d752930dc | betty29/code-1 | /recipes/Python/579024_Simple_FIFO_trading_model/recipe-579024.py | 3,458 | 3.546875 | 4 | from collections import deque
import random
'''
Example below replicates
+75 MSFT 25.10
+50 MSFT 25.12
-100 MSFT 25.22
Realized P&L = 75 * (25.22 - 25.10) + 25 * (25.22 - 25.12) = $ 11.50
A Trade is split into a set of unit positions that are then dequeued on FIFO basis as part... |
ab44c0f0d73bd0b2a5c03ae8afd6048225119c16 | jaimeMontea/Text-Analysis | /tSNE.py | 6,984 | 3.53125 | 4 | '''The following code produces a t-Distributed Stochastic Neighbor Embedding (t-SNE)
technique, which is a dimensionality reduction model used to represent high-dimensional
dataset in a low-dimensional space of two or three dimensions so that we can
visualize it. This code is based on the t-SNE source code fro... |
a5df18ff781e1578cba587e0757865aa92aec2e3 | sincerehwh/Python | /Grammer/3.Container/generator.py | 666 | 3.859375 | 4 |
''' 生成器
- 节省内存
- 通过推倒获取对应的值
- 用到了再计算
'''
# 生成
squares = []
for i in range(1000):
squares.append(i * i)
for i in range(10):
print(squares[i])
print(squares)
squares_generator = (x*x for x in range(200))
for i in range(100):
print(next(squares_generator))
def fib(max):
n,a,b = 0,0,1
while n<max:
yi... |
34fe1c95fd0cde597bb3ab0950a89538d14e1b98 | Anarcroth/daily-code-challenges | /py/a_zero_sum_game_of_threes.py | 1,568 | 3.875 | 4 | #!bin/python3
# Description
#
# Let's pursue Monday's Game of Threes further!
#
# To make it more fun (and make it a 1-player instead of a 0-player game), let's change the rules a bit: You can now add any of [-2, -1, 1, 2] to reach a multiple of 3. This gives you two options at each step, instead of the original singl... |
65a1c8a95efc8e936fe8ef518f78068619a93aa4 | eldss-classwork/MITx | /6.00.1x Intro to Comp Sci/CreditCardDebt2.py | 974 | 4.28125 | 4 | # Evan Douglass
# This program calculates the minimum fixed monthly payment
# (as a multiple of ten) that will pay off a given debt in
# less than one year.
# initialize values
balance = 3926
annualInterestRate = 0.2
# monthly interest rate
monthlyRate = annualInterestRate / 12.0
def findEndBalance(b... |
361e0f993770178c79807c6541cf7f369dbeb7d7 | jfdiel/programming | /python/exercicios/area.py | 308 | 3.9375 | 4 | #calculo de area
a = float(input())
b = float(input())
c = float(input())
pi = 3.14159
print("TRIANGULO:"+str(round(((a*c)/2),3)))
print("CIRCULO:"+str(round((c*c)*pi,3)))
print("TRAPEZIO:"+str(round((((a+b)*c)/2),3)))
print("QUADRADO:"+str(round((b*b),3)))
print("RETANGULO:"+str(round((a*b),3))) |
d01c53f51ed7b1c9fc039566c7dd4715fe8fad27 | ahmedsalah52/Self_Driving_Car_Course | /Python/q3.py | 214 | 4.0625 | 4 | num = int(input("Please enter any number to build a pyramid\n"))
for i in range(num+1):
for j in range(num-i):
print(" ",end ="")
for k in range((i*2)-1):
print("*",end ="")
print("\n")
|
e8d73a23d38a55c9bf7ec46228666bb546e5ec68 | microease/Python-Cookbook-Note | /Chapter_3/3.3.py | 165 | 3.765625 | 4 | # 你需要将数字格式化后输出,并控制数字的位数、对齐、千位分隔符和其他的细节。
x = 1234.56789
res = format(x, '0.2f')
print(res)
|
dbc14e2a8ccf129c0973caa5dc74e7cf1d355d2f | farochocolom/Core-Data-Structures | /source/set_test.py | 5,217 | 3.59375 | 4 | #!python
from hashset import Set
import unittest
class SetTest(unittest.TestCase):
def test_init(self):
s = Set()
assert s.size == 0
assert s.table.length() == 0
def test_init_with_list(self):
s = Set(['A', 'B', 'C'])
assert s.size == 3
assert s.table.length(... |
591fbcaa20fca0a66edeff2a4b54efc47d7fc68a | asiacanady/s18-a05 | /q5.py | 738 | 3.90625 | 4 | import pandas as pd
df = pd.read_csv('crimes.csv')
'''
#5. What is the number of the community area with the most homicides in 2017?
How many were there? What is the community area's name? (You can find a mapping
of community area numbers to names online.)
'''
homicides = df[df['Primary Type'] == 'HOMICIDE']
communitya... |
4a68705438d1658953af47ad0d8c433353761fd0 | jasminegrewal/algos | /ctci/arrays_strings/nullify.py | 822 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 29 18:52:48 2017
@author: jasmine
"""
def nullify(m):
row=[False]*len(m)
col=[False]*len(m[0])
# store which column and rows have zeroes
for i in range(0,len(m)):
for j in range(0,len(m[0])):
if (m[i][j]==0):
row[i... |
3654a947f7bec54a6965fbc5e134e50262871a8c | MicherlaneSilva/ifpi-ads-algoritmos2020 | /fabio_2/fabio_2_p2/f2_p2_q6.py | 551 | 3.828125 | 4 | #Leia o turno em que um aluno estuda
# sendo M para matutino, V para Vespertino ou N para Noturno e
#escreva a mensagem "Bom Dia!", "Boa Tarde!"
# ou "Boa Noite!" ou "Valor Inválido!", conforme o caso.
def main():
print('Saudação\n')
turno = input('Turno (M/V/N): ').upper()
print(saudacao(turno))
... |
32cf78294d58e82313cadc8f1b8a33533cc55c07 | Jabba1988/Python_Examples | /m9_1в.py | 362 | 3.765625 | 4 | # Пример 1
from random import *
# Генерация списка
m = [randint(-5,6) for i in range(5)]
# Вывод списка в целом
print(m)
# Вывод списка поэлементно
a,b = 0,0
for i in m:
if i>=0: a += i
else: b += i
print('Сумма положительных: %d, отрицательных: %d' % (a,b))
|
7f2c7152c1e7bfe30b1861258408f1728ffcba49 | LinearPi/tanzhou_work_file | /lession/minmax.py | 318 | 3.5 | 4 | def minmax(test, *args):
res = args[0]
for arg in args[1:]:
if test(arg, res):
res = arg
return res
def lessthan(x, y): return x < y
def grtrthan(x, y): return x > y
print(minmax(lessthan, 4, 2, 3, 1, 6 ,5))
print(minmax(grtrthan, 4, 2, 3, 1, 6 ,5))
def func(a, b, c=2, d=4):
print(a,b,c,d)
func(1, *(5,6)) |
89ffeb17f800ab821ad5e8488f9ca081bb993412 | vacous/Coursera-Python-Specilization | /Principles of Computing/Puzzle15.py | 13,524 | 3.515625 | 4 | """
Loyd's Fifteen puzzle - solver and visualizer
Note that solved configuration has the blank (zero) tile in upper left
Use the arrows key to swap this tile with its neighbors
"""
import poc_fifteen_gui
# helper function
def unroll(list1):
'''
return the unroll list
'''
output = []
for ele in ... |
5193f7e839ced93442309649c21311d6cc3d761a | dubesar/My-Machine-Learning-Course-Projects | /NeuralNetwork.py | 1,911 | 3.5625 | 4 | import numpy as np
import pandas as pd
dataset=pd.read_csv("train (1).csv")
del dataset['Cabin']
del dataset['Ticket']
del dataset['PassengerId']
del dataset['Name']
del dataset['Embarked']
del dataset['Age']
# creating a dict file
Sex = {'male': 1,'female': 0}
# traversing through dataframe
# Gender column an... |
b403a3e00834ab2ed795fcbe090982353b777c69 | kramerProject/trybe_exercises | /Computer_Science/34_python/34_1/exercises.py | 1,286 | 3.890625 | 4 | import math
def max(x,y):
if (x > y):
return x
elif (x < y):
return y
else:
return "Numbers are equal"
def meanNumber(lst):
return sum(lst) / len(lst)
def square(x):
n = 0
if (x > 1):
while (n < x):
print(x * "*")
n += 1
else:
return ""
def biggestName(names):
big... |
304d7b315810f388c1b4a6512ff4f6d55fc848e5 | ee1tbg/elanFirstPyProj | /dictionaries/dictionaryChallenges.py | 3,322 | 4.03125 | 4 | '''
Created on Feb 1, 2019
@author: Winterberger
'''
# Write your values_that_are_keys function here:
import dictionaryBasics
def values_that_are_keys(my_dictionary):
return [my_dictionary[key] for key in my_dictionary if my_dictionary[key] in my_dictionary.keys()]
'''
for key in my_dictionary:
if my_... |
23ecedd3b431e13c9c9f1048e32db3c55fe86820 | jaford/thissrocks | /jim_python_practice_programs/29.60_print_user_input_fibonacci_numbers.py | 440 | 4.34375 | 4 | # Write a program that will list the Fibonacci sequence less than n
def fib_num_user():
n = int(input('Enter a number: '))
t1 = 1
t2 = 1
result = 0
# loop as long as t1 is less than n
while t1 < n:
# print t1
print(t1)
# assign sum of t1 and t2 to result
result... |
9beca6071b7647792e0fb5c50cd28bd225fbe7db | nidhigup01/Binary_search_in-Python | /binary_search.py | 3,249 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 22 07:03:10 2018
@author: nidhi
learned from : https://www.youtube.com/watch?v=zeULw-a7Mw8
"""
list1 = [0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
value = 6
def binary_search_linear(list1, value):
for i in range (len(list1)):
if list1[i] == value:
... |
f432cf794ed99c15a98410600baa2f1072207f56 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4488/codes/1590_842.py | 283 | 3.546875 | 4 | # Teste seu codigo aos poucos.
# Nao teste tudo no final, pois fica mais dificil de identificar erros.
# Nao se intimide com as mensagens de erro. Elas ajudam a corri
num =int(input("Digite um numero:"))
d1= num//1000
d2=(num//100)%10
d3=(num//10)%10
d4=num%10
print(d1+d2+d3+d4)
|
6efd0b4c730e65f7cce22f1abdbd55af7cc12f6f | Philip-Owen/algorithms | /python/bubble-sort.py | 536 | 3.8125 | 4 | import time
start_time = time.time()
arr = [77, 32, 99, 17, 2, 95]
def bubble_sort(arr):
swapped = True
passes = 0
while swapped:
swapped = False
passes = passes + 1
for i in range(len(arr) - passes):
if i != (len(arr) - 1):
if arr[i] > arr[i + 1]:
... |
887e0b57d0e2b4eaea5d3b93d39ced5776616cc1 | shaikhAbuzar/basicprograms | /curry.py | 254 | 3.625 | 4 | def add_a(a):
def add_a_b(b):
def add_a_b_c(c):
return a++b+c
return add_a_b_c
return add_a_b
ans=add_a(1)(2)(3)
print('Sum: ',ans)
ans1=add_a(1)
ans12=ans1(2)
ans123=ans12(3)
print('SUM: ',ans123)
|
b3737ba7b65cf239791970f9fbf709a6c48f9c11 | anakarlasantana/Exercicios-Python | /Exercício 3.py | 415 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Exercício 3 - Nessa aula, vamos aprender como funcionam os tipos primitivos no Python e as peculiaridades do int() float() bool() e str(). Além disso, veremos como fazer as primeiras operações com a função print() do Python.
"""
n1 = int(input ('Digite o primeiro numero:'))
n2 = int(input('D... |
c0d254cebd98fca0208a96d235ed21bd6f314b5b | lianggangscu/pylearn | /funpar.py | 159 | 3.609375 | 4 | #!/usr/bin/env python
#Filename:funwithpar.py
def maximum(a,b):
if a>b:
print("%d is maximum" %a)
else:
print("%d is maximum" %b)
a=7
b=5
maximum(a,b)
|
4b946226ee7195017b43b231827f57f837fee95e | lutolita/python | /taller3/t6.py | 535 | 3.875 | 4 | valores = []
def fibonacci(actual, cantidad):
index = actual
while (index < cantidad):
if index == 0:
valores.append(0)
elif index == 1:
valores.append(1)
else:
valores.append(valores[actual - 1] + valores[inde... |
80df7cd086497063e9f7e132e935d7321eb53a44 | arifaulakh/Competitive-Programming | /DMOJ/hailstone/hailstone.py | 184 | 3.609375 | 4 | n = int(input())
total = 0
while (n !=1):
if n%2 == 0:
n = n/2
total += 1
else:
n = n*3 + 1
total += 1
if n == 1:
break
print(total) |
0a8fb243e4fb328b4d0795b9af73d57fd879a858 | Vampir007one/Python | /Kalmykov_Practical_9/quest10.py | 347 | 3.65625 | 4 | mass = [int(s) for s in input("Введите информацию: ").split()]
indexMin = 0
indexMax = 0
for i in range(1, len(mass)):
if mass[i] > mass[indexMax]:
indexMax = i
if mass[i] < mass[indexMin]:
indexMin = i
mass[indexMin], mass[indexMax] = mass[indexMax], mass[indexMin]
print(' '.join([str(i) for i ... |
5f422e651695dcc8c1e16e768c53a6805ee42ed1 | adamcfro/practice-python-solutions | /password_generator.py | 559 | 3.984375 | 4 | import string
from random import choice
def password_generator():
strength = int(input("How strong would you like your password? "))
password = ''
for item in range(1, strength + 1):
alphanum = string.ascii_letters + string.digits
rand_alphanum = choice(alphanum)
password += rand_a... |
5d7d46c5e2a994df49516bf1b3c94c095823bf42 | AnatolyDomrachev/karantin | /is28/fedin28/4/4_4.py | 168 | 3.5 | 4 | def func(n):
if ((n%4 == 0) and (n%100 != 0)) or (n%400 == 0):
print(True)
else:
print(False)
n=int(input("Nomer goda: "))
func(n)
|
5402cddf875a574d62350cd820de1fc5a61b405f | oelbarmawi/Ehab | /Session3/UserInput.py | 413 | 4.25 | 4 | def getName():
name = input('What is your name? ')
print("Your name is {}.".format(name))
# getName()
"""
The function input always returns a string.
"""
def getAge():
age = input("What is your age? ")
# To convert a string to an integer [whole numbers]
my_age = int(age) + 10
# To convert a string to a f... |
49f5154f43739fb689857e9afe54972c4058a24e | Meirelesg/Codigos-Python | /Atividade 5/Atividade2.py | 347 | 3.75 | 4 | valores = list()
pares = []
for cont in range(0,5):
valores.append(int(input(f"Isnira o {cont+1}º valor: ")))
if valores[cont] % 2 == 0:
pares.append(valores[cont])
for cont in range(0,len(pares)):
if pares[cont] in valores:
valores.remove(pares[cont])
del(pares)
print(f"Lista sem os va... |
9bad3f9582f4a8a85af82d0e0e6b3a7be9ca02ca | thhuynh91/Python_Practice | /Even_Fibonacci_numbers.py | 478 | 4.46875 | 4 | #The Fibonacci number is generated by adding the previous two terms.
#For example: below is list of Fibonacci numbers:
#1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#Find the sum of the even-valued terms by considering the terms in Fibonacci sequence whose value do not exceed a given "n"
def Fibo(n):
total = 0
f1 =... |
f0ad2a42b0cbf0bfcb2885deabd9fa506bd15b80 | RyanWaltersDev/NSPython_Chapter7 | /sandwich_orders.py | 823 | 4.15625 | 4 | #!/usr/bin/env python3
# RyanWaltersDev Jun 16 2021 -- TIY 7-8 and 7-9
# Initial list
sandwich_orders = [
'pastrami', 'italian', 'ham', 'capricolla',
'pastrami', 'meatball', 'grilled chicken', 'pastrami',
]
finished_sandwiches = []
# Remove pastrami 7-9
print("My apologies, we are out of pastrami! But th... |
1d8a50fe96a7d502f058813eb1b471fbea834eac | MaliciousMatrix/SAPySap | /SAP1/ScheduleGeneration.Core/duration.py | 2,940 | 3.75 | 4 |
class Duration:
def __init__(self, start_date_time, end_date_time, *args, **kwargs):
self._is_init = True
self.start_time = start_date_time
self.end_time = end_date_time
self._is_init = False
assert self.start_time < self.end_time, 'start time must be before end time'
... |
aa7c2aaf64588e63ba783483e36a663dd048d53f | joshua-morris/chess3d | /Chess/Model.py | 4,333 | 3.765625 | 4 | from enum import Enum
class Game:
"""A chess game with game state information."""
def __init__(self, positions=None):
"""Create a new game with default starting positions."""
if positions is None:
self._positions = self._init_positions()
else:
self._position = positions
# true if whit... |
2d6aa76070e4cb2534bcf595ab4bbe30ddd1516d | baewonje/iot_bigdata_- | /python_workspace/01_jump_to_python/5_APP/1_Class/188_4_cal_class5.py | 1,011 | 3.828125 | 4 | class FourCal:
def setdata(self,first, second):
self.first = first # 멤버 변수가 없음에도 객체생성이후에
self.second = second
def add(self):
result = self.first + self.second
return result
def print_number(self):
print("first: %d, second: %d"%(self.first,self.second))
a= FourCal()
... |
4c2bcf20c71c2b536281c7a330705ecc57794ff8 | UdhaikumarMohan/Strings-and-Pattern | /length/longest.py | 331 | 4.1875 | 4 | # Write a function that takes a list of words and returns the length of the longest word
def longest(Array):
length = 0
for a in Array:
if len(a)>length:
length = len(a)
return length
Array = ['Bishop','Heber','College','Tiruchirappalli','udhai','abcdefghijklmnopqrstuvwxyz12345678... |
f9945addf9236f79da3c4a08621e0f6a3e42773a | MaartenAmbergen/MiniProjectGroep5 | /AlarmV2.py | 653 | 3.515625 | 4 | from gpiozero import LED, Button
from time import sleep
led1 = LED(17)
led2 = LED(27)
led3 = LED(13)
button = Button(2)
alarm_aan = False
while True:
if button.is_pressed and alarm_aan == False:
alarm_aan = True
led2.on()
sleep(5)
if alarm_aan:
led3.on()
pri... |
987b846c4b84893c318b17f519790cce262c5108 | ltlongzhu/MLCode | /gradient-descent/gradient-descent-linear-regression.py | 2,197 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
#This is a simple implementation of gradient descent for linera regression on a simle two dimensional data stored in data.csv
from numpy import *
from matplotlib import pyplot as plt
def run():
points = genfromtxt("/home/mirk/ML/mycode/... |
80b1c005f340398f8124089d25374cc48e1f3b1c | xsoer/pytools | /learn-numpy/src/1.Tutorial/1.4.LessBasic.py | 807 | 3.515625 | 4 | import numpy as np
#%%
"""
Broadcasting allows universal functions to deal in a meaningful way with inputs that do not have exactly the same shape.
The first rule of broadcasting is that if all input arrays do not have the same number of dimensions, a “1” will be repeatedly prepended to the shapes of the smaller array... |
0f9c5818d270deb7ac1d18e8538656c23d57f76d | jfxugithub/python | /面向对象的高级编程/多重继承.py | 559 | 3.953125 | 4 | #!/usr/bin/evn python3.5
# -*- coding: utf-8 -*-
#################################
#和java不同的是Python是可以多重继承的
#################################
class Animal(object):
type = 'animal'
class Runable(object):
def run(self):
print('I can run...')
class Dog(Animal,Runable):
def __init__(self):
se... |
9b6d49ba6374688c59eb99d0056afdf7a2388878 | korabelus/python_step | /functions/recursion.py | 4,088 | 4.4375 | 4 | """factorial"""
def factorial(n: int):
if n == 0:
return 1
if n == 1:
return 1
else:
return n * factorial(n-1)
print('factorial')
print(factorial(0))
print(factorial(1))
print(factorial(2))
print(factorial(5))
"""возведение числа а в степень n"""
def my_po... |
75aa4af10cac0093c7ee561771d136f89b659c95 | QMRonline/Tools-I-Use | /PythonTools/qmark-show-pass.py | 4,308 | 3.71875 | 4 |
# Import subprocess so we can use system commands
import subprocess
# Import the re module so that we can make use of regular expressions.
import re
# Python allows us to run system commands by using a function provided by the subprocess module
# (subprocess.run(<list of command line arguments goes here>, <specify ... |
2ffc683a793d402991525d16542e0441c7652758 | AwesomeZaidi/Problem-Solving | /Python-Problems/medium/prime.py | 840 | 4.125 | 4 | def get_number(prompt):
'''Returns integer value for input. Prompt is displayed text'''
return int(input(prompt))
def is_prime(number):
'''Returns True for prime numbers, False otherwise'''
#Edge Cases
if number == 1:
prime = False
elif number == 2:
prime = True
#All other ... |
24e41c4c5e7de5d2f2c20d592792f2f64fbf56fa | gloomysun/pythonLearning | /7-面向对象高级编程/4_定制类.py | 828 | 3.671875 | 4 | class Student():
def __init__(self, name):
self.name = name
def __str__(self):
return 'Student object[name:%s]' % self.name
__repr__ = __str__
s = Student('ly')
print(s)
print('===========================练习===================')
class Chain():
def __init__(self, path=''):
s... |
d58c8e67567ee391c91ebf416adfbed0d51d922c | xzlukeholo/range | /range.py | 517 | 3.71875 | 4 | import random
num = input('你想產生幾個隨機數:')
min1 = input('隨機數的最小值:')
max1 = input('隨機數的最大值:')
min1 = int(min1)
max1 =int(max1)
num = int(num)
for i in range(num):
r = random.randint(min1, max1)
print('第', i+1, '個隨機數:', r)
'你想計算多少加到多少的數值呢?'
start = input( '請輸入開始加總的數字:')
end = input( '請輸入結束加總的數字:')
start = int(start)
en... |
1e0c41fe3ffabc8e270bec6ec4090b96f00dc188 | SoullessStone/mancalaMaster | /gamemodel.py | 1,124 | 3.546875 | 4 | class GameModel:
# Indices for fields
PLAYER1_1 = 0;
PLAYER1_2 = 1;
PLAYER1_3 = 2;
PLAYER1_4 = 3;
PLAYER1_5 = 4;
PLAYER1_6 = 5;
PLAYER1_BASE = 6;
PLAYER2_1 = 7;
PLAYER2_2 = 8;
PLAYER2_3 = 9;
PLAYER2_4 = 10;
PLAYER2_5 = 11;
PLAYER2_6 = 12;
PLAYER2_BASE = 13;
... |
fe4c4fcdd6b6e7e5ba57ad9f52deef86e9f1c81c | helen-research/NNETs_and_Deep_Learning | /Coursera/0-Notes/Python/1-Vectorization.py | 683 | 3.796875 | 4 | """------------------------------------------------ Vectorization.py -----
| Purpose: First Vectorization approach, compares it to traditional
| methods.
|
| Developer:
| Carlos García - https://github.com/cxrlos
|
*----------------------------------------------------------... |
e71c4fe3adf79e6ab8af42bd97d3ac5e694b542b | chandrap08/leetcode | /maximum_product.py | 582 | 3.734375 | 4 | class Solution(object):
def maximumProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums = sorted(nums)
max_list = []
max_list.append(int(nums[-1]) * int(nums[-2]) * int(nums[-3]))
max_list.append(int(nums[0]) * int(nums[1]) * int(nums[2... |
8e603d6f9037dfd392aaa1908c0129457dd2d4f7 | vbraguimcanto/pesquisa-operacional-2 | /buscaFibonacci.py | 1,069 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# CÁLCULO DA FUNÇÃO NO PONTO X
f = (lambda x: x**2 + 2*x)
# CÁLCULO DO NÚMERO DE ITERAÇÕES
w = (lambda a, b, e: (b-a)/e)
# LISTA DE FIBONACCI
def fibonacci(iteracoes):
fib = []
i = 0
while True:
if i == 0:
fib.append(1)
elif i == 1:
fib.append(1)
else:
... |
9cd867ec71ff02fd0b4d67d2b9b67545f78a5774 | audoreven/IntroToPython | /Exercises/count-keywords.py | 803 | 3.734375 | 4 | import keyword
# getting list of keywords
key_words = keyword.kwlist
# initializing dictionary
count = {}
# getting file name
source = input("Enter a filename: ")
while True:
try:
file = open(source, "r")
break
except FileNotFoundError:
print('File does not exist. Please try again. \... |
2a8f87438f6c74b32e6ad8982da7ee94671f1665 | MicahJank/Intro-Python-I | /src/14_cal.py | 4,160 | 4.53125 | 5 | """
The Python standard library's 'calendar' module allows you to
render a calendar to your terminal.
https://docs.python.org/3.6/library/calendar.html
Write a program that accepts user input of the form
`14_cal.py [month] [year]`
and does the following:
- If the user doesn't specify any input, your program should
... |
cd33aa67fa461655557e2cb565841da0051234c8 | HigorSenna/python-study | /guppe/leitura_e_escrita_de_arquivos/sistema_de_arquivos.py | 1,196 | 3.53125 | 4 | """
Sistema de Arquivos e Navegação
Para fazer uso de manipulação de arquivos do sistema operacional, precisamos usar o modulo "os"
"""
import os
# Pega o diretorio atual (current work directory) -> caminho absoluto
print(os.getcwd())
# Mudar o diretório
os.chdir("../")
print(os.getcwd())
# Podemos checar se um di... |
5315567d08092c7a79631a0f3cecee4d3c5d1861 | silvioedu/TechSeries-Daily-Interview | /day21/Solution.py | 228 | 3.765625 | 4 | def num_ways(n, m):
if m == 1 or n == 1 :
return 1
return (num_ways(m - 1, n) +
num_ways(m, n - 1))
if __name__ == '__main__' :
print(num_ways(2, 2))
# 2
print(num_ways(5, 5))
# 70
|
20cf5ea0fcce629803a1b3945d1008a885a95dc6 | vishrutkmr7/DailyPracticeProblemsDIP | /2022/12 December/db12062022.py | 780 | 4.1875 | 4 | """
Given a sorted array of integers, nums, and a target, return the index of the target within nums.
If it does not exist, return the index of where target should be inserted.
Ex: Given the following nums and target...
nums = [1, 5, 8, 12], target = 12, return 3.
Ex: Given the following nums and target...
nums = [3... |
417e5d1633b28c942b66de94a63bbc33c156b9b9 | deltonmyalil/dataSciencePrerequisiteStack | /src/2_pandasTrials/10_joins.py | 549 | 3.609375 | 4 | import pandas as pd
# This uses table1.csv and table2.csv
t1 = pd.read_csv("table1.csv")
t2 = pd.read_csv("table2.csv")
print("Printing both tables separately")
print("Table 1")
print(t1)
print()
print("Table 2")
print(t2)
print()
# Let us join the two tables with respect to user_id attribute. Like natural join.
m =... |
2fb9851a0aa96fcfdf96f4f1cef717d584a6fc21 | kdogyun/algorithm_study | /1920.수찾기.py | 1,018 | 3.625 | 4 | import sys
input = sys.stdin.readline
class binary():
def __init__(self):
self.array = []
def search(self, start, end, num):
mid = int((start + end) / 2)
if start > len(self.array) or end < 0 or start > end:
return False, start
if self.array[mid] == num:
... |
ccb88188ae1505cc7261bd63a9d7d2b0f573b4e7 | Vestenar/PythonProjects | /venv/02_Codesignal/02_The Core/030_appleBoxes.py | 886 | 3.796875 | 4 | def appleBoxes(k):
# diff = 0
# for i in range(1, k+1):
# if i % 2 == 0:
# diff += i * i
# else: diff -= i * i
return sum((i*i) * (-1)**i for i in range(1, k+1))
print(appleBoxes(36))
'''
You have k apple boxes full of apples.
Each square box of size m contains m × m apples.
Y... |
f773a1bed7392592f256568c51791d24430d3c54 | UdayQxf2/tsqa-basic | /employee-salary-calculation/01_employee_salary_calculation.py | 1,245 | 4.34375 | 4 | """
We will use this script to teach Python to absolute beginners
The script is an example of salary calculation implemented in Python
The salary calculator:
Net_Income = Gross_Income - Taxable_Due
Taxable_Due = Federal_tax + Social_security + Medicare_tax
Taxable_Income = Gross_Income -120,00
Social_... |
336840a0a10dd44ceb9f52e8c8fea64d52b3c1a0 | Mahalinoro/python-program | /Omondi/Omondi v2/moto_class_file.py | 3,463 | 4.03125 | 4 | # This is the file containing the moto class
# importing the Vehicle class
# importing numpy to perform mathematic calculation
from vehicle_file import Vehicle
import numpy as np
# This is the moto class
class Moto(Vehicle):
# This is the method __init__ that will create instances automatically
def __init__(s... |
23ed044e85ac279b7dc3f127adab1318a227882e | Connor-Mooney/Clifford-T-Synthesis-Project | /Ops/operator.py | 2,327 | 3.53125 | 4 | import numpy as np
class Operator:
"""This class represents a matrix in SO6(Z[1/sqrt(2)]), storing the name of the operator, i.e. a string of T operators, its actual matrix, its residue,
and its column-permutation-invariant class"""
def __init__(self, LDE, mat,name):
self.matrix = mat
self.LDE = ... |
fbe88e24f6adb88c82fef8e9d0c52baf3edafc37 | franchescaleung/ICS31 | /restaurants6.py | 7,109 | 4.3125 | 4 | #RESTAURANT COLLECTION PROGRAM
# ICS 31, UCI, Winter 2018
# Implement Restaurant as a namedtuple, collection as a list
##### MAIN PROGRAM (CONTROLLER)
from collections import namedtuple
Dish = namedtuple ("Dish", "name price calories") #using to test
#d1 = Dish('noodles', 4.00)
def restaurants(): # nothing -> intera... |
940d0f9da2f3f1b9f5601ef88e23fcfca49d1f3d | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_145/518.py | 768 | 3.703125 | 4 | #!/usr/bin/python
import fractions
num_tests = int(raw_input())
def solve(p, q):
gcd = fractions.gcd(p, q)
if gcd != 0:
p /= gcd
q /= gcd
if p == 1:
return power(q)
if 2*p < q:
return solve(p-1, q/2) + 1
else:
return 1
def power(num):
pow = 0
while num > 1:
num /= 2
... |
0c0d82877422407c6212ee0d5681b9cfe888343c | kussy-tessy/atcoder | /abc191/d/main.py | 1,361 | 4.0625 | 4 | #!/usr/bin/env python3
# 努力した記念提出
import math
X, Y, R = map(float,(input().split()))
def is_in_circle(x, y):
return (x-X)**2 + (y-Y)**2 <= R**2
# https://twitter.com/meguru_comp/status/697008509376835584/photo/3
def count_lat_p(k):
count = 0
# left(円に初めて入る点)
ok = math.floor(X - R)
... |
3cd69b04bdb1507352e919350948402641c88ee4 | SayanNL1996/Cab_Booking_System | /schema.py | 4,332 | 3.546875 | 4 | """ Create all necessary tables required in the project."""
class Schema:
def __init__(self, connection):
self.conn = connection
def setup_admin(self):
"""
Create table employees & users if not exists and insert one row with given pre-details of admin.
:return: True/False
... |
075025805c30115c4518dbdcbe8fcf1198a5d0a3 | Mamatemenrs/Programming-for-Everyone | /Assignment4.6.py | 569 | 3.90625 | 4 | '''def computepay(h,r):
if hrs > 40:
ot = hrs - 40
ot_rate = rate * 1.5
ot_pay = ot_rate * ot
full_pay = pay + ot_pay
else:
print hrs *rate
return full_pay'''
def computepay(h,r):
if hrs > 40:
pay = 40 * rate
ot = hrs -40
ot_rate = rate * 1.... |
dfe50cafce4caecf017c9bf35bda237a3196dd16 | morgante/learn-a-little | /3_sum/index.py | 777 | 4 | 4 | '''
Given a list of numbers and a target N,
return a combination of 3 numbers from the list which sums to N.
This solution is O(n^2)
O(n log n + n*n) = O(n*(log n + n)) = O(n^2)
'''
def get_combination_sum(numbers, n):
numbers = sorted(numbers)
for i, num1 in enumerate(numbers[0:-2]):
left_j = i + 1... |
52581a14a9bb8f5574020a185de2f1ea50fe075b | MeinAccount/ea-snake | /game/direction.py | 2,630 | 3.734375 | 4 | import math
from typing import Tuple, List
GRID_WIDTH = 50
GRID_HEIGHT = 50
class Directions:
RIGHT = 0
UP = 1
LEFT = 2
DOWN = 3
@staticmethod
def to_left(direction: int) -> int:
return (direction + 1) % 4
@staticmethod
def to_right(direction: int) -> int:
return (di... |
6c1319d015f95a7a17d0d8d30feaf7db00243357 | DukhDmytro/py_point | /point.py | 1,254 | 4.375 | 4 | """sqrt func used in calculations"""
from math import sqrt
class Point:
"""Class representing point in 2D space"""
def __init__(self, x_coord: int, y_coord: int):
self.x_coord = x_coord
self.y_coord = y_coord
def find_distance(self, other_point):
"""
Calculate distance bet... |
1de8ebca56bb0e75e55a70634c62d5aef7311693 | vaishnavav99/funproject | /weather.py | 662 | 3.578125 | 4 | import json
from urllib.request import urlopen
x="n"
while(x!='y'and x!='Y'):
city = input("City/State \t")
print("")
key = "<your api key>"
url = "http://api.openweathermap.org/"
url = url+"data/2.5/weather?appid="+key+f"&q={city}&units=metric"
response = urlopen(url)
decoded = re... |
d1d4f91fe596a71e6ecea00ee7daeaffc9fc31b7 | ibourzgui/week3_work | /pyPoll/main_IB.py | 1,810 | 3.53125 | 4 | import os
import csv
total_votes = 0
candidates_names = ''
Dictionary= {}
vote_count = 0
vote_count_cand=0
election_file = os.path.join("","Resources","election_data.csv")
highest_votes = 0
winner = ''
with open(election_file, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
csv_header = ... |
35622c96459eebf0b242d7b51d9dc88fc5f197a1 | msoucy/fuf | /fuf/dispatchdict.py | 2,588 | 3.75 | 4 | #!/usr/bin/env python
"""
Dispatching Dictionary
Matt Soucy
This class provides a way to forward dictionary lookups to a second dictionary
transparently, such that users cannot tell which dictionary the item is in.
This is useful in situations where a form of "inheritance" is needed,
to provide a convenient interface... |
99e02fa63b997cb3156d5427da3833584a99d3c3 | stogaja/python-by-mosh | /12logicalOperators.py | 534 | 4.15625 | 4 | # logical and operator
has_high_income = True
has_good_credit = True
if has_high_income and has_good_credit:
print('Eligible for loan.')
# logical or operator
high_income = False
good_credit = True
if high_income or good_credit:
print('Eligible for a loan.')
# logical NOT operator
is_good_credit = True
c... |
fcc1ea0874b8f5b66f42214be26261314af0ad91 | tsunoda416/KHDKLAB-NLP | /100pon-knock/c1/02.py | 562 | 4.21875 | 4 | # -*- coding: utf-8 -*-
#!/usr/bin/python
import sys
def merge_string(string,string2):
mergestring = ''
for i in range(len(string)):
mergestring += string[i]
mergestring += string2[i]
return mergestring
if __name__ == "__main__":
'''
print result of merge char from string giv... |
2ab544066215b185af0df9a551a99258b1954d26 | Akhil-64/Data-structures-using-Python | /6.py | 1,464 | 3.953125 | 4 | '''
The given binary tree is not a Binary Search Tree (BST) then print the location of 1 st violation.
'''
class Node:
def __init__(self,key):
self.key=key
self.right=None
self.left=None
def isBSTUtil(node,min1,max1):
if node is None:
return True
if node.ke... |
0db86d8bfba1814b20e26db120a79ad22e34da40 | jenkin-du/Python | /pyhon36_study/str2float.py | 681 | 3.515625 | 4 | # 将字符串转化成float型数字
# 这是改过的版本
from functools import reduce
NumMap = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '.': '.'}
def fn(x, y):
return x * 10 + y
def char2num(char):
return NumMap[char]
def str2float(string):
numList = list(map(char2num, string))
n = 0 ... |
d4b8d25390666f419b129fafd5a395a5cefb14c8 | OlgaDrach/kolokviym- | /44.py | 534 | 3.796875 | 4 | #Підрахуйте кількість елементів одновимірного масиву, які збігаються зі
#своїм номером і при цьому кратні 3.
#Драч Ольга Олескандрівна, 122Д
import numpy as np
from random import randint
m = []
n = 0
for j in range(10):
m.append(int(input('Введіть числа: ')))
for i in range(10):
if m[j] == j and m[j... |
a61ae77132528c63366687f13b39dc949a036b98 | jpelaezClub/pyowm | /scripts/generate_city_id_files.py | 6,988 | 3.5 | 4 | #!/usr/bin/env python
import requests, sys, os, codecs, json, gzip, collections, csv
city_list_url = 'http://bulk.openweathermap.org/sample/city.list.json.gz'
us_city_list_url = 'http://bulk.openweathermap.org/sample/city.list.us.json.gz'
city_list_gz = "city.list.json.gz"
us_city_list_gz = "city.list.us.json.gz"
cs... |
9404aec42de685e10361d5edcefade3f3bb7efd4 | Weeeendi/Python | /car.py | 1,251 | 4.1875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
class Car():
"""一次模拟汽车的简单测试"""
def __init__(self,make,model,year):
"""初始化描述汽车的属性"""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_desciptive_name(self):
... |
2d706e8327c739f9af20ef85cc13840dd4b8bfe3 | CarolinaRivera/Python | /Operaciones Matematicas/Operaciones.py | 1,048 | 4.15625 | 4 | # Entrada de Datos
print("Escribe el numero1: ")
number1 = int(input())
print("Escribe numero2: ")
number2 = int(input())
# Operaciones o Calculos Matematicos
suma = number1 + number2
resta = number1 - number2
potencia1 = pow(number1, number2)
potencia2 = pow(number1, number2)
raiz_cuadrada = pow(number1, 0.5)
raiz... |
f6d17ecc473467bff0768727c42c7201ab7c6921 | sujan-thapa/Invoice-In-Python | /Invoice/main.py | 2,533 | 4.0625 | 4 | import first
sujan = first.dict1()
# print(sujan)
sss = sujan.items()
customerName = input("What is your name?: \n")
customer = input("Which prodcut do you want to buy from available products???: ")
# print(customer)
amount = 0
def inside():
for gadgets, prQty in sss: #for loop for nested dictionary
... |
50bd565caffb972a8d3c2a5e0eb611becc7dbfab | cliffpham/algos_data_structures | /algos/loops/K_closets_points_to_origin.py | 1,539 | 3.546875 | 4 | # space efficient solution
import math
def closet(points, K):
output = []
points = merge_sort(points)
while len(output) < K:
output.append(points.pop())
return output
def compare(points, index):
cur = points[index]
return math.trunc(math.pow(cur[0],2) + math.pow(cur[1], 2))
#descen... |
a55758428419de0dcef952e13dd006d0d27a410b | SaitoTsutomu/leetcode | /codes_/0022_Generate_Parentheses.py | 565 | 3.578125 | 4 | # %% [22. **Generate Parentheses](https://leetcode.com/problems/generate-parentheses/)
# 問題:有効な「n個の括弧からなる文字」を列挙
# 解法:左括弧と右括弧について再帰
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
return list(search("(" * n, "", ""))
def search(left, right, cur):
if left:
yield from search(l... |
d89d6e24f1a063a2b3a3cddf84882d4125c4ccf3 | lucassing/SportLeague | /team.py | 343 | 3.515625 | 4 | class Team:
"""
Tournament object
:param name: the team name
foundation: the foundation's year of the team
"""
def __init__(self, name, *args, **kwargs):
self.team_name = name
self.foundation = kwargs.get('foundation')
def __str__(self):
retu... |
32d89207a300b41d758daabcddfd9704c2de3c95 | bmandiya308/python_trunk | /oracle.py | 1,524 | 3.578125 | 4 |
list_input = ["may", "student", "students", "dog","studentssess", "god","god","cat", "act","tab", "bat", "flow", "wolf", "lambs","amy", "yam", "balms", "looped", "poodle"]
'''
list_matched =list()
list_not_matched =list()
for word in list_input:
length_match = [itm for itm in list_input if len(word) == len(itm) ... |
9ee6b7631c5fbe8a124ee2364356d3e5f84faece | maia13/aoc-2020 | /day23a/program_lib.py | 919 | 3.796875 | 4 | import re
def calculate(cups, count):
for _ in range(count):
cups = move(cups)
ix1 = cups.index('1')
result = cups[ix1+1:] + cups[0:ix1]
return ''.join(result)
# (3) [8 9 1] 5 4 6 7 {2}
# (3) [8 9 1] {2} 5 4 6 7
# (3) [8 9 1] 5 4 {2} 6 7
def move(cups):
current_cup_label =... |
ea072f8d767eef8a180818eb41960aed645b2079 | patels20/APC-Hub | /CURSE/code/Classes/user_c.py | 552 | 3.6875 | 4 | class User:
# Base Class that all classes are built off of
def __init__(self, user_id="7", first_name="7", last_name="7", passcode="7"):
# This is the initialization function
# if no paramaters are passed into it, the default listed will be used
self.user_id = user_id # U... |
7409c7ee4377af3be4e3cc14ebdd6291cff2306b | ahmedyoko/python-course-Elzero | /DB_fetch_data80.py | 1,415 | 3.875 | 4 | #................................................
# DB => sqlite => retrive data from data base
#................................................
# fetchone => return single record or non if no more rows are available
# fetchall => fetch all rows of the query result.It returns all the rows as a list of tuple
# ... |
41a948615ca54ff0acccf40d8dbd3a13f49d29dc | atulmishra/try_git | /day2/statisticsDemo.py | 796 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 12 09:59:59 2018
@author: Administrator
"""
import statistics
print (statistics.mean([1,2,3,4,4]))
print (statistics.mean([-1.0,2.5,3.25,5.75]))
from fractions import Fraction as F
print(statistics.mean([F(3,7),F(1,21),F(5,3),F(1,3)]))
print (F(3,67))
... |
8230479d2659a733c178413664ea18b695925711 | perennialAutodidact/PDXCodeGuild_Projects | /Python/lists_practice/problem10.py | 237 | 4 | 4 | def merge(a,b):
pairs = []
[pairs.append([a[i], b[i]]) for i in range(len(a))]
return pairs
def main():
list1 = ["a", "b", "c"]
list2 = [1,2,3]
print(f"{list1}, {list2}. Merged: {merge(list1, list2)}")
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.