blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
3ec9e308d5718f980021cf4ba02a33d522e9c3a5 | alveraboquet/Class_Runtime_Terrors | /Students/Eric/Lab11/V2/changev2.py | 972 | 3.734375 | 4 | coins = {
'half-dollar': 50,
'quarter': 25,
'dime': 10,
'nickel': 5,
'penny': 1
}
def userinput():
while True:
x = input('Enter a dollar amount:')
try:
x = float(x)
return (x)
except:
print('\nInvaid input try again!')
def again():
while Tr... |
60f842b0afc1a457897a470053eeb291261192b7 | DuDaria/Homework_backend | /lesson_6/hw06_easy/hw06_easy_1.py | 928 | 4.375 | 4 | # Задача-1:
# Следующая программа написана верно, однако содержит места потенциальных ошибок.
# используя конструкцию try добавьте в код обработку соответствующих исключений.
# Пример.
# Исходная программа:
def avg(a, b):
"""Вернуть среднее геометрическое чисел 'a' и 'b'.
Параметры:
- a, b (int или fl... |
6e9d8f9cc5b0d1ecfdb9ff31d975378be3694419 | michlee1337/practice | /Python/heap.py | 2,146 | 3.671875 | 4 | # making a binary max heap
# math definition
# a[k] <= a[2*k+1]
# a[k] <= a[2*k+2]
#mapping heap parents to kids
# root node = 0
# parent = (index-2)/2
# left child = index*2 +1
# right child = index*2 + 2
def maxH(A):
sorted = []
while len(A) > 1: #while the list is not 1 item
for i in range(1,len(... |
cfed7d457133ce1fd3a7b014211ee82965595e6b | kpiszczek/wzorceuj | /cw8 - Mediator, Obserwator/cw8b.py | 4,188 | 3.625 | 4 | """
Treść zadania:
Przeprojektuj program z zadania 5a tak, zeby uzywal wzorca
Obserwator.
"""
class Observer:
"""
Observer
"""
def update(self, observable, arg=None):
pass
class ClickObserver(Observer):
"""
Concrete observer
"""
def __init__(self):
self._subject_... |
3ebbe46069799917a21c128faf015d7b773cf763 | 24emmory/Python-Crash-Course | /52moreconditionaltests.py | 1,061 | 4.03125 | 4 | people = "Troy"
if people == 'Troy':
print("It's a-me!")
user = 'karen'
new_user = 'Karen'
#print(user == new_user.lower())
#print(user)
#print(new_user.lower())
#testing to find issue. only used { } when replacing variable for value in strin
#g
if (user == new_user.lower()):
print("User name already taken... |
8cd30959172177ab8e8592367bc469167b8ccf74 | SVMarshall/programming-challanges | /leetcode/add_digits.py | 289 | 3.59375 | 4 | # https://leetcode.com/problems/add-digits/
class Solution(object):
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
num_str = str(num)
while len(num_str) > 1: num_str = str(sum(map(int,num_str)))
return int(num_str) |
0369a09248530357f8676b640290622ff5f06d05 | nabraham/advent-of-code | /2017/17_spinlock.py | 703 | 3.5625 | 4 | def main(step_size, n_steps):
buff = [0]
i = 0
for s in range(n_steps):
i = (i + step_size) % len(buff) + 1
buff = buff[:i] + [s+1] + buff[i:]
print(i-1, buff)
return buff
def solve(step_size, n_steps):
buff = main(step_size, n_steps)
i_find = buff.index(n_steps)
r... |
dd08a2b2fcc15aed69e229d90838813697732c5d | lzamparo/practice | /queue_exercises/myqueue.py | 925 | 3.9375 | 4 | from stack import Stack
from node import Node
class MyQueue(object):
''' A queue that is implemented via two stacks. Enqueue by pushing onto the new stack, dequeue by moving all data from new to old stack, and popping from the old stack '''
def __init__(self):
self.new_stack = Stack()
sel... |
6baf840099ce8ee01b3024aaaea10e8e494632ea | Kingomac/Ejercicios-Logica-Programacion | /Py5/Py5.py | 1,009 | 4.40625 | 4 | '''
LOS CUATRO PERROS. Tenemos cuatro perros: un galgo, un dogo, un alano y un podenco.
Éste último come más que el galgo; el alano come más que el galgo y menos que el dogo,
pero éste come más que el podenco. ¿Cuál de los cuatro será más barato de mantener?.
podenco
alano
dogo
galgo <--
'''
import random
intentos =... |
5099e55cbe057a996e8a49d2ce6bc175959795ff | iam-kelsey/CSC-202 | /Lab8/stack_array.py | 2,392 | 4.0625 | 4 | #Kelsey Nguyen
#CPE 202 Section 7
#Lab3
#Implements an efficient last-in first-out Abstract Data Type using a Python List
class StackArray:
#a capacity is an int
#an item is a list
#num_items are int
#Creates and empty stack with a capacity
def __init__(self, capacity):
self.capacity = capaci... |
21989b7c82a8b6f51d1c6b52511f66545fc793a3 | ran0527/Coding | /Lintcode/Fibonacci.py | 343 | 3.796875 | 4 | class Solution:
# @param n: an integer
# @return an integer f(n)
def fibonacci(self, n):
# write your code here
memo = {1:0, 2:1}
return self.helper(n, memo)
def helper(self, n, memo):
if not n in memo:
memo[n] = self.helper(n-1, memo)+self.helper(n-2, memo)
... |
a0a86a6c0772540e663e313ad7f7771bf3679a09 | Harry-Rogers/PythonNotesForProfessionals | /Chapter 9 Simple MathematicalOperators/9.3 Exponentiation.py | 692 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 27 16:23:01 2020
@author: Harry
"""
a,b,c =2,3,2
c = (a**b)
print(c)
print(pow(a,b))
print(pow(a,b,c))
#pow can use 3 arguments insterad of 2 with math.pow
import math
print(math.pow(a,b))
#math.pow uses the float instead of int
import operator
print(ope... |
ee10ca13d042ce0e368c079e6bdd980714fc1d89 | southpawgeek/perlweeklychallenge-club | /challenge-121/stuart-little/python/ch-2.py | 627 | 3.859375 | 4 | #!/usr/bin/env python
# run <script> <nr of cities>
from itertools import permutations
import random
import sys
def mkRMat(n):
return [[0 if j==i else random.randint(1,9) for j in range(1,n+1)] for i in range(1,n+1)]
def sayMat(m):
for i in m: print(i)
def pathCost(path,mat):
return sum([mat[path[i]][p... |
00ae0507eda5fba23569ef90b7f71cea924533f2 | tcoolb007/pitch | /cards.py | 1,958 | 3.734375 | 4 | import random
# cards = []
class Card:
def __init__(self, num, suit, value):
self.num = num
self.suit = suit
self.disp = num + suit
self.value = value
class Stack:
def __init__(self):
self.hand = []
def add_card(self,card):
self.hand.append(card)
... |
a47a885ac8ab4220141ff7eaefbb79b9aba337d7 | praveen-lokhande/python | /tut13.py | 299 | 3.890625 | 4 | list=[1,2,3,4]
print(5 not in list)
var1=int(input())
var2=7
if var1>var2:
print("greater")
else:
print("lesser")
#quize
print("enter the age:")
age=int(input())
if age>18:
print("yes you can drive")
elif age==18:
print("we can see about")
else:
print("no you cannot drive") |
c6a52a911cf1aa9355af7a7e90c97de8548df785 | mengtest/MengPyTest | /src/HelloWorld.py | 592 | 3.859375 | 4 | #!/bin/python
#coding=utf-8
'''
Created on 2014年4月23日
@author: Administrator
'''
print("测试中 !");
# a="xiao's book"
# b='dfasfasf'
# print a
# print b
# 有两点要注意:
# 1语句后面有:号
# 2子句要缩进
# a = 16;
# if a>10:
# print "a>=10"
# elif a > 15:
# print "a>=15"
# else:
# print "a<=XXX"
#内置函数range(起始值,终止值,步长)
#起始值缺省... |
e77e6302a9a53ab21af03d6c52fa319f21ca4ab4 | AsadullahGalib007/Python-Playground | /5. Regex/regex-1.py | 204 | 3.609375 | 4 | import re
x = 'My favourite 2 numbers are 21 and 92'
print('Using [0-9]+\t: ',re.findall('[0-9]+',x))
print('Using [0-9]\t: ',re.findall('[0-9]',x))
print('Using [AEIOU]+\t: ',re.findall('[AEIOU]+',x)) |
ad35c0601e64bbd33737a2cba0fae7336d790bc4 | MariaAfanaseva/Tasks_Python | /basic/task_5.py | 1,800 | 4.4375 | 4 | """
Task 5 *. Improve the program "Bank deposit".
The third argument to the function must be a fixed
monthly amount of deposit replenishment. Needed in main function
implement a nested function for calculating interest for the replenished amount.
We assume that the client deposits funds on the last day of each month,
... |
ba638eed09f7efd74d38771948d4f0e3cd9827ba | saulorodriguesm/ifsp-exercises | /Python/Lista 4/exer05.py | 231 | 3.78125 | 4 | telefone = input("Digite um telefone\n")
traco = False
for i in telefone:
if i == '-':
traco = True
if len(telefone) == 7 or len(telefone) == 8 and traco:
telefone = '3' + telefone
print("Seu telefone é",telefone) |
fe1295fb141419aeb2020a60aa5b6c4d260414e5 | lijun7141880/python-practice | /调试程序.py | 2,476 | 3.578125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# todo 1.读错误信息
# todo 例子
import random
a = 0
for i in range(5):
b = random.choice(range(5))
a += i / b
print a
# todo 这个程序中,i从0循环到4,每次循环中,b是0到4中的一个随机数。把i/b的结果累加到a上,最后输出结果。
# todo 运行这段程序,有时候会输出结果,有时候却跳出错误信息:
# todo Traceback (most recent call last):
# todo File "E:/ѧϰ... |
7f78871f43ba7183c97f92ec191f07f39a56ce56 | shakibul07/com411 | /basics/output/and_opertator.py | 349 | 4.3125 | 4 | #ask user what heared
print("What did i hear? (grr) ")
hear = input()
# ask user what did saw
print(" What did i see? (two red eyes) ")
saw = input()
#if and operator
if (hear == "grr") and (saw == "two red eyes"):
print("There is a scary creature. i should get out of here! ")
else:
print("I am a little scar... |
5ef16d15fe097becf384e05584caf4cb888f65d2 | tejaswinisail/HACKTOBER-2021_Questions | /Designer Door Mat/Solution.py | 396 | 3.5 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
n,m=[int(y) for y in input().split()]
halfnolines=(n-1)//2
t=halfnolines
for i in range(1,halfnolines+1):
b=2*i-1
print("-"*3*t+".|."*b+"-"*3*t)
t=t-1
#print("WELCOME")
a=(3*halfnolines*2+1-7)//2+1
print("-"*a+"WELCOME"+"-"*a)
t=1
for i i... |
67268df2b1c5d79c997bc0e1bde26ef089e43389 | t4k48n/fibonacci | /scratch.py | 903 | 4.21875 | 4 | def fibonacci(n):
""" フィボナッチ数列のn番目を計算する.
定義:
fibonacci(0) = 0
fibonacci(1) = 1
fibonacci(2) = fibonacci(n - 1) + fibonacci(n - 2)
ただし,n >=0
"""
if n in fibonacci.memo:
return fibonacci.memo[n]
if n <= 1:
fibonacci.memo[n] = n
retu... |
66c46e3f2d0f27e5715a692bafc5d42387ffa06c | swarnanjali/lakshmi5 | /armstronginterval.py | 205 | 3.6875 | 4 | lower=int(input())
upper=int(input())
for num in range (lower , upper+1):
order=len(str(num))
sum=0
temp=num
while temp >0:
digit=temp%10
sum+=digit**order
temp//=10
if num==sum:
print(num)
|
90233e801ae204d17c260c32f126d52529858083 | gaogep/LeetCode | /剑指offer/25.反转链表.py | 771 | 4.15625 | 4 | # 定义一个函数,输入一个链表的头结点
# 反转该链表并输出反转后链表的头结点
class listNode:
def __init__(self, Value, Next=None):
self.Value = Value
self.Next = Next
def insert(self, Value):
next_node = listNode(Value)
while self.Next:
self = self.Next
self.Next = next_node
head = listNode(... |
a707f864f2438ddcb06d4ee061e1dec10b1843cb | a-soliman/pythonData-structureAndAlgorithms | /sec-16-trees/bst.py | 2,191 | 3.828125 | 4 | class BST(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def isLeaf(self):
return self.left == None and self.right == None
def insert(self, value):
if value <= self.value:
... |
dd2bfc72270f64d15a0e4e5dca29336155e311c5 | VS-Datas/Python-project--Censor-email | /script.py | 2,116 | 3.953125 | 4 | # These are the emails you will be censoring. The open() function is opening the text file that the emails are contained in and the .read() method is allowing us to save their contexts to the following variables:
email_one = open("email_one.txt", "r").read()
email_two = open("email_two.txt", "r").read()
email_three = o... |
30981be2edcbd8057238d571a96059dad3269b7a | llGuy/tf-tests | /cnn.py | 3,968 | 3.625 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot = True)
learning_rate = 0.0001
epochs = 10
batch_size = 50
x = tf.placeholder(tf.float32, [None, 784])
# In order to do max pooling, we need to provide a 4D piece of data
# For... |
76a6dbfb4347cb351de1678716c6207a649f8c68 | xiaojinghu/Leetcode | /Leetcode0338_DP.py | 724 | 3.53125 | 4 | class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
if num == 0:
return [0]
if num == 1:
return [0,1]
if num == 2:
# res = [0, 1, 1]
return [0, 1, 1]
res = [0, 1, 1]... |
011229120417ee342dffad869466a079c080b23a | 6112/project-euler | /problems/072.py | 1,161 | 3.875 | 4 | # encoding=utf-8
## SOLVED 2014/12/01
## 303963552391
# Consider the fraction, n/d, where n and d are positive integers. If n<d and
# HCF(n,d)=1, it is called a reduced proper fraction.
# If we list the set of reduced proper fractions for d ≤ 8 in ascending order
# of size, we get:
# 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/... |
03d07d220cb9b202afb4c6984ea951ad5f882350 | avenortoz/EilerProject | /task20r.py | 430 | 3.75 | 4 | """n! означает n × (n − 1) × ... × 3 × 2 × 1
Например, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
и сумма цифр в числе 10! равна 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Найдите сумму цифр в числе 100!."""
def factorial(n):
if n == 0:
return 1
else:
return n*factorial(n-1)
sum = 0
for s in str(facto... |
9d54107f47925748445da9fc0df30583663d6975 | carlosfabioa/TDS_exercicios_logica_programacao | /6- Matriz com duas dimensoes/03exercicio.py | 382 | 4.09375 | 4 | '''
3. Ler 20 elementos para uma matriz qualquer, considerando que esta matriz tenha
o tamanho de 4 linhas por 5 colunas
'''
LINHAS = 4
COLUNAS= 5
a = []
#matriz A
print('Entre com os valores para matriz A')
for i in range(LINHAS):
linha = [] #cria alinha i
for j in range(COLUNAS):
linha.append(int(input('Entre c... |
5324a6a3f4be27ba560465a0e7ea05b7e473d6ba | Yanisiman/game_of_life | /py/gol_tests.py | 1,193 | 3.515625 | 4 | import unittest
import game_of_life
class TestGameOfLife(unittest.TestCase):
def test_zero_generations(self):
input_board_state = [
[1, 0, 0],
[0, 1, 1],
[1, 1, 0]
]
generation_count = 0
output_board_state = game_of_life.get_generation(
... |
a2febf3bd2e095e7781c0c712134855a617014b1 | jiangshen95/PasaPrepareRepo | /Leetcode100/leetcode100_python/SortList2.py | 1,699 | 3.828125 | 4 | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def sortList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
length = 0
cur = head
while cur:
length += 1
... |
f9b0cc2c56e5ec017251bceb4704aa0ac54ecc71 | IanCBrown/practice_questions | /first_non_repeating.py | 845 | 3.859375 | 4 |
def first_non_repeating_char(string):
char_map = {}
for s in string:
if s in char_map:
char_map[s] += 1
else:
char_map[s] = 1
for key, value in char_map.items():
if value == 1:
return key
return
def nsquared(string):
char_map = {... |
cdf264501ace4d2460a40955af00ea5bc3778ea6 | preeth96/pythontask | /pythontask1.py | 147 | 4.25 | 4 | from math import pi
rad=float(input("Input the radius of the circle:"))
print("The area of the circle with radius "+str(rad)+"is:"+str(pi*rad**2))
|
36ea2793ec46601fc949d1de75f6ff20b27fdea2 | kayvera/random_python_files | /pets.py | 1,531 | 3.953125 | 4 | #pets = ['dog','cat','dog','goldfish','cat','rabbit', 'cat']
#print(pets)
#while 'cat' in pets:
# pets.remove('cat')
#print(pets)
def describe_pet(pet_name, animal_type='dog'):
"""display information about a pet."""
print("\nI have a " + animal_type + '.')
print("My " + animal_type + "'s name is " + pet_... |
ba53b52dc3932039a995d94e745d9ae6503f50e1 | assafZaritskyLab/Intro_to_CS_SISE_2021-2022 | /week_8/FootballPlayer_ABC.py | 1,639 | 4.03125 | 4 | from abc import ABC, abstractmethod
class FootballPlayer(ABC):
def __init__(self, name, salary, performance):
self.name = name
self.salary = salary
self.performance = float(performance)
@abstractmethod
def play(self, num):
pass
def __repr__(self):
return f"Na... |
003a41a5c946c4ec266662be5df6e8db0ad2ec23 | blueteapot/programming-questions | /zrzahid/swap_alternate.py | 539 | 3.859375 | 4 | class Node:
def __init__(self, v):
self.v = v
self.next = None
def set_next(node):
self.next = node
def swap_alternate(head):
if head is None:
return
new_head = None
prev = head
current = head.next
while current != None and current.next != None:
... |
870e72532144fa67daa37639f0d2313c1bcfc988 | tiancao9/LeetCode-python | /139-Word_Break.py | 982 | 3.984375 | 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. You may assume the dictionary does not contain duplicate words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Re... |
c025ca00b1e848f99296aee6861ceb6dc67a4b30 | paulbrennan95/DavidsonBioInformatics | /BioInformatics/final.py | 8,313 | 3.84375 | 4 | '''
Bioinformatics Fall 2017 Take-Home Final
Author: Paul Brennan
Time spent: 8 hours
'''
GAP = -4
def pwn_scan(pwmdict, dna):
''' Determines presence of motifs in dna sequences given a certain motifs
defined by DNA position weight matrix (PWM) dictionary.
Args:
pwmdict - di... |
433785a21b76f9eaf8e0b48f0e254444ec03e5b1 | damian1421/python | /cctv-storage-calculator.py | 2,865 | 3.546875 | 4 | #Description: Utility to caculate storage needed for CCTV storage.
#Author: l0gg3r
#Date: 2021-08-16
import os
clear = lambda: os.system('clear') #Define 'clear' command
try:
nl = '\n' #Variable for new lines
clear() #Clear screen
nl
print ("CCTV Storage Calculator") #Greetings
#Complete with the... |
e7b138f3d57799214252b27184e159fbdb945edd | deepdatanalytics/ASSIGNMENTS | /01_Assigments/Assig-2(Comf.Words).py | 244 | 3.96875 | 4 | left = {"a", "q", "z", "w", "s", "x", "v", "t", "r", "d", "g", "f", "c"}
right = {"y", "n", "m", "j", "h", "b", "k", "u", "o", "l", "p"}
word = set(input("Wright a word to check if comfortable : "))
print(bool(word-left) and bool(word-right)) |
216ac6792a6f2a33b2ef2c55447da2a38b4482ea | Kartavya-verma/Python-Programming | /22.py | 135 | 4.03125 | 4 | #22.Write a python program to print even numbers present in list.
l=[1,2,3,4,5,6,7,8,9,10]
for i in l:
if i%2==0:
print(i)
|
82058a6b2624cbbe1b8a4ce2605d1ff12cc1ffae | paulorobertocruz/trabalhos_pi_uft | /bimestre_1/dist.py | 852 | 3.5 | 4 | from math import sqrt
def euclidian(a, b):
return sqrt( (a[0] - b[0])**2 + (a[1] - b[1])**2 )
def d4(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def d8(a, b):
return max(abs(a[0] - b[0]), abs(a[1] - b[1]))
if __name__ == "__main__":
import sys
if len(sys.argv) < 4:
print("poucos a... |
e6edf7d2b442ad0c3194dce0f46b30df2ac1d6de | jcbroe/showcase | /Algorithms/Python/MergeSort.py | 845 | 4.3125 | 4 | from heapq import merge
def merge_sort(somelist):
# if size of list is 1 or smaller, return the list
if len(somelist) <= 1:
return somelist
# find the middle, use floor in Python to return int
middle = len(somelist) // 2
# split the original into 2 lists/arrays, left from beginning to mid... |
107cc9ee6e4212757f20acfc230a4e542c1d3ed4 | rafaelperazzo/programacao-web | /moodledata/vpl_data/412/usersdata/331/79874/submittedfiles/av1_programa1.py | 172 | 4.15625 | 4 | # -*- coding: utf-8 -*-
x = int(input('insira um numero inteiro aqui:'))
if x>0:
print('positivo')
elif x<0:
print('negativo')
else x=0:
print('nulo')
|
299f05e012e0d1ab5a7900da14204bac1744474b | sunivers/Study__Algorithm | /Section_01/8. 뒤집은 소수/aa.py | 508 | 3.53125 | 4 | import sys
sys.stdin = open('in5.txt', 'rt')
n = int(input())
a = list(map(int, input().split()))
def isPrime(x):
if x == 1:
return False
# 소수 파악하려면 그 수의 절반까지만 계산해보면 된다.
for i in range(2, x // 2 + 1):
if x % i == 0:
return False
else:
return True
def reverse(x):
res=0
while x > 0:
t... |
ec3d45523a5ffdf7d9e88abca0496af068701321 | GergelyM/ClassroomHelper | /loginHandler.py | 4,945 | 3.578125 | 4 | ### Author: Salik, Gary
### Trasferred from Pulled project file by Gary
# it would be a bit more efficient if you would use a single data query for the user by login input name
# in that way the code could decide if the input name exists in the DB,
# and if it does, then that the stored password is equal to the u... |
e15c383569d58f12be5e5b044893d17a78ca6f4d | SmischenkoB/campus_2018_python | /Kateryna_Liukina/4/4.1 Dungeon Game.py | 1,359 | 4.0625 | 4 | import Map_generator
import Warning_generator
import math
def dungeon_game():
"""
Function launch the dungeon game
Returns:
none
"""
size_of_map = int(input("Enter size of map"))
game_map = Map_generator.generate_map([size_of_map] * 2, 0.1, 0.05)
player_position = Map_generator.ge... |
d5c5fd1db9bcc6cacaf97d29f57af976c93d0262 | FranckNdame/leetcode | /problems/437. Path Sum III/solution.py | 806 | 3.78125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> int:
self.result = 0
def depthFirstSearch(node, target):
if ... |
ae4a6227d86e3ff6482e862136c8c01565a81b95 | cmnaveen/study_cmp | /python/list.py | 422 | 4 | 4 | letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print letters
print "list len"
print len(letters)
print "replace some values"
letters[2:5] = ['C', 'D', 'E']
print letters
# now remove them
print "now remove them"
letters[2:5] = []
print letters
print "clear the list by replacing all the elements with an empty list"
lette... |
d4b0a8391cf09f9725a4f0b363e73f9c00e2b526 | iopasd753951/Learn_Python | /ㅎ문제풀이/N-gram만들기(hard)_11월_5일.py | 233 | 3.59375 | 4 | limit = int(input())
text = input()
word = text.split(' ')
if len(word) < limit:
print("wrong")
else :
for i in range(len(a) - (n - 1)):
for j in range(len(n)):
print(word[i + j], end='')
print() |
6fbee22c3d7d87144f2da036d0e47f7706fcac80 | mjbijitha/variables | /tuple.py | 953 | 4.15625 | 4 | thistuple=("apple","banana","cherry")
print(thistuple)
#tuple allows duplicate value
thistuple=("apple","banana","cherry","apple","kiwi")
print(thistuple)
print(len(thistuple))
#to create tuple with one item ,put comma
thistuple=("apple",)
print(type(thistuple))
#accessing element
thistuple=("apple","banana","cherry"... |
bff1341844983ffa1a4f4d88ef0180e57ef3f6f7 | git4rajesh/python-learnings | /Closures/ex2.py | 625 | 4.21875 | 4 | def print_msg(msg):
# This is the outer enclosing function
def printer():
# This is the nested function
print(msg)
return printer # this got changed
# Now let's try calling this function.
# Output: Hello
another = print_msg("Hello")
another()
# The print_msg() function was called wit... |
7572cd3122308f60c22eb6a0faab0f59e38ca637 | RasulKg/intro2python | /sds.py | 287 | 4 | 4 | print "Please enter two numbers"
number=raw_input(">")
print
number=raw_input("<")
age=int('number 1')-int('number 2')
if number 1 < number 2
print "the amount of lead"
if number 1 > namber 2
print "the amount of lead"
if number 1 * number 2
print "the amount of lead"
|
64e1a254ef60662c23b96d9db6b6b69cbba46331 | samhassan20/Algorithms | /Sorting_Algo_Compare/bubble.py | 1,247 | 3.75 | 4 | import random, datetime
def bubblesort(num_list):
for i in range(len(num_list)):
for j in range(len(num_list) - 1, i, -1):
if (num_list[j] < num_list[j - 1]):
swap(num_list, j, j - 1)
def swap(A, x, y):
tmp = A[x]
A[x] = A[y]
A[y] = tmp
def perforamnce_bubblesort(... |
e28f0d7ca7156339470072a839a88353aba28b55 | mycode1947/mypythonproject | /classes/mycar.py | 651 | 3.828125 | 4 | class mycar(object):
def __init__(self,car):
self.car=car
def cartype(self,owner):
if self.car=="swift":
print "it is %s's maruti suzuki" %(owner)
elif self.car=="city":
print "it is naveen's honda city"
elif self.car=="corolla":
print "it ia toyota"
elif self.car=="i20":
print "it is a Hyundai"... |
9fb6ac0b87a3678631bd13d9f4e647efbf6bb197 | hanrick2000/LeetcodePy | /leetcode/interval/interval.py | 387 | 3.875 | 4 | # Definition for an interval.
class Interval(object):
def __init__(self, s=0, e=0):
self.start = s
self.end = e
def __eq__(self, other):
if not isinstance(other, Interval):
return NotImplemented
return self.start == other.start and self.end == other.end
def __re... |
eba19dc31cc924238ed3b825bfdae702863f69c6 | Abdelhamid-bouzid/problem-Sovling- | /Medium/isSubsequence.py | 1,012 | 3.59375 | 4 | '''
392. Is Subsequence
Easy
3124
253
Add to List
Share
Given two strings s and t, return true if s is a subsequence of t, or false otherwise.
A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions... |
0e286006167f898a740efb98d0c82b59135811fa | AnthonyFloyd/2017-AdventOfCode-Python | /day10.py | 5,373 | 3.671875 | 4 | '''
Advent of Code 2017
Day 10: Knot Hash
'''
TEST_INPUT = '3,4,1,5'
TEST_SIZE = 5
NROUNDS = 64
DAY10_INPUT = '225,171,131,2,35,5,0,13,1,246,54,97,255,98,254,110'
DAY10_SIZE = 256
def computeHashCheck(ringInputString, ringSize):
"""Calculate the knot hash check.
Args:
ringInputString (str): The li... |
41d4ad480d2931e557c50659febc86a9d67fc234 | RubeusH/Python_Learning | /Chapter-04/Algorithm-Workbench/question-09.py | 431 | 4.3125 | 4 | #This program solves the following problem:
#Write code that prompts the user to enter a number in the range of 1 through 100 and validates
#the input.
user_input = float(input("Please enter a number in the range of 1 to 100 inclusive: "))
while user_input < 1 or user_input > 100:
print("The number is out the range... |
6eb10e51e822594bf627e840e930f396aac94237 | floppp/programming_challenges | /project_euler/001-050/49.py | 2,490 | 3.5 | 4 | # The arithmetic sequence, 1487, 4817, 8147, in which each of the
# terms increases by 3330, is unusual in two ways:
# (i) each of the three terms are prime, and,
# (ii) each of the 4-digit numbers are permutations
# of one another.
#
# There are no arithmetic sequences made up of three 1-, 2-,
# or 3-... |
9fb73e39aaebe86aca0c3dfe48f284cfe80507d5 | VoidArchive/Code-War-Kata-Traning | /Code War/Bit Counting.py | 558 | 4.09375 | 4 | # Write a function that takes an integer as input, and returns the number of bits that are equal
# to one in the binary representation of that number. You can guarantee that input is non-negative.
# Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
def count_... |
59679459ca7557f7954531af00ee86acba3d1dcd | GuoQin8284/PythonCode | /20190426/test_20190426_no3.py | 182 | 3.984375 | 4 | # 使用while循环输出九九乘法表
i=1
while i<10:
a =1
while a<=i:
b =i*a
print("%d=%d*%d"%(b,i,a),end="\t")
a += 1
print("\n")
i += 1 |
7d18e661c0b677254baf29f39ffcf7fe3e0ab13e | sonoprob/0x56 | /bot/py/r3340/cervelle.py | 3,309 | 3.609375 | 4 | # cervelle is a class that contains various string methods used by r3340
# Usage:
#seq = cervelle("!___!---!___!--##")
#serviette = {'!': "!_!", 'x': "xxxx", '_': "sdfghj"}
#seq.debains(serviette)
#print seq.message
import random
class cervelle:
def __init__(self, message):
self.message = message
... |
c8aa7c9b52cd7822dfc17e8ffa60ca3a9bda14a3 | VictorTadema/How_to_think_project_Victor | /How to think/Week 3/Exercise 7.py | 165 | 3.609375 | 4 | response1 = input("Length first side")
response2 = input("Length second side")
r1 = float(response1)
r2 = float(response2)
length = (r1*r1+r2*r2)**0.5
print(length) |
09b576297ead08259ec372bed04d7101c1b52b93 | dgoscn/PyCrashCourse | /Chapter1e2/name.py | 633 | 3.84375 | 4 | name = "ada lovelace"
print(name.title())
#print(name.upper())
#print(name.lower())
#first_name = "ada"
#last_name = "lovelace"
#full_name = first_name + " " + last_name
#print(full_name)
#print("Hello, " + first_name.title() + "!")
#message = ("Hello, " + full_name.title() + "!")
#print(message)
#favorite_language... |
9673f14a8eba3606e0277c227b75568c5f9a2b0c | wkwkgg/atcoder | /abc/problems080/075/c.py | 1,085 | 3.5 | 4 | class UnionFind:
def __init__(self, n: int):
self.__n = n
self.__par = list(range(self.__n))
self.__size = [1 for _ in range(self.__n)]
def root(self, x: int) -> int:
if self.__par[x] == x:
return x
self.__par[x] = self.root(self.__par[x])
return self... |
dde77a93dffd16646b6f99d8cd34340ef38718eb | aongenae/leetcode | /src/merge_intervals.py | 1,646 | 3.859375 | 4 | #!/usr/bin/env python3
################################################################################
#
# Filename: merge_intervals.py
#
# Author: Arnaud Ongenae
#
# Leetcode.com: problem #56
#
# Problem description:
# https://leetcode.com/problems/merge-intervals/description/
#
... |
36e61f46bb92811c96ac0634a43cc632f4983a3c | rknyx/algorithms_advanced | /gaussian_elimination.py | 2,100 | 3.625 | 4 | #python3
from sys import stdin
def read_real_input():
return stdin.readlines()
def test_input_1():
return """4
1 0 0 0 5
0 1 0 0 6
0 0 0 1 6
0 0 1 0 7"""
def format_float(fl):
return "{0:.3f}".format(fl)
def print_array(data):
print("\n".join([" ".join(map(format_float, data[i])) for i in range... |
5181df2b254ba2f747efc27cd0aed4b4526991e3 | Mdcrab02/Python | /Scripts/Rabbits & Foxes.py | 3,718 | 4.1875 | 4 | import random
import pylab
# Global Variables
#max/current rabbit population, current fox population
MAXRABBITPOP = 1000
CURRENTRABBITPOP = 500
CURRENTFOXPOP = 30
def rabbitGrowth():
"""
rabbitGrowth is called once at the beginning of each time step.
It makes use of the global variables: CURRENTRABBITPO... |
e0487f3862f3e919ba2d36db136ede9801241820 | jaredsanchez/nba_stats | /parseJSON.py | 6,441 | 3.703125 | 4 | import os
import sys
import json
'''
This is a script I wrote for a project I have been working on to gather and visualize NBA statistics.
This code opens up all the files in a directory related to given season, all of which are gathered in a different script and stored in JSON format as .txt files.
Each file contain... |
82924abf7be87546e41f887713cd55ec1c43357a | sandeepshiven/python-practice | /function_exercises/Given a list of ints, return True if the array contains a 3 next to a 3 somewhere/my_logic.py | 361 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 23 20:05:53 2019
@author: sandeep
"""
def has_33(nums):
for i in range(len(nums)-1):
if (nums[i]==3) and (nums[i+1] == 3):
return True
return False
# Check
print(has_33([1, 3, 3]))
# Check
print(has_33([1, 3, ... |
05e354f984a43fe3ae12a80bea0d5970fef6cbe7 | jagadeesh-b-ch/spoj | /PrimeGenerator.py | 1,216 | 3.828125 | 4 | # Using Segmented Sieve approach
from math import sqrt, floor
def get_primes_till_a_number(n):
numbers = [True] * (n-1)
for num in range(2, n+1):
if numbers[num-2]:
for num2 in range(num*2, n+1, num):
numbers[num2-2] = False
primes_of_sqrt = []
index = 2
for num... |
b9976a068edf0efcaa50df14fd30b393d8b105e7 | ylqm666/AtCoder | /144/A.py | 106 | 3.515625 | 4 | a,b = map(int,input().split())
if a > 9 or b > 9:
print("-1")
else:
num = a*b
print(int(num)) |
85f18e7aeebe609cadcc556a4f4d0f5943ca9cdb | UdhaikumarMohan/Strings-and-Pattern | /freq of char/test_freq.py | 350 | 3.75 | 4 | # Test case for finding the frequency of the character
def test_canassertTrue():
assert True
import freq_of_char
def test_freq():
#Arrange:
String = 'udhaikumar'
expected = {'u':2,'d':1,'h':1,'a':2,'i':1,'k':1,'m':1,'r':1}
#Actual:
actual = freq_of_char.freq_char(String)
#Assert:
... |
b61f3453b36d5343dae75697023a463ae87833dd | pragatirahul123/Interview | /Loop_Question3.py | 121 | 3.828125 | 4 | user = input("enter a number:")
index = len(user)-1
while index>=0:
print(user[index],end="")
index=index-1
|
54f6b5b67e8b60f7dad3b3df6fa90c661cd5a4f1 | kiljoy001/supplementary_files | /src/py220_supplemental/lessons/lesson09/extras/warnings.py | 499 | 3.78125 | 4 | # Robust code
# python -W module.py - use in tests
import warnings
class Car:
def turn_left(self):
warnings.warn("turn_left is deprecated; use turn instead", DeprecationWarning)
self.turn(direction="left")
def turn(self, direction):
"""Turn the car in some direction.
:param d... |
c3247a8417cde1ff814bda09ee92aa2b45cecfd5 | Vinay-Harke/codemonk-solutions | /Monk and Suffix Sort.py | 183 | 3.84375 | 4 | # Write your code here
s1,pos=input().split()
pos = int(pos)
all_suffix = []
for i in range(len(s1)-1,-1,-1):
all_suffix.append(s1[i:])
all_suffix.sort()
print(all_suffix[pos-1])
|
618b031ec7bc4728715a312a8762adfeb1ee86b4 | kolyasalubov/Lv-585.1.PythonCore | /HW7/chyhut/squarefigures.py | 467 | 3.953125 | 4 | import math
def square_of_rectangle():
a = float(input("Input width: "))
b = float(input("Input height: "))
return "square of rectangle is = {}".format(a*b)
def square_of_triangle():
a = float(input("Input basis: "))
h = float(input("Input height: "))
return "square of triangle is = {}".format... |
48c1e094bf0809918a35955de1c3d02d984e6bed | maksimok93/Dp-189 | /python06/python06.py | 1,157 | 3.84375 | 4 | """This program demonstrates the work of timer decorator that records time even when an error occurs."""
import functools
import time
def timer(func):
"""Print the runtime of the decorated function."""
@functools.wraps(func)
def wrapper_timer(*args, **kwargs):
start_time = time.perf_counter()
... |
1d468106b0416e4cddef1e963c05fd7f403e97e3 | khaki4/basic_algorithm | /problem/출력문/1015.py | 413 | 3.953125 | 4 | # 실수(float) 1개를 입력받아 저장한 후,
# 저장되어 있는 값을 소수점 셋 째 자리에서 반올림하여
# 소수점 이하 둘 째 자리까지 출력하시오.
# 참고
# %.3f 와 같은 형식으로 지정하면,
# 소수점 이하 넷 째 자리에서 반올림하여 소수점 이하 셋 째 자리까지 출력하라는 의미이다.
f = float(input())
print("{0:0.2f}".format(f)); |
65b9287db33628d6f87add3bdfd8b51d92b874e4 | brodiewindle/Practicals | /Prac_01/shop_calculator.py | 876 | 4.125 | 4 | """this is code that makes a shop calculator.
the user will assign a number of items to which
they will then be prompted to insert the price of each one """
# number_of_items = int(input("How many items do you have? "))
# array = []
# for i in range(0, number_of_items):
# item_price = float(input("What is the pr... |
1d6b480f66d04e0616189243a3f62133d86c7740 | kokospapa8/algorithm-training | /baekjoon/2562.py | 131 | 3.703125 | 4 | i = 1
maxi = 0
max = 0
for _ in range(9):
j = int(input())
if j > max:
max = j
maxi = i
i+=1
print(max)
print(maxi)
|
a5a4c5e717594f50af655eb51f2d1636476ef927 | litvinovserge/WebAcademy | /HomeWork_06/AssertTests/assert_Task_05.py | 583 | 4.28125 | 4 | """
Найти сумму и произведение элементов одномерного числового списка.
"""
def calc_sum(some_list):
summ = 0
for i in range(len(some_list)):
summ += some_list[i]
return summ
def calc_multp(some_list):
multp = 1
for i in range(len(some_list)):
multp *= some_list[i]
return mult... |
bb7a3937421548080c6ae09a6c624df9515f2a9e | findingxvlasova/my-works | /game.py | 515 | 4.0625 | 4 | word = input("Enter your word: ")
letters = list(word)
life = 3
while True:
letter = input("Guess the word (enter letter by letter, u have only 3 lifes): ")
if letter in letters:
print(letter," is in this word! ")
letters.remove(letter)
if len(letters) == 0 and life >= 0:
p... |
762e85dd49a5e09bb0a66be937989a45f5851a50 | alimirferdos/pacman_ai | /layout.py | 2,008 | 3.8125 | 4 | class Layout:
"""
A Layout manages the static information about the game board.
"""
def __init__(self, layout_text):
self.width = len(layout_text)
self.height = len(layout_text[0])
self.walls = [[False for y in range(self.width)] for x in range(self.height)]
self.food = [0, ... |
4cea38769605ad41d85ae4eee478c831a6014229 | rickarter/snake | /snake.py | 1,902 | 3.703125 | 4 | import pygame
class Snake:
def __init__(self):
self.head = [10, 10]
self.speed = 7
self.body = [[10, 10]]
self.width = 10
self.height = 10
def move(self, control):
if control.flag_direction == 'RIGHT':
self.head[0] += self.speed
elif control... |
86512d0b33b8defdf85ba1874322cac89a4609c8 | rarose67/Python-practice- | /Studio/Wagon Wheel.py | 3,150 | 4.46875 | 4 | import turtle
import sys
sys.setExecutionLimit(70000)
def draw_square(t, size):
for i in range(4):
t.forward(size)
t.right(90)
for i in range(4):
t.forward(size)
t.left(90)
for i in range(4):
t.backward(size)
t.right(90)
for i in range(4):
t.b... |
0c5448eefd80fc9f8f424cdf532300a15007199d | veratsurkis/infa_2020_postnikov | /lab2_1/ex13.py | 805 | 3.734375 | 4 | import turtle as tr
import numpy as np
tr.shape("turtle")
def circle(x,y,r):
tr.penup()
tr.goto(x+r,y)
tr.pendown()
for i in range(361):
tr.goto(x+r*np.cos(i*np.pi/180),y+r*np.sin(i*np.pi/180))
def arc(x,y,r,angle_1,angle_2):
tr.penup()
tr.goto(x+r*np.cos(angle_1*np.pi/180),y+r*np.sin(... |
21af070953137b0da58e884f3a977186348c50e2 | mollinaca/ac | /code/test/bit全探索/1.py | 947 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# https://qiita.com/gogotealove/items/11f9e83218926211083a
# みかん(100円)りんご(200円)ぶどう(300円)がそれぞれ1つずつ果物屋さんにありました。
# 財布の中には300円ありますが、考え得るすべての買い物パターンを列挙しなさい。
money = 300
item = (("みかん", 100), ("りんご", 200), ("ぶどう", 300))
n = len(item)
#print (item)
for i in range(2 ** n):
# ... |
1ce746e1986af1e68fa3138f84d8041e7430eafe | Naveensng20/bruce | /armstrongbwinterval.py | 241 | 3.515625 | 4 | # your code goes here
a=raw_input()
nk=a.split()
num1=int(nk[0])
num2=int(nk[1])
for num in range(num1,num2):
pow=len(str(num))
sum=0
temp=num
while(temp>0):
sum=sum+((temp%10)**pow)
temp=temp//10
if(sum==num):
print(num),
|
d463db11b39cac9bca123c6542f5035c5513c303 | aarushirai1997/pythonlearn | /averageofn.py | 84 | 3.609375 | 4 | a=int(input())
b=0
for i in range(a):
c=int(input())
b+=c
b=b/a
print (b)
|
46e085e3662b510b0cea843366ce638f25be8bad | gabriellaec/desoft-analise-exercicios | /backup/user_269/ch22_2020_03_03_23_47_39_467978.py | 147 | 3.515625 | 4 | a=int(input("Quantos cigarros voce fuma por dia "))
b=int(input("Ha quantos anos voce fuma "))
c=a*365*b
print("Voce perdeu %s minutos de vida"%c)
|
528321ba817f7bc450fbc816f048a6da32c5de63 | wzqwsrf/python-practice | /Working-with-Data/19.py | 1,935 | 4.28125 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Wangzhenqing <wangzhenqing1008@163.com>
# Date: 2014年11月29日23:33:02
"""
Problem 19: Implement unix commands head and tail.
The head and tail commands take a file as argument
and prints its first and last 10 lines of the file respectively.
"""
import sys
def h... |
0ce160cedb2e872a60502b6f0350d3d24447b287 | tenqaz/crazy_arithmetic | /leetcode/剑指offer/剑指 Offer 26. 树的子结构.py | 480 | 3.59375 | 4 | """
@author: zwf
@contact: zhengwenfeng37@gmail.com
@time: 2023/6/24 19:21
@desc:
https://leetcode.cn/problems/shu-de-zi-jie-gou-lcof/?envType=study-plan-v2&envId=coding-interviews
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution... |
d7c88711c36246e3ab6fc657b894ef447085114b | jerbob/python-challenges | /challenges/medium/word_count/__init__.py | 319 | 4 | 4 | # coding=utf-8
__author__ = "Gareth Coles"
"""
Write a program that takes a filename as a command-line argument, counts how many times each word appears in the file,
and prints the word that appears the most (and the number of times it appears).
"""
if __name__ == "__main__":
print("Your answer should be printe... |
3a174c92caac4be7b630a1a4c0464257b71c942c | ssmi4th98/AdvFunctions | /Lambda_Define.py | 649 | 4.1875 | 4 | def square(x):
return x ** 2
print(square(3))
print(square)
#anonymous function = lambda
# cannot have complex function or if and or args.
#lambda functions can be used in the same way as any other function
cube = lambda x: x * x * x
print(cube(3))
add = lambda x,y: x + y
sub = lambda x,y: x - y
mult = lam... |
3efce4e94e10e146bc85ea7f34194ade136f3ce9 | tanmayi-exe/Lucky-number-generator | /d3.py | 1,279 | 3.796875 | 4 | from tkinter import *
win = Tk() # ...generates a window...
win.title("Lotto Number Generator")
#win.geometry("500x500")
win.resizable(False,False)
#-----Widget Declaration-----# ...With Labels and Buttons
Labl = [Label(win),Label(win),Label(win),Label(win),Label(win),Label(win),Label(win),Label(win),Label(w... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.