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 |
|---|---|---|---|---|---|---|
0ac3164ef281adcb3582b9e021f4ce07829f32de | kirteekishorpatil/dictionary | /Q_10_counting.py | 178 | 3.84375 | 4 | dict = {
'Alex': ['subj1', 'subj2', 'subj3'],
'David': ['subj1', 'subj2']}
i=0
count=1
while i<len(dict):
count=count+len(dict)
i=i+1
print("totalcount",count)
|
2791583af83b9ff15ac5fe9d30acd2313e6cfd2a | kirteekishorpatil/dictionary | /studant_data_8.py | 375 | 4.34375 | 4 | # i=0
# dict1={}
# if i<3:
# num=input("enter the student name")
# num2=int(input("enter the students marks"))
# i=i+1
# new_type={num:num2}
# dict1.update(new_type)
# print(dict1)
num=input("enter the student name")
num2=int(input("enter the students marks"))
# i=0
dict1={}
# while i<8:
new_type={... |
48c828ff98de27eff0e2e7bae0b3c752f0abf64f | cxzzzz/algorithms | /leetcode/3.无重复字符的最长子串.py | 1,523 | 3.65625 | 4 | #
# @lc app=leetcode.cn id=3 lang=python3
#
# [3] 无重复字符的最长子串
#
# https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/description/
#
# algorithms
# Medium (28.49%)
# Total Accepted: 90.4K
# Total Submissions: 316.6K
# Testcase Example: '"abcabcbb"'
#
# 给定一个字符串,请你找出其中不含有重复字符的 ... |
d7a258f5c7aaeaba9f1767eb419e0810dde36c24 | TriniBora/CodoACodo-DWFullStackPyhton | /Ejercicios/Python/Estructurada/05.py | 446 | 4.09375 | 4 | '''Escribe un programa que pida dos números y escriba en la pantalla cual es el
mayor.'''
num1 = int(input("Ingrese el primer número: "))
num2 = int(input("Ingrese el segundo número: "))
#print(f"El numero {num1} es el mayor") if num1 > num2 else print(f"El numero {num2} es el mayor")
if num1 > num2:
(f"El nume... |
10a92a8db224c7d81ac7c9324ef384735cf2884a | daniel2234/python_fundamentals | /python_fundamentals_objects/person.py | 1,030 | 3.96875 | 4 | class Person:
def __init__(self, fname, lname, x=0, y=0):
self.first_name = fname
self.last_name = lname
self.x_position = 0
self.y_position = 0
def __str__(self):
return "Person object:{}".format(self.full_name())
def introduce(self):
return "Hello, my name... |
7af8b77a791d567ac85b2749936633f166f719f7 | Ratashou/Tic-Tac-Toe | /tictactoe.py | 2,675 | 4.25 | 4 | #! python3
#A program to make a simple tic tac toe/noughts and crosses game
theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ',
'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ',
'bot-L': ' ', 'bot-M': ' ', 'bot-R': ' '} #the different positions on the board
def printBoard(ticSpace):
print(ticSpace['top-L'] + '|... |
40147a8acbc73ab53ad7f2195b00ba8092ec0ee5 | MananDesai54/python | /learning/jsonModule/app.py | 510 | 3.78125 | 4 | import json;
string = '{"name":"Manan","languages":["python","javaScript"]}';
json1 = json.loads(string);
print(json1);
with open('data.json') as f:
a = json.load(f);
print(a['name']);
dict1 = {
"name" : "Manan",
"coder" : True,
"language" : ('js','py','c/c++'),
"hobby" : ['co... |
73994e06f35f05a6a877d6c2fe03c2cf8c24acc7 | MananDesai54/python | /passwordGenerator/password.py | 866 | 3.671875 | 4 | import string
import random
if __name__ == "__main__":
s1 = string.ascii_lowercase
s2 = string.ascii_uppercase
s3 = string.digits
s4 = string.punctuation
allChar = []
allChar.extend(list(s1))
allChar.extend(list(s2))
allChar.extend(list(s3))
allChar.extend(list(s... |
129eea6362ba30c2e4706166ce1d325765f23128 | Fedalto/n-puzzle | /heuristica.py | 5,510 | 3.75 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Heuristica (object):
""" Classe base de heurísticas. """
def __init__ (self, n):
self.n = n
def _lde(self, x):
""" Linha que X deveria estar """
return x==0 and self.n-1 or (x-1)/self.n
def _cde(self, x):
""" Coluna ... |
7da4990756849a0f4c50691ff3cc268c10bad0d4 | soukainamelhaoui/Atelier-1-2 | /Exercice1-8.py | 349 | 3.703125 | 4 | # Fonction qui calcul le nombre d'occurrence d'un nombre
def frequence(word, x):
c = 0
for i in range(len(word)):
if x in word[i]:
c += 1
return c
x = "y"
word = "heyy"
# Affichage du nombre d'occurrence d'un caractère
print ("L'element ", x, "est ", frequence(word, x), "fois dans votr... |
aa8135dd92bdb44d0c527f65d5576158f04640f1 | soukainamelhaoui/Atelier-1-2 | /Exercice2-3.py | 478 | 3.703125 | 4 | # Fonction qui calcul le nombre d'occurrence d'un élément
def dicList(lst):
dct = {}
for i in range(len(lst)-1):
c = 0
for j in range(len(lst)):
if lst[i] == lst[j]:
c += 1
dct[lst[i]] = c
return dct
l = [1, 2, 2, 3, 4, 3, 2, 1, 5]
# Affichage du diction... |
2bbf90d8645ba21f97c0e4fc635cd50be9bffe2c | milnorms/pearson_revel | /ch7/ch7p5.py | 841 | 4.15625 | 4 | '''
(Sorted?)
Write the following function that returns True if the list is already sorted in increasing order:
def isSorted(lst):
Write a test program that prompts the user to enter a list of numbers separated by a space in one line and displays whether the list is sorted or not. Here is a sample run:
Sample Run 1... |
97d6ffbe6671998c18f37757459a61aea61de6f0 | milnorms/pearson_revel | /ch8/ch8p4.py | 1,626 | 4.46875 | 4 | '''
(Markov matrix)
An n by n matrix is called a positive Markov matrix if each element is positive and the sum of the elements in each column is 1. Write the following function to check whether a matrix is a Markov matrix:
def isMarkovMatrix(m):
Write a test program that prompts the user to enter a 3 by 3 matrix of... |
c15f0bec4691b59ccddfa52d5cf261f07b0ea133 | milnorms/pearson_revel | /ch2/ch2p1.py | 743 | 3.96875 | 4 | '''
(Financial application: calculate tips)
Write a program that reads the subtotal and the gratuity rate and computes the gratuity and total. For example, if the user enters 10 for the subtotal and 15% for the gratuity rate, the program displays 1.5 as the gratuity and 11.5 as the total. Here is another sample run:
... |
d5ae42360d6c5b28032c26f94bf5570608378ae7 | milnorms/pearson_revel | /ch4/ch4p2.py | 888 | 4.3125 | 4 | '''
(Convert letter grade to number)
Write a program that prompts the user to enter a letter grade A/a, B/b, C/c, D/d, or F/f and displays its corresponding numeric value 4, 3, 2, 1, or 0.
Sample Run 1
Enter a letter grade: B
The numeric value for grade B is 3
Sample Run 2
Enter a letter grade: b
The numeric val... |
c54e78731fa62bc05f222e87bb91d0961b89766a | milnorms/pearson_revel | /ch2/ch2p5.py | 1,009 | 4.21875 | 4 | '''
(Financial application: calculate future investment value)
Write a program that reads in an investment amount, the annual interest rate, and the number of years, and then displays the future investment value using the following formula:
futureInvestmentAmount = investmentAmount * (1 + monthlyInterestRate) ^ numbe... |
222ef0b76f9c6af3093c26bdc8db3c19be0091b0 | symonkipkemei/DataFlair-Python-Course | /1.4 Basic Python Syntax.py | 3,731 | 4.03125 | 4 | # SYNTAX STRUCTURE IN PYTHON
# 1. PYTHON LINE STRUCTURE
print("I am composed of logical lines")
print("a ne token follows each of those")
# 2.PYTHON MULTILINE STRUCTURE
# Double quotes on string in every new line
# makes it readable but does not create a paragraph
print("HI "
"how are you symon")
print("\n"... |
c7f58b891057a659e5ba8b7baf00bde7d6a3b087 | Saksykov/Stepik_Python_Courses | /python_basics_and_application/pop3.2.1.py | 280 | 3.78125 | 4 | # Стандартные методы и функции для строк
s = input().strip()
a = input().strip()
b = input().strip()
cnt = 0
if a in s and a in b:
print('Impossible')
else:
while s.find(a) != -1:
s = s.replace(a, b)
cnt += 1
print(cnt) |
bfe7eb6e9a53b9c10f269f143867e50555cdf4ce | Saksykov/Stepik_Python_Courses | /python_basics_and_application/pop1.6.3.py | 266 | 3.5 | 4 | import time
class Loggable():
def log(self, msg):
print(str(time.ctime()) + ": " + str(msg))
class LoggableList(Loggable, list):
def append(self, _T) -> None:
self._T = _T
Loggable.log(self, self._T)
list.append(self, _T) |
dbd4e4c237851a9bc7c4598d90526dc6bcbda9d3 | Saksykov/Stepik_Python_Courses | /adaptive_trainer/ad5.8.py | 214 | 3.5 | 4 | # Koch curve
n = int(input())
def koch(x):
if x == 0:
return
koch(x - 1)
print('turn 60')
koch(x - 1)
print('turn -120')
koch(x - 1)
print('turn 60')
koch(x - 1)
koch(n)
|
f96567cd7769179e1192ddda76022832c3454a8f | Saksykov/Stepik_Python_Courses | /introduction_to_python_practicum/lesson2.2_step5.py | 533 | 4.125 | 4 | """
Простое число делится без остатка только на 1 и на само себя.
Напишите программу, которая прочитает число и выведет "prime" если число простое и
"composite" в противном случае (без кавычек).
"""
x = int(input())
j = x - 1
f = True
while j > 1:
if x % j != 0:
j -= 1
continue
else:
f ... |
4f93d1b7847ec9d3e813c1503236590228c01b22 | lmsanchezv/spell-checker | /ElapsedTimeFormatter.py | 401 | 3.578125 | 4 | from datetime import timedelta
import time
class ElapsedFormatter():
def __init__(self):
self.start_time = time.time()
def format(self, record):
elapsed_seconds = record.created - self.start_time
#using timedelta here for convenient default formatting
elapsed = timedelta(secon... |
d5190ae9ca8ffa8b9063985b8df9a6d6b4f609f0 | mfreedman15/CUS1166_mfreedman15_git-test.- | /02_python_flask/01_first/app.py | 542 | 3.6875 | 4 | #Importing Flask class from the flask module
from flask import flask
#Create an instane of Flask class
app = Flask(__name__)
#This we define a new route
# -- Flask is designed in terms of routes
#-- Routes are part of the URL a client is requesting
#-- When a user goes to the default route -- this is the function I w... |
b739f7234edb9a80f55cd7189512a7455ebc33de | Jaisu-Algorithms/Hashing-1 | /isomorphicWords.py | 600 | 3.640625 | 4 | """
Time Complexity : O(N)
Space Complexity : O(N)
Did this code successfully run on Leetcode : yes
Any problem you faced while coding this : no
"""
import collections
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
d_s = collections.defaultdict(list)
d_t = collections.defau... |
94e1e2f107723e9ea3d4ea648cbd16487b69af16 | pectoraux/python_programs | /question5.py | 2,323 | 4.125 | 4 | '''
Efficiency:
----------------------------------------------
member function get_length() of class Linked_List runs in O(1)
member function get_at_position() of class Linked_List runs in O(n)
make_ll() runs in O(n)
So question5() runs in O(n)
'''
class Node(object):
def __init__(self, da... |
8922a01071d644395e7e6e57c5043bf676ccf8aa | patpij2/Different-Types-of-Data-Sorting | /robot.py | 422 | 3.515625 | 4 | def robot(batP,dlD):
bateria = sum([i for i in range(batP+1)])+1
droga = dlD
x = 0
i = -1 #kierunek
while bateria > 0:
if x == droga or x == 0:
i+=1
bateria-=1
bateria-=1
if bateria < 0 :
print('STOP')
if... |
6f03403f56b965bbe74e8d162f811966a3a9a105 | Escended/Chat-bot | /chat_bot.py | 1,321 | 3.953125 | 4 | def greet(bot_name, birth_year):
print(f'Hello! My name is {bot_name}.')
print(f'I was created in {birth_year}.')
def remind_name():
print('What is your name?...')
name = input()
print(f'Pleasure to make your acquaintance, {name}.')
def guess_age():
print('I bet I can guess your age...')
... |
180fb82c432b79c04dae92cf2da12d8a6df23d34 | asidonlylips/func_git | /manager.py | 581 | 3.609375 | 4 | class Context_manager():
def __init__(self, file_name, method):
self.file_name = file_name
self.method = method
def __enter__(self):
self.file = open(self.file_name, self.method)
return self.file
def __exit__(self, exc_type, exc_value, exc_traceback):
self.file.clo... |
0ea2be9f8e5691551d0796a72bd89028f14515f9 | mkzlay/BooleanType | /BooleanType.py | 755 | 3.625 | 4 | Python 3.8.6 (tags/v3.8.6:db45529, Sep 23 2020, 15:52:53) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> #The Python Boolean type is one of Pythons built-in data types. C mon, lets show it.
>>> a = "Python"
>>> b = "Python"
>>> a
'Python'
>>> b
... |
b295c995ac4295f271abfdcb5c4bf87a0ef1fe42 | lenamax2355/solver | /forecast_reconcilation/data_structure.py | 2,474 | 3.875 | 4 |
from collections import OrderedDict
class HierarchyTree(object):
def __init__(self):
self._nodes = OrderedDict()
self._bottom = []
def add(self, node):
self._nodes[node.name] = node
def remove(self, node):
del self._nodes[node.name]
for parent in node.par... |
d9f3eb4bae308c1b317e682d977a315cf31e3afe | autoloading8822/LIP_Sodoku_solver | /sudoku_solver.py | 7,079 | 4.1875 | 4 | #!/usr/bin/env python3
import sudoku
import sys
import pandas as pd
import math
import numpy as np#!/usr/bin/env python3
"""A module containing tools for solving Sudoku puzzles."""
import pulp
def var_name(i, j, k):
"""Returns a string in the format x_{i,j,k}."""
return "x_{%d,%d,%d}" % (i, j, k)
def cr... |
19fdb7f7dae575ee269533173b790f500d509ba4 | FreddyGJ/Portafolio-de-prog-3 | /Clase4/app/__init__.py | 3,322 | 3.828125 | 4 | def imprimir_lista(x):
print("\nMi lista de supermercado...")
for a in x:
print(str((int(x.index(a)+1))) + ". " + a)
def imprimir_lista(x):
print("\nMi lista de supermercado...")
for a in x:
print(str((int(x.index(a)+1))) + ". " + a)
def imprimir_diccionario(w):
print("\nMi lista d... |
302a1b732a2cd79543ce26dcba9b0ab38eb4eaf6 | JustinMaurina/cmpt120maurina | /pi.py | 407 | 4.09375 | 4 | # pi.py
# Approximates the value of pi
# JA: You also had to print the difference between the calculated value
# and math.pi
def main ():
n = int(input("Enter the number of terms to use:"))
pi = 0
sign = 1
for i in range(1, n * 2 + 1, 2):
term = 4/ i * sign
pi = pi + term
sign =... |
7ebafb9fd8aa97d54517b750570b5e5aab2d0c02 | Ahn-seokjoo/Algorithm | /수식 최대화.py | 585 | 3.5 | 4 | import re
from itertools import permutations
def solution(expression):
expression = re.split('([-+*])',expression)
results = []
operators = list(permutations(['-','+','*'],3))
for opertator in operators:
exp = expression[:] #리스트 전체 복사
for op in opertator:
while op in ex... |
36818398f808de5c16bf87022f024cd5c8bad684 | Ahn-seokjoo/Algorithm | /부품 찾기.py | 904 | 3.796875 | 4 | def binary_search(array, target, start, end):
if start > end:
return None
mid = (start + end) // 2
if array[mid] == target:
return mid # 리스트의 인덱스를 반환
elif array[mid] > target: # 찾는 값이 중간 값보다 작은 경우
return binary_search(array, target, start, mid -1) # 끝점을 중간 -1로 잡고, 다시 수행
else : # 찾는 값이 중간 값... |
4fbefa0f4554ff1871a619d16aff1777c690bd9f | Ahn-seokjoo/Algorithm | /다트 게임.py | 1,100 | 3.625 | 4 | import re
#eval 쓰면 문자열을 계산한다
def solution(dartResult):
charConv ={'S':'**1','D':'**2','T':'**3','#':'*-1'}
result =[]
#숫자랑 문자를 나눔
dartResult = re.sub('([SDT][*#]?)','\g<1> ',dartResult).split()
print(dartResult)
for dart in dartResult:
for word in dart:
dart = dart.replace(w... |
41ad1238055f8657136aebbfdddd50e81ac0e66b | ebrahim-j/FindMissingLab | /MissingNumber.py | 662 | 4.125 | 4 | def find_missing(list1, list2):
inputList = [] #list with extra number
checkList = [] #template list
if len(list1) > len(list2): #determines the variable (input and check)lists will be assigned to
inputList = list1
checkList = list2
else:
inputList = list2
checkList = li... |
401c10f8fa46a5f8acb58cbbf8723301424ac6f0 | SiddhantBhardwaj2018/ISTA-350 | /hw5_1.py | 3,884 | 4.0625 | 4 | '''
Name - Vibhor Mehta
Section Leader -
ISTA 350 HW5
Date - 4/1/2020
Collaborators - Siddhant Bhardwaj
'''
class Node:
def __init__(self,data):
'''
This constructor initializes the instance variable datum to the data
and the instance variables left and right to None.
'''
self.datum = data
self.left = Non... |
dc0a18ad6edf12a91c5d8b8be215c2f531ef82ed | Hodge-zf/math-with-python | /Chapter2/SimplePendulum.py | 417 | 3.921875 | 4 | import matplotlib.pyplot as plt
import math
def draw_graph(x, y):
plt.plot(x, y, marker='o')
plt.xlabel('Period in seconds')
plt.ylabel('Length in meters')
plt.title('Period of a simple pendulum')
plt.show()
def generate_T_l():
l = range(1, 1000, 20)
T = []
g = 9.81
for length in l:
period = (2*math.pi)*((... |
5b7e902688e61276f0ea89716cd7e3fd02644879 | Hodge-zf/math-with-python | /Chapter2/VisualizeExpenses.py | 535 | 3.671875 | 4 | import matplotlib.pyplot as plt
def create_bar_chart(data, labels):
num_bars = len(data)
positions = range(1, num_bars+1)
plt.barh(positions, data, align='center')
plt.yticks(positions, labels)
plt.xlabel('Dollars')
plt.ylabel('Expense')
plt.title('Monthly expenses')
plt.grid()
plt.show()
if __name__ == '__... |
55424fb2c95b27305c2c149d3218080a49192bd4 | Hodge-zf/math-with-python | /Chapter3/FindingMedian.py | 460 | 3.96875 | 4 | def calculate_median(numbers):
N = len(numbers)
numbers.sort()
if N % 2 == 0:
m1 = N/2
m2 = (N/2) + 1
m1 = int(m1) - 1
m2 = int(m2) - 1
median = (numbers[m1] + numbers[m2])/2
else:
m = (N+1)/2
m = int(m) - 1
median = numbers[m]
return median
if __name__ == '__main__':
grades = [97, 85, 91, 93,... |
eab7c224f4b84434d4879d6ae5c509c764e58bc5 | Marinofull/teoria-dos-grafos | /code/Warshall/warshall.py | 921 | 3.796875 | 4 | #!/usr/bin/python
# vim: set fileencoding: utf-8 :
#Encontra para cada elemento do grafo, as arestas que chegam e saem
#Para cada par de aresta de chegada e saida, coloca 1 na matriz de saída
def warshall(p, n):
for k in range(n):
for i in range(n):
for j in range(n):
p[i][j]=max(p[i][j],(p[i][k]&... |
140e3c4387f048b561791e2cbfd2b57185ea7128 | LukeOsburn/PlottingDataFromExcel | /HousePriceIndexVsTotalLoans.py | 3,538 | 3.953125 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import io
import seaborn as sns
#Lets make a plot of total home loans from the Big Four Australian Banks
#Versus a capital weighted housing index
#We will use these data
HouseIndex= pd.read_excel("641601.xls", "Data1")
banks=pd.read_e... |
69911d6cf8617c788b731dfd35e55ee6d5606ed3 | nuke-droid/hashbr0wns | /crackhash.py | 2,652 | 3.59375 | 4 |
from hash import hash
import time
from os import strerror, system
class crackhash:
#Start time is recorded and stored for duration calulation
def main(self):
starttime = time.time()
#List of exceptions is created
e = (IndexError)
#hash object is created as h
h ... |
21e5ff9c3242bc692963530933f3ee28515d89fb | e2crawfo/hrr-scaling | /hrr_scaling/tools/distributions.py | 1,688 | 3.765625 | 4 | from scipy import integrate
import numpy as np
# Base class taken from nengo 2.0
class Distribution(object):
"""
A base class for probability distributions.
The only thing that a probabilities distribution needs is a
``sample`` function. This base class ensures that all distributions
accept the s... |
ea72a053d110f4f3b9c40838e8fb826410bc944a | Jay23Cee/Car_Class | /Cars.py | 456 | 3.890625 | 4 | class cars:
def __init__(self, year, model,make):
self.year= year
self.model= model
self.make= make
def toString(self):
print( self.make, self.model, str(self.year) )
p1 = cars(2016, "Altima coupe", "Nissan")
p2= cars(2020, "GTR", "Nissa")
p3= cars(2001, "Celica", "Toyota")
dealer= { p1... |
4cd52636027021227a8195e5a0a8ed31cb7753b3 | 7Aishwarya/HakerRank-Solutions | /30_Days_of_Code/day5_loops.py | 343 | 4.125 | 4 | '''Given an integer, n, print its first 10 multiples. Each multiple n x i (where 1<=i<=10) should be printed on a new line
in the form: n x i = result.'''
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input())
for i in range(10):
print(... |
a54c264ff8d529e8ca6257f3725a32b97a1731ba | 7Aishwarya/HakerRank-Solutions | /Algorithms/divisible_sum_pairs.py | 883 | 3.859375 | 4 | '''You are given an array of n integers, ar=[ar[0],ar[1],...,ar[n-1]], and a positive integer, k.
Find and print the number of (i,j) pairs where i<j and ar[i] + ar[j] is divisible by k.
For example, ar = [1,2,3,4,5,6] and k=5. Our three pairs meeting the criteria are [1,4], [2,3] and [4,6].
'''
#!/bin/python3
impo... |
bf8db85839a19528d8f6be770db71872e74e39b6 | 7Aishwarya/HakerRank-Solutions | /Algorithms/modified_kaprekar_numbers.py | 1,957 | 4 | 4 | '''A modified Kaprekar number is a positive whole number with a special property. If you square it,
then split the number into two integers and sum those integers, you have the same value you started with.
Consider a positive whole number n with d digits. We square n to arrive at a number that is either 2*d digits lo... |
8bb2e6edbb2d703ad41e899b57cb32b228676557 | 7Aishwarya/HakerRank-Solutions | /Algorithms/beautiful_days_at_the_movies.py | 1,685 | 4.46875 | 4 | '''Lily likes to play games with integers. She has created a new game where she determines the difference between a number and
its reverse. For instance, given the number 12, its reverse is 21. Their difference is 9. The number 120 reversed is 21, and their
difference is 99.
She decides to apply her game to decision ... |
6ce7779a588924aab0caea37a70bbe7be5d93ff2 | 7Aishwarya/HakerRank-Solutions | /30_Days_of_Code/day25_running_time_and_complexity.py | 745 | 4.15625 | 4 | '''Given a number, n find if it is prime or not.
Input Format
The first line contains an integer, T, the number of test cases.
Each of the T subsequent lines contains an integer, n, to be tested for primality.
Constraints
1<=T<=30
1<=n<=2*10^9
Output Format
For each test case, print whether n is Prime or Not Prime on a... |
2f509b8a7d905dc97a55f900c7182e4ad7239625 | brunocaregnato/python-parser | /teste.py | 704 | 3.84375 | 4 | def main():
# aqui um comentario simples
for a in "teste":
a = a + 1
if (a > x and x >= b):
a = 2
b = 3
soma (a , b)
'''aqui eh comentario
multiplo '''
name = "Bruno"
number = 7.5
c = 3 + a
d += i
recebeFunc = Function()
exp = (14 * a - (a / c... |
d720375e7ce3008d12fd36fe003f73a0d3ddbd91 | Lucky-Dutch/cov-19 | /codewars/findOddNumbers.py | 648 | 3.640625 | 4 | """
test.assert_equals(find_it([20,1,-1,2,-2,3,3,5,5,1,2,4,20,4,-1,-2,5]), 5)
test.assert_equals(find_it([1,1,2,-2,5,2,4,4,-1,-2,5]), -1);
test.assert_equals(find_it([20,1,1,2,2,3,3,5,5,4,20,4,5]), 5);
test.assert_equals(find_it([10]), 10);
test.assert_equals(find_it([1,1,1,1,1,1,10,1,1,1,1]), 10);
test.assert_equals(... |
512281d46e18bec5814e6bbee63dba82313cf135 | Lucky-Dutch/cov-19 | /codewars/sumArray.py | 260 | 3.640625 | 4 | a = [-5,7,1,1,3]
def is_uppercase(inp):
i = 0
string = ""
while i < len(inp):
if inp[i].islower() == True:
string += inp
i += 1
if len(string) > 0:
return False
else:
return True
is_uppercase(a) |
f2ededda879d82226a7d70a6f748ede53c7c7f65 | Lucky-Dutch/cov-19 | /kurs_python_a_do_z/programowanie obiektowe/98_decorator@staticmetod.py | 488 | 3.578125 | 4 | class Student:
lista_studentów = []
def __init__(self, imie, nazwisko, wiek):
self.imie = imie
self.nazwisko = nazwisko
self.wiek = wiek
self.lista_studentów.append(self)
@staticmethod
def liczba_studentow():
print("liczba studentów:", len(Student.lista_studentó... |
b55732e5f781f37d956fa69d1b31177c67ef777d | kha-github/python-coding-team | /2021.09.15/2608/ha_2608.py | 1,087 | 3.609375 | 4 | alphadict = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
numdict = {'1':'I', '5':'V', '10':'X', '50':'L', '100':'C', '500':'D', '1000':'M', '4':'IV', '9':'IX', '40':'XL', '90':'XC', '400':'CD', '900':'CM'}
def alphaToNumber(alpha):
result = 0
before = -1
for i in range(len(alpha)-1, -1, -1):
if... |
d4ab2159ea70603165a6701ec55839544aa495c4 | kha-github/python-coding-team | /2021.10.13/1068/ej_1068.py | 609 | 3.5625 | 4 | # 79%에서 틀림, 반례 못 찾음
def dfs(x):
global count
if len(graph[x]) == 0:
count += 1
for j in range(len(graph[x])):
if graph[x][j] == del_node:
if len(graph[j]) == 1:
count += 1
else:
continue
else:
dfs(graph[x][j])
cou... |
23762300a2216e3857109706032a91bf1684f586 | kha-github/python-coding-team | /2021.10.20/2138/ha_2138.py | 968 | 3.640625 | 4 | n = int(input())
fromList_origin = list(input())
toList = list(input())
fromList = list(fromList_origin)
def invert(val): #전구의 상태를 invert
if val == '1':
return '0'
else:
return '1'
resList = []
for k in range(2): #첫번째 전구를 무조건 킨 경우와 안 킨 경우 모두 확인
result = 0
if k == 0: #첫번째 전구를 무조건 킴
fromList[0] = i... |
c3f85796f913eafe463665720aae0791e24960bd | stijnrosaer/plagiarism-detection-ir | /signatureMatrix.py | 2,599 | 3.890625 | 4 | from nltk import ngrams
import random
def get_hash(gram, mask):
"""
the "random hash function used to get different hash functions for each different permutation
:param gram: the object to be hashed
:param mask: the random string (of size 64 bits) used to make every hash function different but consist... |
2d5ce47031343a70ffc92ab6791475c6719eb21e | fforrespect/tree | /tree.py | 822 | 4.09375 | 4 |
nodes = {"/":"+", "0":"x", "00":"3", "01":"4", "1":"5"}
def draw_tree(dict_of_values):
output = nodes["/"]
pass
class Node:
def __init__(self, value, left_child=None, right_child=None, label=""):
self.value = value
self.operator = True if type(value) == "string" else False
... |
820995d14015b22070fe924a7685040a94605083 | adamrd231/caesar-cipher | /vigenere.py | 2,122 | 4.03125 | 4 | from helpers import index_list, add_lists
def encrypt(string, index):
#if nothing is entered for index, restart function and ask for input of keyword
if index == "":
print( "Index must have value" )
return vig(string, (input("Type in your keyword: ")))
new_string = ""
orig_cipher_lis... |
c0afc50c0c7194f15656f6b58464908626e4c230 | VITA-mlr/cbs_lessons | /Python/es_4-2_iterator_generator.py | 1,409 | 4.25 | 4 | """
task1:
Напишите итератор, который возвращает элементы заданного списка в обратном порядке (аналог reversed).
task2:
Перепишите решение первого задания с помощью генератора.
"""
class ListIterator:
def __init__(self, collection):
self.collection = collection
self.cursor = len(self.... |
34b20f235f38d254bad71eeb0f45c83f7325e467 | VITA-mlr/cbs_lessons | /Python/es_1-2_books.py | 2,830 | 3.984375 | 4 | """
Создайте класс, описывающий книгу. Он должен содержать информацию об авторе, названии, годе
издания и жанре. Создайте несколько разных книг. Определите для него операции проверки на
равенство и неравенство, методы __repr__ и __str__.
"""
class Book:
def __init__(self, author, title, year, publishing_h... |
4e97e62cfe374305ce0c60544d4d02e522f72125 | Jinx-Heniux/Python-2 | /dynamicprogramming/fibonacci_dp.py | 390 | 3.796875 | 4 | def fibonacci(nth: int) -> int:
"""
>>> fibonacci(0)
0
>>> fibonacci(1)
1
>>> fibonacci(2)
1
>>> fibonacci(9)
34
"""
fibs = [0] * (nth + 2)
fibs[0] = 0
fibs[1] = 1
for i in range(2, nth + 1):
fibs[i] = fibs[i - 1] + fibs[i - 2]
return fibs[nth]
if _... |
abb691603f4655d3c1a116d94b76f83655d182c3 | Jinx-Heniux/Python-2 | /maths/odd_check.py | 980 | 4.4375 | 4 | def is_odd(number: int) -> bool:
"""
Test if a number is a odd number.
:param number: the number to be checked.
:return: True if the number is odd, otherwise False.
>>> is_odd(-1)
True
>>> is_odd(-2)
False
>>> is_odd(0)
False
>>> is_odd(3)
True
>>> is_odd(4)
Fals... |
16e10cb0339572ee3255d795bc033d518071bd30 | Jinx-Heniux/Python-2 | /basics/boolean_example.py | 817 | 3.734375 | 4 | def main():
"""
Boolean example.
>>> 3 > 4
False
>>> 3 == 4
False
>>> 3 < 4
True
>>> 3 < 4 < 5
True
>>> 3 < 4 > 5
False
>>> name = "Python"
>>> age = 29
>>> name == "Python" and age == 29
True
>>> 'a' in 'abc'
True
>>> 'd' in 'abc'
Fals... |
8bd8af36d1693829ebbf3e958a11b8a15fe44e0c | Jinx-Heniux/Python-2 | /sorts/quick_sort.py | 1,336 | 4.125 | 4 | """
https://en.wikipedia.org/wiki/Quicksort
"""
def quick_sort(array, left: int = 0, right: int = None):
"""
Quick sort algorithm.
:param array: the array to be sorted.
:param left: the left index of sub array.
:param right: the right index of sub array.
:return: sorted array
>>> import r... |
82c56958204986ce03caf2d8e913b06ccf433ac5 | Jinx-Heniux/Python-2 | /searches/binary_search_recursion.py | 871 | 4.15625 | 4 | """
https://en.wikipedia.org/wiki/Binary_search_algorithm
"""
def binary_search(array, key) -> int:
"""
Binary search algorithm.
:param array: the sorted array to be searched.
:param key: the key value to be searched.
:return: index of key value if found, otherwise -1.
>>> array = list(range(... |
4ac7bdb19de1529b3ac6864ed395e84225932431 | Jinx-Heniux/Python-2 | /maths/absolute_min.py | 345 | 3.625 | 4 | def absolute_min(array):
"""
Returns absolute min value of a array.
:param array: the array.
:return: absolute min value
>>> absolute_min([1, -2, 5, -8, 7])
1
>>> absolute_min([1, -2, 3, -4, 5])
1
"""
return min(array, key=abs)
if __name__ == "__main__":
from doctest impor... |
e4e543b6ea0faa9209f3ac4267b2f46c0bb51252 | Shahzaib2028/Tkinter-Tutorial | /calculator.py | 3,264 | 3.609375 | 4 | from tkinter import *
from tkinter import ttk
window = Tk()
window.title("CALCULATOR")
window.configure(background = "black")
ent = Entry(window , width = 30 , borderwidth = 10 , relief = "ridge" , font = "Times 20")
ent.grid(row = 0 , column = 0 , columnspan = 5 , pady = 10)
def button_press(num):
cu... |
67d92acecc6b1b42e9b31a5d358dd3e138c0d69e | zhanghongwei125828/python_data | /day3/4-str索引切片.py | 518 | 4 | 4 | # 字符串索引切片
# 字符串的索引与切片
s = "abcdefghigklmn"
# 索引
#取第一位
s1 = s[0]
print(s1)
#取最后一位
s2 = s[-1]
print(s2)
################################################################################
# 切片 # 原则顾头不顾尾
# 取abcd
s3 = s[0:4]
print(s3)
# 取全部字符串
s4 = s[:]
print(s4)
########################################... |
a3e53b8910178cef43b88e40dd79bc606ca607cf | zhanghongwei125828/python_data | /day1/3-用户交互.py | 544 | 3.921875 | 4 | # 用户交互
# input
'''
input('请输入你的密码: ')
'''
# 打印结果:
# 请输入你的密码: 123456
########################################################################################################################
'''
name = input('请输入你的姓名: ') #将用户输入的内容赋值给了变量
age = input('请输入你的年龄: ')
print('我的名字是'+name,'我的年龄'+age)
'''
# 打印结果:
# 请输... |
8c78217b15121bae6770e78f7730157fb9068297 | SunnerLi/U4240 | /Lession11_MultiClassification/dataProduce.py | 921 | 3.90625 | 4 | import matplotlib.pyplot as plt
import plotin1 as pi1
import numpy as np
"""
This program would generate three groups of data
In each group, it would contain N data point
So the total number of data point is 3N
"""
# The number of data you want to generate
N = 10
# Step 1. Generate the data
x1 = np.rando... |
097eccef08494e44f0cdc904fbb9d94350c54805 | SunnerLi/U4240 | /homework3/q10.py | 427 | 3.5 | 4 | from q8 import *
def newton(u, v):
"""
Compute the NewTon direction
(Assume we know the format of Hessian matrix)
"""
_u = -(deltaU_1(u, v) / (deltaU_2(u, v)))
_v = -(deltaV_1(u, v) / (deltaV_2(u, v)))
return _u, _v
if __name__ == "__main__":
u = 0
v = 0
eta = 1
for... |
98a41f50b1060f511ccd07be956e261e57d09175 | SunnerLi/U4240 | /homework1/pocket.py | 4,506 | 3.78125 | 4 | import matplotlib.pyplot as plt
from homework15_IO import *
from homework16 import *
import numpy as np
sign = lambda x: 1 if x > 0 else -1
# Variable
threshold = 1
# Constant
Use_Training_Dataset_To_Validate = 100
Use_Testing_Dataset_To_Validate = 101
Better = 102
Worst = 103
def validate(X, Y, W, X_, Y_, W_):
... |
f3e95f6973a332bea4aabb098aa2dc8ed3146bed | SunnerLi/U4240 | /Lession6_BoundingFunction/Stack.py | 608 | 3.84375 | 4 | """
The stack stucture defined by me
Function: push - insert the data at the top position
pop - drop the data at the top position
len - return the size of the stack
show - return the list value of the stack
"""
class Stack():
stackNum = []
... |
d49bd18ece92701d1bfb65bf03feb5470efe749a | Sara-Pelivani/House-Prices | /House Prices [2] | 7,425 | 3.78125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 17 18:48:33 2019
@author: sarapelivani
"""
#Import important libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from ... |
0d56aa5047f1f172ffdc73425b26d25c9706dee7 | ShashikantBhargav/Bubble_sort- | /bubble_shor_using_list(user input).py | 446 | 4.1875 | 4 | print("program in assending order by user input:")
list1=[]
num=int(input('how many number you want to enter:-'))
print("enter values do you wants:")
for k in range(num):
list1.append(int(input("enter element:-")))
print("user entered list:",list1)
for j in range(len(list1)-1):
for i in range(len(list... |
844ec8c503889c0fbe51dc1270efbbb914a5ed39 | Nashtic/Programlama-Lab. | /Uzaktan Egitim Hafta 2/uzaktan-egitim-hafta2.py | 752 | 3.515625 | 4 | from sympy import Symbol
x = Symbol('x')
y = Symbol('y')
p = x*(x + x)
p = (x + 2)*(x + 3)
print(p)
from sympy import factor,expand
expr = x**2 - y**2
factors = factor(expr)
expand = expand(factors)
print(factors,expand)
expr = x**3 + 3*x**2*y + 3*x*y**2 + y**3
factors = factor(expr)
from sympy import pprint
... |
9b795603ebc35579a5cae85505e8ff5355d483b4 | cesarfois/Estudo_Livro_python | /#Livro_Introd-Prog-Python/cap-6/Listagem 6.2 - Uma lista com tres elementos TDD.py | 253 | 3.546875 | 4 |
print('=' * 72)
print('{0:=^72}'.format(' Listagem 6.2 '))
print('{0:=^72}'.format(' By César J. Fois '))
print('=' * 72)
print('{0:=^72}'.format(' Uma lista com tres elementos '))
print('=' * 72)
print('')
l = [15, 8, 9]
assert l == [15, 8, 9]
|
0d6f70006416003bf88f4557f4ee344394c71ffd | cesarfois/Estudo_Livro_python | /#Livro_Introd-Prog-Python/cap-4/Listagem 4.4 Calculo de imposto de Renda.py | 620 | 3.921875 | 4 | print('='*72)
print('{0:=^72}'.format(' Listagem 3,17 '))
print('{0:=^72}'.format(' By César J. Fois '))
print('='*72)
print('{0:=^72}'.format(' Calculo de imposte de renda '))
print('='*72)
print('')
salario = float(input('Digite o salario para calculo do imposto: '))
base = salario
imposto = 0
if base >... |
98691d7afdc531c9acaf7b9421fb4bfb119a8e4c | cesarfois/Estudo_Livro_python | /#Livro_Introd-Prog-Python/cap-3/Listagem 3.7 A função len v2_TDD.py | 411 | 3.671875 | 4 | print('='*72)
print('{0:=^72}'.format(' Listagem 3,7 v2'))
print('{0:=^72}'.format(' By César J. Fois '))
print('='*72)
print('A função len')
print('='*72)
print()
list_a = ["a", 'AB', '', '"o rato roe a roupa"']
for c in list_a:
print('Comprimento da String', c, '=', len(c))
print()
assert 1 =... |
2d0e193b7701899a9db99bb9ddedce443626bfac | cesarfois/Estudo_Livro_python | /#Livro_Introd-Prog-Python/cap-5/Listagem 5.9 Tabuada Simples .py | 373 | 3.78125 | 4 | print('='*72)
print('{0:=^72}'.format(' Listagem 5.9 '))
print('{0:=^72}'.format(' By César J. Fois '))
print('='*72)
print('{0:=^72}'.format(' Tabuada simples '))
print('='*72)
print('')
t = int(input('\nDigite tabuada de: '))
x = 0
while x <= 10:
#print("%2d x %2d = %3d" %(t , x, t*x))
prin... |
06b8d4dfc8fa3e5114d1b767c3d30820bae2b640 | cesarfois/Estudo_Livro_python | /#Livro_Introd-Prog-Python/cap-6/Listagem 6.30 - Transformação do resultado de range em uma lista.py | 288 | 3.5625 | 4 | print('=' * 72)
print('{:=^72}'.format(' Listagem 6.30 '))
print('{:=^72}'.format(' By César J. Fois '))
print('=' * 72)
print('{0:=^72}'.format(' Listagem 6.30 - Transformação do resultado de range em uma lista '))
print('=' * 72)
print('')
L = list(range(100, 1100, 50))
print(L)
|
b1a1c7c3c7480735453e33a9efe2526695077f36 | cesarfois/Estudo_Livro_python | /#Livro_Introd-Prog-Python/cap-4/4.6 Conta Telefone 3 Faixas preço.py | 328 | 3.640625 | 4 | print('='*59)
print('+'*20, 'PREÇO PASSAGEM KM', '+'*20)
print('='*59)
print()
minutos = int(input('Quantos minutos quer contratar: '))
if minutos < 200:
preco = 0.20
if minutos >= 200 and minutos <= 400:
preco = 0.18
else:
preco = 0.15
print('Valor total do plano: %6.2f' % ( preco * min... |
6641ef6efb53e46bbd91c1dc93a989604a0ce281 | cesarfois/Estudo_Livro_python | /#Livro_Introd-Prog-Python/cap-6/Listagem 6.31 - Impressão de indices sem usar a função enumerate.py | 326 | 3.71875 | 4 | print('=' * 72)
print('{:=^72}'.format(' Listagem 6.31 '))
print('{:=^72}'.format(' By César J. Fois '))
print('=' * 72)
print('{0:=^72}'.format(' Listagem 6.31 - Impressão de indices sem usar a função enumerate '))
print('=' * 72)
print('')
L = [5, 9, 13]
x = 0
for e in L:
print("[%d] %d" % (x, e))
... |
d6e4543fae8d1b3abc63bbb5c4301fc819c383d0 | cesarfois/Estudo_Livro_python | /#Livro_Introd-Prog-Python/cap-3/Exercício 3.10 Aumento de Salario.py | 433 | 3.8125 | 4 | print('='*72)
print('{0:=^72}'.format(' Exercício 3.10 '))
print('{0:=^72}'.format(' By César J. Fois '))
print('='*72)
print('{0:=^72}'.format(' Aumento de Salario '))
print('='*72)
print('')
salario = float(input('Salario: '))
porcentagem = int(input('Aumento em %: '))
salario_com_aumento = salario + (sal... |
b9aca9eca98fbf4cc6d5fd8f75935c1632664204 | cesarfois/Estudo_Livro_python | /#Livro_Introd-Prog-Python/cap-6/Listagem 6.29 - Uso da função range com saltos.py | 287 | 3.71875 | 4 | print('=' * 72)
print('{:=^72}'.format(' Listagem 6.29 '))
print('{:=^72}'.format(' By César J. Fois '))
print('=' * 72)
print('{0:=^72}'.format(' Listagem 6.29 - Uso da função range com saltos '))
print('=' * 72)
print('')
for t in range(3, 33, 3):
print(t, end=" ")
print()
|
aeea33515ed6f354a9067bc820e986435f214ca1 | cesarfois/Estudo_Livro_python | /#Livro_Introd-Prog-Python/cap-5/Listagem 5.6 Imprimir de 1 até a um número digitado pelo usuário.py | 338 | 3.828125 | 4 | print('='*72)
print('{0:=^72}'.format(' Listagem 5.6 '))
print('{0:=^72}'.format(' By César J. Fois '))
print('='*72)
print('{0:=^72}'.format(' Impressão de 1 até um número digitado pelo usuário While '))
print('='*72)
print('')
fim = int(input('Digite o fim do contador: '))
x = 1
while x <= fim:
prin... |
f35b3045fc422fc284446d969680ed10d7a577aa | JordanWalker28/PythonGames | /hangman.py | 1,149 | 3.9375 | 4 | word = "world of warcraft"
def check(wordThree):
if "_" in wordThree:
print("keep going sucka")
else:
print("You have won!")
def update(wordThree, guess):
count = 0
print("letter is in word")
for i in word:
if guess == i:
wordThree[count] = guess
cou... |
a3360d030120a822296c5c3912e4aae91043e6a0 | MaiaDandachi/Algorithms | /fibonacci2.py | 311 | 3.8125 | 4 | #python 3
import sys
def fibonacci (n):
a = []
a.insert(0,0)
a.insert(1,1)
for i in range (2,n+1):
a.append(a[i-1] + a[i-2])
#return a[-1]
return a[n]
print(fibonacci(7))
# if __name__ == '__main__':
# input = sys.stdin.read()
# n = int(input)
# print(fibonacci(n))
|
477a797b1477dffdc4ad7b4430550cf57a35f72a | MaiaDandachi/Algorithms | /change_dp.py | 1,049 | 3.703125 | 4 | # Uses python3
import sys
import math
def get_change(money, coins):
infiniteValue = money + 1
minNum = [infiniteValue] * (money + 1) # fill in the stack with large amount temporally
minNum.insert(0, 0)
# get min number of coins for each cell (sub problem) and use it for the next cell until we reach ... |
9426064299058a6b51eb21b8596b60499934f38c | sahaavi/AI-Algorithms | /N-Queen_attackinPairs Dynamic.py | 1,090 | 3.9375 | 4 | # Number of queens
print("Enter the number of queens")
N = int(input())
# chessboard
# NxN matrix with all elements x
board = [['x']*N for _ in range(N)]
for b in range(N):
print('---Give No.', b+1, 'Queen Position---')
row = int(input("Enter row position: "))
column = int(input("Enter column pos... |
78a6b8f566eeb9d32121ef41cdadaa16484d0cc8 | gcgq/python-adventure-time | /python-adventure-time-mk2.py | 3,367 | 3.90625 | 4 | import random
class Room(object):
def __init__(self, exits=["hallway"]):
self.items = []
self.exits = exits
class House(object):
def __init__(self):
self.rooms = {"bedroom": Room(),
"bathroom": Room(),
"storage room": Room(),
... |
3473c3506bfac279f5e3fa4d1a606d8aac692e74 | parthpankajtiwary/codeforces | /round289/A.py | 295 | 3.5 | 4 |
n = input()
array = [["#" for x in xrange(n)] for y in xrange(n)]
for y in xrange(n):
array[0][y] = 1
for x in xrange(1, n):
for y in xrange(n):
if y != 0:
array[x][y] = array[x-1][y] + array[x][y-1]
if y == 0:
array[x][y] = array[x-1][y]
print array
print array[n-1][n-1] |
a08ca12c51bb89773fbd5c91ac527dd8116873cb | rohankumar10/MachineLearning_Templates | /Regression/polynomial_regression.py | 1,087 | 3.703125 | 4 | # Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:, 1:-1].values
y = dataset.iloc[:, -1].values
# Training the dataset on Linear Regression first
from sklearn.linear_model import Lin... |
8bc35aad9612c3f6eaf4db2c279aee6dbd0052c9 | deanakira2020/python | /turtle/many_squares1.py | 216 | 3.625 | 4 | from turtle import *
shape('turtle')
speed(0)
def square():
for i in range(4):
forward(100)
rt(90)
def many_squares():
for i in range (144):
square()
rt(5)
many_squares()
|
93f1ec4e576c4d805a26e8e0a8b9adef0e021aca | rockchar/CODE_PYTHON | /Sets.py | 598 | 4.28125 | 4 | # sets are unordered collections of unique objects. They contain only one
# unique object
# Lets create a set
my_set = set()
my_set.add(1)
my_set.add(2)
my_set.add(3)
print(my_set)
# lets try to add a duplicate element to the set
my_set.add(3)
print(my_set)
#lets declare a list with duplicate objects
my_list =... |
7cc27a72252e117308e304a779db124234ec3e1e | zmsubin/Alg | /calcproduct.py | 378 | 3.546875 | 4 | import addarrays
def calcproduct(array, start, direction, numprod):
product = array[start[0]][start[1]]
currentpoint = start
for n in range(numprod-1):
currentpoint = addarrays.addarrays(currentpoint, direction)
product *= array[currentpoint[0]][currentpoint[1]]
return product
#print ca... |
83f469c37a848c400f8b9b5844ba974654bf78b9 | LunaVicta/coding-practice | /python-practice/Project_Euler_5.py | 252 | 3.65625 | 4 | def GCF(a,b):
i = 2
while(i<=a and i<=b):
if(a%i==0 and b%i==0):
return i * GCF(a/i,b/i)
i+=1
return 1
def LCM(a,b):
return a*b/GCF(a,b)
x = 20
for i in range(19,1,-1):
x = LCM(x,i)
print(x)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.