blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
e2e9e0822f868d43f96f7adb3e5c885159db227b | spd94/Marvellous_Infosystem_Python_ML_Assignments | /Marvellous_Infosystem_Assignment_4/Assignment4_5.py | 664 | 3.5625 | 4 | from functools import reduce
import math
def ChkPrime(n):
c=0
for i in range(2,int(math.sqrt(n))+1):
if(n%i==0):c=1
if(c==0):return(n)
def max_list(n,y):
if(n>y):return(n)
else: return(y)
def accept_N_elem(n):
ls=list()
i=0
sum=0
print("Input Elements :",end=" ")
while(i<n):
ls.append(int(input()))
... |
d5b42355b1136deef409b9bd892ed04d7daebd8b | spd94/Marvellous_Infosystem_Python_ML_Assignments | /Marvellous_Infosystem_Assignment_3/Assignment3_3.py | 331 | 3.515625 | 4 | def accept_N_min(n):
ls=list()
i=0
print("Input Elements :",end=" ")
while(i<n):
ls.append(int(input()))
i+=1
i=0
sum=ls[0]
while(i<n):
if(sum>ls[i]):sum=ls[i]
i+=1
return(sum)
if __name__ == "__main__":
print("Input : Number of Elements :",end=" ")
x=accept_N_min(int(input()))
print("Output :"... |
20f4e8a0618bd5f9a0a9beeb9b7851d0af09dcdc | spd94/Marvellous_Infosystem_Python_ML_Assignments | /Marvellous_Infosystem_Assignment_2/Assingment2_7.py | 197 | 3.6875 | 4 | def print_pattern(n):
i=0
print("Output :")
while(i<n):
j=0
k=1
while(j<n):
print(k,end=" ")
k+=1
j+=1
print("")
i+=1
print("Input :",end=" ")
x=int(input())
print_pattern(x) |
cede3101dcebb7ca00c09dbf06c620664e444bc6 | farzaa/AlmostUnlimited | /FileController.py | 2,177 | 3.6875 | 4 | import json
import os
class FileController:
links = {}
def __init__(self):
self.filename = 'links.json'
FileController.links = FileController.links
def process_json(self):
"""
Processes the json file as a python dictionary for O(1) lookup
"""
if os.path.isfi... |
b9309e29726fbdd81593c7584f10bba6b3b39e8b | Herraiz/eoi | /12-testing/learning_python.py | 1,243 | 3.890625 | 4 | import unittest
def suma(a, b):
return a + b
def resta(a, b):
return a - b
def check_equality(a, b):
if a != b:
raise Exception (str(a) + ' is not equal to ' + str(b))
print('Check equality')
def multiplicacion(a, b):
return a * b
def division(a, b):
if b == 0:
raise Arit... |
dcbe358f8337658a190aa6ec199638eebd75178f | PohSayKeong/python | /practical4/q5_count_letter.py | 156 | 3.625 | 4 | def count_letter(str,ch):
if len(str) == 0:
return 0
return (str[0] == ch) + count_letter(str[1:],ch)
print (count_letter("Welcome", 'e'))
|
af36097ff4c7e7b24a376723a19a37ad652b32b6 | PohSayKeong/python | /practical3/q7_convert_ms.py | 314 | 3.859375 | 4 | import math
n = int(input("please enter time in ms: "))
def convert_ms(n):
second = math.floor(n/1000)
second_final = second % 60
minutes = second // 60
minutes_final = minutes % 60
hour = minutes // 60
print(str(hour) + ":" + str(minutes_final) + ":" + str(second_final))
convert_ms(n)
|
79445ff503849570898444870ad4881f5c9b3216 | PohSayKeong/python | /practical2/q11_find_gcd.py | 259 | 3.921875 | 4 | n1 = int(input("first integer: "))
n2 = int(input("second integer: "))
minimum = min(n1,n2)
def gcf(minimum,n1,n2):
if n1 % minimum == 0 and n2 % minimum == 0:
return minimum
else:
return gcf(minimum-1,n1,n2)
print(gcf(minimum,n1,n2))
|
5e8fe335b23c11406377182f99d4205c739b414f | oneNutW0nder/config-dns | /dnsconfig.py | 5,540 | 3.90625 | 4 | def readHeader():
"""
This function reads the "header.conf" file which is where the
dns options for the zone file
:return: (string)the contents of the "header.conf" file
"""
with open("./header.conf", "r") as fd:
header = fd.readlines()
return header
def backup(zoneFile, rever... |
4e8834fd82ae0c6b78a0d134058afbdb11d2da95 | MaxiFrank/calculator-2 | /new_arithmetic.py | 1,560 | 4.28125 | 4 | """Functions for common math operations."""
def add(ls):
sum = 0
for num in ls:
sum = sum + num
return sum
def subtract(ls):
diff = 0
for num in ls:
diff = num - diff
return diff
# def multiply(num1, num2):
def multiply(ls):
"""Multiply the two inputs together."""
res... |
cdfa4e30f49d0b3c920cad94865be8647920b54c | rashid32/python_nov_2017 | /Rashid_Ashfaq/OOP/add.py | 746 | 3.859375 | 4 | class Vehicle(object):
def __init__(self,wheels,capacity,make,model):
self.wheels=wheels
self.capacity=capacity
self.make=make
self.model=model
self.mileage=0
def drive(self,miles):
self.mileage+=miles
return self
def reserve(self,miles):
self.mileage -=miles
return self
class Bike(Vehicle):
def v... |
691c4a41c38d1d260cfc11e7a5ca119ec1a74159 | jerseymec/Orapy | /loop.py | 155 | 4.15625 | 4 | for i in range(1,22):
if (i % 2 != 0):
print(str(i) + " is Odd")
elif (i % 2 == 0):
print(str(i) + " is Even")
print("\n")
|
5432f1d6e0171b8ff7ff86533e4bf32f6afceef7 | jerseymec/Orapy | /DoorMat.py | 921 | 3.65625 | 4 | def draw_pattern(n,m):
for i in range(0,n//2):
for j in range(0,(m//2)- (i*3+1)):
print("-", end="")
for k in range(i*2 +1 ):
print(".", end="")
print("|" , end="")
print(".", end="")
for j in range(0,(m//2) - (i*3+1)):
print("-... |
5098723d0627372bda3626de4491fde1defaf3b7 | beka1cfc/first_week | /dom.py | 4,536 | 3.734375 | 4 | #задача 1
#list: ordered, changeable, allow duplicates
#tuple: ordered, allow duplicates
#set: changeable
#dict: ordered, changeable
#задача 2
a = "HELLO I AM WRITING CODE"
b = ("HELLO" , "I" , "AM" , "WRITING" , "CODE")
print(sorted(b))
#задача 3
names = ["Beks" , "Zhenya" , "Dana" , "Alibek"]
job = ["программис... |
4c7f7cb569736ce96f619dba622cf735ac06215a | PMiskew/Python3_Turtle_Code | /TurtlePolygon.py | 200 | 3.96875 | 4 | import turtle
import math
bob = turtle.Turtle()
n = 80
side = 3
angle = (180 * (n-2))/n
print(angle)
for i in range(0,n,1):
bob.right(180 - angle)
bob.forward(side)
turtle.done()
|
be4af2cdcda36c58fc8be5211a4f09e31a26119c | ishtiaque06/problems_python | /printPascal.py | 538 | 3.78125 | 4 | """
>>> printPascal(5)
"""
def printPascal(n):
if n == 0:
return []
pascal = [[1]]
for i in range(1, n):
if i == 1:
pascal.append([1, 1])
else:
previous = pascal[-1]
new = [0] * (len(previous)+1)
new[0] = 1
new[-1] = 1
... |
6d95e49a3e9aad5a1f77b435e15ae00775377f78 | shrekchan259/MyProjects | /Tic_Tac_Toe.py | 4,931 | 4.0625 | 4 | print('Welcome to Tic Tac Toe !')
def replay():
return input('Would you like to play again? y/n : ').lower()
while True:
test_board = ['#',' ',' ',' ',' ',' ',' ',' ',' ',' ']
print('Kindly note the following positions for your choice of input\n')
print(' 1 '+'|'+' 2 '+'|'+' 3 ')
prin... |
2813d77e5130bafe428f16f0347b81786b4971b9 | OskarSliwinskiPK/JS-Automat-MPK | /src/mpk_exceptions.py | 931 | 3.625 | 4 | class Error(Exception):
""" Raise for an exception in this app """
pass
class NotValidCoinValue(Error):
""" When the value does not match the available ones. """
def __init__(self):
super().__init__("The value is not available")
class CoinAttributeError(Error):
""" Only Coin object avail... |
4d24eb2e43a3f1fc37132ab82470f0127b4535e1 | kunata928/python_functions | /leetcode_solutions(1).py | 1,194 | 3.75 | 4 | import itertools
import math
def multiply1(num1, num2) -> str:
res = str(int(num1) * int(num2))
return res
def multiply2(num1: str, num2: str) -> str:
if num1 == '0' or num2 == '0':
return '0'
num = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4,
'5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
... |
e85d275232a800eb6961bced98ee841dd0fd7f5d | KevinTsaiCoding/LiveCoding | /Python/Tutorial/003_list-tuple.py | 582 | 3.96875 | 4 | # 有序可變動列表 List (列表意思類似 C語言的陣列)
grades=[12,60,15,70,90]
print(grades[0])
# 變更列表裡的值, 把 55 放到列表中第一個位置
grades[0]=55
print(grades[0])
grades[1:4]=[]
""" 列表名稱[?:!]=[] 意思是把 列表中第?個位子
到第!個位子刪除 """
print(grades)
# 有序不可動列表 Tuple (列表意思類似 C語言的陣列)
data=(3,4,5)
print(data)
print('\n') # 換行
print(data[0:2])
"""
data[0]=5 錯誤... |
5e7b6a828549f431d40fa054c50450c24f6d6e79 | madara-tribe/AlphaZero_TicTacToe | /LR-algorithms/Tic-Tac-Toe/mini_max_action.py | 1,369 | 3.53125 | 4 | import random
# ミニマックス法で状態価値計算
def cal_value_by_mini_max(state):
# 負けは状態価値-1
if state.is_lose():
return -1
# 引き分けは状態価値0
if state.is_draw():
return 0
# 合法手の状態価値の計算
best_score = -float('inf')
for action in state.legal_actions():
score = -cal_value_by_mini_max(st... |
df285e765e14c3e52ad754416131402c786dd4ed | brandle26/Learning | /Section 4 - Pandas/Lec 18 - Drop Entry/Drop_Entry.py | 650 | 3.796875 | 4 | import numpy as np
from pandas import Series,DataFrame
import pandas as pd
ser1=Series(np.arange(3),index=['a','b','c'])
print(ser1)
print("="*50)
#dropping an index
print(ser1.drop("b"))
print("="*50)
#dropping on dataframe
dframe1=DataFrame(np.arange(9).reshape((3,3)),index=["SF","LA","NY"],columns=["... |
f2f72ff26c869436946fa208fd716396f67d2b69 | brandle26/Learning | /Section 4 - Pandas/Lec 23- MIssing Data/missingData.py | 1,412 | 3.609375 | 4 | import numpy as np
from pandas import Series,DataFrame
import pandas as pd
data=Series(["one","two",np.nan,"four"])
print(data)
print("="*50)
#chekcing if there is a null value in the serices
print(data.isnull())
print("="*50)
#dropping null value
print(data.dropna())
print("="*50)
#working with dat... |
3264f6baf0939442a45689f1746d62d6be07eece | aacampb/inf1340_2015_asst2 | /exercise2.py | 2,014 | 4.5 | 4 | #!/usr/bin/env python
""" Assignment 2, Exercise 2, INF1340, Fall, 2015. DNA Sequencing
This module converts performs substring matching for DNA sequencing
"""
__author__ = 'Aaron Campbell, Sebastien Dagenais-Maniatopoulos & Susan Sim'
__email__ = "aaronl.campbell@mail.utoronto.ca, sebastien.maniatopoulos@mail.utoron... |
9e588c6baf50932fa110c6f72645a6ae2c9274b8 | jdpoints/python | /roll.py | 3,164 | 3.53125 | 4 | import sys
import re
from random import randint
pattern = (
r"^(?:(?:\[([1-9][0-9]{1,2}|[2-9])" #match.group(1) 2-999 valid
"/([1-9][0-9]{0,2})" #match.group(2) 1-999 valid
"([\+\-])?\])" #match.group(3) + or - valid
"|([1-9][0-9]{0,2}))?" #match.group(4) 1-999 valid
"d([1-9][0-9]{1,2}|[2-9])"... |
313f48aadc4c94d41ee421e57984c8489d3ee4d4 | zerosai7/scenic_tourist_information_system | /test4.py | 134 | 3.53125 | 4 | import re
string=input()
result=re.search(re.compile('(.*?)/(.*)/(.*)'),string)
print(result)
print(result[1],result[2],result[3]) |
6a23fff85f3e17d471083c8b8ef6dcd64c75b329 | LiuYyunHao/PythonDemo | /Person.py | 691 | 3.734375 | 4 | class Person:
def __init__(self):
self.__age = 20
# @property
# def age(self):
# return self.__age
#
# @age.setter
# def age(self, value):
# self.__age = value
def get_age(self):
return self.__age
def set_age(self, value):
... |
a4796c4173346b3045f83184127312e5083e4b42 | ngxson/edu-insa-3a | /python/ex34.py | 1,363 | 3.59375 | 4 | print(set('totto'))
# erreur car set([iterable])
# on doit écrire set(('totto'))
print({'totto'})
# affiche {'totto'}
print({{'toto'}, {'tata'}})
# TypeError: unhashable type: 'set'
print('abcde'[-1])
# affiche 'e'
print({'abcde'}[0][1])
# erreur car 'set' n'a pas de ordre
print('abcdefg'[2:5])
# ... |
af799dec3e9a457c8304ed8e9a178e15b31b1782 | bboats/trabFormais | /src/menu.py | 2,332 | 3.734375 | 4 | #!Python3
import AutomataClasses
from os import system, name
###########################
##### main menu class #####
###########################
class Menu:
"""text-based menu class, receives a list of options and a title as init arguments"""
def __init__(self, options, title='|'):
self.options = options
self.ti... |
052c75ab47504d71824eaf54d2333a6b71c5a3d3 | Sekinat95/May-30-day-leetcode | /day9.py | 308 | 3.8125 | 4 | def isPerfectSquare(self, num: int):
#using binary search
if num<2:
return True
L,R=2,num
while L<=R:
mid=(L+R)//2
if mid**2 == num:
return True
elif mid**2 > num:
R = mid-1
else:
L = mid +1
return False
|
2e4390f52c1c87a8430e3ddd099c74ce74a67b0c | RiccardoTonini/algo_think_2014 | /week1/project1.py | 2,206 | 3.78125 | 4 | """
This modules exposes 3 functions: make_complete_graph, compute_in_degrees, in_degree_distribution
"""
# Represents graph 1,2,3 as adjancency lists
EX_GRAPH0 = {0: set([1, 2]), 1: set([]), 2: set([])}
EX_GRAPH1 = {0: set([1, 4, 5]), 1: set([2, 6]), 2: set([3]),
3: set([0]), 4: set([1]), 5: set([2]), 6: set([])}
... |
af0b765e91865a5b1ab26e54593e65af36066423 | dongso/Python-Project | /day4.py | 3,658 | 3.734375 | 4 | i = 0
while True:
print(i)
i = i+1
if i == 100:
break
for i in range(10000):
print(i)
if i==100:
break
# ****
# ****
# ****
for i in range(3):
for j in range(4):
print("*",end='')
print("\n")
# *
# **
# ***
# ****
for i in range(1,5):
for j in range(i):
... |
b355ffb5f1e84b9f6ec449c9fc0c6319c6e54e21 | dongso/Python-Project | /day4-prac.py | 1,817 | 3.890625 | 4 | #문제 1
print("문제 1번 ******************")
for i in range(1,6):
for j in range(0,i):
print(" ",end='')
print("*\n")
#문제 2
print("문제 2번 ******************")
for i in range(2,10) :
print("%i단 시작 -->"%i)
for j in range(1,10):
print("%s * %s = %d"%(i,j,i*j))
#문제 3
print("문제 3번 ***************... |
d2aa07f91a4fff951d42cb84bde47fe9ae61c0d9 | dongso/Python-Project | /day6.py | 6,627 | 3.640625 | 4 | # #정규표현식 : 패턴(규칙)을 가진 문자열을 표현하는 방법
# #규칙이 있는 문자열을 추출, 변경 등의 작업을 수행하기 위해 작성
# #re module을 사용해서 정규표현식 작성.
# #re.match('패턴','문자열')을 사용.
#
import re
print(re.match('Hi', 'Hello, hi, world'))
print(re.match('hi', 'hi, world')) #문자열의 첫번째부터 비교해서 있으면 span(0,n) return
print('hello hi, world'.find('hi')) #문자열의 시작위치가 나옴
# #re.mat... |
8dff4ae8dc22466b0feaa8abb4a1e421ea4401e8 | sesch023/Python-Uebungen | /Übung (Übersetzer Schwierigkeit 4)/Lösung.py | 479 | 4.0625 | 4 | dictionary = {
"Zug": "train",
"Hochschule": "university",
"Küche": "kitchen",
"Tisch": "table",
"Computer": "computer"
}
eingabe = input("Bitte geben sie ein Wort zum Übersetzen ein: ")
while eingabe != "ende":
if eingabe in dictionary:
print(f"{eingabe} -> {dictionary[eingabe]}")
... |
21b82a9809a13020bb6e3f6cec6dacb75bd638f1 | sesch023/Python-Uebungen | /Übung (Vergleich Nutzereingaben Schwierigkeit 2)/Lösung.py | 284 | 3.984375 | 4 | x = float(input("Bitte geben Sie die erste Zahl an: "))
y = float(input("Bitte geben Sie die zweite Zahl an: "))
if x < y:
print("Kleinere Zahl: " + str(x))
print("Größere Zahl: " + str(y))
else:
print("Kleinere Zahl: " + str(y))
print("Größere Zahl: " + str(x))
|
23fc2ba6008d38ce8aec051f0400efe197442efb | klfoulk16/mazes | /util.py | 13,133 | 3.78125 | 4 | import random
from PIL import Image
"""Contains the objects necessary to create and solve various mazes.
Order from top to bottom: Cell, StackFrontier, Queuefrontier, Maze"""
class Cell():
"""Structure to keep track of various cells in the maze and which cell we used to get there"""
def __init__(self, locatio... |
1e4dfefa54c79312347a8f47d26993530358041a | graceke/TowerBlaster | /towerblaster.py | 12,324 | 3.90625 | 4 | import random
turn_count = 0
def setup_bricks():
'''sets up the game main pile with 1-60 in a list and discareded empty then return them as a tuple'''
main_bricks = list(range(1, 61))
discarded_bricks = []
return main_bricks, discarded_bricks
def shuffle_bricks(bricks):
'''shuffl... |
a37130786c5c2843c24c631a50f50252f46d6038 | wenima/codewars | /kyu4/Python/src/holdem.py | 2,473 | 3.78125 | 4 | """Solution for https://www.codewars.com/kata/texas-holdem-poker/python."""
from collections import Counter, defaultdict
from operator import itemgetter
CARDS = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
class PokerHand(object):
def __init__(self, hand):
self.values = sorted([CAR... |
d01bb2f5979a27a5effb327f51e40ea9402906fa | wenima/codewars | /kyu4/Python/src/test_next_bigger.py | 846 | 3.609375 | 4 | """Tests for codewars kata https://www.codewars.com/kata/next-bigger-number-with-the-same-digits."""
import pytest
TEST_BIGGEST = [
(9, True),
(111, True),
(531, True),
(123, False),
(9998, True),
(54321, True),
]
TEST_INPUT = [
(999, -1),
(12, 21),
(513, 531),
(2017, 2071),
... |
ffd69ed1f0ce038a4e5856193af501b38e3df2db | wenima/codewars | /kyu3/src/sudoku_solver_hard.py | 12,269 | 4.03125 | 4 | """Module to solve the code-kata https://www.codewars.com/kata/sudoku-solver."""
from math import sqrt, ceil
from itertools import islice, chain, groupby
from operator import itemgetter
from collections import defaultdict
def sudoku_solver(m):
"""Return a valid Sudoku for a given matrix.
Store all startin... |
e88fde32a4ed8daa66714905a4d258032ec9a473 | wenima/codewars | /kyu5/python/src/best_travel.py | 418 | 3.625 | 4 | """Module to solve the code-kata https://www.codewars.com/kata/best-travel/train/python."""
from itertools import combinations
def choose_best_sum(t, k, ls):
"""Return a value closest to, but not great than, t out of a combination of
elements in ls with size k.
"""
best = 0
for c in combinations(l... |
9b5b28301d930fefb61ae250b93fe05e7fb34bd8 | wenima/codewars | /kyu5/python/src/prime_factorization.py | 954 | 4 | 4 | """Module to solve https://www.codewars.com/kata/prime-factorization."""
from collections import defaultdict
class PrimeFactorizer(int):
def __init__(self, n):
"""Initialize a Prime object."""
def prime_factors(self):
"""Return a list of prime factors for a given number in ascending order.... |
7c423e6b96739cfdfe456783f34bb3b1d95c7d07 | wenima/codewars | /kyu5/python/src/domain_name.py | 673 | 3.84375 | 4 | """Module to solve the code-kata
https://www.codewars.com/kata/extract-the-domain-name-from-a-url-1/train/python.
This is just a proof of concept/prototype. The correct solution covering all
domain names as well as private domains is alot more complicated. It would
involve getting the current viable top-level domains a... |
e900d08e1f44c4ca6fa0a6a451bc9d379e346c1a | SwierkKlaudia/python | /basics/lists.py | 11,112 | 3.734375 | 4 | # 1
def L1(elements):
sum_elem = 0
for list_elem in elements:
sum_elem += list_elem
return sum_elem
print("L1:",L1([1, 4, 19]))
# 2
def L2(elements):
mult_elem = 1
for list_elem in elements:
mult_elem *= list_elem
return mult_elem
print("L2:",L2([1, 4, 19]))
# 3
def L3(el... |
02bebd11b10ef4d17d530355ec86707b9057900e | ijazali5555/my-project | /loops.py | 89 | 3.5625 | 4 | for i in range (1, 10+1):
print (i)
print("Hello")
for i in range (10):
print(i)
|
dcfe8eb511f4b1a89852df183bb01fcd35d9d924 | sxhmilyoyo/Algorithm_Python | /topologicalSort.py | 1,325 | 3.53125 | 4 | class DirectedgraphNode():
def __init__(self, x):
self.label = x
self.neighbors = []
class Solution():
def dfs(self, i, countrd, ans):
ans.append(i)
countrd[i] -= 1
for j in i.neighbors:
countrd[j] = countrd[j] - 1
if countrd[j] == 0:
... |
72c683ad118af4ccde4a1b82886052c2e1a06046 | sxhmilyoyo/Algorithm_Python | /parseMathExprTree.py | 2,143 | 3.671875 | 4 | from Tree import *
from Stack import *
import operator
def parseTree(expr):
exprList = expr.split()
r = Tree('')
s = Stack()
s.push(r)
currentTree = r
for i in exprList:
if i == '(':
currentTree.inserLeft('')
s.push(currentTree)
currentTree = current... |
ee72d040abf29e921923c49602687d93fb4ae955 | sxhmilyoyo/Algorithm_Python | /test.py | 2,256 | 3.546875 | 4 | def recMinCoin(availableCoins, money):
# baseline: use the penny
minNumber = money
# subproblems
# recMinCoin(money-i)
if money in availableCoins:
return 1
# choices
else:
for i in [c for c in availableCoins if c <= money]:
# recursive
number = rec... |
3c6dc004885df3bd3ea923b825914c23d1a5e824 | tomaswender/praktic2 | /lesson3/task_7.py | 1,005 | 3.796875 | 4 | #7. В одномерном массиве целых чисел определить два наименьших элемента.
# Они могут быть как равны между собой (оба являться минимальными), так и различаться.
import random
arr=[]
arr2=[0,0,0]
for i in range(30):
arr.append(random.randint(0, 10))
for i in range(0, len(arr)):
if arr[i]>0:
arr2[0], a... |
c7bcfb032cb28fd655e128c0438245b08d4b44b6 | tomaswender/praktic2 | /lesson3/task_1.py | 412 | 3.6875 | 4 | #1. В диапазоне натуральных чисел от 2 до 99 определить, сколько из них кратны каждому из чисел в диапазоне от 2 до 9.
list1 = []
list2 = {2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0}
for i in range(2, 100):
list1.append(i)
for n in list1:
for i,y in list2.items():
if n%i==0:
list2[i]=list2[i]+1
print(... |
976fa3e3320c3f98d38e73de80a3ca7d37c3ae14 | RinatZialtdinov/Codewars | /ex14/First_nonrepeating_character.py | 371 | 3.640625 | 4 | def first_non_repeating_letter(string):
if len(string) == 0:
return ""
copy_s = list()
for i in string.lower():
if i not in copy_s:
copy_s.append(i)
else:
copy_s.remove(i)
if len(copy_s) == 0:
return ""
if copy_s[0] in string:
return co... |
ad8fcd08ed6d77c4072cf02aa16394ba4d28ecd6 | kaamayao/AlgorithmsUN2021I | /Lab13/2_primitive_calculator/primitive_calculator.py | 899 | 3.515625 | 4 | # Uses python3
import sys
d = {}
def fillCache(cache):
for i in range(1, len(cache)):
min_operation = cache[i-1] + 1
if i % 3 == 0:
min_operation = min(cache[i // 3] + 1, min_operation)
elif i % 2 == 0:
min_operation = min(cache[i // 2] + 1, min_operation)
... |
44909bca4f4dfb10a59c009503d9fca298f80155 | Amoghk18/AI_1BM18CS014 | /tic-tac-toe.py | 5,859 | 3.640625 | 4 | import random
import time
def printBoard(board):
print()
print("----------------------- Board ----------------------------")
print()
print()
for i in range(3):
print(" ", end="")
for j in range(3):
print(" " + str(board[i][j]) + " ", end=... |
3c4eb1005c04b680331f97fcfb3f09e45b0b7c3d | beng0/my_python_leaning | /t01/practice.py | 2,440 | 3.640625 | 4 | #coding=utf-8
# num = 2
# if num%2 == 0:
# print '{}是偶数'.format(num)
# if num%2 == 1:
# print '%d是奇数'%(num)
# str = 'hello'
# flag = False
# list = ['apple','pear','helloo']
# for n in range(len(list)):
# if list[n] == str:
# print '有这个数了'
# flag = True
# break
# if flag == False:
... |
c710946ade385e713a64c29018a7d3e6c131d51b | metatoaster/IdleISS | /src/idleiss/battle.py | 15,527 | 3.53125 | 4 | from __future__ import division
import random
import math
from collections import namedtuple
from idleiss.ship import Ship
from idleiss.ship import ShipAttributes
from idleiss.ship import ShipLibrary
SHIELD_BOUNCE_ZONE = 0.01 # max percentage damage to shield for bounce.
HULL_DANGER_ZONE = 0.70 # percentage remain... |
ea75860295faafad4a689deb8145f0c822b93910 | ozhatuka/oz | /python_part2B.py | 6,401 | 3.796875 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
def find_most_frequent_year(df, n):
'''
:param df: pd.Dataframe
:param n: positive, integer; n'th most frequent year
:return: int; the n'th most frequent year
:raise: ValueError - if n is not a posi... |
e13e24bf0755c4702df538be012150898740dc46 | lakshmivisalij/dicesimulatorpython | /dice simulator.py | 929 | 3.84375 | 4 | import random
print("Let's roll the dice!")
i = 'y'
while i == 'y':
x = random.randint(1,6)
if x==1:
print(" ---------")
print("| |")
print("| O |")
print("| |")
print(" ---------")
if x==2:
print(" ---------")
print("| |")
print("| O O |")
print("| ... |
5fe747190880d0c7a78641be6b47217b1584a863 | enginSacan/RobotFrameworkExample | /lib/Check_firmware_size.py | 939 | 3.84375 | 4 | """This file is created for checking file size in a specific limit for file specified."""
import os
FIRMWARE_MAX_LIMIT = 40000000
TARGET_PATH = "D:/DM/LSD/MSPS_ITEST/DAT/AutoDAT/"
def file_size(target, file_name, threshold):
"""This function is checking file size under the target folder."""
THRESHOLD = 400*102... |
77ebd8b2998277bbe8377055c10f429680bd833a | witalomonteiro/testes-automatizados | /tests/test_dominio.py | 2,721 | 3.609375 | 4 | from unittest import TestCase
from src.leilao.dominio import Lance, Leilao, Usuario
from src.leilao.excecoes import LanceInvalido
class TestLeilao(TestCase):
def setUp(self):
self.leilao_teste = Leilao("Cavalo")
self.witalo = Usuario("Witalo", 1000)
self.witalo.propor_lance(self... |
c82c07f64dcfb548733526cdb88a990074b57520 | akshatasawhney/BFS-3 | /Problem1.py | 2,066 | 3.703125 | 4 | """
// Time Complexity : o(n)
// Space Complexity : o(n), queue
// Did this code successfully run on Leetcode : yes
// Any problem you faced while coding this : no
// Your code here along with comments explaining your approach
"""
from collections import deque
class Solution:
def is_valid(self, s): #function to c... |
70c4989fada0dd3800427c2da1038807d5abb88a | anhlh93/Techkids | /Season 4/Session4-Assignment 4.4.py | 232 | 3.765625 | 4 | from turtle import*
color("blue")
bgcolor("green")
speed(-1)
def square(length):
for i in range(4):
forward(length)
left(90)
number=20
length=100
for i in range(number):
square(length)
left(360/number)
|
67ec1c51f1bf73cf5f944ace9a89e95882e94250 | kemoelamorim/python_URI | /exercicios_URI/URI_1013.py | 667 | 3.890625 | 4 | """ Faça um programa que leia três valores e apresente o maior dos três valores lidos seguido da mensagem “eh o maior”. Utilize a fórmula:
maiorAB = (a + b + abs( a - b))/2
Obs.: a fórmula apenas calcula o maior entre os dois primeiros (a e b). Um segundo passo, portanto é necessário para chegar no resultado esperado... |
9faf895647e7eb6f6a0fa1f00a4b38bb5bd7ffe9 | sicou2-Archive/pcc | /python_work/part2/alien_invasion/alien_invasion/laser.py | 1,088 | 3.75 | 4 | import pygame
from pygame.sprite import Sprite
class Laser(Sprite):
"""A class to manage lasers fired from the ship."""
def __init__(self, ai_game):
"""Create a laser object at the ship's current position."""
super().__init__()
self.screen = ai_game.screen
self.settings = ai_... |
10e9d887ece56205449d1c3412d614e91bc723ee | sicou2-Archive/pcc | /python_work/part1/ch05/c5_8.py | 1,590 | 3.859375 | 4 | usernames = ['admin', 'todd', 'betty', 'adam', 'scott', 'sally']
def looping(names):
if names:
for name in usernames:
if name == 'admin':
print("Welcome, keeper of the keys. The motor is still "
"running!")
else:
print(f"Welcome u... |
bb81d71014e5d45c46c1c34f10ee857f5763c75a | sicou2-Archive/pcc | /python_work/part1/ch03/c3_4.py | 1,813 | 4.125 | 4 | #Guest list
dinner_list = ['Sam Scott', 'Tyler Jame', 'Abadn Skrettn', 'Sbadut Reks']
def invites():
print(f'You want food {dinner_list[0]}? Come get food!')
print(f'Please honor me {dinner_list[1]}. Dine and talk!')
print(f'Hunger gnaws at you {dinner_list[2]}. Allow me to correct that.')
print(f'Poi... |
f5e0dd2d5fa00bff0eeac7772b2fc041a1c6d2b1 | sicou2-Archive/pcc | /python_work/part1/ch06/c6_1.py | 4,170 | 4.3125 | 4 | alice = {'first_name': 'alice', 'last_name': 'maple',
'city': 'springfield', 'age': 25, 'hair': 'brown',}
for num in alice:
print(alice[num])
#6_2
print("\nNEXT 6_2 and 6-10")
numbers = {'todd': [3, 4, 6, 8,],
'sammy': [5, 7, 3, 8,],
'joe': [6,],
'kyle': [... |
bc7185beb2e51477149df4606d5976d7bd8607bc | sicou2-Archive/pcc | /python_work/part2/alien_invasion/alien_invasion/diy/target_14_2.py | 991 | 3.59375 | 4 | import pygame
class Target:
"""A class for the target in Target Practice."""
def __init__(self, ai_game):
"""Initialize target settings and position."""
self.screen = ai_game.screen
self.settings = ai_game.settings
self.color = self.settings.target_color
self.screen_r... |
f644021c93bb0affb75399edf463fcb554c56ddf | sicou2-Archive/pcc | /python_work/part1/ch11/city_functions.py | 336 | 3.890625 | 4 | """A module for returning a 'City, Country' string."""
def a_city(city, country, population=None):
"""Generate a neatly formatted 'City, Country'"""
if population:
city_country = f"{city}, {country}, population: {population}"
else:
city_country = f"{city}, {country}"
return city... |
a4d7377ac20dd283f71b0101c05f6ed682a4e849 | sicou2-Archive/pcc | /python_work/part1/ch05/amusement_park.py | 622 | 3.890625 | 4 | age = 12
if age < 4:
print("Your admission cost is $0.")
elif age < 18:
print("Your admission cost is $25.")
else:
print("Your admission cost is $40.")
#Better way to do this.
print("Better\n")
age = 12
if age < 4:
price = 0
elif age < 18:
price = 25
elif age < 65:
pri... |
a2ddf6304441dfd004e6d90802554d4dca90467a | ayymk/code-algo-dicho | /find_the_number.py | 403 | 3.671875 | 4 | from random import *
x =randint(0,100)
y=int(input("Trouve le nombre entre 0 et 100: "))
z=0
while y!=x and z<7:
z=z+1
if y<=x:
y=int(input("Le nombre recherché est plus grand, réessaye: "))
else:
y=int(input("Le nombre recherché est plus petit, réessaye: "))
if x==y:
print ("bravo c'est bien... |
91d8233f7d92a9b1a60d8a8d4226b250cc4833df | dilynfullerton/vpython | /projectile.py | 4,065 | 3.75 | 4 | __author__ = 'Alpha'
from visual import *
# Simple program where projectile follows path determined by forces applied to it
# Velocity is vector(number, number, number)
# Force is vector(number, number, number)
# Momentum is vector(number, number, number)
# Mass is number
# Position is vector(number, number, nu... |
35d5bf06474999e2fdb2d06b16b2081abd52ca9d | Ashikur-ai/Starry-sky-with-python | /Game development 6.py | 544 | 3.9375 | 4 | import turtle as t
import random as r
# defining screen
win = t.getscreen()
win.bgcolor("black")
# defining turtle
rock = t.Turtle()
rock.color("yellow")
rock.speed(0)
# get random cordinate
for i in range(50):
x = r.randint(-300, 300)
y = r.randint(-300, 300)
# Turtle up down and... |
7d8db8c7e276d208bb4e6fa3b92539e76cb9ff71 | anantkaushik/stein | /python/problems/array/reverse.py | 262 | 3.96875 | 4 | def reversed_arr(arr,count):
if count==len(arr):
return arr
temp = arr[count]
count += 1
reversed_arr(arr,count)
arr[len(arr) - 1 - (count - 1)] = temp
return arr
arr = [22, 11, 20, 76, 123, 70]
count=0
print ("Reversed array: ",reversed_arr(arr,count)) |
e38fec0a8e17078c5e29d5c2bbd6e1db604a1af7 | alexandermfisher/cs50_artificial_intelligence | /01 - Knowledge/minesweeper/minesweeper.py | 11,932 | 4.3125 | 4 | import itertools
import random
class Minesweeper():
"""
Minesweeper game representation
"""
def __init__(self, height=8, width=8, mines=8):
# Set initial width, height, and number of mines
self.height = height
self.width = width
self.mines = set()
# Initializ... |
d56a0b6bc5da1d2a3e7000ac10738c93caf7875a | diacarcor/day-3-5-exercise | /main.py | 890 | 4.09375 | 4 | # 🚨 Don't change the code below 👇
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
#Combine both lower names
names = name1.lower() + name2.lower()
#Calculate digit one
digit... |
a30f252bdb52d336ef70f5d1e7f7deaf388568a3 | bmasse/Dev | /Python/L_Intro_A_Python/code/chap5/pipoem.py | 1,424 | 3.703125 | 4 | #!/usr/local/bin/python
# Contribution to the forever lasting discussion on indentation!
# After Petrarca, Shakespeare, Milton, Drs. P and many, many others,
# a sonnet has 14 lines and a certain rhyme scheme.
# Jacques Bens presented in 1965 in Paris the pi-sonnet with
# 3,1,4,1 and 5 lines, but the ultimate pi-poem... |
25dbf9ad6efbef56ef718b4c0c8095b38cc4e933 | TroyCode/Super-Blinder | /app/stastics.py | 1,158 | 3.609375 | 4 | import time
class Words:
def __init__(self):
self.count_list = []
def add_list(self, word_array, time):
for word in word_array:
is_inside = False
for item in self.count_list:
if word in item["Name"]:
is_inside = True
item["Count"] = item["Count"] + 1
item[... |
b7df9f711fba030043cb701c961918d9ff2d51f2 | diegoasanch/Project-Euler | /16 - Power Digit sum.py | 115 | 3.765625 | 4 | def digit_sum(number):
digits = [int(x) for x in str(number)]
return sum(digits)
print(digit_sum(2**1000)) |
e6873cf3124c7d86f97c7a744f6e6da908a908c4 | sun1218/MyTest | /fab_test.py | 676 | 3.515625 | 4 | class Fab(object):
def __init__(self, max):
self.max = max
self.n, self.a, self.b = 0, 0, 1
def __next__(self):
if self.n < self.max:
r = self.b
self.a, self.b = self.b, self.a + self.b
self.n += 1
return r
raise StopIteration()
... |
8ab27a2740fb89fe98d49ea63d334f7e5caec3c0 | kenu/g-coin | /gcoin/proof.py | 756 | 3.84375 | 4 | import hashlib
DIFFICULTY = 1 # number of digits is difficulty
VALID_DIGITS = '0' * DIFFICULTY
def valid_proof(last_proof, proof):
""" Validates proof
last digits of hash(last_proof, proof)
== VALID_DIGITS
Args:
last_proof (int): previous proof
proof (int): proof to validate
... |
86850fbb6c751efce65db5088fb83dee06b6ae84 | chrisullyott/wordsearch-solver | /app/file.py | 205 | 3.9375 | 4 | """
Helpers for files.
"""
def read_file_upper(filename):
"""Read a file as an uppercase string."""
with open(filename) as file:
contents = file.read().strip().upper()
return contents
|
d11c1c967cc19dff7e538080266d08eb9f148366 | GSacchetti/Segmentation-of-multispectral-and-thermal-images-with-U-NET | /Construction_data/excel_to_tif_array.py | 5,669 | 3.578125 | 4 | #######. This algorithm is to convert the excel files into tiff images and arrays. #######
#Our dataset were in the form of excel tables, to convert these tables into a tiff image, I created this Convert function.
#To perform this conversion, we have calculated a displacement step called "step",
#because this table... |
73097e79c8ed996ebe58bc1638b3dfc938750d0e | abishamathi/python-program- | /even numbers.py | 120 | 3.546875 | 4 | even = []
for n in l :
if(n % 2 == 0):
even.appened(n)
return even
print(even num([1,2,3,4,5,6,7,8,9]))
|
8b3f291d7d9b0ecd8bc8584833a650e913c94773 | abishamathi/python-program- | /number of spaces.py | 124 | 3.703125 | 4 | fname=input('Enter file name:')
words=line.splits()
if(letter.isspace):
k=k+1
print('Occurrance of blank spaces:')
print(k)
|
0a4cc84bd54d8e538b82324172d78b145d7df88e | abishamathi/python-program- | /largest.py | 226 | 4.21875 | 4 | num1=10
num2=14
num3=12
if (num1 >= num2) and (num1 >= num3):
largest=num1
elif (num2 >= num1) and (num2 >=num3):
largest=num2
else:
largest=num3
print("the largest num between",num1,"num2,"num3,"is",largest)
|
54ed98a7d0f6c1fdde317afe0b8ff53b0cefe343 | LucaRuggeri17/pdsnd_github | /script.py | 7,337 | 4.125 | 4 | # Explore Bikeshare data
# Data creation May 2020
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to anal... |
935f658529bd76c0f58a1dc795567d10ead00b20 | mhtarek/Uri-Solved-Problems | /1049.py | 648 | 3.78125 | 4 | x= input()
y= input()
z= input()
if x == "vertebrado":
if y=="ave":
if z=="carnivoro":
print("aguia")
elif z == "onivoro":
print("pomba")
elif y=="mamifero":
if z=="onivoro":
print("homem")
elif z == "herbivoro":
prin... |
cf3ef53dc91ea47ef1cdd9cc7c5fc36c05732d61 | mhtarek/Uri-Solved-Problems | /1216.py | 205 | 3.734375 | 4 | sum = 0
count = 0
while True:
try:
input()
sum+=int(input())
count+=1
except EOFError:
avg = float(sum/count)
print("%.1f" % avg)
break
|
033a7a9082b24b1ba9781d4ae26c98eac30cf805 | mhtarek/Uri-Solved-Problems | /1161.py | 249 | 3.5625 | 4 | def fact(m):
if m==1 or m==0:
return 1
else:
return m*fact(m-1)
while True:
try:
ar = [int(i) for i in input("").split()]
print(fact(ar[0])+fact(ar[1]))
except EOFError:
break
|
c289e68604c1ec7c15f08f2ab33b64e44a63983e | FuelDoks48/Project | /command_if.py | 1,410 | 3.515625 | 4 |
# Обработка специальных значений
# requsted_topping = ['mushrooms', 'green peppers', 'extra chesse']
# for requsted_topping in requsted_topping:
# print (f'Adding {requsted_topping}.')
# print(f'Finished make your pizza!')
# __________________________________________________________
#
# Проверка вхождений
# ... |
c76282a14c6a1c54f0566890377035a533786f6c | Engineering-Course/LIP_JPPNet | /get_maximum_square_from_segmented_image.py | 3,716 | 3.609375 | 4 | # This function is used to get the largest square from the cropped and segmented image. It can be further used to find patterns
import cv2
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import time
from collections import namedtuple
import glob
def printMaxSubSquare(M):
"""" find the lar... |
da16b14210a67f0b8bff8212d023eff2040e5424 | AlifeLine/toolkit | /tools/quick_sort2.py | 617 | 4 | 4 | def quick_sort(arr, left=0, right=None):
if right is None:
right = len(arr) - 1
if left >= right:
return
l = left
r = right
key = arr[left]
while left < right:
while left < right and arr[right] >= key:
right -= 1
arr[left] = arr[right]
while... |
72a89c29b77bca2fcada96ce5a4b46cc965128c4 | AlifeLine/toolkit | /tools/lru.py | 815 | 3.8125 | 4 | class Node(object):
def __init__(self, val):
self.val = val
self.next = None
class Lru(object):
def __init__(self, vals):
self._head = None
for val in vals:
node = Node(val)
if self._head:
self._head.next = node
else:
... |
bd001f39c500f13c409b9e4f22f41156cabc636d | leolion0/490-Lesson-3 | /question 1.py | 1,451 | 3.890625 | 4 | class Employee:
numEmployees = 0
def __init__(self, name="", family="", salary="", department=""):
self.name = name
self.family = family
self.salary = salary
self.department = department
Employee.numEmployees += 1
def fillFromUser(self):
self.name = str(inpu... |
6ee056c951856f4bc7e8e6bd7d95b10865c3085b | rohitbapat/NQueensNRooks-Problem | /a0.py | 8,287 | 4.1875 | 4 | #!/usr/bin/env python3
# nrooks.py : Solve the N-Rooks problem!
#
# The N-Queens problem is: Given an empty NxN chessboard, place N queens on the board so that no queens
# can take any other, i.e. such that no two queens share the same row,column or are on the same diagonal
#
# Citations mentioned at the end of the cod... |
bad58f360c606e5a92312ffd2115872b42fffd57 | tenasimi/Python_thero | /Class_polymorphism.py | 1,731 | 4.46875 | 4 | # different object classes can share the same name
class Dog():
def __init__(self, name):
self.name = name
def speak(self): # !! both Nico and Felix share the same method name called speak.
return self.name + " says woof!"
class Cat():
def __init__(self, name... |
5cd6aae2bacc1b6626dafbc541c626c811e67aac | tenasimi/Python_thero | /Class_Inheritance.py | 717 | 4.15625 | 4 | class Animal():
def __init__(self):
print("ANIMAL CREATED")
def who_am_i(self):
print("I am animal")
def eat(self):
print("I am eating")
myanimal = Animal() #__init__ method gets automatically executed when you
# create Anumal()
myanimal.who_am_i()
myanim... |
ef64e2b1091b79e6c1df275002c49bb501b70759 | tenasimi/Python_thero | /test_test_test.py | 1,345 | 3.828125 | 4 | print(1 % 2)
print(2 % 2)
print(3 % 2)
print(4 % 2)
print(5 % 2)
print(6 % 2)
print(7 % 2)
print(8 % 2)
print(9 % 2)
def almost_there(n):
return (abs(100-n) <= 10) or (abs(200-n) <= 10)
print(almost_there(190))
print(abs(20-11))
#help(map)
print()
def square(num):
return num**2
print(square(6))
def up_low... |
6abeba2d5f744e34aa97a48fe06a5dac4cf27207 | tenasimi/Python_thero | /sec4_comparison_operators.py | 7,715 | 4.46875 | 4 | print(1 < 2 and 2 > 3)
print(1 < 2 and 2 < 3)
print('h' == 'h' and 2 == 2) # AND!! both of them must be true
print(1 == 2 or 2 < 3) # OR!! one of them must be true
print(not 1 == 1) # NOT !! for opposite boolean result
#
if True:
print('ITS TRUE!')
#
if False:
print('ITS False!')
else:
print('Its always Tru... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.