blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
74db4bbda81ffe5b91734d7dabe19d2deb00aa28 | kasettakorn/Python | /dynamic_programming/fibo_with_2elements_of_array.py | 642 | 3.9375 | 4 | def fibonacci(n):
for i in range(n+1):
fibo = [0, 1]
if i == 0:
print ("fibo( 0 ) = ", 0)
elif i == 1:
print ("fibo( 1 ) = ", 1)
else:
flag = True
for j in range(2, i):
if flag: # Replace first element fibonacci(n) + fib... |
b3fbe57678e5e430da8e9fd482c67612bdf00b67 | AndreasAndityaTI/UG10_A_71210690 | /3_A_71210690.py | 233 | 3.796875 | 4 | pilihan=(input("Mendatar/Menurun?: "))
jumlah=int(input("Masukkan kolom: "))
if pilihan=="Mendatar":
print("#"*jumlah)
elif pilihan=="Menurun":
print("*\n"*jumlah)
else:
print("Pola tidak dikenali")
|
34e07e3437d2734550450888c444bfb802d2f582 | spidermedic/Games | /tic/tic.py | 2,105 | 3.84375 | 4 | """Simple command line tic-tac-toe game"""
import sys
# initalize board. c[0] is used as a counter
c = [0,' ',' ',' ',' ',' ',' ',' ',' ',' ']
def main():
""" Main function """
draw_board()
player1()
# Player 1's turn
def player1():
"""Player 1's turn"""
p1=''
while not p1.isdigit() ... |
f9c55f05d33d980657a7bd8f7229faab24f4136c | yingkun1/python-django | /django-rest-framework/day130_1/test.py | 518 | 3.5625 | 4 | # def func(arg):
# if callable(arg):
# print(arg())
# else:
# print(arg)
#
# # func(123)
# func(lambda :666)
class Foo(object):
def __init__(self,a1):
self.a = a1
def __new__(cls, *args, **kwargs):
"""
1.根据类创建对象,并返回
2.执行返回值的__init__
:param args:
... |
9b35c270f2c4835c097d22aff2feb2302631d69d | jasonodoom/PyMaths | /LearnMaths.py | 874 | 4.4375 | 4 | def LearnMaths():
'''Takes input from user on what math operation they want to learn.
Choices are: +, -, * and /'''
Learn = input('What would you like to learn? ')
if Learn in ['Addition', 'addition', 'add', 'Add', 'adding', 'Adding', '+']:
from modules import LearnToAdd
print(LearnToAdd())... |
cd962a5001ce75941d2d88ae219045bee4a91c9c | puhsu/numerical_methods | /integral.py | 1,075 | 3.84375 | 4 | """Integration module.
"""
import numpy as np
def integrate(grid_function):
"""Computes integral of a function with trapezodial rule.
Finds integral of a given grid function numerically with accumulated error
of O(h^2), where h is a step size in grid.
Args:
func: numpy.ndarray storing grid f... |
f3765c02652b503fc3e0ea331e3adbbc9b7371a2 | TheChuey/DevCamp | /list_overview.py | 1,214 | 4.0625 | 4 | """
User Database query
Kristine
Tiffany
Jordan
"""
users = ['kristine', 'Tiffancy', 'Jorda']
# A true data structure
#list are inmutable
# you can only call the functions the data type excepts
print(users)
users.insert(1, 'Anthony')
print(users)
users.append('Ian')
print(users)
print (users[2]... |
5ed048b1801803d69daf1d944e1f671021d95c87 | kgao9/python_3_5_multiple_prob | /three_five_multiple.py | 317 | 4.34375 | 4 | # the purpose of this function is to get the sum of
# all multiples of 3 and 5
# @param upperbound
# @return sum of all multiples of 3 and 5
def sum_multiples(upper_bound):
sum = 0
for number in range(0, upper_bound):
if(number % 3 == 0 or number % 5 == 0):
sum += number
return sum
|
239c92d99414ef234394aeec915b8454c01f986f | gan3i/CTCI-Python | /Revision/TreeAndGraph/LowestCommonAncestor_4.8/solution_one.py | 1,452 | 3.828125 | 4 | # ask can each tree node have a pointer to it's parent node
# is it guaranteed that nodes are present in tree.
# can one of the node be the lCA
class BinaryTreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
self.parent = None
def common_ancest... |
f78213e77abee8a77c334013d38ba5a0432fc0ad | Aleks-du/Pyhton | /lectur04/lecture4.py | 1,599 | 3.640625 | 4 | #Ввод
stroka = input("Вывод ПРОСТЫХ чисел до числа ... ")
stroka = stroka.strip() # удаляем пробелы
#Проверка ввода
if not stroka.isdigit(): #проверяем, чтобы были только числа
print('не подходит под условие')
exit(1)
#Преобразуем строку в число
num = int(stroka)
#Создаем список
a = [0] * num # создаем масс... |
f2539230ad76e946bd2c6d9790e2ae5f924a4628 | starkizard/CrudeCode | /CSES Problem Set/Introductory Problems/5-Permutations.py | 519 | 4.3125 | 4 | # auth: starkizard
# printing all the odd elements first in descending order and then the even elements should work
# the only case where the largest even and the smallest odd (1) have the difference of 1 is in case of n=2 or 3
def main():
#CODE GOES HERE:
n=ii()
if n<=3 and n>1:
print("NO SOLUTION"... |
51a4cd8c360c533a51b7dd9e1b2c4527350657e9 | asadch1/Math_2305_Final_Project | /Functions/graph_operations.py | 972 | 3.515625 | 4 | # -*- coding: utf-8 -*-
# shows edges not in tree
def incident_edges(G, T):
edges = []
for e in G[1]:
for vertex_a in T[0]:
for vertex_b in T[0]:
#considers edges already seen
if (vertex_a in e) and (e not in T[1]) and (e not in edges):
... |
b4c989ed44ba28f5d197c58faf64742185a44af3 | pingsoli/python | /python_cookbook_3rd/chap04/14.py | 393 | 3.515625 | 4 | # 4.14 Flattening a Nested Sequence
from collections import Iterable
def flatten(items, ignore_types=(str, bytes)):
for x in items:
if isinstance(x, Iterable) and not isinstance(x, ignore_types):
yield from flatten(x)
else:
yield x
items = [1, 2, 3, [4, 5, [7, 8, [9, 0] ] ... |
dbddabbdbbbd0da9f0ccab5f4f3ef2f98a41d3ed | bmcdonnel/data-structures | /python/exercises/concurrency/dining_philosophers.py | 1,722 | 3.609375 | 4 | import random
import time
from multiprocessing import Process, Lock, Event
class Philosopher(Process):
def __init__(self, name, left_fork, right_fork, stop_event):
super().__init__()
self.name = name
self.left_fork = left_fork
self.right_fork = right_fork
self.stop_event =... |
063f8d5e20aa2473e95c737c9e263781daced9fc | jsstevenson/tabroom_csv_process | /cleaning/cleaning_tools.py | 706 | 3.546875 | 4 | import csv
def print_schools(reader):
schools = []
for line in reader:
for team in [4, 7]:
if line[team] not in schools:
schools.append(line[team])
schools.sort()
for school in schools:
print(school)
def print_tournaments(reader):
tournaments = []
... |
271b2dd684a16669520a9108c003f260bec7042a | alankx/programmingAK | /codeGIT/prog_03.py | 1,206 | 3.953125 | 4 | def salutation(name):
salutation = 'Hello ' + name
return salutation
def average(first, second):
averageValue = (first + second)/2.0
return averageValue
print salutation('Alan')
print(average(5, 6))
print [1,2,3,]
print range(1,10)
mylist = [1,2,3,4,5]
mylistlength = len(mylist)
print myl... |
06b73cc4692dbcb6976a9db1046f849554949cdf | morganbrunelle/python_for_me | /guacamole.py | 231 | 3.640625 | 4 | ingredients = ['avocado', 'onion', 'tomato', 'garlic', 'jalapeno', 'lime']
for x in range(0, len(ingredients)):
print("%d - %s" % (x + 1, ingredients[x]))
for x in [0, 1, 2, 3, 4, 5]:
print("%d - %s" % (x + 1, ingredients[x]))
|
c50dc8bed26c617e511d3b2a56aba9f9b728f333 | valar-m0rghulis/Python | /Infosys-Foundation-Program/MODULES/Module_1_Programming_Fundamentals/Assignment38.py | 1,299 | 3.5625 | 4 |
def check_baggage(baggage_weight):
try:
if(baggage_weight >= 0 and baggage_weight < 40):
return True
else:
return False
except TypeError:
print("INVALID baggage weight entered")
def check_immigration(expiry_year):
try:
if(expiry_year >= 2001 and expir... |
309b9bda51a244fe3a52086845cc44a5af5a162b | Shulun/basic-graph-theory | /eulerian_tour.py | 1,134 | 3.984375 | 4 | # Find Eulerian Tour
#
# Write a function that takes in a graph
# represented as a list of tuples
# and return a list of nodes that
# you would follow on an Eulerian Tour
#
# For example, if the input graph was
# [(1, 2), (2, 3), (3, 1)]
# A possible Eulerian tour would be [1, 2, 3, 1]
def find_tour(node, graph, tour)... |
d6b39c0c11601720ced7bdcff359ac68265e638c | dersonf/aulaemvideo | /exercicios/ex051.py | 247 | 3.71875 | 4 | #!/usr/bin/python36
print('='*30)
print('{:^30}'.format('10 TERMOS DE UMA PA'))
print('='*30)
n = int(input('Primeiro termo: '))
r = int(input('Razão: '))
for c in range(0, 10):
print('{} -> '.format(n), end = '')
n += r
print('ACABOU')
|
db23432af21158bff7ef1d123064812522587f4d | zwMargaretProject/BigW | /dataStructures/linkedList.py | 2,672 | 3.90625 | 4 |
class Node(object):
def __init__(self, value=None, next=None):
self.value, self.next = value, next
class LinkedList(object):
def __init__(self, maxsize=None):
self.maxsize = maxsize
self.root = Node()
self.tailnode = None
self.length = 0
def __len... |
f2aa1baa6ff390a0b2f4ed43b1d914c2936e071a | GauthamAjayKannan/guvi | /hunter108.py | 155 | 3.546875 | 4 | n=input()
s=0
if len(n)==1:
s+=int(n)**2
print(s)
else:
for i in range(len(n)-1):
s+=int(n[i])**int(n[i+1])
s+=int(n[len(n)-1])**int(n[0])
print(s)
|
805fed31ef6cefe26aeb8ebfdce0684bc7d415d0 | SharathKumar2036/Python-Basic-Programs | /Patterns/pattern4.py | 187 | 3.96875 | 4 | from __future__ import print_function
n=int(input("Num:"))
for i in range(n):#When value of i is 1 then in it prints one star
for j in range(n-i):
print('#',end='')
print("\r")
|
43866a96d955443d49f51011ca7a40dbe6403cbb | rashed091/Algorithm-and-Data-structures | /Arrays/palindrome.py | 449 | 3.8125 | 4 |
def palindrom(s):
flag = True
for i in range(len(s)):
if s[i] == s[len(s) - i - 1]:
flag = True
else:
return False
return flag
T = int(input())
for _ in range(T):
S = input()
isPalin = 'YES' if palindrom(S) else 'NO'
isEven = 'EVEN' if len(S) % 2 == 0 ... |
69c44e59148cf088cee0390dd2d168cf10ffef56 | nightimero/annal_report_test | /my_class/is_class_true.py | 973 | 3.890625 | 4 | # -*- coding:utf-8 -*-
# 在 Python 中使用 bool 函数、if、while 等对某个对象进行真值判断时,有一定的算法。
#
# 以下情况则为 False
# None
# False
# 所有为 0 的数值,比如:0, 0L, 0.0, 0j
# 任何空的序列,比如: '', (), []
# 任何空的映射,比如 {}
# 用户定义的类的实例:如果该类定义了 ** __nonzero__ ** 或者 ** __len__ ** 方法,且返回值为数值 0 或者 False
# 其它所有情况都为 True
# 其实真值判断在 Python 入门时,大家都有遇到过,基本对于前 6 种会被判定为 False... |
4dd274c2cdec97bae0e3c0c6f248e1505b4f324c | mizm/TIL | /python/swexpert/sw1989.py | 114 | 3.5625 | 4 | for i in range(int(input())) :
s = input()
print(f'#{i+1} 1') if s == s[::-1] else print(f'#{i+1} 0')
|
d66fcfab0d4647fcb5a9a56c8a97c47456397a9c | lipegomes/python-django-udemy-studies | /Lessons/Section-04/lesson_0101/main.py | 541 | 3.78125 | 4 | # 101. Composição - Python Orientado a Objetos
from classes import Cliente, Endereco
cliente1 = Cliente("João", 50)
cliente1.insere_endereco("São Paulo", "SP")
print(cliente1.nome)
cliente1.lista_enderecos()
del cliente1
print()
cliente2 = Cliente("Maria", 42)
cliente2.insere_endereco("Curitiba", "PR")
print(client... |
adb9da6df08e84cdf46ef524fd206d4a872e2ed1 | dinhtq/coding_practice | /linkedLists/reverseList.py | 999 | 3.953125 | 4 |
class LinkedNode:
def __init__(self, val, next=None):
self.val = val
self.next = next
def reverseList(head):
return
# test
def appendToList(head, val):
tail = head
while(tail.next is not None):
tail = tail.next
tail.next = LinkedNode(val)
return tail.next
def assertEqual(a, b, desc):
if... |
f8106956cf5fe97cfd56cac2fe29922151f8c09f | chanjulee/Algorithm | /1_파이썬문법/6_중첩반복문.py | 526 | 3.953125 | 4 | '''
중첩 반복문 (2중 for문)
for i in range(5):
print('i:', i, sep='', end=' ')
for j in range(5):
print('j:', j, sep='', end=' ')
print()#줄바꿈
# i:0 j:0 j:1 j:2 j:3 j:4
# i:1 j:0 j:1 j:2 j:3 j:4
# i:2 j:0 j:1 j:2 j:3 j:4
# i:3 j:0 j:1 j:2 j:3 j:4
# i:4 j:0 j:1 j:2 j:3 j:4
'''
for i in range(5): #0,1,2,3... |
ab37ba60e6e21eb515bfef7cab18912f401583e2 | ravikorat/python_example | /datatypes/sets_example.py | 775 | 3.9375 | 4 | my_set = {1, 2, 3, 4, 3, 2}
print(my_set)
print(type(my_set))
my_set.add(10)
print(my_set)
my_set.update([12, 13, 4])
print(my_set)
my_set.discard(6)
print(my_set)
# my_set.remove(6)#raise an error
# print(my_set)
my_sets = set("HelloWorld")
print(my_sets)
my_sets.pop()
print(my_sets)
my_sets.clear()
print(m... |
0490e5e10ad42b2a90e86bba51710cc4e1d5ca37 | ni-da/iap_1819 | /vbExamen/test1.py | 534 | 3.75 | 4 | def substring(s, x, y):
new_str = ""
for i in range(y):
new_str += s[(i + x) % len(s)]
return new_str
def count_words(string, word):
word_count = 0
s = 0
while len(string) > 0:
if string[s] == word[s]:
ss = substring(string, s, len(word))
if ss == word:
... |
e96dedf22e86d293ad7c05354cc34eab3855f375 | wuligiao4630/COVID19-D | /hello_world.py | 464 | 4.21875 | 4 | print("hello world")
name = input("best country in the world: ")
print(name)
'''
name = name.lower()
name = name.capitalize()
if (name == "china"):
print(name + " is the best!")
elif(name == "russia"):
print(name + " is the second best")
else:
print("怎么可能")
'''
fruits = ['apple, grannysmith, gala', 'orang... |
bc20182b596773f0f82f23e89595877cd7e6d422 | robertefreeman/PE-scripts | /problem10.py | 1,252 | 3.984375 | 4 | import math
import time
#Problem 10: The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million.
#check if number is prime
def isPrime(num):
# We know 1 is not a prime number
if num == 1:
return False
i = 2
# This will loop from 2 to int(sqrt... |
bdfcc1220bdbe8b7b5b0c9c01da58e3680a23691 | yingliufengpeng/algorithm | /zhengwei/08 贪心策略与动态规划/12 动态规划例题_背包之dp解法.py | 1,685 | 3.59375 | 4 | # -*- coding: utf-8 -*-
'''
这类的方法是通过dynamic programming的模式
有N个重量和价值分别为wi, vi的物品,从这些物品中挑选出总重量不超过W的物品,求所有挑选方案中价值
总和最大的值
'''
'''
f(x, y) = z
x: 由小到大选择物品个数,按序选择, eg x = 2. eg(x选择0, 1, 2这些数)
y: 所选择的物品的重量,代表着一个值
z: 代表着价格
动态规划的解决方案
python格式
dp[(w, n)]: ... |
a815368161d02d4659e495da1338a32b0d144410 | huangmxsysu/leetcode | /leetcode_19. Remove Nth Node From End of List_list( )_42ms.py | 763 | 3.6875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
collection=list();
ptr=head;
collection.append(ptr)
while ptr.next is n... |
2fa7c13c44c7ea398b48978af11f7fbc59a760dd | jasonpoonia/Python-Practice-2 | /Python/Problems/problem1.py | 596 | 3.796875 | 4 | #problem1.py
#Doing onenote problem1 that the teacher has given us
#Jason Singh, 12 February
import time
def cardbalance(z,purchase,y,x):
print("Intial Card Balance:{}".format(z))
time.sleep(1)
print("Name of purchase: {}".format(purchase))
time.sleep(1)
print("Cost of purchase: {}".format(round(y... |
85836036becdff5cacbd695bc2f758934de7632c | innsmthdwlr/AoC2019 | /Day04/main.py | 1,141 | 3.515625 | 4 | from collections import Counter
def never_decrease(password_candidate):
password_candidate_str = str(password_candidate)
return ''.join(sorted(password_candidate_str)) == password_candidate_str
def adjacent_are_the_same(password_candidate):
password_candidate_str = str(password_candidate)
return len(s... |
333ef078fa1d6bb44e2070b0c5687f088eeea21f | ECasielles/BasicPythonGeneticALG | /Python_WordFinder_GA/wordfinder_ga_threading.py | 14,038 | 4.15625 | 4 | """Basic architecture for a simple Genetic Algorithm example."""
import random
import numpy as np
import time
from multiprocessing import Pool
from multiprocessing.dummy import Pool as ThreadPool
from operator import methodcaller
# 1 - Heredity
# 2 - Variation
# 3 - Selection
# Setup: Make a random a pop of N eleme... |
72112798687c85b428ef647c84afe130f7f78ee7 | RaquelBentimHarrison/pythonrobot | /robot.py | 1,940 | 4.0625 | 4 | # robot game
# use commands: right, left, up, down, fire, status and quit
class Robot:
def __init__(self):
self.XCoordinate = 10
self.YCoordinate = 10
self.FuelAmount = 100
def move_left(self):
if (self.FuelAmount <=0):
print("Insufficient fuel to perform action")
else:
self.... |
4ab00137ecab0e14a8cc721bd97120f7bb7f5160 | lllchen/python100daysscript | /05/fibonacci_false.py | 474 | 4.25 | 4 | #这是一个生成器不能使用递归函数的例证,本想写个永不停止的斐波那契数列生成式,但是失败了,因为递归函数下一层yield的结果只能被上一层调用,不能直接给for...in...里的next()
def fibonacci(a=0,b=1):
print('a:',a)
yield b
a , b = b , a+b
#print('a')
r = next(fibonacci(a,b))
print('r:',r)
yield r
f = fibonacci()
for i in range(10):
print('i:',i)
print('数列',next... |
8bf7f578d3b2a59701cb788144172c2dbf251b1e | briangoss541/advent_of_code_2020 | /15_2.py | 1,132 | 3.53125 | 4 | data_list = [12, 1, 16, 3, 11, 0]
# data_list = [0, 3, 6]
memory_dict = dict()
def speak_memory():
turn_count = 1
spoken_number = None
while turn_count <= 30000000:
# Starting numbers
if turn_count <= len(data_list):
spoken_number = data_list[turn_count - 1]
me... |
a7ec5d3c2cc3dc8f5189a60d354a50783a46696b | rpi-techfundamentals/introml_website_fall_2020 | /site/_build/jupyter_execute/notebooks/06-unsupervised/04-regression-feature-selection.py | 6,787 | 3.546875 | 4 | [](http://rpi.analyticsdojo.com)
<center><h1>Boston Housing - Feature Selection and Importance</h1></center>
<center><h3><a href = 'http://rpi.analyticsdojo.com'>rpi.analyticsdojo.com</a></h3></center>
##... |
a9a5e9517f35e7c602b82bb884f1a5d441d6de1e | moqi112358/leetcode | /solutions/0139-word-break/word-break.py | 2,105 | 3.9375 | 4 | # Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
#
# Note:
#
#
# The same word in the dictionary may be reused multiple times in the segmentation.
# You may assume the dictio... |
979ca54ebcef876429b0f7d58e7e4bcf03ccf4b9 | Vahid-Esmaeelzadeh/CTCI-Python | /educative/06 In-Place Reversal of a LinkedList/05 Rotate a LinkedList (medium).py | 2,654 | 3.984375 | 4 | '''
Rotate a LinkedList
Given the head of a Singly LinkedList and a number ‘k’, rotate the LinkedList to the right by ‘k’ nodes.
'''
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def print_list(self):
temp = self
while temp is not None:... |
61543e6cc16a5353b5631f99505169fa1cbef88d | julienalarcon/minimax | /main.py | 736 | 3.984375 | 4 | from tictactoe import *
# main
print("#########################")
print("Starting TicTacToe Game !")
print("#########################")
board = newGame()
# Player choice
myPlayer, computer = choosePlayer()
# Start (X always start)
while True:
result = gameTurn(myPlayer, computer, board)
if not result is Non... |
42424bd7d275e843642546a2b9f437f70353efd9 | baharaysel/python-study-from-giraffeAcademy | /if_Statements.py | 1,184 | 4.25 | 4 | # I wake up
# If I'm hungry
# I eat breakfast
#
#I leave my house
#If it's cloudy
# I bring an umbrella
#oterwise
# I bring sunglasses
#I'm at the restaurant
#If I want meat
# I order steak
#otherwise if I want pasta
# I order spaghetti & meatballs
#otherwise
# I order a salad.
is_... |
870ee91ee817b9357f1e752057e01ff19bc99400 | Lanmezhe/pythonLearning | /try_except.py | 569 | 3.84375 | 4 | #!/usr/bin/python
class ShortInputException(Exception):
'''A user-defined except class.'''
def __init__(self, length, atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast
try:
s = raw_input('Enter somthing-->')
if len(s) < 3:
raise ShortInputException(len(s), 3)
print'Other wo... |
fa3ea4dee8dbe44bbd5ec98a6ceb4ba18d9bad03 | wanuch/legacy | /Security/onetimepad.py | 846 | 3.78125 | 4 | def one_time_pad():
key = 0
count = 0
ciphertext = ''
plaintext = input('Please enter the message: ')
key_text = 'thequickbrownfoxjumpsoverthelazydog'
for i in plaintext:
if i.isalpha():
num = ord(i)
if count >= len(key_text):
... |
62560b23800a7a5836a627d782527078703d53f8 | gabriellaec/desoft-analise-exercicios | /backup/user_337/ch54_2020_04_10_19_24_00_128837.py | 191 | 3.71875 | 4 | def calcula_fibonacci(n):
lista = []
lista.append(1)
lista.append(1)
while len(lista) < n and n>2:
x = lista[n-1] + lista[n-2]
lista.append(x)
return lista |
b37dec6305b78af181ba5f5af171ef88f892ec69 | chloevo26/Python-Data-Structures | /AnagramCheck2.oy.py | 681 | 3.734375 | 4 | def anagram(s,t):
s = s.replace(' ','')
t = t.replace(' ', '')
if len(s) != len(t):
return False
else:
dict = {}
for letter in s:
if letter not in dict:
dict[letter] = 1
else:
dict[letter] += 1
for letter in t:
... |
874c77c62b54b97892041a7c7f2687080dcb3f96 | Korabliov/python-labs | /Starter/003_Examples/02-single-line-if.py | 135 | 3.8125 | 4 | x = int(input('x = '))
# такая форма записи возможна, но нежелательна
if x < 0: x += 1
print(x) |
c83118ec676be320a345710fddf3f8e06de34e2e | markjluo/MITOCW6.00.1x | /Week 5_Object Oriented Programming/W5_Lecture_Hierarchies.py | 4,300 | 4.09375 | 4 | import random
# Create a class "Animal", which inherits from "object" class. e.g. properties of
# underlying Python object class. (Basic operations in Python, like binding variables, etc)
class Animal(object):
creator = 'Mark'
def __init__(self, age):
self.age = age
self.name = None
def... |
51b8e7a14365772805c031ec39f592872ccb79dc | jonathanrfisher/MTGManaBase | /Deck.py | 2,502 | 3.515625 | 4 | class Deck:
# 7 different possible mana costs for 7 different
# possible converted mana costs started with 1 as our
# zeroth converted mana cost.
#cards = [[0 for x in range(7)] for x in range(7)]
def __init__(self, cards):
self.cards = cards
# A standard deck wil... |
b1799118f5d9a52874bea1892541d3118e330f43 | IbrahimDaurenov/Incoop-cohort-1 | /Week 2/Day 5 (July 22)/Modules/hello.py | 163 | 3.625 | 4 | import main
def greeting(name):
return ('Hello ' + name)
def main():
a = 10
b = 20
c = a + b
greeting('Bob')
print('Hello world!')
|
4b6ba8828c7094a23a01712518f7fb391d9f53fe | MalondaClement/Projet_LU3IN013 | /graphGen.py | 2,038 | 3.703125 | 4 | import networkx as nx
from networkx.algorithms import bipartite
import matplotlib.pyplot as plt
from random import randint
from utils import *
def edgesWeight(n):
"""This fuction create a dictionary with run time for each task
:param arg1: Number of task
:type arg1: int
:return: Return a di... |
246c343f752928efecb4b14f079a339e04c3e591 | EdikCarlos/Exercicios_Python_basico | /ex_Triangulo.py | 398 | 3.921875 | 4 | l1 = float(input('Digite a primeira medida: '))
l2 = float(input('Digite a segunda medida: '))
l3 = float(input('Digite a terceira medida: '))
if (l2 - l3) < l1 < l2 + l3 and (l1 - l3) < l2 < l1 + l3 and (l1 - l2) < l3 < l1 + l2:
print('\033[32mÉ POSSIVEL FAZER UM TRIÂNGULO COM ESSAS MEDIDAS!!!\033[m')
else:
pr... |
c44eae288482815dd191681aa9e571df78fa3f24 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2363/60591/236636.py | 197 | 3.578125 | 4 | string = bin(eval(input())).split("0b")[1]
temp = list(string)
for x in range(len(temp)):
if(temp[x]=='0'):
temp[x] = '1'
else:
temp[x] = '0'
print(eval("0b"+"".join(temp))) |
ec3af85268b80447e921d547c7349ada0bcd60fd | gozeberke/python_temel_projeler | /list-method-uyg.py | 504 | 3.953125 | 4 | names=['Berke','Yağmur','Efe','Deniz']
years=[1998,2000,1998,1987]
names.append('Cenk')
names.insert(0,'Sena')
#names.remove('deniz')
names.count('Deniz')
index=names.index('Deniz')
result='Ali' in names #names dizisinde ali var mı
names.reverse()
names.sort()
years.sort()
min=min(years)
max=max(years)
print(years)
p... |
e83d557900141ca4be3bf0c668684bee96142073 | mivargas/Master-python | /1-script/17modulos/mimodulo.py | 523 | 3.828125 | 4 | def holaMundo(nombre):
return f"hola que tal estas {nombre}"
def calculadora(num1, num2, basicas = False):
suma = num1+num2
resta = num1-num2
multi = num1*num2
division = num1/num2
cadena = ""
if basicas != False:
cadena += "suma: " + str(suma)
cadena += "\n"
cade... |
b3771c487a3b1e38dac7d5311e9b443a89e289a5 | jones6ju/it3038c-scripts | /python/Labs/Lab5.py | 1,380 | 4.03125 | 4 |
import random, time
bottom = 1
top = 100
h = random.randint(bottom, top)
count = 0
###If you have ever played Apex Legends, I keep thinking of the machine as Pathfinder. haha
print("Hello will you play a game with me friend?")
time.sleep(1)
print("yes or no?")
answer = input()
if answer == 'yes':
print("You only... |
2ba42640c2d20d4d5929c6ec6f0954e5334cc08f | CesaireTchoudjuen/programming | /week08-Plotting Data/Lab8.3.py | 267 | 3.8125 | 4 | # Program that makes a list , called salaries, that has 10 random numbers (20000 - 80000)
# Add 5000 to each salary
# Author: Cesaire Tchoudjuen
import numpy as np
salaries = np.random.randint(20000,80000,10)
salariesPlus = salaries + 5000
print(salaries)
print(salariesPlus) |
2843dae2a0b8b792fe1a5705eb7c8cf4e48d8bdb | AAliAbidi/Python-Code | /73_Fibonacci.py | 394 | 3.5625 | 4 | rng = int(input("Print positive Range: "))
try:
if(rng>0):
firstNo = 0
SecondNo= 1
fiboSum = firstNo+SecondNo
print ("%d\n%d\n%d"%(firstNo, SecondNo, fiboSum))
for i in range(1, rng):
firstNo = SecondNo
SecondNo = fiboSum
fiboSum = firstNo+... |
1bf823d516d0cf7691f72845c5a25fc049bfa310 | ayamaguire/July2015 | /serverF.py | 2,916 | 3.5625 | 4 | # Aya Maguire
# July 2015
# This is the code that sets up the Server.
import socket
import sys
import datetime
class TCPHandler:
###############################
# TCPHandler is not as modular as Client. If I had time to rewrite it I'd
# break it into more readable functions.
#
# This first part es... |
d7298f5558a5f116694c875dfc695c4df647a65b | DenisVritov/algorithms | /easy_collection/other/valid_parentheses.py | 1,127 | 4.34375 | 4 | """
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Input: s = "([)]"
Output: False
"""
from typi... |
8c2329339565fde32aa122e43f0ab93e45209d2e | fernandochimi/Intro_Python | /Exercícios/130_Validacao_sem_funcao.py | 182 | 4.15625 | 4 | # -*- coding: utf-8 -*-
while True:
v=int(input("Digite um valor entre 0 e 5: "))
if v<0 or v>5:
print("valor inválido")
else:
print("O número digitado foi: %d" % v)
break |
9002bbb013ce8809abedb4bb7418f0c0c64a08f7 | Ekeopara-Praise/python-challenge-solutions | /Ekeopara_Praise/Phase 2/SET/Day56 Tasks/Task5.py | 111 | 4.25 | 4 | '''5. Write a Python program to find the length of a set.'''
set1 = {1, 2, 3, 4, 5, 6, 7, 8}
print(len(set1)) |
4d619731398c0139c53df3077ca7d7459de00757 | bkornpob/kbastroutils | /kbastroutils/container.py | 573 | 3.765625 | 4 | class Container:
"""
Example:
keys = ['x','y']
values = [1,2]
a,b = Container(keys),Container(keys,values)
a.x,a.y >>> None, None
b.x,b.y >>> 1, 2
-----------
keys = list of names to be set as attribute names
values = list of values parallel to keys to be set as values
"""
... |
9295d16377925956383b4239f6688be9ff8c3011 | KonekoTJ/TQC-Python | /第7類:數組(Tuple)、集合(Set)以及詞典(Dictionary)/PYD706.py | 218 | 3.59375 | 4 | # TODO
k = int(input())
str_abc = set('abcdefghijklmnopqrstuvwxyz')
for i in range(k):
instr = input()
instr = instr.lower()
instr = instr.replace(' ', '')
instr = set(instr)
print(str_abc == instr) |
d78d8514d0ee61eaf428c59c40410272cf60d76f | darthols/mooc_Python-3 | /w4/w4-s3-x4-power.py | 1,733 | 4.125 | 4 | #!/usr/bin/env python3
# coding: utf8
"""
Power
fonction qui met un objet x à la puissance entière n.
Le paramètre x doit pouvoir être multiplié par lui même, et le paramètre n est un entier >=1 (pas la peine de vérifier).
Naturellement on s'interdit d'utiliser l'opérateur prédéfini **; notamment notre algorithme doi... |
28478997355000c10cff4b07231cd7f5a727752b | hughsurdeau/MuseumProject | /models/agents/route_panner.py | 1,257 | 3.921875 | 4 | #TODO This file might be no longer relevant haha
class RoutePlannter:
"""
Class for planning routes based on agent preference
and relative prestige of paintings
The aim here is to find an algorithm that maximises enjoyment of paintings.
For a linear museum - agents will only skip if the desire to ... |
d231fc039decfdbcfe80d1f1868f26522269b886 | phyuzinzaw/coding-sprint | /python-exercises/ex16.py | 678 | 3.609375 | 4 | from sys import argv
script,filename=argv
print(f"we're going to erase {filename}.")
print("if you don't want that,hit CTRL-C (^C).")
print("if you do wnat that,hit RETURN.")
print("if you do want that ,hit RETURN.")
input("?")
print("opening the file...")
target=open(filename,'w')
print("truncating the file,goodbye!")... |
0c4871b4391821afd81d74bd63c01836f968d2e5 | akapet00/python-loves-data | /http/src/3_scraping_web.py | 859 | 3.671875 | 4 | # HTML is a max of unstructured and structured data
# to create useful data from raw HTML, parsing and extracting structured data needs to be done
# BEAUTIFUL SOUP - converts 'tag soup' to parsed, pretty data
import requests
from bs4 import BeautifulSoup
url = 'https://www.python.org/~guido/'
r = requests.get(url)
ht... |
5901182dde67dad51e43cf1118f8da175bab0db5 | Ritikajain18/Problem-Solving | /Staircase.py | 534 | 4.46875 | 4 | '''
Consider a staircase of size n :
#
##
###
####
Observe that its base and height are both equal to n, and the image is
drawn using # symbols and spaces. The last line is not preceded by any spaces.
Write a program that prints a staircase of size n .'''
import math
import os
import random
impo... |
5a5aff75927c502f4661b69c7a8db17bb720097a | jinyesong/Python | /base/practice2/2.2_while.py | 98 | 3.609375 | 4 | input_num = int(input())
i = 1
while i<=input_num:
print(str(i)+" "+str(i*i))
i += 1 |
051593e6db475a2a2144de514cdbe725bd58a5b4 | tenhobi/BI-PYT | /homeworks/05-cyclic-list/__main__.py | 411 | 3.53125 | 4 | #!/usr/bin/env python3
from cyclic_list import CyclicList
xs = CyclicList(range(10))
print(1, '...', xs)
print(2, '...', len(xs))
print(3, '...', xs[9])
print(4, '...', xs[10])
print(5, '...', xs[8:])
print(6, '...', xs[18:])
print(7, '...', xs[-10])
print(8, '...', xs[-11])
print(9, '...', xs[::3])
print(10, '...', ... |
4cb07265a7245e1b194c72649f86d8b90eace205 | alexcummins/partyLightRave | /Animations/default_colours.py | 1,146 | 3.671875 | 4 | from dataclasses import dataclass, astuple
@dataclass
class Colour:
red: int
green: int
blue: int
def __getitem__(self, item) -> int:
if item == 0:
return self.red
elif item == 1:
return self.green
elif item == 2:
return self.blue
def _... |
36aed068f192f88b72f3837eadfd74c0c7332bb2 | 99dneyleta/CHNU_Python | /sqlite.py | 1,009 | 3.875 | 4 | import sqlite3
class Sqlite:
def __init__(self, dbName):
self.dbName = dbName
self.Connection = sqlite3.connect(dbName)
self.Cursor = self.Connection.cursor()
def close(self):
self.Connection.close()
# rows must be dictionary with type and value
def createTable(self, ta... |
69a5d2289b128d9c47ee7c1b6091e734c0b65127 | eduardo92005-debug/Gilson | /Exercício-07/Lista_07.py | 1,403 | 4.53125 | 5 | ##### Exercício 07 #####
'''
Neste exercício é utilizado um módulo chamado MinhasCurvas.py
Todas as funções estão no outro arquivo e não neste.
Este aquivo principal só testa as funções.
Não tem plot, mas se quiser visualizar pode usar os mesmos passos do exercício passado
Exemplo de execução deste ... |
632303916dc0994792596ca85912903bbe52a0fe | nikser86/les2_work | /work1.py | 2,062 | 3.890625 | 4 | # Задание 1
# (Подсказка: ищите как это сделать с помощью методов строк)
# 1. Определите является ли строка записью числа. (Подсказка: ищите как это сделать с помощью методов строк)
s = '1234123454634563456'
print(s.isdigit())
# 2. Посчитайте сколько у вас пробелов в строке.
s = 'asdf wqer qwer '
print(s.count(' '))
... |
9d3e7a661851dec78bda0007d7f747fae86ef569 | asutosh97/nptel-python | /week3/alternate.py | 435 | 3.859375 | 4 | def alternating(l):
n = len(l)
if n == 0 or n == 1:
return True
elif n == 2:
diff = l[0] - l[1]
if diff:
return True
else:
return False
else:
flag = False
prev = l[1] - l[0]
for i in range(1,n-1):
diff = l[i+1] - l[i]
if (diff > 0 and prev > 0) or (diff < 0 and prev < 0) or (prev == 0) ... |
ad65e2980e5a1b96b1939a5a160ec2a1ffc8fecc | SourabhShenoy/Python-Code | /Google Foobar/GitCodes/google-foobar-master/3_2_fix_my_phone_minion.py | 2,247 | 3.921875 | 4 | # Copyright (c) 2012-2014 Kapiche Limited
# Author: Ryan Stuart <ryan@kapiche.com>
"""
Fix my phone, minion!
=====================
"She escaped? This can't be happening! Get me the security team!"
Professor Boolean, a notorious mad scientist, just found out his precious rabbit specimen has escaped! He rushes to call
... |
c3099c5d15bb1030caa5b2eaea7e29753e2b0192 | Achyutha18/College_Sample_2 | /Sample2_16.py | 208 | 4.3125 | 4 | #Python Program to Multiply All the Items in a Dictionary
dict1 ={'one':1,'two':2,'three':3,'four':4,'five':5}
product=1
for i in dict1:
product=product*int(dict1[i])
print("Sum of values is :",product) |
024911baef9bc709c387743eab0c1bb2180d772e | lucianofa/dio-intro-python | /Aula3.py | 143 | 3.75 | 4 | a = input('Digite o primeiro valor: ')
b = input('Digite o segundo valor: ')
soma = a + b
print('O valor da soma é: {soma}'.format(soma=soma)) |
f270962014f0bed85d1da6927501b07cf50ed8cd | thhuynh91/Python_Practice | /GCD_LCM.py | 306 | 3.828125 | 4 | #Write a function to find out what is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
from functools import reduce
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def lcm(a, b):
return a*b/gcd(a, b)
print(reduce(lcm, range(1, 20+1)))
|
ae1291287fe3008f3eb624ce5c9aa7b73c088ddb | callous4567/UoE-Projects | /2nd Year Miscellanies/error4.py | 380 | 3.84375 | 4 | """
Print out a series of integers
"""
nmax = 10
for n in range(nmax + 1):
print(("The number is {}").format(int(n)))
# This assumes you actually want the value of 0... if you don't, run:
"""
from OOP1 import utilities
import time
for d in range(1, nmax + int(1)):
utilities.time_delay(str(int(d)))
time.sleep(0.... |
ff2f2bb6004895456a165652c94ab5e3b4b4842d | luc-zago/exercises-python | /Programas - Python/devolve_maiusculas.py | 171 | 3.515625 | 4 |
def maiusculas(string):
newString = ''
for letra in string:
if (ord(letra) > 64 and ord(letra) < 91):
newString += letra
return newString
|
a43cb13d045dff333f53a95ff4c2b85f04d6a752 | UnnamedHero/project-lvl1-s566 | /brain_games/games/progression.py | 592 | 3.53125 | 4 | from random import randint
DESCRIPTION = 'What number is missing in the progression?'
MAX_START_NUMBER = 20
PROGRESSION_LENGTH = 10
MAX_STEP = 10
def get_question_data():
step = randint(1, MAX_STEP)
start_num = randint(1, MAX_START_NUMBER)
missing_index = randint(0, PROGRESSION_LENGTH - 1)
end_num =... |
f0ee465a2f00a631ab3d15a30d31ff962e6c08b3 | hed854/adventofcode2020 | /day7/day7.py | 3,542 | 3.703125 | 4 | #!/usr/bin/env python
"""
advent of code 2020 day 7: Handy Haversacks
https://adventofcode.com/2020/day/7
"""
import re
class ColoredString():
def __init__(self):
self.reset = "\033[0m"
def red(self, text):
red = "\033[0;31m"
return(f"{red}{text}{self.reset}")
def yellow(self, text)... |
17dbee909162be158669dd231968c5d440322ce5 | Ash515/PyAlgorithms | /Searching/linearsearch.py | 846 | 4.0625 | 4 | def linearsearch(arr,key):
for i in range(len(arr)):
if arr[i]==key:
return i
return -1 ... |
ad3794c2a3929b8efb71a972c1c50cf04ab3476a | biyak/CodingChallenges | /CodeExcersizes/searchrange.py | 1,101 | 3.984375 | 4 |
def searchrange(nums, target):
#Find the starting and ending point of a target value in an array
#Ex. find start and end of target = 8 in nums = [1,2,3,3,7,8,8,8,10,10]
#Ans: return [5,7]
print(nums)
ind = helper(nums, target)
print(ind)
if ind == -1:
return [-1,-1]
else:
... |
e66d5d3833ac213079e7c369deb0d67f1fb280bc | mhetrerajat/ds-challenge | /hackerrank/Other/xml_find_the_score.py | 359 | 3.796875 | 4 | #!/usr/bin/python3
# xml_find_the_score.py
# Author : Rajat Mhetre
# follow and drop me a line at @rajat_mhetre
import xml.etree.ElementTree as etree
count = 0
lines = int(input())
xml = ""
for _ in range(lines):
xml += str(input())
tree = etree.ElementTree(etree.fromstring(xml))
for element in tree.iter():
... |
0d7f150d6bc47e9b058732c220c5ddc3709aa199 | linnndachen/coding-practice | /Leetcode_By_Topic/dp-123.py | 1,573 | 3.5625 | 4 | class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) <= 1:
return 0
min_cost = prices[0]
max_price = prices[-1]
n = len(prices)
left_profits = [0] * n
right_profits = [0] * (n+1)
for l in range(1, n):
left_pro... |
893be5ce051c82a8ea701dbef309d9b8a4307b4b | niufenjujuexianhua/Leetcode | /[131]Palindrome Partitioning.py | 1,184 | 3.984375 | 4 | # Given a string s, partition s such that every substring of the partition is a
# palindrome. Return all possible palindrome partitioning of s.
#
# A palindrome string is a string that reads the same backward as forward.
#
#
# Example 1:
# Input: s = "aab"
# Output: [["a","a","b"],["aa","b"]]
# Example 2:
... |
301cb185d730575decaca10ce3fab6789af74d34 | bookpark/Fastcampus | /python/python-practice/function_practice/function_practice5.py | 202 | 3.734375 | 4 | def count_args(*args):
print('%d개' % len(args))
count_args(1, 2, 3, 4)
def args_count(*args):
c = len(args)
print(c)
return c
result = args_count(3, 5, 2, 10, 'ABC')
print(result)
|
b3871228243fd1a6054d7d932b3437ac1bc48fd0 | ustcwhc/trickylib.python | /file_writer.py | 872 | 4 | 4 | #!/usr/bin/python
# filename: file_writer.py
# functions
# 1. print_list(file_path, input_list)
# 2. print_dictionary(file_path, input_dic)
# FUNCTION
def print_list(file_path, input_list):
'''print each item in the input_list as a line in the file_path'''
with open(file_path, 'w') as sw:
for item in i... |
549d396aa865f3c12e111ec6fe150d17b78b89b0 | priyamore/lc-problems | /data-structures/twoSums.py | 1,167 | 3.921875 | 4 | '''
Problem Statement:
Given an array of integers nums and an integer target,
return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution,
and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums ... |
797d928f0dbe56251c8ea59f79e944daeaf10787 | claytonjr/ProgrammingCollectiveIntelligenceExercises | /Chapter5/Exercise1.py | 2,228 | 4 | 4 | """ Chapter 5 Exercise 1: Group travel cost function.
Add total flight time as a cost equal to $0.50 per minute on the plane.
Next try adding a penalty of $20 for making anyone get to the airport before 8 a.m.
The function was altered to include the costs mentioned above.
"""
def schedulecost(sol):
... |
43556a3d57cd9f518a891c77b38d01f4d71c2827 | erjan/coding_exercises | /find_greatest_common_divisor_of_array.py | 402 | 3.765625 | 4 | '''
Given an integer array nums, return the greatest common divisor of the smallest number and largest number in nums.
The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.
'''
from math import gcd
class Solution:
def findGCD(self, nums: List[int]) -> int... |
b7f94cf0152b82e8af6ae23a8e783398623b09f5 | BinghuaDuan/Sensor_django | /Sensor/recognize.py | 786 | 3.515625 | 4 | print("---------------------------------")
print("the size of dataset(飞猪):658")
print("功能识别:")
print("#precision:0.935, #recalll:0.894")
print("变化类型分类:")
print("#precision:0.912, #recall:")
print("---------------------------------")
print("---------------------------------")
print("the size of dataset(养老):54"... |
8516c4be1fe769adf5a5c7cd025e5a5672df2d0e | eric496/leetcode.py | /binary_search/875.koko_eating_bananas.py | 1,346 | 3.6875 | 4 | """
Koko loves to eat bananas. There are N piles of bananas, the i-th pile has piles[i] bananas. The guards have gone and will come back in H hours.
Koko can decide her bananas-per-hour eating speed of K. Each hour, she chooses some pile of bananas, and eats K bananas from that pile. If the pile has less than K ban... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.