blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
7c2b254aa44385702cfe828b4d0f1bb68348575b | vik-tort/hillel | /Homework_/Task_30.py | 443 | 3.84375 | 4 | str=input("Введите строку, которую хотите зашифровать")
tab_of_encryption = ["a",'b',"c","d","e","f","g","h","i","j","k","l",'m','n','o','p','q','r','s','t','u','v','w','x','y','z']
str_2 = ""
for i in str:
idx_1 = str.find(i)
idxPlus5 = idx_1 + 5
elem_of_tab = tab_of_encryption[idxPlus5%len(tab_of_encrypt... |
7cbcc62a8da35aca576632a03156316f8f8ccab8 | vik-tort/hillel | /Homework_/Task_12.py | 667 | 4.09375 | 4 | #1попытка
# def sum_of_3_numbers (number):
# f_number = number.find(0)
# s_number = number.find(1)
# th_number = number.find(2)
# result = int(f_number)+ int(s_number) + int(th_number)
# return result
#2попытка
# f_number = number[0]
# s_number = number[0:1]
# th_number = number[1:2]
# sum_of_numbe... |
d784c7310908825f371cd1e33c3eb64557b2aa0e | vik-tort/hillel | /Test/Task_7(TEST).py | 256 | 3.875 | 4 | n=10
fibonnachi=[1,1,2]
for num in range(3,n):
fibonnachi.append(fibonnachi[num-1]+fibonnachi[num-2])
print(fibonnachi)
sum_of_fib=sum(fibonnachi)
print("Сумма первых 10 чисел ряда Фибоначчи равна %d" % (sum_of_fib)) |
d8d06bed1a5b93e9a5bdd3461d3d8cc9987fad3d | vik-tort/hillel | /Homework_/1-6.py | 532 | 3.59375 | 4 | import math
a=43.2
b=25
c=42
result_1= a + b * (c/2)
print("Answer of 1 task is -","%.2f"%result_1)
result_2 = ((a**2)+(b**2))%2
print("Answer of 2 task is -","%.2f"%result_2)
result_3= (a+b)/ 12 * c % 4 + b
print("Answer of 3 task is -","%.2f"%result_3)
result_4= (a - b * c ) / ( a + b ) % c
print("Answer of 4 task i... |
958ae8eece0cea36cd00c26e92404a7c2ce3a5e8 | vik-tort/hillel | /Homework_/Task_29.py | 638 | 3.75 | 4 | import random
lst = []
while len(lst)<=11 :
num= random.randint (-1,1)
lst.append(num)
print(lst)
zeros = lst.count(0)
ones = lst.count(1)
minus_ones = lst.count(-1)
if zeros==ones or zeros==minus_ones or minus_ones==ones:
print('')
else:
if zeros == max(zeros,ones,minus_ones):
print("Наиболее ... |
0e5d96b0ff3047d96af4b517712fd29838fc64af | Abhimanyu9539/Customer-Complaint-Classification-using-NLP-and-deployment-using-Flask | /complain_classification_ML_model.py | 4,219 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 11 18:11:09 2020
@author: ACER
Purporse:
1.To train a ML Model which will classify the product departments.
"""
### Customer Classification using Complaints Database
# Creating a ML Model to classify the customers in to different Departments of Complain... |
96d90ae34f7e20c90adcc4637b04bdd885aa6865 | HimanshuKanojiya/Codewar-Challenges | /Disemvowel Trolls.py | 427 | 4.28125 | 4 | def disemvowel(string):
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
for items in vowels:
if items in string:
cur = string.replace(items,"") #it will replace the vowel with blank
string = cur #after completing the operation, it will update the current string
else... |
7d1547f6d3d93fc3253321c5edd6509165493910 | JCarter111/Python-kata-practice | /Square_digits.py | 2,368 | 4.46875 | 4 | # Kata practice from codewars
# https://www.codewars.com/kata/546e2562b03326a88e000020/train/python
# Welcome. In this kata, you are asked to square every digit of a number.
# For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1.
# Note: The function accepts an integer a... |
162bd224c8a098bb60f34a75f36b7c5b7dd93579 | Zadibinnyi/oop | /fib.py | 490 | 3.640625 | 4 | import time
def decorator(func):
def wrapper(arg):
start = time.time()
b = func(arg)
stop = time.time()
result = stop - start
print (f'Elapsed time: {result}')
return b
return wrapper
@decorator
def fib (n: int) -> int:
a = 0
b = 1
... |
014c2005dcfbf3cc083ed6f7269bdc5fc1fb8961 | kodeid-resources/python-text-rpg | /runner.py | 711 | 3.5 | 4 | from characters.player import Player, Commands
def main():
p = Player()
p.name = input("What is your character's name? ")
print("(type help to get a list of actions) \n")
print("{} enter a dark cave, searching for an adventure.".format(p.name))
while(p.health > 0):
line = input(">> ")
... |
dbeaab4352a5cf9f75c963b50f23830453c633ff | ulises-8/Python | /06_test.py | 8,823 | 3.6875 | 4 | """
CS3B, Assignment #6, Complex Numbers
Ulises Marian
testing
"""
import unittest
import copy
from assignment06 import *
class ComplexTestCase(unittest.TestCase):
def setUp(self):
self.c1 = Complex(1, 2)
self.c2 = Complex(3, 4)
def testAddComplex(self):
"""Test addition between 2 C... |
464228896868afabaa7203087a211c6ee14cc0c1 | ulises-8/Python | /09_gameboard(part3_AI).py | 14,933 | 3.96875 | 4 | """
CS3B, Assignment #9, AI tic-tac-toe player
Ulises Marian
"""
import copy
import random
import time
from abc import ABC, abstractmethod
from enum import Enum
# GameBoardPlayer probably should be an inner class of GameBoard, but because
# GameBoard class is introduced later (after studying inheritance/ABC),
# Game... |
116b62bea985148eca679c2181faba7f38566912 | ulises-8/Python | /16_MinHeap.py | 2,282 | 3.625 | 4 | """
CS3C, Assignment #6
A few min heap coding exercises
Ulises Marian
"""
from minheap import *
class MedianHeap(MinHeap):
def remove(self):
if len(self) == 0:
raise IndexError("Remove from empty min heap")
return_data = self._heap[len(self)//2]
# Always remove data at the end... |
36ffa55561554d79847629645c3978aefce59ff8 | anirvan90/tensorflow-work | /lesson1.py | 317 | 3.59375 | 4 | import numpy as np
scores = np.array([3.0, 1.0, 0.2])
def softmax(x):
"""
Compute the softmax values for x
"""
return np.exp(x) / np.sum(np.exp(x), axis=0)
print(softmax(scores))
print('\n')
print(softmax(scores / 10))
bill = 1e+9
for i in range(1000000):
bill = bill + 1e-6
print(bill - 1e+9)
|
952778fc235c524214badea27d66d14f08075c31 | AndrewVasilenko/Lab1_Python_ | /Calc.py | 931 | 3.984375 | 4 | from sys import exit
def getNum():
while True:
try:
num = int(input("Запишіть число: "))
return num
except:
print("Хибне число, повторіть")
def getOperation():
while True:
try:
operation = input("Впишіть операцію: ")
if operation in ("+", "-", "*", "/", "%", "//"):
r... |
5280f17272181f7eb09eef6b47e975e8bb8b7063 | katgzco/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/tests/6-max_integer_test.py | 860 | 4.15625 | 4 | #!/usr/bin/python3
"""
Unittest for max_integer([..])
"""
import unittest
max_integer = __import__('6-max_integer').max_integer
"""
max_integer return the max integer of a list
"""
class TestMaxInteger(unittest.TestCase):
def test_integer(self):
"Test numbers cases"
self.assertEqual(max... |
6225fffb43fcb4726853c4aa02dd242e41201b68 | katgzco/holbertonschool-higher_level_programming | /0x03-python-data_structures/5-no_c.py | 258 | 3.90625 | 4 | #!/usr/bin/python3
def no_c(my_string):
new_string = ""
for index in range(len(my_string)):
if my_string[index] == "c" or my_string[index] == "C":
continue
new_string = new_string + my_string[index]
return(new_string)
|
f23abbb68fb06b0373b105e03457d82ce9b74f05 | katgzco/holbertonschool-higher_level_programming | /0x0F-python-object_relational_mapping/model_city.py | 707 | 3.625 | 4 | #!/usr/bin/python3
"""Contains the class definition of a City
class:
City
"""
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
from model_state import Base, State
class City(Base):
"""Declarative class that defines the columns and
maps the... |
e3e46d8a2cc4f8e0fa8f5781d401b300b6ac3010 | romankondratiev/leetcode-python | /min-stack.py | 1,030 | 4 | 4 | class MinStack: #intuitive
def __init__(self):
self.stack = []
def push(self, x: int) -> None:
self.stack.append(x)
def pop(self) -> None:
self.stack.pop()
def top(self) -> int:
return self.stack[-1]
def getMin(self) -> int:
return min(self.stack)
class Min... |
19206c3f48b9fc3cda6c3c5c5f4211c92a3835fd | jnriver/leetcode | /231.2-的幂.py | 896 | 3.890625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @lc app=leetcode.cn id=231 lang=python
#
# [231] 2的幂
#
# https://leetcode-cn.com/problems/power-of-two/description/
#
# algorithms
# Easy (45.74%)
# Likes: 111
# Dislikes: 0
# Total Accepted: 19.7K
# Total Submissions: 43K
# Testcase Example: '1'
#
# 给定一个整数,编写一个... |
a14587811f55d316dc09c240d5008bdf1b26b614 | jnriver/leetcode | /11.盛最多水的容器.py | 1,239 | 4 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @lc app=leetcode.cn id=11 lang=python
#
# [11] 盛最多水的容器
#
# https://leetcode-cn.com/problems/container-with-most-water/description/
#
# algorithms
# Medium (55.66%)
# Likes: 774
# Dislikes: 0
# Total Accepted: 76.5K
# Total Submissions: 133.2K
# Testcase Example: ... |
a0511e28b7c328fc2a489d942fc7a3ffc1cf475d | Dary85/GB-Python | /Task16.py | 736 | 3.90625 | 4 | a = list()
i = 0
result_dict = {"name": list(), "price": list(), "quantity": list(), "unit": list()}
while True:
answer = input("Do you want to add new position y/n: ")
if answer != "y":
break
name = input("Enter position name: ")
price = float(input("Enter position price: "))
qty = float(in... |
d64f75c580010313a445ef52873dbd16ad5eef72 | Dary85/GB-Python | /Task25.py | 622 | 3.84375 | 4 | def func(nlist):
global result
for i in nlist:
if i.upper() == "Q":
return (0, result)
else:
try:
result += float(i)
except ValueError:
print(f"Type error {i}. Current result is {result}")
return (1, result)
... |
194d9d7864d4d16faecfae1d5a2efa7318f836d7 | Dary85/GB-Python | /Task55.py | 576 | 3.59375 | 4 | class Stationery:
def __init__(self, title):
self.title = title
def draw(self):
print("Запуск отрисовки.")
class Pen(Stationery):
def draw(self):
print(f"Start draw.{self.title}")
class Pencil(Stationery):
def draw(self):
print(f"начали рисовать.{self.title}")
class Handl... |
8e76903c9598638c5530eb864205cd9e4989e474 | Dary85/GB-Python | /Task74.py | 4,154 | 3.6875 | 4 | class Store:
__rack = list()
__department = list()
def __init__(self, cells):
try:
self.cells = int(cells)
except ValueError:
print("Параметр может быть только числом")
self.cells = 0
def move_to_storage(self, ob, qty):
print("Склад полон, ни... |
da174240ca1fd4538b33b5edfd38a48c05ddd1ba | Dary85/GB-Python | /Task06.py | 240 | 3.875 | 4 | a = float(input("Enter first value(km): "))
b = float(input("Enter second value(km): "))
i = 1
while a <= b:
a = a * 1.1
print(f"day{i}: {a:.1f}")
i = i + 1
print(f"on the {i}th day, the athlete achieved a result of < {b} km")
|
bd3af2c85a29e8f785fc9f53d8370ca5b95cb1ee | ckkhandare/mini_python_part2 | /City&tree.py | 1,767 | 4.21875 | 4 | dict1={}
while True:
print(''' 1. Add new city and trees commonly found in the city.\n
2. Display all cities and the list of trees for all cities.\n
3. Display list of trees of a particular city.\n
4. Display cities which have the given tree.\n
5. Delete city\n
6. Modify tree list\n
7. Exit\n''')
... |
0cc70b2f08527d0970a1d43d67072dc30c404573 | Rudy359/Competitive-Programming | /main.py | 935 | 3.546875 | 4 | c = [0, 0, 0, 0] # Dummy objective function
A = [
[3, 5, 3, 4],
[4, 3, 2, 1],
[1, -1, 0, 2],
[2, 2, -1, -3]
]
b = [2, 5, 1, -4]
import numpy as np
from scipy.optimize import linprog
# Coefficients of the linear inequalities
c = [0, 0, 0, 0] # Dummy objective function
A = [[3, 5, 3, 4], [4, 3, 2, 1], ...] # Coeffi... |
ffe6e48cf5ee5d8772174532e9010d947f23542b | krishnakanthati/advent-of-code | /Day6/part1.py | 521 | 3.546875 | 4 | file1 = open(r"inputs.txt", "r")
inputs_in_file = file1.readlines()
count = 0
for i in inputs_in_file:
if len(inputs_in_file):
string = ''.join(inputs_in_file[: inputs_in_file.index('\n')])
string = string.replace('\n', '')
# print(string)
ans = ""
for i in string:
... |
090692c04908fc2c72f8dadeda7f104d67d20c8e | turastory/Algorithms | /algorithms/python/fibonacci.py | 462 | 3.84375 | 4 | def naiveFibo(n):
if n < 0:
raise ValueError("n must be not negative")
elif n <= 1:
return n
else:
return naiveFibo(n - 1) + naiveFibo(n - 2)
def dynamicFibo(n):
if n < 0:
raise ValueError("n must be not negative")
# Memorize every calculation results
# -1 for default value
memo = [-1] *... |
da150fe746bbd0afc807dac115956bafe3a0de25 | celiacailloux/Breast-Cancer-Wisconsin | /Ex1_PlottingAttributes.py | 911 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 6 18:06:15 2018
@author: celiacailloux
"""
from LoadingData import *
from matplotlib.pyplot import figure, plot, title, legend, xlabel, ylabel, show
# Data attributes to be plotted
i = 20
j = 7
##
# Make a simple plot of the i'th attribute agai... |
99c32e6ca3b0e050237320a7ab5effba1555bc6b | LeonMarqs/Curso-Em-Video-Python3 | /MUNDO 1/Exercícios MUNDO 1/ex029 (radar eletronico).py | 355 | 3.703125 | 4 | print('\033[30m-=-'*20)
v = float(input('Qual a velocidade atual do carro? '))
print('-=-'*20)
multa = (v - 80) * 7
if v > 80:
print('\033[30mVocê foi \033[31mmultado\033[m \033[30mpor exceder o limite de \033[32m80km/h\033[30m\n A multa custará R${:.2f}'.format(multa))
print('-=-'*20)
print('Tenha um bo... |
3ec937b8a171bf10b7a270a69b15bdecbc66da59 | LeonMarqs/Curso-Em-Video-Python3 | /MUNDO 3/Exercícios MUNDO 3/ex078 (Maior e menor na lista).py | 672 | 3.640625 | 4 | lista = []
for c in range (0, 6):
n = int(input(f'Digite um número para a posição {c}: '))
lista += [n]
print('=='*20)
print(f'Você digitou os valores: {lista}')
enumerate (lista)
#maiorIndex = lista.index(max(lista))
#menorIndex = lista.index(min(lista))
maior = max(lista)
menor = min(lista)
pri... |
cf2c56bc21dcaa184df5747511fa5abf6e53ae8c | LeonMarqs/Curso-Em-Video-Python3 | /MUNDO 3/Exercícios MUNDO 3/ex088 (Palpites para Mega Sena).py | 594 | 3.578125 | 4 | from random import randint
from time import sleep
dados = []
megasena = []
print('=='*20)
print('{:^40}'.format('MEGA-SENA'))
print('=='*20)
n = int(input('Quantos jogos você quer que eu sorteie? '))
print(f'-=-=-=-=-= SORTEANDO {n} JOGOS -=-=-=-=-')
for c in range (1, n+1):
for d in range(0, 6):
... |
3dcb17d07fb87e84f2ef9fef643ab6c01b67b2b0 | LeonMarqs/Curso-Em-Video-Python3 | /MUNDO 1/Exercícios MUNDO 1/ex004 (infomações sobre variavel).py | 462 | 3.765625 | 4 | q = input('Digite algo: ')
print('O tipo primitivo desse valor é: \033[32m{}'.format(type(q)))
print('É um número? {}'.format(q.isnumeric()))
print('É alfabético? {}'.format(q.isalpha()))
print('É alfanumérico? {}'.format(q.isalnum()))
print('Só tem espaços? {}'.format(q.isspace()))
print('Está em minúsculas? {}'... |
0fa1dfb90e3714803a691cbc971c6db280ceaedf | LeonMarqs/Curso-Em-Video-Python3 | /MUNDO 3/Exercícios MUNDO 3/ex081 (Extraindo dados de uma lista).py | 592 | 4 | 4 | valores = []
while True:
n = int(input('Digite um valor: '))
valores.append(n)
continuar = ' '
while continuar not in 'SN':
continuar = str(input('Quer continuar? [S/N]: ')).upper().strip()[0]
print('=='*20)
if continuar == 'N':
break
print('=='*20)
print(f'For... |
edd4a2d501189bc6211bd9e227dbb54ba65a1980 | LeonMarqs/Curso-Em-Video-Python3 | /MUNDO 1/Exercícios MUNDO 1/ex007 (média).py | 162 | 3.875 | 4 | n1 = float(input('Digite a primeira nota: '))
n2 = float(input('Digite a segunda nota: '))
print('A média entre {} e {} é: {:.1f}'.format(n1, n2,(n1+n2)/2)) |
23d967152092db9a96ddc18c964b8690131ee52e | LeonMarqs/Curso-Em-Video-Python3 | /MUNDO 1/Exercícios MUNDO 1/ex013 (calculadora de aumento).py | 129 | 3.515625 | 4 | n = float(input('Digite o salário: '))
f = (15/100)*n
print('O novo salário com 15% de aumento será RS{:.2f}'.format(n + f)) |
8b2a5b80b8f30f33a4c46bec150b73212de176e8 | LeonMarqs/Curso-Em-Video-Python3 | /MUNDO 2/Exercícios MUNDO 2/ex055 (Maior e menor da sequência).py | 431 | 3.65625 | 4 | maior = 0
menor = 0
for c in range (1, 6):
peso = float(input('\033[35mPeso da {} pessoa:\033[m '.format(c)))
if c == 1:
maior = peso
menor = peso
else:
if peso > maior:
maior = peso
if peso < menor:
menor = peso
print('\033[32mO maior va... |
fdaf4307691f1246c1e620bef238312771d7723d | LeonMarqs/Curso-Em-Video-Python3 | /MUNDO 1/AULAS/(aula010) condições.py | 354 | 3.703125 | 4 | media = 1
if media >=7:
print('Aprovado')
else:
if media <6:
print('Reprovado')
else:
print('Recuperação')
numero = 99
if numero >= 100 and numero <= 200:
print('Correto')
else:
print('Errado')
numerow = 100
if numerow ==100 or numerow ==200:
print('verdade... |
3a132beedaa72e3cd601e9117baa48195b921f87 | LeonMarqs/Curso-Em-Video-Python3 | /MUNDO 2/Exercícios MUNDO 2/ex051 (Progressão aritmética).py | 278 | 3.890625 | 4 | print('-=-'* 10)
print('PROGRESSÃO ARITMÉTICA')
print('-=-'* 10)
termo1 = int(input('Digite o primeiro termo da PA: '))
razao = int(input('Digite a razão da PA: '))
decimo = termo1 + (10 - 1) * razao
for c in range(termo1, decimo + 1, razao):
print(c, end='. ') |
f0f529c9d18cd724f0e600213363e4882778791d | LeonMarqs/Curso-Em-Video-Python3 | /MUNDO 2/Aulas/Aula13 - Estrutura de rep. FOR.py | 249 | 3.875 | 4 | # Contar de trás pra frente
for c in range(6, 0, -1):
print(c)
# Pulando de 2 em 2
for c in range(0, 10, 2):
print(c)
# somar valores
s = 0
for c in range(0, 4):
n = int(input('Digite um valor: '))
s += n
print('Fim') |
090da4f0a0bef58df953d7c1fa1c2a7c988dee34 | LeonMarqs/Curso-Em-Video-Python3 | /MUNDO 1/Exercícios MUNDO 1/ex030 (par ou ímpar).py | 209 | 3.875 | 4 | print('-=-'*20)
n = int(input('Digite um número qualquer: '))
print('-=-'*20)
calculadora = n % 2
if calculadora == 0:
print('O número {} é PAR'.format(n))
else:
print('O número é ÍMPAR') |
202235591992d3f45f24ec2180e2256068e36540 | veksel1/coding_and_ML_club | /LilySort.py | 963 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 3 13:16:51 2018
@author: ilja.surikovs
"""
#!/bin/python3
#import sys
def lilysHomework(arr):
print(arr)
asc_arr = arr.copy()
desc_arr = arr.copy()
print()
asc_arr.sort()
print(asc_arr)
desc_arr.sort(reverse=True)
print(desc_arr)
as... |
54b41012a205f79365ed54c5907c1d2a3a045bec | socialpanic/cs121 | /ch2prob6.py | 274 | 3.921875 | 4 | mass=float(input("What is the objects mass in kg? "))
velo=float(input("What is the objects velocity in m/s (meters per second)? "))
momt=mass*velo
KE=(mass/2)*velo**2
print "The objects momentem is", momt, "(kg x m/s)"
print "the objects kinetic energy is", KE |
12f4b2ebb6f5eae34ed8ed83d6a4e72ad6fff13a | weitaishan/algorithm-basics | /Python/初级算法/数组_4_存在重复元素.py | 1,722 | 3.609375 | 4 | # *_*coding:utf-8 *_*
'''
存在重复元素
给你一个整数数组 nums 。如果任一值在数组中出现 至少两次 ,返回 true ;如果数组中每个元素互不相同,返回 false 。
示例 1:
输入:nums = [1,2,3,1]
输出:true
示例 2:
输入:nums = [1,2,3,4]
输出:false
示例3:
输入:nums = [1,1,1,3,3,4,3,2,4,2]
输出:true
提示:
1 <= nums.length <= 105
-109 <= nums[i] <= 109
'''
from typing import List
class Solution:
... |
2d4ae931777f45b7bb6a1b549d838bf6b37ab4eb | LuciRamos/python | /pep8.py | 928 | 4.15625 | 4 | """
PEP 8
São propostas de melhorias para a linguagem Python
A ideia da PEP8 é que possamos escrever códigos Python de forma Pythônica.
[1] - Utilize Camel Case para nomes de classes; - Iniciais maiusculas e sem
[2] - Utilize nomes em minusculo, separados por underline para funções ou variáveis
[3] - Utilize 4 e... |
ff224cde20e65c47c777c45c9e7089a9d454b448 | Kihyun92/menu-picker | /src/practice.py | 2,041 | 3.640625 | 4 | import random
lunch = random.choice(["된장찌개", "파스타", "피자", "스테이크", "제육볶음", "짜장면"])
dinner = random.choice(["된장찌개", "파스타", "피자", "스테이크", "제육볶음", "짜장면"])
# 반복문
for x in range(3):
print(x, lunch)
print('-----')
print(lunch)
print(dinner)
print('------')
me = {"name": "기현", "age": 30, "sex": "male"} # 딕셔너리
print(me... |
b3b5a2de27491dc77c2a377119b90bab54397b2b | thebenign/game | /load_graphics.py | 1,055 | 3.640625 | 4 | #load graphics
import os, inspect
from pygame import image as image
from pygame import Surface as surface
def load(screen):
"""
Loads the graphics for the game into a list,
then converts the graphics from png to something more
appropriate for blitting.
Perameters:
screen: a pygame Surface object for Surfa... |
dd5fb2c6de1850bf270a48b5326ce6bb95ca050b | bhranti100/pdsnd_github | /bikeshare.py | 7,244 | 4.375 | 4 | """
This is U.S. bikeshare data analysis. This bikeshare data is provided by Motivate.
"""
import time
import pandas as pd
import numpy as np
import datetime
from constants import CITY_DATA, MONTH, WEEK
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) c... |
759a19df61f429346f357df1038124e5d83d9597 | lincappu/pycharmlearningproject | /LNH/day2/02 function/06 expression、Anonymous+builtins function.py | 7,730 | 4 | 4 | # !/usr/bin/env python3
# _*_coding:utf-8_*_
# 1.三元表达式:只针对简单的 if、else 语句
# number=input('number:')
# res='ok' if number=='1' else 'error'
# print(res)
# 2.列表推导式:
# 常规写法:
# egg_list=[]
# for i in range(10):
# egg_list.append('鸡蛋%s' %(i))
#
# print(egg_list)
# 表达式写法:(一个 for 循环,前面只能有一个参数,)
# egg_list=['鸡蛋%s' %ite... |
9c3735d4df3de40f986d7d30ff49a0e6d5038286 | lincappu/pycharmlearningproject | /LNH/day5/08 other.py | 6,491 | 3.890625 | 4 | # !/usr/bin/env python3
# _*_coding:utf-8_*_
# __author__:FLS
# 1.isinstance() 和 issubclass()
# class Foo(object):
# pass
#
#
# class Bar(Foo):
# pass
#
#
# obj=Foo()
# print(isinstance(obj,Foo))
#
# print(issubclass(Bar,Foo))
# 2.反射(自省):通过字符串的形式操作对象的相关属性,python 的一切事物都是对象,都可以反射
# hasattr(object,str)
# getat... |
5148804793d1880d15b6443c094b792b784b451c | lincappu/pycharmlearningproject | /LNH/day10-teacher/2 线程相关/5 守护线程.py | 1,421 | 3.765625 | 4 | #1.对主进程来说,运行完毕指的是主进程代码运行完毕
#2.对主线程来说,运行完毕指的是主线程所在的进程内所有非守护线程统统运行完毕,主线程才算运行完毕
# from threading import Thread
# import os
# import time
# import random
#
# def task():
# print('%s is runing' %os.getpid())
# time.sleep(random.randint(1,3))
# print('%s is done' %os.getpid())
#
#
# if __name__ == '__main__':
#... |
0f0b0f4245bed46e40f5e87fcd8b4e0f0343a075 | lincappu/pycharmlearningproject | /LNH/day7-teacher/7继承.py | 5,346 | 4.25 | 4 | #继承 —— 面向对象的三大特性之一
#想产生继承关系,必然是两个类以上
#继承表达的是一种 什么 是 什么的关系
# class Animal:
# def __init__(self,name,aggr,life_value):
# self.name = name
# self.aggr = aggr
# self.life_value = life_value
#
# def func(self):
# print(self.name)
#
# class Foo:
# def func(self):
# print(se... |
3980ca2e9b93ea054fc94dc96405b30647a0c138 | lincappu/pycharmlearningproject | /LNH/day2/02 function/04 generator.py | 6,491 | 3.625 | 4 | # !/usr/bin/env python3
# _*_coding:utf-8_*_
# __author__:FLS
# 什么是迭代器:
# 迭代是一个重复的过程,每次结果都是基于上次的结果来的,
# 针对没有索引的数据类型,必须有一种不依赖索引的取值方式,
# 可迭代对象:只要对象有__iter__方法就是可迭代对象。
# 目前所学的所有类型都是可迭代对象。数值类型不是
# 迭代器对象:既要有__iter__对象,也要有__next__方法。
# 可迭代度对象
# 'hello'.__iter__()
# [1,2].__iter__()
# (1,2).__iter__()
# {'a':1}.items()
# {1... |
b39e2527022d8b2bdb47bc317e270a3f10ba2aae | lincappu/pycharmlearningproject | /日常练习/2023/2023-03/dict类型的key值类型.py | 1,411 | 3.578125 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Author : FLS
# @Software : PyCharm
# @Time : 2023/3/31 17:04
# @Project : pycharmlearningproject
# @File : dict类型的key值类型.py
'''
1 字典的定义与特性
字典是Python语言中唯一的映射类型。
定义:{key1:value1,key2:value2}
特性:
1.key-value结构
2.key必须可hash、且必须为不可变数据类型、必须唯一
3.可存放任意多个值、可... |
9592b1d9edc9e72400d02d708e9deebfaecdbc2d | lincappu/pycharmlearningproject | /基本模块库/day11-teacher/1 协程.py | 5,578 | 4.09375 | 4 | '''
并发的解决方案1:
多进程
多线程
总结两点:
什么叫并发:看起来同时运行,
如何实现并发*
进程线程都是由操作系统调度的
并发的解决方案2:
协程:单线程下实现的并发,应用程序级别的切换,操作系统无法感知
找到一种解决方案:
1、在多个任务直接切换+保存状态
2、检测应用程序里的IO,实现遇到IO操作时才切换
'''
# 单线程串行执行,
# import time
#
# def func1():
# for i in range(10000000):
# i+1
#
# def func2():
# ... |
3c40909d874138a1d1e5cd170d6ff831e498a252 | lincappu/pycharmlearningproject | /LNH/day5/03 Object oriented combination.py | 1,868 | 3.59375 | 4 | # !/usr/bin/env python3
# _*_coding:utf-8_*_
# __author__:FLS
# 面向对象的组合:
# 就是面向对象的属性就是也是一个面向对象,反映的是一种所属关系。
# class Bithrday:
# def __init__(self,year,month,day):
# self.year=year
# self.month=month
# self.day=day
#
# class Person:
# def __init__(self,name):
# self.name=name
#
#... |
6ee17ca68c67ced9f2370d81b5ab06107c57d786 | lincappu/pycharmlearningproject | /基本模块库/Letcode/1. 两数之和.py | 2,318 | 3.78125 | 4 | # !/usr/bin/env python3
# _*_coding:utf-8_*_
# __author__:FLS
# 1. 两数之和
nums = [3, 2, 3, 3]
target = 6
# 这个是我写的,问题很明显没有考虑到列表中特殊情况的存在:
# def two(nums,target):
# for n in nums:
# x=target-n
# if x==n and nums.index(n)== nums.index(x):
# continue
# if x in nums:
# pr... |
b2d665b628fb1e076dca2b18c8e489293accc2e6 | lincappu/pycharmlearningproject | /LNH/day10-teacher/2 线程相关/10 事件Event-FLS-MPB.py | 5,305 | 3.6875 | 4 | # 用 threading 的 event 方法来模拟交通信号灯
# set():可设置Event对象内部的信号标志为True
# clear():可清除Event对象内部的信号标志为False
# isSet():Event对象提供了isSet()方法来判断内部的信号标志的状态。当使用set()后,isSet()方法返回True;当使用clear()后,isSet()方法返回False
# wait():该方法只有在内部信号为True的时候才会被执行并完成返回。当内部信号标志为False时,则wait()一直等待到其为True时才返回
import threading,time,random
def light():
... |
1f6c49f967d296ba39ff7ab47a9159e0435f999d | vikas4786/python | /identation.py | 140 | 3.75 | 4 | if 5 > 2:
print ("5 is greater than 2!")
"""this is an example of
docstring,can be used using three quation at the started
and ending"""
|
d4af0bd6715e31efe8cf9fbe5ca1b1032b49c91a | vikas4786/python | /classtest.py | 168 | 3.6875 | 4 | print("Hello World.")
class point:
def __init__(self,x,y,z):
self.v_x=x
self.v_y=y
self.v_z=z
p1=point(2,3,5)
print p1.v_x
|
daecd78c732f2723a0128dfa4d14177f79c1db55 | landeholt/python-course-material | /helpers/coordinates.py | 1,496 | 3.53125 | 4 | import json
from math import radians, sin, cos, sqrt, asin
class Street:
def __init__(self, lat, lon, name, number = '-'):
self.name = name
self.number = number
self.lat = lat
self.lon = lon
self.distance = None
def computeDistance(self, lat, lon):
# Haversin... |
60cb4ecde4b0a43f729e56b9576f4acaaac0d34a | Lelethu-Ndidi/EOMpythonlottery | /code.py | 10,957 | 3.875 | 4 | #Creating a window
from tkinter import *
from random import sample
from tkinter import messagebox
import random
#Creating a window
window = Tk()
window.title("6 Figure Lottery!!!")
window.resizable(1000, 2000)
lblEnter= Label(window, text="Press play before playing then enter 6 Numbers!")
lblEnter.grid(row=0,column=... |
55a061a1c0cd20e5ab7413c671bc03573de1bbdf | jasonmichaelhancock/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/100-print_tebahpla.py | 179 | 3.5625 | 4 | #!/usr/bin/python3
"""
list = list(range(97, 123)
for (i in list):
if (i % 2 == 0):
i = (i - 32)
"""
for letter in "zYxWvUtSrQpOnMlKjIhGfEdCbA":
print('{:s}'.format(letter), end = "")
|
5342f5e86a10b0cbb9efa365cda0d0c18717cfc0 | jasonmichaelhancock/holbertonschool-higher_level_programming | /0x0A-python-inheritance/100-my_int.py | 347 | 3.703125 | 4 | #!/usr/bin/python3
""" module 100-my_int contains class MyInt, a subclass of int """
class MyInt(int):
""" defines class MyInt """
def __eq__(self, other):
""" == now acts like != """
return int.__ne__(self, other)
def __ne__(self, other):
""" != now acts like == """
retu... |
fc22ede62dbfff1d6ad38bc27c353d41def148fe | Talw3g/pytoolbox | /src/pytoolbox_talw3g/confirm.py | 1,356 | 4.5 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
def confirm(question, default_choice='yes'):
"""
Adds available choices indicator at the end of 'question',
and returns True for 'yes' and False for 'no'.
If answer is empty, falls back to specified 'default_choice'.
PARAMETERS:
- question is man... |
a2d5ce07c4cbab438f90124fbc9507263c2a99e2 | dyanfee/pyLearn | /test_file/temp1.py | 251 | 3.96875 | 4 | """--- 第一个小游戏 ---"""
temp = input("不妨猜一下老王现在心里想的数字:")
guess = int(temp)
while guess != 8:
temp = input("哎呀,猜错了,请重新输入吧:")
guess = int(temp)
string = ""
print(string)
|
00fefec4fc45c94d56d1a24e17594ca6b7a1e1ec | Jamesbarford/advent-of-code2020 | /day7/solve.py | 1,463 | 3.5 | 4 | import re
def split_line(line):
return re.split(" bags contain | bags, | bag, | bags.\n| bag.\n", re.sub("\d+\s", "", line))
class Solver:
def __init__(self):
self.SHINY_GOLD = "shiny gold"
self.dictionary = {}
self.valid_bags = set()
def count_valid_bags(self):
file = op... |
9f653f6fd51c36d8df47e58edb6ba554a27f0532 | ngareleo/maze-solve-v1 | /maze Solve/test.py | 1,621 | 4.03125 | 4 | from random import randint
"""""
def create_grid(x,y):
result_grid = []
for i in range(x+1):
for j in range(y+1):
result_grid.append([])
result_grid[i].append(randint(1,243))
return result_grid
for grid in create_grid(10,10):
print(grid)
"""
test_grid = [
[91,92,93,94,59,96,97,98],
[12... |
8bca4e2ecf33149ef23d5810f9306936ca938765 | Halerfermatqing/Python_learning_freshman | /数据可视化/chapter9_class/rw_visual.py | 940 | 3.5 | 4 | import matplotlib.pyplot as plt
from chapter9_class.random_work import Randomwork
# 创建一个RandomWork实例,并将其包含的点都绘制出来
while True:
rw = Randomwork(num_points=50000)
rw.fill_walk()
#设置绘图窗口的尺寸
plt.figure(figsize=(10,6))
#给点渐变色
points_numbers = list(range(rw.num_points))
plt.scatter(rw.x_values... |
ba73a0600fffb40ece1b2d78de83baf3aa1ee23a | paszel/Python | /Plurarsight/Games/guessWord.py | 1,301 | 3.953125 | 4 | import random
def getRandomWord():
words = ["pizza","cheese","apples","oranges"]
word = words[random.randint(0, len(words)-1)]
return word
def showWord(word):
for character in word:
print(character, " ", end='')
print("")
def getGuess():
print("Enter a letter: ")
return input()
... |
4be255babbcefffb52ca337b38a2be1c3ba69159 | davidgur/Flappy-Bird | /Base.py | 464 | 3.5625 | 4 | """
Base.py
Author: David Gurevich
Date Last Modified: January 20th, 2018
Python Version: 3.X
"""
import pygame
BASE_HEIGHT = 112
BASE_WIDTH = 336
class Base(object):
def __init__(self):
self.x = 288
self.y = 400
self.x_vel = -3 # px
def draw(self... |
4ed87fff33d71e48e84cd999e958bd06ac029579 | helioemjunior/viraCopo | /viraCopo.py | 2,860 | 3.859375 | 4 | #Loading...Férias
import random
import os
import time
lista = []
def tempo():
time.sleep(5)
for i in range(51):
lista.append(i)
def exibirnumeros(lista):
#exibição dos números
ini = 0
fim = 11
d = 5
if len(lista) <= 11:
d = 1
elif len(lista) <= 22:
... |
e7d9e99375459e1031bf9dd0c2059421978ef31b | KartikeyParashar/Algorithm-Programs | /calendar.py | 1,434 | 4.28125 | 4 | # To the Util Class add dayOfWeek static function that takes a date as input and
# prints the day of the week that date falls on. Your program should take three
# commandline arguments: m (month), d (day), and y (year). For m use 1 for January,
# 2 for February, and so forth. For output print 0 for Sunday, 1 for Monda... |
63e77ca2c9b458409caa5492065cf02fde327ecd | surister/code-jam-3 | /project/sprites/combat.py | 3,180 | 3.640625 | 4 | import logging
import random
import pygame as pg
from project.sprites.game_elements import Item, Projectile
logger = logging.getLogger('last_judgment_logger')
class Combat:
"""
Class to handle combat for every Sprite that needs it
* damage
* shooting
* drops
* Sprite disposa... |
ac682122ab1b801bba82fe18714d3f5b2a4466a6 | bulat22101/BashkirSU_Python_Course | /computer_game/main.py | 3,550 | 3.703125 | 4 | from enum import IntEnum
from typing import List
import random
import math
class DoorType(IntEnum):
MONSTER = -1,
ARTIFACT = 1
class Door:
def __init__(self, door_id: int, door_type: DoorType, value: int):
self.door_id = door_id
self.door_type = door_type
self.value = value
... |
a0ed5451838a79d9496eccd8dba514bff6bbf053 | Chih-YunW/LeapYearTesting | /unittest_leapYear.py | 494 | 3.640625 | 4 | import unittest
import leapYear
class testLeapYear(unittest.TestCase):
def test_is_a_leapYear(self):
self.assertEqual(leapYear.leapYear(2000), "It is a leap year")
def test_not_a_leapYear(self):
self.assertEqual(leapYear.leapYear(1999), "It is not a leap year")
... |
6ecd96ff740672816954dc9773a4fd363a18d4cc | kcarollee/Problem-Solving | /Python/13771.py | 280 | 3.515625 | 4 | class Prices:
def __init__(self, arr):
self._arr = arr
self._arr2 =sorted(self._arr)
def answer(self):
print("%.2f" % (self._arr2[1]))
if __name__ == "__main__":
n = int(input())
arr = []
for i in range(n):
a = float(input())
arr.append(a)
Prices(arr).answer()
|
0a99bd7689397f90bd133a8183a4583ddddc0f5c | kcarollee/Problem-Solving | /Python/1547.py | 181 | 3.734375 | 4 | def switch(arr, a, b):
arr[a], arr[b] = arr[b], arr[a]
a = int(input())
arr = [1, 2, 3]
for i in range(a):
a, b = map(int, input().split())
switch(arr, a-1, b-1)
print(arr[0])
|
8fdfb73a11e07e86617376c866ef62590a0af576 | kcarollee/Problem-Solving | /Python/5426.py | 651 | 3.515625 | 4 | import math
class Crypt:
def __init__(self, arr):
self._arr = arr
self._len = len(arr)
self._slen = int(math.sqrt(self._len))
self._board = [[None] * self._slen for i in range(self._slen)]
self.fill_board()
def fill_board(self):
index = 0
for i in range(self._slen):
for j in range(self._slen):
s... |
a96e4cbd638e45efcc3beb1e05174b341f80d27a | kcarollee/Problem-Solving | /Python/9946.py | 1,190 | 3.578125 | 4 | def len_cmp(arr1, arr2):
if len (arr1) == len (arr2):
return 1
else:
return 0
def compare(arr1, arr2):
set1 = set(arr1)
set2 = set(arr2)
if set1 != set2:
return 0
list_set1 = list(set1)
list_set2 = list(set2)
dict_1 = {}
dict_2 = {}
l = len(set1)
l2 = len(arr1)
for h in range(l):
dict_1[list_set1[h... |
1f674c5e461a914f3d29e1ff7ec25ba4cc00c686 | kcarollee/Problem-Solving | /Python/12605.py | 611 | 3.546875 | 4 | class Flip:
def __init__(self, arr):
self._arr = arr
self._temp1 = []
self._temp2 = []
def stack(self, tc):
l = len(self._arr)
for i in reversed(range(l)):
if self._arr[i] != ' ' and i != 0:
self._temp1.append(self._arr[i])
elif self._arr[i] == ' ' or i == 0:
if i == 0:
self._temp1.appe... |
4f33ad5ba998dfeac43a180865e9a5e742fba2d5 | kcarollee/Problem-Solving | /Python/2530.py | 920 | 3.5625 | 4 | class Oven:
def __init__(self, Hour, Min, Sec, Sec2):
self._hour = Hour
self._min = Min
self._sec = Sec
self._sec2 = Sec2
def manageHour(self):
if self._sec2 >= 3600:
self._hour += self._sec2 // 3600
if self._hour > 23:
self._hour %= 24
self._sec2 -= 3600 * (self._sec2 // 3600)
def manageMin... |
3683ed81ae8ccb09fcedbeb8aea7f7ac57893da8 | kcarollee/Problem-Solving | /Python/2749.py | 97 | 3.59375 | 4 | def fib(n):
if n <= 1:
return(n, 0)
else:
(a, b) = fib(n-1)
return (a+b, a)
print(fib(5)) |
35aa4aca736efcb38d0c9135c838423219756c21 | kcarollee/Problem-Solving | /Python/13772.py | 309 | 3.640625 | 4 | def read(arr):
x = 0
l = len(arr)
for p in range(l):
if arr[p]=='A'or arr[p]=='D'or arr[p]=='O'or arr[p]=='P'or arr[p]=='Q'or arr[p]=='R':
x += 1
elif arr[p] == 'B':
x += 2
elif arr[p] == '\0':
break
return x
tc = int(input())
for i in range(tc):
arr = list(input())
print(read(arr))
|
76f53dc1db322d00276cd735b7519a9947911e03 | headneZzz/Project-Euler | /Project-Euler/_1.py | 462 | 4.03125 | 4 | #Problem 1
#If we list all the natural numbers below 10 that are multiples of 3 or 5,
#we get 3, 5, 6 and 9. The sum of these multiples is 23.
#Find the sum of all the multiples of 3 or 5 below 1000.
import time
#var1
start=time.time()
a = 1
s = 0
while a<1000:
if a%3==0 or a%5==0:
s += a
a += 1
print... |
b59b0b070037764fc71912183e64d047c53f9cf1 | aruntonic/algorithms | /dynamic_programming/tower_of_hanoi.py | 917 | 4.375 | 4 | def tower_of_hanoi(n, source, buffer, dest):
'''
In the classic problem of the wers of Hanoi, you have 3 towers and N disks of different sizes which can slide onto any tower.
The puzzle starts with disks sorted in ascending order of size from top to bottom (i.e., each disk sits on top of an even larger one).You ha... |
b57541bed294256b0470643be9c68275df5f78f8 | gagolucasm/Codingame | /Temperatures.py | 565 | 3.78125 | 4 | import sys
n = int(raw_input()) # the number of temperatures to analyse
temps = raw_input() # the n temperatures expressed as integers ranging from -273 to 5526
if n>0:
temps=map(int, temps.split(' '))
# Write an action using print
print >> sys.stderr,"La lista es", temps
pmc=9999
nmc=-9999
for i in range (n):
... |
ddf399fe88a37b734bdfed3e6ac93ea5ad68e006 | gbarszcz/python-learning | /exercises_6/zad1.py | 613 | 3.546875 | 4 | # coding=utf-8
# Napisz funkcję, która pobierze od użytkownika liczbę i wyświetli jej pierwiastek.
# Obsłuż wszystkie wyjątki, które mogą wystąpić w wyniku działania programu.
from math import sqrt
try:
liczba = input("Podaj liczbę: ")
pierwiastek = sqrt(liczba)
except (NameError, SyntaxError) as ex:
print... |
6f76b8124eebb52dc08ecf21d9993b994224f72d | gbarszcz/python-learning | /exercises_1/example.py | 631 | 3.734375 | 4 | print('Hello world!')
# data = raw_input('Wprowadz dane') # wczytuje zawsze jako string
# data2 = input('Wprowadz')
# print(data)
# print(data2)
#
# data3 = int(data) + data2
# print(data3)
def suma(a, b):
return a + b
print(suma(2, 4))
print(suma('a', 'b'))
a = 4
b = 2
if a > b:
print("wieksze")
elif a ... |
3b67c88b6c3e73f750595731980d4f3bec55ee50 | gbarszcz/python-learning | /exercises_4/zad4.py | 625 | 4 | 4 | # coding=utf-8
# Napisz program który w parametrze otrzymuje nazwę pliku lub znak '-' oraz ciąg znaków. Program ma
# wczytać plik i wyświelić te linie, w których znajduje się podany ciąg znaków. Jeżeli zamiast nazwy pliku jest znak
# '-', to linie są wczytywane ze standardowego wejścia. Pusta linia kończy wczytywanie.... |
b90a8f194b91fa172fbba6ebfb8201d52045b171 | gbarszcz/python-learning | /exercises_8/example.py | 3,091 | 4.125 | 4 | # TKinter
import Tkinter as tk
import tkFont
# funkcja ktora zmienia wyglad labela
def labelConfig(label, txt):
label.config(text=txt, fg="light green", bg="dark green")
root = tk.Tk()
# l = tk.Label(root, text="Hello Tkinter!")
# l.pack() # dopasowanie okna
# labelConfig(l, "123")
# globalna modyfikacja czci... |
313eaa9691c0e150f67522606067e75f9a3883d3 | AnkittPareek/pong_game | /ball.py | 708 | 3.703125 | 4 | from turtle import Turtle
import random
BALL_STEP = 6
class Ball(Turtle):
def __init__(self):
super().__init__()
self.shape("circle")
self.color("white")
self.penup()
self.goto(0, 0)
self.movespeed =0
self.xmove = BALL_STEP
self.ymove = BALL_STEP
... |
bf1ac608b75bca4f9f65da676c241eec0520e030 | DIEGORIBEIRO9080/curso_metodos_numericos_em_Python_e_C- | /1_aula_metBissec.py | 1,218 | 3.625 | 4 | # -*- coding: utf-8 -*-
'''
**************************************************************************************
* Name: Método da Bisseção em python *
* Copyright: Computação Cientifica *
* Author: Luciano Mendes ... |
87d6a565d0bd21cbf144976f6e6a4ebdd979386f | jharris1993/Craps_CLI | /keep_playing.py | 2,806 | 3.6875 | 4 | # Keep Playing?
#
# This routine takes the status of the last round played and determines if the round should
# automatically continue, or stop and ask the player.
#
# Rules:
# 1. If the playmode is 0, (rolling for point):
# (a) If the player has *NOT* lost, automatically continue.
# (i) If... |
43dd9278049a8bb7a728f8774ebf7898bdff4114 | AndreySkryl/Codewars | /Python/8 kyu/Sum without highest and lowest number/main.py | 486 | 3.96875 | 4 | def sum_array(array):
return 0 if array is None or not array or len(array) <= 2 \
else sum(array) - max(array) - min(array)
assert sum_array(None) == 0
assert sum_array([]) == 0
assert sum_array([3]) == 0
assert sum_array([-3]) == 0
assert sum_array([3, 5]) == 0
assert sum_array([-3, -5]) == 0
assert sum_... |
fc2a8ca9dc9df23be5527ab06667a773f910d3f8 | AndreySkryl/Codewars | /Python/5 kyu/Help your granny/main.py | 963 | 3.546875 | 4 | def get_leg(hypotenuse, other_leg):
return (hypotenuse**2 - other_leg**2)**0.5
def tour(friends, friend_towns, home_to_town_distances):
friend_towns_in_meters = []
for friend in friends:
friend_town = list(filter(lambda item: item[0] == friend, friend_towns))
if friend_town:
to... |
d6a91c46a14f42a61fda60caee83d90241f5c1af | AndreySkryl/Codewars | /Python/7 kyu/Write out expression/main.py | 1,040 | 4.0625 | 4 | import re
operators = {
'+': 'Plus', '-': 'Minus',
'*': 'Times', '/': 'Divided By',
'**': 'To The Power Of',
'=': 'Equals', '!=': 'Does Not Equal'
}
numbers = '# One Two Three Four Five Six Seven Eight Nine Ten'.split()
def expression_out(exp):
matches = re.match(r'(\d+) (.+) (\d+)', exp)
if mat... |
6a869c192d1fcb9e0cb981fa14c90129fb3b0d43 | AndreySkryl/Codewars | /Python/8 kyu/Invert values/main.py | 182 | 3.828125 | 4 | def invert(lst):
return [-x for x in lst]
assert invert([1, 2, 3, 4, 5]) == [-1, -2, -3, -4, -5]
assert invert([1, -2, 3, -4, 5]) == [-1, 2, -3, 4, -5]
assert invert([]) == []
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.