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 |
|---|---|---|---|---|---|---|
89309e6aa3917fee2427a1e16113a3de202994d5 | achmielecki/AI_Project | /agent/agent.py | 2,136 | 4.25 | 4 | """
File including Agent class which
implementing methods of moving around,
making decisions, storing the history of decisions.
"""
class Agent(object):
""" Class representing agent in game world.
Agent has to reach to destination point
in the shortest distance. World is random generat... |
b1e4492ff80874eeada53f05d6158fc3ce419297 | lovepurple/leecode | /first_bad_version.py | 1,574 | 4.1875 | 4 | """
278. 2018-8-16 18:15:47
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
Suppose y... |
1c84d570d09e47bf4e8e5404c637724605941471 | lovepurple/leecode | /binarySearch.py | 904 | 3.921875 | 4 | """
Given a sorted (in ascending order) integer array nums of n elements and a target value,
write a function to search target in nums.
If target exists, then return its index, otherwise return -1.
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index i... |
309d38b353e45b90da17d15b021b83ab43c80b1e | lovepurple/leecode | /contains_duplicate.py | 1,127 | 3.890625 | 4 | """
217. Contains Duplicate 2018-8-8 0:05:01
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
Example 1:
Input: [1,2,3,1]
Output: t... |
a1c12b3b59535fe7e82558ffe416e6cba5dbb1f6 | ravi4all/Oct_AdvPythonMorningReg | /01-OOPS/02-ObjDemo.py | 527 | 4 | 4 | class Emp:
"""This is my first class demo"""
id = 1
name = "Ram"
print("Hello world")
if __name__ == '__main__':
obj_1 = Emp()
# print(ram)
print(obj_1.id, obj_1.name)
obj_1.name = 'Shyam'
print(obj_1.name)
print(Emp.name)
obj_2 = Emp()
obj_2.name = 'Ra... |
da39acfbccae16f554fc22a7e9d21300a1fac7f2 | ravi4all/Oct_AdvPythonMorningReg | /02-Inheritance/03-MultipleInheritance.py | 1,255 | 3.90625 | 4 | class Emp:
def __init__(self):
self.name = ""
self.age = 0
self.salary = 0
self.company = "HCL"
def printEmp(self):
print("Emp Details :",self.name, self.age, self.salary, self.company)
class Bank:
def __init__(self,balance,eligible):
self.... |
03b65050e19e551c68bb94c17e6712357db67c09 | GuillemMartinezArdanuy/Becas-Digitaliza--PUE--Programaci-n-de-Redes | /Python/06_for.py | 1,033 | 3.90625 | 4 | #Crear un archivo llamado 06_for.py
#Crear una lista con nombres de persona e incluir, como mínimo, 5 nombres (como mínimo, uno ha de tener la vocal "a")
listaNombres=["Antonio","Manuel","Jose","Manuela","Antonia","Pepita","Carol","Ivan","Guillem","Alberto","Luis"]
#Crear una lista llamada "selected"
selected=[]
#... |
be16fc36b1664629aed50ab10065ee94ad2858f1 | stefan9x/pa | /vezba01/z3.py | 370 | 3.8125 | 4 | #Napiši program koji na ulazu prima dva stringa i na osnovu njih formira
# i ispisuje novi string koji se sastoji od dva puta ponovljena prva tri
# karaktera iz prvog stringa i poslednja tri karaktera drugog stringa
if __name__ == "__main__":
s = input('Unesite dva stringa:')
s1, s2 = s.split(' ')
s_out... |
4425e49cff1337a3691b647d5d7752bd451fad87 | stefan9x/pa | /vezba01/z2.py | 441 | 3.59375 | 4 | #Napisati funkciju koja računa zbir kvadrata prvih N prirodnih brojeva
#parametar N se unosi kao ulazni argument programa;
import sys
def zbir2_n(n):
zbir = 0
for i in range(n):
zbir+=i**2
zbir+=n**2
return zbir
if __name__ == "__main__":
if len(sys.argv) < 2:
print('Unesite... |
5f54615d6649e495f45e630ba3c7d690e94c308a | AbelHristodor/ideas | /Games/Tris aka TicTacToe.py | 3,848 | 3.71875 | 4 | import time
player1 = 0
player2 = 0
answer = input("Ciao, vuoi giocare a Tris? Si/No ")
if answer == 'Si':
player1 = input("Giocatore 1, vuoi essere X oppure 0? ")
if player1 == 'X':
player2 = '0'
else:
player2 = 'X'
else:
print("Vabbè giocheremo un'altra volta.")
def dis... |
ebed420431aece5085c524bc4a5ad5a4fdbf67ee | Willjox/WebSecurity | /HA1/micromint.py | 780 | 3.6875 | 4 | import random
import sys
import math
def stddev(results, average):
y= []
for x in results:
y.append((x - average)**2)
return math.sqrt( ( (sum(y))/z) )
def mint(u,k,c):
i = 0;
p = 0;
korg = [0]*(2**u)
rand = random.SystemRandom()
while p < c:
x = rand.randint(0, len(k... |
6cffaeeb5b02ee6140fea0392f37d680fed205ae | dzenre/python-project-lvl1 | /brain_games/cli.py | 241 | 3.59375 | 4 | """Module to ask player's name."""
import prompt
def welcome_user():
"""Ask player's name.""" # noqa: DAR201
name = prompt.string('May I have your name? ')
print('Hello, {}!'.format(name)) # noqa: WPS421 P101
return name
|
2a381d75c58b0a97e5599adf17466bda066f9e02 | hyeongyun0916/Algorithm | /acmicpc/python/13163.py | 105 | 3.671875 | 4 | num = int(input())
for i in range(num):
name = input().split(' ')
name[0] = 'god'
print(''.join(name)) |
8b6c96bcb94daa09063d873ab6649f49f316edca | andersoncruzz/service-ENEM | /banco.py | 1,141 | 3.546875 | 4 | import sqlite3
def newTeacher(Nome, Email, Matricula, Senha):
try:
conn = sqlite3.connect('openLab.db')
cur = conn.cursor()
cur.execute("""
INSERT INTO teachers (idTeacher, Nome, Email, Password)
VALUES (?,?,?,?)
""", (Matricula, Nome, Email, Senha))
#gravando no bd
conn.commit()
print('Dados... |
9f7091f4f2d58967ef4f5e15f1ec47cd81995694 | cleytonoliveira/pythonLearning | /Fundamentals/exercise6.py | 215 | 3.96875 | 4 | firstNumber = int(input('Write the first number: '))
sucessor = firstNumber + 1
predecessor = firstNumber - 1
print('The number {} has the predecessor {} and sucessor {}'.format(firstNumber, predecessor, sucessor))
|
de8bc57cba471bb94f6aed67eb0a35077cca72bb | cleytonoliveira/pythonLearning | /Fundamentals/exercise14.py | 215 | 4 | 4 | salary = int(input('How much is your salary? '))
calculateImprove = salary + (salary * 0.15)
print('Your salary is R${}, but you received 15% of higher and now your salary is R${}'.format(salary, calculateImprove))
|
a91e85e800e795b48d9dac1586ad9b69bbd87221 | bacasable34/formation-python-scripts-exemples | /carnet.py | 4,882 | 3.5 | 4 | #! /usr/bin/env python3
# programme carnet.py
# import du module datetime utilisé dans la class Personne pour calculer l'âge avec la date de naissance
import datetime
class Contact:
#attribut de la class Contact
nb_contact =0
# __init__ dunder init est le constructeur de la class --> qd tu fais c1=Contact... |
11fa3e02f3663a34cbd2804a52ac2525e2c84d35 | bacasable34/formation-python-scripts-exemples | /test_sub.py | 950 | 3.84375 | 4 | #! /usr/bin/env python3
#
# test_sub.py - Mickaël Seror
# demande à l'utilisateur une chaine et une sous chaine
# Compte le nombre de fois qu'apparaît la sous chaine dans la chaine
# affiche les positions de la sous chaine dans la chaine
# affiche la chaine avec le caractère * à la place de la sous chaine
#
# Usage : .... |
29ef17e51ae29ba273a3b59e65419d73bacf6aa0 | mathivananr1987/python-workouts | /dictionary-tuple-set.py | 1,077 | 4.125 | 4 | # Tuple is similar to list. But it is immutable.
# Data in a tuple is written using parenthesis and commas.
fruits = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print("count of orange", fruits.count("orange"))
print('Index value of orange', fruits.index("orange"))
# Python Dictionary is an unord... |
4f1a69c960fb3c4575ad1dd493da268cb9b2298b | mathivananr1987/python-workouts | /try-except.py | 1,745 | 4.03125 | 4 | import os
import sys
# various exception combinations
# keywords: try, except, finally
try:
print("Try Block")
except Exception as general_error:
# without except block try block will throw error
print("Exception Block. {}".format(general_error))
try:
vowels = ['a', 'e', 'i', 'o', 'u']
print(vow... |
f984cc81842f604c1c29e1ddecf630c2f49df851 | cd-chicago-june-cohort/dojo_assignments_mikeSullivan1 | /python_OOP/product.py | 1,605 | 3.875 | 4 | class product(object):
def __init__(self,price,name,weight,brand,cost):
self.name = name
self.price = price
self.weight = weight
self.brand = brand
self.cost = cost
self.status = "for sale"
def sell(self):
self.status = "sold"
print self.name,... |
6c96a66ca122128582076cba695de6325d6b32e9 | cd-chicago-june-cohort/dojo_assignments_mikeSullivan1 | /python_fundamentals/strings_and_lists.py | 993 | 3.96875 | 4 | '''def replace_string(long_string, old,new):
return long_string.replace(old,new)
words = "It's thanksgiving day. It's my birthday,too!"
old_string = "day"
new_string = "month"
print words
print replace_string(words,old_string,new_string)
def minmax(some_list):
some_list.sort()
x=len(some_list) -1
... |
7ca52317a28ac1a45a2a44b3d8d769def95493e5 | cd-chicago-june-cohort/dojo_assignments_mikeSullivan1 | /python_fundamentals/MakingDicts.py | 329 | 4.34375 | 4 |
def print_dict(dict):
print "My name is", dict["name"]
print "My age is", dict["age"]
print "My country of birth is", dict["birthplace"]
print "My favorite language is", dict["language"]
myDict = {}
myDict["name"]="Mike"
myDict["age"]=34
myDict["birthplace"]="USA"
myDict["language"]="Python"
print_dic... |
7732208f5d3e7826e263da85dd8941cadd25fa37 | MarkiianAtUCU/TeamTask | /interface.py | 2,375 | 3.796875 | 4 | from main import *
import os
menu = """
1) - Add Client
2) - Add Mail
3) - Send All
4) - Mail Number
5) - Clients info
6) - Quit
"""
clients = []
mails = MailBox()
def create_client(lst):
name = input("[Client name] > ")
age = input("[Client age] >")
while not age.isdigit() and not (1 < int(age) < 110):... |
09d3cf114f83a5d284c0f810b02ca87dee711b30 | ical9016/bootcamp13_fundamental | /fundamental_01.py | 892 | 4 | 4 | """
syntax programming language consist of:
- Sequential
- Branching
- Loop
- Modularization using :
a. Function
b. Class
c. Package
example program to be made :
Blog with Django
"""
judul = 'Menguasai python dalam 3 jam'
author = 'Nafis Faisal'
tanggal = '2019-11-02'
#jumlah_artikel = 100
#
#if jumlah_ar... |
188abf2fd259085a3bcf6d538ce8dfb67d6357f5 | ashley015/python20210203 | /3-2.py | 370 | 3.625 | 4 | m=[]
total=0
high=0
low=100
n=int(input('How many people in this class?'))
for i in range(n):
score=int(input('Plase input the score:'))
total=total+score
if high< score:
high=score
if low>score:
low=score
m.append(score)
average=total/n
print(m)
print('average... |
63cd3250a2453bc5dcf1083a3f9010fd6496fe1f | BrandonCzaja/Sololearn | /Python/Control_Structures/Boolean_Logic.py | 650 | 4.25 | 4 | # Boolean logic operators are (and, or, not)
# And Operator
# print(1 == 1 and 2 == 2)
# print(1 == 1 and 2 == 3)
# print(1 != 1 and 2 == 2)
# print(2 < 1 and 3 > 6)
# Example of boolean logic with an if statement
# I can either leave the expressions unwrapped, wrap each individual statement or wrap the whole if con... |
5cf03dca2de00592db494a9bb2c00b80147f387a | frba/biomek | /biomek/function/spotting.py | 6,045 | 3.59375 | 4 | """
Functions to create CSV files to be used in biomek
Source Plate Name,Source Well,Destination Plate Name,Destination Well,Volume
PlateS1,A1,PlateD1,A1,4
PlateS1,A1,PlateD1,B1,4
PlateS1,A2,PlateD1,C1,4
PlateS1,A2,PlateD1,D1,4
"""
from ..misc import calc, file
from ..container import plate
import sys
MAX_PLATES = 1... |
3605da3592356af8f961812c48b5d8b0ea3a7a16 | CharnyshMM/python_tracker | /console_interface/parser.py | 344 | 3.578125 | 4 | """This module describes Parser class"""
import argparse
import sys
class Parser(argparse.ArgumentParser):
"""Just a wrapper for default ArgumentParser to add ability to print help in case of error arguments"""
def error(self, message):
sys.stderr.write('error: %s\n' % message)
self.print_hel... |
ddda02473ba71bf752d22572e92a52bd9dff6f35 | BlandineLemaire/StegaPy | /tools/charSearch.py | 1,223 | 3.75 | 4 | '''
Fonction :
charSearcher(byteList)
byteList : liste de byte dans lesquels on va chercher tout les caracteres qui sont imprimable
Explication :
charSearcher est une fonction qui permet de trouver tout les caracteres imprimable qui sont dans
une liste de bytes et de les retourner dans une v... |
38ea269387d3a34e05fa0831239d249f487347f9 | LeeJiangWei/algorithms | /8-puzzle.py | 3,999 | 3.796875 | 4 | import random
class puzzle:
def __init__(self, state=None, pre_move=None, parent=None):
self.state = state
self.directions = ["up", "down", "left", "right"]
if pre_move:
self.directions.remove(pre_move)
self.pre_move = pre_move
self.parent = parent
self.... |
4dacc73ac8d08acb3a6ac4d6fda0c62c4b89305f | kyle-yan/python | /sets.py | 134 | 3.828125 | 4 | #集合-用大括号表示,去重
sets = {1, 2, 3, 4, 5, 6, 1}
print(sets)
if 3 in sets:
print('haha')
else:
print('hoho')
|
8545c73344abaabdafdd6686bafe4a6382e48b2f | bhattacharyya/biopythongui | /objects.py | 6,264 | 3.65625 | 4 |
class Item:
def save(self, filename=0):
import cPickle
if filename==0:
filename = self.name
ext = filename.split('.')[-1]
if ext == filename:
filename += self.extension
file = open(filename, 'wb')
cPickle.dump(file, self, -1)
file.close()
def changeName(se... |
e6042faa1b4190457bf74b49b0d8728a36e14bbe | Ang3l1t0/holbertonschool-higher_level_programming | /0x0A-python-inheritance/4-inherits_from.py | 305 | 3.859375 | 4 | #!/usr/bin/python3
"""Inherits
"""
def inherits_from(obj, a_class):
"""inherits_from
Arguments:
obj
a_class
Returns:
bol -- true or false
"""
if issubclass(type(obj), a_class) and type(obj) is not a_class:
return True
else:
return False
|
aacccdbd244dd21b31268344bc4a6cbcd31fa597 | Ang3l1t0/holbertonschool-higher_level_programming | /0x0B-python-input_output/1-number_of_lines.py | 311 | 3.703125 | 4 | #!/usr/bin/python3
"""Number of Lines
"""
def number_of_lines(filename=""):
"""number_of_lines
Keyword Arguments:
filename {str} -- file name or path (default: {""})
"""
count = 0
with open(filename) as f:
for _ in f:
count += 1
f.closed
return(count)
|
6ae9ddc15cbedfe51a661dbcd58911f22b616280 | Ang3l1t0/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/6-print_comb3.py | 239 | 3.921875 | 4 | #!/usr/bin/python3
for n1 in range(0, 9):
for n2 in range(0, 10):
if n1 < n2:
if n1 < 8:
print("{:d}{:d}".format(n1, n2), end=', ')
else:
print("{:d}{:d}".format(n1, n2))
|
674d9922f89514e4266c48ec91b98f223fdcf313 | Ang3l1t0/holbertonschool-higher_level_programming | /0x0B-python-input_output/4-append_write.py | 410 | 4.1875 | 4 | #!/usr/bin/python3
"""Append
"""
def append_write(filename="", text=""):
"""append_write method
Keyword Arguments:
filename {str} -- file name or path (default: {""})
text {str} -- text to append (default: {""})
Returns:
[str] -- text that will append
"""
with open(filena... |
982c7852214a41e505052c5674006286fc26b4b9 | Ang3l1t0/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/4-print_square.py | 444 | 4.34375 | 4 | #!/usr/bin/python3
"""print_square"""
def print_square(size):
"""print_square
Arguments:
size {int} -- square size
Raises:
TypeError: If size is not an integer
ValueError: If size is lower than 0
"""
if type(size) is not int:
raise TypeError("size must be an integ... |
af528387ea37e35a6f12b53b392f920087e5284b | Ang3l1t0/holbertonschool-higher_level_programming | /0x02-python-import_modules/2-args.py | 596 | 4.375 | 4 | #!/usr/bin/python3
import sys
from sys import argv
if __name__ == "__main__":
# leng argv starts in 1 with the name of the function
# 1 = function name
if len(argv) == 1:
print("{:d} arguments.".format(len(sys.argv) - 1))
# 2 = first argument if is equal to 2 it means just one arg
elif len(a... |
5253817eac722b8e72fa1eadb560f8b7c7d73250 | weeksghost/snippets | /fizzbuzz/fizzbuzz.py | 562 | 4.21875 | 4 | """Write a program that prints the numbers from 1 to 100.
But for multiples of three print 'Fizz' instead of the number.
For the multiples of five print 'Buzz'.
For numbers which are multiples of both three and five print 'FizzBuzz'."""
from random import randint
def fizzbuzz(num):
for x in range(1, 101):
if x ... |
4d221fa61d3ec90b303ef161455e3cf4f328c40e | Pavanyeluri11/LeetCode-Problems-Python | /numTeams.py | 833 | 3.5625 | 4 | def numTeams(rating):
ans = 0
n = len(rating)
#increasing[i][j] denotes the num of teams ending at soldier i with length of j in the order of increasing rating.
increasing = [[0] * 4 for _ in range(n)]
#decreasing[i][j] denotes the num of teams ending at soldier i with length of j in the order ... |
1efbc8cb0c81c8e34da0c5ec8370f2b7eee61095 | NeutronCat/EarlyLearningPython | /String_Challenge.py | 3,057 | 4.0625 | 4 | #counts letters
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
def unique_english_letters(word):
uniques = 0
for letter in letters:
if letter in word:
uniques += 1
return uniques
print(unique_english_letters("mississippi"))
# should print 4
print(unique_english_letters("Apple"))
# shou... |
d6f097dd5b99e039ac4d33ba958ca79834075248 | NeutronCat/EarlyLearningPython | /BasicMathFunctions.py | 2,936 | 4.0625 | 4 | # average
# Write your average function here:
def average(num1, num2):
return (num1+num2)/2
# Uncomment these function calls to test your average function:
print(average(1, 100))
# The average of 1 and 100 is 50.5
print(average(1, -1))
# The average of 1 and -1 is 0
# tenth power
# Write your tenth_power function... |
7b55bb9eddd6cf5f9a4be3738a2fab13dfcfca00 | abdullahelshoura/MOBILE-COMPUTING | /NerualN.py | 987 | 3.515625 | 4 | #1 Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn import datasets
from sklearn import metrics
iris = datasets.load_iris()
X = iris.data[:, :4]
y ... |
e2ad5022f9820b69b1f85f863bf6326155d7f876 | Jonly-123/homework1_3 | /获取文件大小.py | 795 | 3.828125 | 4 |
import os
# def getFileSize(filePath,size = 0): 定义获取文件大小的函数,初始文件大小是0
# for root, dirs, files in os.walk(filePath):
# for f in files:
# size += os.path.getsize(os.path.join(root, f))
# print(f)
# return size
# print(getFileSize('./yuanleetest'))
all_size = 0
def dir_s... |
d49ada9b93882faf7afc97e34094015263f8dfc4 | Yuxiao98/PE | /PE34.py | 595 | 3.953125 | 4 | # Project Euler: Q34
# Find the sum of all numbers which are equal to the sum of the factorial of their digits.
import math
def individualDigits(num):
digitsList = []
while num:
digitsList.append(num%10)
num //= 10
digitsList = digitsList[::-1]
return digitsList
magicSet = se... |
0e8b73b3dd48465db2b9f1c6673d8437b9876908 | Yuxiao98/PE | /PE25.py | 510 | 3.875 | 4 | # Project Euler: Q25
# Find the index of the first term in the Fibonacci sequence to contain 1000 digits
def countDigits(num):
c = 0
while num:
num //= 10
c += 1
return c
fibonacci_numbers = [0, 1]
i = 2
while True:
fibonacci_numbers.append(fibonacci_numbers[i-1]+fibonacci_n... |
a3cb355f81a27113efd62c52523b958855e673fa | Kirstihly/Edge-Directed_Interpolation | /edi.py | 5,388 | 3.625 | 4 | import cv2
import numpy as np
from matplotlib import pyplot as plt
import math
import sys
"""
Author:
hu.leying@columbia.edu
Usage:
EDI_predict(img, m, s)
# img is the input image
# m is the sampling window size, not scaling factor! The larger the m, more blurry the image. Ideal m >= 4.
# ... |
87a46c9d2df91ef1d4fdddd74e1c7c0771b72fd9 | linnil1/2020pdsa | /teams.sol.py | 1,140 | 3.765625 | 4 | from collections import defaultdict
from typing import List
from queue import Queue
class Teams:
def teams(self, idols: int, teetee: List[List[int]]) -> bool:
# build the graph
self.nodes = defaultdict(list)
for i,j in teetee:
self.nodes[i].append(j)
self.nodes[j].a... |
f10d6210fc4e22a2d9adaf14ec5b40f756804f09 | atjason/Python | /learn/map_reduce.py | 765 | 3.890625 | 4 |
def str2int(str):
def merge_int(x, y):
return x * 10 + y
def char2int(c):
char_dict = {
'0': 0,
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9
}
return char_dict[c]
# map means apply function to each member ... |
9a6e7b9ac1d4dceb8acf9e618cbe5dc63a92566e | roger1688/AdvancedPython_2019 | /03_oop_init/hw1.py | 1,039 | 4.125 | 4 | class Node:
def __init__(self, val):
self.val = val
self.next = None
def print_linked_list(head):
now = head
while now:
print('{} > '.format(now.val),end='')
now = now.next
print() # print newline
# # Linked-list and print test
# n1 = Node(1)
# n2 = Node(3)
# n3 = Node... |
fe1e263511e1f24f17a10b4dc54e0b1c3cd40bc9 | David-Loibl/gistemp4.0 | /steps/eqarea.py | 9,455 | 3.703125 | 4 | #!/usr/local/bin/python3.4
#
# eqarea.py
#
# David Jones, Ravenbrook Limited.
# Avi Persin, Revision 2016-01-06
"""Routines for computing an equal area grid.
Specifically, Sergej's equal area 8000 element grid of the Earth (or
any sphere like object). See GISTEMP code, subroutine GRIDEA
Where "tuple" is used below,... |
4544382ae2d171e544bf693e0f84d632df1e1a8f | egorov-oleg/hello-world | /task36.py | 450 | 3.765625 | 4 | m=int(input('Введите 2 натуральных числа: \n'))
n=int(input())
if m>n:
mini=n
else:
mini=m
mindiv=0
i=2
while i<=mini:
if n%i==0 and m%i==0:
mindiv=i
break
else:
i=i+1
if mindiv!=0:
print('Наименьший нетривиальный делитель данных чисел:',mindiv)
else:
print('Наименьшего н... |
51a0fb3465dfc09150fa00db37fecb5bb9277ce9 | egorov-oleg/hello-world | /task25.py | 163 | 3.71875 | 4 | x=int(input('Введите число и его степень: \n'))
n=int(input())
r=1
while n!=1:
if n%2!=0:
r=r*x
x=x*x
n=n//2
print(x*r)
|
6e26a991dae4e695874e3744a09f4b8dee29c693 | egorov-oleg/hello-world | /task46.py | 152 | 3.734375 | 4 | n=int(input('Введите n: '))
fib0=0
fib1=1
i=2
while i<=n:
fib=fib1+fib0
fib0=fib1
fib1=fib
i=i+1
if n==0:
fib1=0
print(fib1)
|
f2e80b4dfe9683fb3acba1272bde622fc4d55bc0 | egorov-oleg/hello-world | /task38.py | 408 | 3.828125 | 4 | n=int(input('Введите натуральное число: '))
a=n
digits=0
while a!=0:
a=a//10
digits=digits+1
i=1
right=0
while i<=digits//2:
right=right*10+n%10
n=n//10
i=i+1
if digits%2==1:
n=n//10
if n==right:
print('Данное число является палиндромом')
else:
print('Данное число не является палиндромом... |
1c9a70bd869ed86792485f45a8e9b9a649c70042 | egorov-oleg/hello-world | /task31.py | 128 | 3.625 | 4 | n=int(input('Введите натуральное число: '))
r=0
while n!=0:
r=r*10
r=r+n%10
n=n//10
print(r)
|
8380193b3ae6c07d2468b2914b353b75f23424f0 | egorov-oleg/hello-world | /task42.py | 377 | 3.6875 | 4 | a=int(input('Введите последовательность чисел:\n'))
count1=0
while a!=0:
count=0
b=1
while a>=b:
if a%b==0:
count=count+1
b=b+1
else:
b=b+1
if count==2:
count1=count1+1
a=int(input())
print('Простых чисел в последовательности:',count1)
|
0a91701ab33752409a27a9a242025a6f68025a10 | egorov-oleg/hello-world | /task16.py | 253 | 3.71875 | 4 | a=int(input('Введите натуральное число: '))
count=0
b=1
while a-b>-1:
if a%b==0:
count=count+1
b=b+1
else:
b=b+1
print('Количество делителей у данного числа:',count)
|
1cd6467c387ad89b19c6d34ecac63ccae15b2e4e | vasugarg1710/Python-Programs | /fibonachi.py | 304 | 3.890625 | 4 | # 0 1 1 2 3 5 8 13
def fibonachi(n):
if n==1:
return 0
elif n==2:
return 1
else:
return fibonachi(n-1)+fibonachi(n-2)
print(fibonachi(5))
def factorial_iterative(n):
fac = 1
for i in range(n):
fac = fac * (i+1)
return fac
print(factorial_iterative(5)) |
6577851c9f791b876a6b7d7fc09f5e725d911091 | vasugarg1710/Python-Programs | /2.py | 335 | 4.03125 | 4 | # Variables
a = 10
b = 20
# Typecasting
y = "10" # This is a string value
z = "20"
# print(int(y)+int(z)) # Now it it converted into integer
"""
str
int
float
"""
# Quiz
# Adding two numbers
print ("Enter the first number")
first = int(input())
print ("Enter the second number")
second = int(input())
print ("The sum is... |
504c061e4c8e3a19dc54ce43005b902b1cce23f8 | SK9415/Python | /loops.py | 794 | 4.09375 | 4 | #there are only two types of loop: for and while
def main():
x = 0
print("while loop output")
#while loop
while(x<5):
print(x)
x = x+1
print("for loop output")
#for loop
#here, 5 is inlusive but 10 is excluded
for x in range(5,10):
print(x)
#for loop over a... |
31a4cbc00d468ecffbf4d4963ef68dca9015d6ee | citcheese/aws-s3-bruteforce | /progressbar.py | 3,922 | 3.640625 | 4 | #!/usr/bin/python
#
# Forked from Romuald Brunet, https://stackoverflow.com/questions/3160699/python-progress-bar
#
from __future__ import print_function
import sys
import re
import time, datetime
class ProgressBar(object):
def __init__(self, total_items):
"""Initialized the ProgressBar object"""
... |
da0858bbaa399f271317a1bc72db9bc496741a7c | RicardoPereiraIST/Design-Patterns | /Behavioral Patterns/Interpreter/example.py | 2,546 | 3.796875 | 4 | import abc
class RNInterpreter:
def __init__(self):
self.thousands = Thousand(1)
self.hundreds = Hundred(1);
self.tens = Ten(1);
self.ones = One(1);
def interpret(self, _input):
total = [0]
self.thousands.parse(_input, total)
self.hundreds.parse(_input, total)
self.tens.parse(_input, to... |
3d6e9293a05058f88e080a1ca82c5c0640c3a0ff | RicardoPereiraIST/Design-Patterns | /Structural Patterns/PrivateClassData/private_class_data.py | 551 | 3.84375 | 4 | '''
Control write access to class attributes.
Separate data from methods that use it.
Encapsulate class data initialization.
'''
class DataClass:
def __init__(self):
self.value = None
def __get__(self, instance, owner):
return self.value
def __set__(self, instance, value):
if self.value is Non... |
0637d75b9e1a1968a0e5420e81c25834a5be6e81 | RicardoPereiraIST/Design-Patterns | /Behavioral Patterns/Null Object/example.py | 678 | 3.5 | 4 | import abc
class AbstractStream(metaclass=abc.ABCMeta):
@abc.abstractmethod
def write(self, b):
pass
class NullOutputStream(AbstractStream):
def write(self, b):
pass
class NullPrintStream(AbstractStream):
def __init__(self):
self.stream = NullOutputStream()
def write(self, b):
self.stre... |
949c75b95b53ea80f89808de44e048b8d35c46b2 | lBenevides/CS50 | /pset6/credit.py | 951 | 3.6875 | 4 | from cs50 import get_int
card_number = get_int("Number: ")
card = card_number
count = 1
sum1 = 0
checksum = 0
c = card
while card_number >= 10: # loop to know how many digits
card_number /= 10
count += 1
i = count/2
card = int(card * 10)
for x in range(int(i)+1): # iterates the number, diving by 10 an... |
83807f66e3b59665593c9f8f0afa45f1f795d5b1 | superlisohou/aspect-term-extraction | /add_pos_tag.py | 1,364 | 3.5 | 4 | #-*-coding:utf-8-*-
"""
Created on Sat Feb 24 2018
@author: Li, Supeng
Use nltk package to perform part-of-speech tagging
"""
from xml_data_parser import xml_data_parser
import nltk
def add_pos_tag(input_file_name, split_character_set):
#
xml_data_parser(input_file_name=input_file_name, split_character_set=... |
5c154be5da45623e64754aea0b096f32c30ea47a | chapman-cs510-2017f/cw-04-cpcw3 | /primes.py | 1,295 | 3.96875 | 4 | #!/usr/bin/env python3
# Name: Chelsea Parlett & Chris Watkins
# Student ID: 2298930 & 1450263
# Email: parlett@chapman.edu & watki115@mail.chapman.edu
# Course: CS510 Fall 2017
# Assignment: Classwork 4
def eratosthenes(n):
""" uses eratosthenes sieve to find primes"""
potential_primes = list(i for i in rang... |
5f0faab3f8ab77137a26b7767c0b45aa8d1ff12e | ThaisSouza411/ac3_arquitetura | /ac3_teste.py | 994 | 3.5 | 4 | import unittest
from ac3 import Calculadora
class PrimoTeste(unittest.TestCase):
def teste_soma(self):
calculadora = Calculadora()
resultado = calculadora.calcular(20, 4, 'soma')
self.assertEqual(24, resultado)
def teste_subtracao(self):
calculadora = Calculadora()
res... |
584a23a449e725e67f40ac8888b91359737e4a97 | ARTC-RatLord/Puzzles | /collatz conjecture.py | 338 | 3.625 | 4 |
# coding: utf-8
# In[5]:
def collatz(a):
collatz_conjecture=[a]
while collatz_conjecture[-1]>1:
if collatz_conjecture[-1]%2 == 0:
collatz_conjecture.append(collatz_conjecture[-1]//2)
else:
collatz_conjecture.append(collatz_conjecture[-1]*3+1)
return collatz_conjec... |
fec505b5d8d11af5ff062722996be56342931a5a | ARTC-RatLord/Puzzles | /chess.py | 1,336 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 7 13:35:20 2020
@author: 502598
"""
def ValidChessBoard(move):
valid_pieces = ['pawn', 'bishop', 'king', 'queen', 'knight', 'rook']
valid_letters = ['a','b','c','d','e','f','g','h']
valid_colors = ['w', 'b']
square_flag = True
f... |
ebb9cedc7c5ab5fe70d00d81b91daad46cdfac55 | Zokhira/basics | /functions/functions_exercises.py | 315 | 3.53125 | 4 | def favorite_book(book_title):
print(f"One of my favorite books is '{book_title}'")
favorite_book("Harry Potter")
def multi_num(a: int, b: int):
c = a * b
print(f"product of {a} and {b} is {c}.")
multi_num(5, 6)
multi_num(0,6)
multi_num(-1, -1)
multi_num(True, True)
def swap(a,b):
return a, b
swap(5,6... |
df03b5998aa5f44ee50831fc37137489c6248f77 | Zokhira/basics | /classes/cars_exec.py | 1,134 | 3.984375 | 4 | # 04/03/2021
# This file is for executing the cars.py classes
from classes.cars import Car
# Execution
# drive() we will not have an access to this function yet
# mycar = Car() # Car is the class, mycar is an object...in this line we are creating instance of the (instantiation)
mycar = Car("BMW", "530xi", "black")
... |
fbfd41c416a36b7435a0cfab07969af7468500ad | Zokhira/basics | /dictionaries_loops.py | 213 | 3.890625 | 4 | rivers = {'nile': 'Egypt', 'tigres': 'Iraq', 'amazon': 'Brazil', 'mississippi': 'Usa'}
for river, country in rivers.items(): #or key for values
print(f"The {river.title()} runs through {country.title()}. ") |
9274b177898d108ffe4b872c3a7e9c9bd70ad50e | MeeSeongIm/computational_complexity_py | /discrete_fourier_transform.py | 722 | 3.59375 | 4 |
# Discrete Fourier Transform: only for the case when the signal length is a power of two.
from cmath import exp, pi, sqrt
x = 3 # change this to any nonnegative integer.
N = 2**x
j = sqrt(-1)
data = []
# for the moment, let all x_n = 1 for all n and for each DFT sample.
for p in list(range(int(N))):
... |
a5fa1b5ffe4d5c21331d4773736bdd7939bb729e | keepmoving-521/LeetCode | /程序员面试金典/面试题 02.03. 删除中间节点.py | 1,718 | 4.03125 | 4 | """
实现一种算法,删除单向链表中间的某个节点(即不是第一个或最后一个节点),
假定你只能访问该节点。
示例:
输入:单向链表a->b->c->d->e->f中的节点c
结果:不返回任何数据,但该链表变为a->b->d->e->f
"""
# Definition for singly-linked list.
class LinkNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
# create a linklist
def cr... |
25d76b3da92239864774bebd5d2c47ddce06974e | kknnn/ProjectEuler | /SummationOfPrimes.py | 293 | 3.59375 | 4 | def esPrimo(numero):
for i in range(2,numero):
if ((numero%i)==0):
return False
return True
suma = 0
for i in range(2, 2000001):
if (esPrimo(i)):
suma += i
print(suma)
#NO TERMINA DE EJECUTAR NUNCA -.- HAY QUE BUSCAR UNA SOLUCION MAS EFICIENTE |
b0e2d53e58c970e711f06a7ae3715181d070f3f7 | jugal13/Design_And_Analysis_Algorithms | /Programs/Breadth First Search(Layers).py | 832 | 3.625 | 4 | graph={
1 : [ 2, 3 ],
2 : [ 1, 3, 4, 5 ],
3 : [ 1, 2, 6, 7 ],
4 : [ 2, 5, 8, 9],
5 : [ 2, 4, 9],
6 : [ 3, 7 ],
7 : [ 3, 6 ],
8 : [ 4, 9 ],
9 : [ 4, 5, 8, 10 ],
10 : [9]
}
source = 1
def bfs(graph,source):
tree = []
traversal = []
layer = []
i = 0
visited = [0]*11
visited[source] = 1
layer.append([sour... |
c1c431abb02873134f13691a27cef1d4ad842600 | jugal13/Design_And_Analysis_Algorithms | /Programs(User Input)/Breadth First Search(Layers).py | 871 | 3.6875 | 4 | def bfs(graph,source,n):
tree = []
traversal = []
layer = []
i = 0
visited = [0]*(n+1)
visited[source] = 1
layer.append([source])
traversal.append(source)
while layer[i]:
r = []
for u in layer[i]:
for v in graph[u]:
if visited[v] == 0:
traversal.append(v)
tree.append([u,v])
visited[v]... |
bca96439911f431aab27a193f351a810c6424436 | jugal13/Design_And_Analysis_Algorithms | /Programs/Knapsack.py | 731 | 3.546875 | 4 | items = {
1 : [ 3, 10 ],
2 : [ 5, 4 ],
3 : [ 6, 9 ],
4 : [ 2, 11]
}
W = 7
M = [[0]*(W+1)]
def matrix(items,M,W):
for i in range(1,len(items)+1):
row = [0]
wi = items[i][0]
vi = items[i][1]
for w in range(1,W+1):
if w < wi:
row.append(M[i-1][w])
else:
row.append(max(M[i-1][w],vi+M[i-1][w-... |
27f2639a391a5e7ad4d6a25e6f6b5da9fe74a97c | luisjimenezlinares/AGConsta | /Fuentes/funciones_AG/comasaf/mutation.py | 1,930 | 3.515625 | 4 | # -*- coding: utf-8 -*-
import random
def mutation(G):
#Muta un 1% de los genes
genes_a_mutar = []
genes1p = len(G) / 100
#Si el 1% es 0, se selecciona un gen al azar
if genes1p == 0:
genes_a_mutar = [random.randint(0, len(G)-1)]
#Sino se selecciona un 1% de los genes
else:
... |
9bd622894d7e1dde61b4957a91975f4cbced94fb | benv587/baseML | /LinearRegression/LinearRegression_bgd.py | 2,039 | 3.8125 | 4 | import numpy as np
class LinearRegression(object):
"""
根据批量梯度下降法求线性回归
"""
def __init__(self, alpha, max_iter):
self.alpha = alpha
self.max_iter = max_iter
def fit(self, X, y):
X = self.normalize_data(X) # 标准化数据,消除量纲影响
X = self.add_x0(X) # 增加系数w0的数据,就不需要对w区别对待了
... |
6305227ae30aa254fc14bbe65e646b3ecfc38224 | guingomes/Linguagem_Python | /1.operadores_aritmeticos.py | 385 | 4.125 | 4 | #objetivo é criar um programa em que o usuário insere dois valores para a mensuração de operações diversas.
n1 = int(input('Digite um valor: '))
n2 = int(input('Digite outro valor: '))
s = n1+n2
m = n1*n2
d = n1/n2
di = n1//n2
e = n1**n2
print('A soma é: {}, o produto é: {} e a divisão é: {:.3f}'.format(s, m, d))
pri... |
6724a08be69d5429e28bbf028f3cafe78337b8f2 | zzfima/GrokkingAlgorithms | /Rec_sum_p81.py | 357 | 4.125 | 4 | def main():
print(SummArrayNumbers([3, 5, 2, 10]))
def SummArrayNumbers(arr):
"""Sum array of numbers in recursive way
Args:
arr (array): numerical array
Returns:
int: sum of numbers
"""
if len(arr) == 1:
return arr[0]
return arr[0] + SummArrayNumbers(arr[1:])
i... |
01af00a403187b6b3a2e68e0c1a3c82b475b8794 | walleri18/Programming-tasks-Python-3.x | /Programming tasks/The first paragraph/Six tasks/Six tasks.py | 1,177 | 4.21875 | 4 | # Ипортирование мматематической библиотеки
import math
# Катеты прямоугольного треугольника
oneCathetus, twoCathetus = 1, 1
# Получение данных
oneCathetus = float(input("Введите первый катет прямоугольного треугольника: "))
twoCathetus = float(input("Введите второй катет прямоугольного треугольного: "))
oneCathetus ... |
2c4ecba0227a2e6c535e541e91ca1d1ab822ba8c | walleri18/Programming-tasks-Python-3.x | /Programming tasks/The first paragraph/One tasks/One tasks.py | 496 | 4 | 4 | # Действительные числа a и b
a, b = 0.0, 0.0
# Получение данных
a = float(input("Пожалуйста введите число A: "))
b = float(input("Пожалуйста введите число B: "))
# Ответы задачи
print("\n", a, " + ", b, " = ", (a + b))
print("\n", a, " - ", b, " = ", (a - b))
print("\n", a, " * ", b, " = ", (a * b))
input("\nДля зав... |
6b560a28e34a507c79d88f04995fc7dd0bd4571a | walleri18/Programming-tasks-Python-3.x | /Programming tasks/The first paragraph/Twenty one tasks/Twenty one tasks.py | 1,276 | 3.96875 | 4 | # Импортирование математической библиотеки
import math
# Действительные числа
c, d = 0, 0
# Корни уравнения x_one, x_two
x_one, x_two = 0, 0
# Получаем данные
c = float(input("Введите коэффициент C: "))
d = float(input("Введите коэффициент D: "))
# Находим корни уравнения
D = (-3) ** 2 - 4 * (-math.fabs(c * d))
if... |
bfc77608f4fff3bf16b36463a0a34debfe4052d6 | Adva-Bootcamp21/google-project-efrat-noa | /data.py | 356 | 3.703125 | 4 | class Data:
"""
Save all the sentences can be searched in a dictionary format that includes all the word as the keys
"""
def __init__(self):
self.__list = []
def get_sentence(self, index):
return self.__list[index]
def add(self, sentence):
self.__list.append(sentence)
... |
d350f927573693cfbf32b423e7d41150ea61ef2d | callmebg/arcade | /arcade/examples/perlin_noise_1.py | 4,490 | 3.546875 | 4 | """
Perlin Noise 1
If Python and Arcade are installed, this example can be run from the command line with:
python -m arcade.examples.perlin_noise_1
TODO: This code doesn't work properly, and isn't currently listed in the examples.
"""
import arcade
import numpy as np
from PIL import Image
# Set how many rows and col... |
c412c9b5239cab36c3d23beffcf2c6429de45701 | callmebg/arcade | /arcade/examples/texture_transform.py | 3,380 | 3.75 | 4 | """
Sprites with texture transformations
Artwork from http://kenney.nl
If Python and Arcade are installed, this example can be run from the command line with:
python -m arcade.examples.sprite_texture_transform
"""
import arcade
from arcade import Matrix3x3
import math
import os
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 60... |
e7836387e0f7799a52b6ed24c912e502cb1b4066 | callmebg/arcade | /arcade/geometry.py | 2,384 | 3.890625 | 4 | """
Functions for calculating geometry.
"""
from typing import cast
from arcade import PointList
_PRECISION = 2
def are_polygons_intersecting(poly_a: PointList,
poly_b: PointList) -> bool:
"""
Return True if two polygons intersect.
:param PointList poly_a: List of points t... |
152e9cbfbd601c868fd22ed95b71745f0fcf377f | mchrzanowski/ProjectEuler | /src/python/Problem112.py | 995 | 3.59375 | 4 | '''
Created on Mar 15, 2012
@author: mchrzanowski
'''
from time import time
def main():
LIMIT = 0.99
iteration = 101 # 101 is the first bouncy number
bouncies = 0
while float(bouncies) / iteration != LIMIT:
strIteration = str(iteration)
monoIncrease = mo... |
2e0b949e98c20620649d095cd49012fe9266a323 | mchrzanowski/ProjectEuler | /src/python/Problem138.py | 993 | 3.671875 | 4 | def main():
'''
God, I hate these recurrence relation problems.
We are given the first two Ls: 17, 305.
Note that:
305 = 17 * 17 + 16 * 1
5473 = 17 * 305 + 16 * 18
....
Let P = [1, 18]. Then, the general formula, found with much
trial and error, is:
L_new = ... |
6b03bb6a11c7d281b149df1f39c25239e6161dbf | mchrzanowski/ProjectEuler | /src/python/Problem135.py | 2,511 | 3.5 | 4 | '''
Created on Sep 20, 2012
@author: mchrzanowski
'''
def produce_n(z, k):
return 2 * k * z + 3 * k ** 2 - z ** 2
def main(max_n, solution_number):
solutions = dict()
# we can write x ** 2 - y ** 2 - z ** 2 = n as:
# (z + 2 * k) ** 2 - (z + k) ** 2 - z ** 2 == n
# if you find the partial der... |
8a0fc1fe53bd0be86da21a304645c84fa192c215 | mchrzanowski/ProjectEuler | /lib/python/ProjectEulerLibrary.py | 5,447 | 3.765625 | 4 | '''
Created on Jan 19, 2012
@author: mchrzanowski
'''
from ProjectEulerPrime import ProjectEulerPrime
def generate_next_prime(start=2):
''' generator that spits out primes '''
# since 2 is the only even number,
# immediately yield it and start
# the below loop at the first odd prime.
if start ==... |
f9d31311fa563aacdbb541583f00ac178d2b1cdc | mchrzanowski/ProjectEuler | /src/python/Problem019.py | 1,268 | 3.78125 | 4 | '''
Created on Jan 16, 2012
@author: mchrzanowski
'''
from time import time
YEAR_LIMIT = 2001
YEAR_BASE = 1900
daysInMonth = {
1: 31,
2: 28,
3: 31,
4: 30,
5: 31,
6: 30,
7: 31,
8: 31,
... |
3648ca0b5536bcc00bb779e8a023079364e19003 | iljones00/TicTacToe | /TicTacToe.py | 1,409 | 3.71875 | 4 | import Model
from View import View, ConsoleView, MiniView
from Strategies import *
def main():
model = Model.Model(3, 3)
view = MiniView(model)
strategy = playAnyOpenPosition(model)
print("This is the game of Tic Tac Toe")
print("Moves must be made in the format 'x,y' where x and y are the coordin... |
4ef7941c333484fc25c4b37e9cfd8a58993e6722 | ykmc/contest | /atcoder-old/2015/0818_abc027/b.py | 730 | 3.578125 | 4 | # Python3 (3.4.3)
import sys
input = sys.stdin.readline
# -------------------------------------------------------------
# function
# -------------------------------------------------------------
# -------------------------------------------------------------
# main
# -------------------------------------------------... |
0d304747aaae387f0fe931a0f1ca1f9666faaaba | prtk94/Python-Scripts | /hangman.py | 1,497 | 3.796875 | 4 | #A basic hangman game.
import random
#dict with keys as movie name and values as a list of clues.
movie_db={'Inception' : ['Sci fi movie','Directed by Chirstopher Nolan'],
'Spiderman' : ['Superhero movie','Features a friendly neighbourhood guy'],
'Home Alone' : ['Kids movie']
}
gameOver= False
themo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.