blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
debdc0fe04ed974773677932ed48fab64ffef54d | sulai1/parseq | /parseq/src/parser.py | 1,308 | 3.515625 | 4 | import re
class parser(object):
"""The Parser parses a code file for its components."""
ERROR_GRP = "err"
ESCAPE = '[\^$.|?*+(){}"'
id = 0
def __init__(self,regex,groups=[]):
self.groups = groups
self.regex = regex
def parse(self,string):
""" Parse the string and return the matches. The matches can be sea... |
5f824d8fe3fcf51d8550f1d7bb78a43694e2f037 | BeniyamL/alx-higher_level_programming | /0x03-python-data_structures/6-print_matrix_integer.py | 447 | 4.34375 | 4 | #!/usr/bin/python3
def print_matrix_integer(matrix=[[]]):
"""
print_matrix_integer - print matrix of an integer
@matrix: the given matrix
@Return : nothing
"""
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if j == len(matrix[i]) - 1:
print("{:d... |
a19ee324078a41a9ec52a7ba73ed315c13f1d6ee | habibor144369/python-all-data-structure | /dictionary-3.py | 1,285 | 3.8125 | 4 | # dictionary data structure--
marks = {
1:{'name': 'Habibor Rahaman', 'roll': 14, 'result':{'Bangla': {'first': {'sahitto': 77, 'kobita': 76}, 'second': 65}, 'English': 79, 'Programing': 98, 'Math': 92, 'Science': 80}},
2:{'name': 'Abdullah', 'roll': 17, 'result':{'Bangla': 78, 'English': 79, 'Programing': 80, ... |
225cc1a1097052b861c48073c96566a1a23618fa | TetianaHrunyk/DailyCodingProblems | /challenge28.py | 2,507 | 4.125 | 4 | """
Write an algorithm to justify text. Given a sequence of words and an integer
line length k, return a list of strings which represents each line,
fully justified.
More specifically, you should have as many words as possible in each line.
There should be at least one space between each word. Pad extra spaces
wh... |
970ae608a12d199e1a55f189e86820be9422f871 | hamidhmz/python-exercises | /basic.py | 110 | 3.5625 | 4 | """basic"""
items = [1, 2, 3, 4]
afterMapping = list(map(lambda item: item+1, items))
print(afterMapping)
|
92c30a32bbd6e010f67b522a5eb14d89365492c8 | FlorianMuller/bootcamp-machine-learning-day03 | /ex01/data_spliter.py | 2,995 | 3.8125 | 4 | import numpy as np
def data_spliter(x, y, proportion):
"""
Shuffles and splits the dataset (given by x and y) into a training and a
test set, while respecting the given proportion of examples to be kept in
the traning set.
Args:
x: has to be an numpy.ndarray, a matrix of dimension m * n.
... |
4200f0a7ccc3699f2ec2af733432ff0939222686 | cwavesoftware/python-ppf | /ppf-ex05/moreless.py | 170 | 4.15625 | 4 | num = int(input('Enter number? '))
if(num<0):
print("Number is less than zero")
elif(num>0):
print("Number is higher than zero")
else:
print("Number is zero") |
4064b17b933d9825ece9f1869cb5fc31429112a2 | jvillega/App-Academy-Practice-Problems-II | /OrderedVowelWords.py | 2,046 | 4.34375 | 4 | #!/usr/bin/env python3
# Write a method, `ordered_vowel_words(str)` that takes a string of
# lowercase words and returns a string with just the words containing
# all their vowels (excluding "y") in alphabetical order. Vowels may
# be repeated (`"afoot"` is an ordered vowel word).
#
# You will probably want a helper m... |
8b577e25449fc3c16300e2b55bbe21f91282d0e5 | Austin-Bell/PCC-Exercises | /Chapter_4/threes.py | 185 | 4.21875 | 4 | # Make a lsit of the myltiples of 3 from 3 to 30. Use a for loop to print the numbers in your list.
threes = list(range(3,31))
for three in threes:
three = three * 3
print(three)
|
16ba80d504687e4de4ae0b6e758938b16a6d55d7 | alblaszczyk/python | /simplepythonexercises/longest_word.py | 248 | 3.953125 | 4 | x = ['chuj', 'matrioszka', 'oj']
def longest_word(x):
lst = []
for i in x:
lst.append(len(i))
max_value = lst[0]
for i in lst:
if max_value < i:
max_value = i
return max_value
print longest_word(x)
|
951076ff342a7f68944c928250c809c2668fadfb | efrainc/data_structures | /linked_list.py | 3,315 | 4.46875 | 4 | #! /usr/bin/env python
# Linked List Python file for Efrain, Mark and Henry
class Node(object):
"""Class identifying Node in linked list
with a pointer to the next node and a value
"""
def __init__(self, value, pointer=None):
"""Constructor for node
which requires a value, and an opti... |
d17020af0c45849006328be4364c6309fdd8d4c0 | michaelvwu/Introduction-to-Programming | /Python Projects/lo_shu.py | 1,654 | 3.734375 | 4 | # Nancy Zhang (nz2bc)
# Michael Wu (mvw5mf)
num = [['', '', ''], ['', '', ''], ['', '', '']]
a, b, c, d, e, f, g, h, i = input("Numbers: ").split()
row1 = [a, b, c]
row2 = [d, e, f]
row3 = [g, h, i]
num_square1 = [int(x) for x in row1]
num_square2 = [int(y) for y in row2]
num_square3 = [int(z) for z in row3]
summ... |
18efca361cd1e33413c9a0f890c00f42f442771e | danamulligan/APTsPython | /ps2/PortManteau.py | 438 | 3.90625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 4 12:40:55 2018
@author: danamulligan
"""
def combine(first,flen,second,slen):
length = flen + slen
final = [0] * length
counter = 0
end = len(second)
for k in range(0, flen):
final[k] = first[k]
counter += 1
... |
1a33f76741af88b32104558937187e4d56af938b | balturu/SmartCoding | /HomeworkAssignments/Ex2_phone_book.py | 428 | 3.796875 | 4 | names = ["Peter", "Mary", "Jane", "Mark"]
locations = ["Stockholm", "Gothenburg", "Helsingborg", "Umea"]
phones = [46701111111, 46702222222, 46703333333, 46704444444]
#for n, l, p in zip(names, locations, phones):
#print('{0}, {1}, {2}'.format(n, l, p))
phoneBook = {}
count = 0
for name in names:
phoneBook[na... |
1852540df4630e62782444bfec667bb0bec224d2 | ecastillob/project-euler | /051 - 100/80.py | 1,142 | 3.875 | 4 | """
It is well known that if the square root of a natural number is not an integer, then it is irrational. The decimal expansion of such square roots is infinite without any repeating pattern at all.
The square root of two is 1.41421356237309504880..., and the digital sum of the first one hundred decimal digits is ... |
a6a8a3c87fe930c93693cb273ff7968047f05f31 | YolieQQQ/AtCoder | /abc174/c.py | 326 | 3.609375 | 4 | def sevens():
num = 7
while True:
num = num*10+7
yield num
if __name__ == '__main__':
K = int(input())
for i, sv in enumerate(sevens()):
if sv%K==0:
print(sv)
print(i+2)
quit()
if K<=i:
print(-1)
quit()
... |
4fdf08b69859547541561d5a15e76082d0f865d1 | ccsandhanshive/Practics-Code | /Practics/returnMissingNumber.py | 482 | 3.546875 | 4 |
'''def getMissingVal(numbers):
return ((max(numbers)*(max(numbers)+1))//2)-(sum(numbers))'''
def getMissingVal(numbers,count):
ans=[]
for i in range(1,count):
if i not in numbers:
ans.append(i)
return ans
n=int(input())
for _ in range(n):
numbers=input()
count=... |
d307cf7f1e96abda54b4f140240767d3043088e2 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/meetup/7c93fa4e609349ef8806bc92ab59953d.py | 602 | 3.859375 | 4 | import calendar
from datetime import date
def meetup_day(year, month, day, week):
day_int = list(calendar.day_name).index(day)
cal = calendar.Calendar()
cal_iterator = cal.itermonthdays2(year, month)
if week[0].isnumeric():
week_index = int(week[0]) - 1
elif week == 'last':
week_i... |
5648b3f543947f1fb15ba0fdab2df999da2cb63f | derick-droid/codingbat | /warm up 2/first_half/first_half.py | 343 | 4.1875 | 4 | """
Given a string of even length, return the first half. So the string "WooHoo" yields "Woo".
first_half('WooHoo') → 'Woo'
first_half('HelloThere') → 'Hello'
first_half('abcdef') → 'abc'
"""
def first_half(str):
if len(str) % 2 == 0:
index = str[:int(len(str) / 2)]
return index
else:
... |
cf5654c32fdfcb93bdea7c4e8935a30af0fd188e | siggame/MegaMinerAI-15 | /server/game_app/maze.py | 5,251 | 3.5625 | 4 | import random
#directions
NORTH = 0
EAST = 1
SOUTH = 2
WEST = 3
#map array states
EMPTY = 0
SPAWN = 1
WALL = 2
class Wall:
def __init__(self, x, y, wallDir):
self.x = x
self.y = y
self.wallDir = wallDir
class BFSTile:
def __init__(self, x, y):
self.x = x
self.y = y
... |
bb79a65544913ca54d0845a598613b3a2854a5cb | balajipothula/python | /fraction.py | 355 | 3.703125 | 4 | import fractions
from fractions import Fraction as fr
print(fractions.Fraction(1.5)) # 3/2
print(fractions.Fraction(5)) # 5
print(fractions.Fraction(1,3)) # 1/3
print(fractions.Fraction(1.1))
print(fractions.Fraction('1.1')) # 11/10
print(fr(1,3) + fr(1,3)) # 2/3
print(1 / fr(5,6)) # 6/5
print(fr(-3,10) > 0) # ... |
750f67d881e555c51cb5f834b305c3c58914c82c | ravi4all/PythonAugReg_1-30 | /02-Inheritance/03-Multiple.py | 1,265 | 3.984375 | 4 | class Person:
def __init__(self):
self.company = "HCL"
self.bank = "HDFC"
self.name = ""
self.age = None
self.gender = ""
self.salary = None
class Emp:
def __init__(self, name, age, gender, salary):
super().__init__()
self.name = n... |
50f11daf72924c09b2d348d235f36ec02d42a42a | JoanRamallo1/RESER_VAVOL | /ES/src/Hotels.py | 1,010 | 3.5 | 4 | class Hotels:
def __init__(self):
self.code = []
self.nom = []
self.hostes = []
self.habitacions = []
"""Numero de dies"""
self.durada = []
self.Price = []
def add_Hotel(self, nom, code = 0, hostes = 0, habitacions = 0, durada = 0, p... |
3d9ad55a1e76660c59519431c17077156a23ef23 | Amar0589/Session6_12_assigment | /palindrome.py | 143 | 3.859375 | 4 | def ispalindrome(ip):
s=str(ip)
print("Input string is:",s)
rev=s[::-1]
if s == rev:
print("string is palindrome") |
4e32c7d9c70ed77c454de096f0a22952abb7330d | DarelShroo/eoi | /05-libs/external/pillow/payaso.py | 247 | 3.578125 | 4 | from PIL import Image, ImageDraw
leon = Image.open("leon.jpg")
width, height = leon.size
x, y = width //2, height // 2
y += 80
rect = (x-55, y-55, x+55, y+55)
draw = ImageDraw.Draw(leon)
draw.ellipse(rect, fill=(255, 0, 0), width=3)
leon.show()
|
a188a512e3698c43336e0f210be56a4416556edb | namnt14/practice-python | /char_input.py | 384 | 3.90625 | 4 | import time
def years():
name = input("Enter your name: ")
age = int(input("Input your age: "))
curYear = time.localtime(time.time())
year = str(int(curYear[0]) + (100 - age))
times = int(input ("How many times would you like the message to print out: "))
message = name + " would turn into 100 y... |
87d14a779960a30d87d2994f251ea79f0cdfc378 | xiangyang0906/python_lianxi | /zuoye5/集合推导式01.py | 424 | 4.125 | 4 | set01 = {1, 2, 3, 3, 4, 5, 6, 6, 7, 2}
print(set01)
for i in set01:
print(i, end=" ")
print()
set02 = {i for i in set01}
print(set02)
list01 = [1, 2, 3, 3, 4, 5, 6, 6, 7, 2]
set03 = {i for i in list01}
print(set03)
# 计算列表中list01中每个值的平方,并去重
set07 = {i * i for i in list01}
set08 = {i * i for i in list01}
print(set0... |
fd42fc6a0c04a76a0e134aa7569b2c2be4b12c67 | jingyiZhang123/leetcode_practice | /partition/Kth_largest_element_in_an_array_215.py | 1,472 | 4 | 4 | """
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
For example,
Given [3,2,1,5,6,4] and k = 2, return 5.
Note:
You may assume k is always valid, 1 ≤ k ≤ array's length.
"""
from random import randint
class Solutio... |
f064552bf961f453cef9d2a20e3b873f05bae6e1 | OokGIT/pythonproj | /stochastic/roll_die.py | 861 | 3.84375 | 4 | import random
'''
random - uses time in milliseconds since January 1, 1968.
That is called seed generating
Given a seed you always get the same sequence
'''
random.seed(0) # use zero as seed
def rollDie():
'''
Returns a randomly chosen int beween 1 and 6
'''
return random.choice([1, 2, 3, 4, 5, 6])
de... |
3b78aeaf3d738cc6d5b416eee1c61bff85af6d34 | sotrnguy92/udemyPython | /udemy4/pythonPrinting/homework1.py | 804 | 3.53125 | 4 | ###
# Part 1
###
print('Practice', " Makes Perfect.")
# Practice Makes Perfect.
print("Children must be taught\n how to think\n NOT\n what to think")
#Children must be taught
# how to think
# NOT
# what to think
print("\"\"")
#""
print('2 * 3 * 4 * 5 / 10 = ')
#2 * 3 * 4 * 5 / 10 =
print(2 * 3 * 4 * 5 / 10)
#12.0
... |
daa30ab2b8cc42616613d552c4e8d41253753cf6 | ivancete66/M01-2016-2017 | /M03/bucles_for/ejercicio-bucle-for-contar2.py | 119 | 3.890625 | 4 | #coding: utf8
numero = 1
final=input("Introduce el final del contador: ")
for numero in range(1,final):
print numero
|
6419a504a30690b864264b1e013cd4eb7a4f4a9e | mpcalzada/data-science-path | /3-PROGRAMACION-ORIENTADA-OBJETOS/algoritmos_ordenamiento/ordenamiento_burbuja.py | 590 | 3.59375 | 4 | import random
def ordenamiento_burbuja(lista):
n = len(lista)
for i in range(n):
for j in range(0, n - i - 1):
if lista[j] > lista[j + 1]: # O(n) * O(n - i -1) = O(n) * O(n) = O(n ** 2)
lista[j], lista[j + 1] = lista[j + 1], lista[j]
return lista
if __name__ == '__... |
f6de31f7f84fedb3573cc8e0863c050393886091 | paulosrlj/PythonCourse | /Módulo 1 - Python Básico/Aula13/Exercicio03.py | 269 | 3.828125 | 4 | nome = input('Informe o seu primeiro nome: ')
try:
if len(nome) <= 4:
print('Seu nome é curto.')
elif len(nome) <= 6:
print('Seu nome é normal.')
else:
print('Seu nome é maior que o normal.')
except:
print('Nome inválido.') |
43a7a0f57ecb78f05eb45bad6ddd514b132b39fb | bunmiaj/CodeAcademy | /Python/Tutorials/Loops/enumerate.py | 796 | 4.625 | 5 | # Counting as you go
# A weakness of using this for-each style of iteration is that you don't know the index of the thing you're looking at.
# Generally this isn't an issue, but at times it is useful to know how far into the list you are.
# Thankfully the built-in enumerate function helps with this.
# enumerate work... |
3a591ec7ab4727c5e4a54b7c40495c925c8ef6b0 | jaeheehur/algorithm-programmers | /src/practice/12906.py | 228 | 3.671875 | 4 | '''
Programmers - 같은 숫자는 싫어
https://programmers.co.kr/learn/courses/30/lessons/12906
'''
import itertools
def solution(arr):
return list(map(int, (''.join(map(str, (i for i, _ in itertools.groupby(arr)))))))
|
4e17c944ff2d96f134bee8242076c315cdb2c375 | Jesper-dev/madlibGame | /main.py | 506 | 4.28125 | 4 | # This will read a random Mad Lib
import random
# Opens the text file
f = open('madlibs.txt', 'r')
# Reads the whole file and stores it in a list
madlibText = f.readlines()
# Choose a random line from that list
madlib = random.choice(madlibText)
# Shows the users what the text will be
print(madlib)
# Ask the user ... |
1554708b0d7e4f1997e74481a510dc2211dcbf89 | chenyang1999/coding | /python100/tm04.py | 655 | 3.765625 | 4 | '''
题目:输入某年某月某日,判断这一天是这一年的第几天?
程序分析:以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于2时需考虑多加一天:
程序源代码:
'''
y=int(input("year:"))
m=int(input("month:"))
d=int(input("day:"))
months = (31,28,31,30,31,30,31,31,30,31,30,31)
sum=0
if 0 < m <= 12:
for i in range(m-1):
sum+=months[i]
else:
print ('data error')
sum+=... |
0221f1d669d47f137ba169d16634330962bc8aa4 | akshaa5197/chatbot-in-python | /CHATBOT.py | 776 | 3.78125 | 4 | import math
import random
naameq=['what is your name','what is your name?','what\'s your name','your name','Who are you']
greetings=['hi','hello','welcome','hey nice to meet you']
greets=['hi','hello','hey']
shoplist={'soap':20,'shampoo':30,'mascara':40,'cream':180,'bindi':50,'eyeliner':100}
print("products for... |
75bd87c19305bbcfbbb7157ff33cb3b974c2e6bc | ITkachenko799/itstep-python-web | /python/lesson2/conditions.py | 800 | 4.3125 | 4 | # if/else, or and not, ternary
# > < == >= <= !=
# and or not
# if "":
# print("Hello")
# print(bool(0.0))
# print(bool("123"))
# a = 12
# b = "abc"
# if a and b:
# print("Values: " + str(a) + " " + str(b))
# print(type (None or ''))
# car_speed = 100
# motorcycle_speed = 50
# if car_speed > motorcycl... |
0e01ccdfae50686ebba65e9fd7436ec076bdc0e2 | pasinimariano/masterUNSAM | /clase04/4.13Extraccion.py | 1,202 | 3.765625 | 4 | # Ejercicio 4.13: Extracción de datos
# 4.13Extraccion.py
import csv
def carga_camion(nombre_archivo):
'''Devuelve una lista del lote del camion, recibe como parametro un archivo .csv'''
f = open(nombre_archivo, encoding= 'utf8')
rows = csv.reader(f)
headers = next(rows)
lote = []
try:
... |
ccb31fe0db45c12c06a3c3acc8bc34c090bb272e | mastan-vali-au28/My-Code | /coding-challenges/week08/Day01/Q3.py | 381 | 4.21875 | 4 | '''
Q-3 ) Reverse a string using recursion:(5 marks)
If we have a string, write a function that prints reverse of that string, using
recursion.
Sample Input:
ABCD
Sample Output:
DCBA
'''
def reverse(string):
if len(string) == 0:
return string
else:
return reverse(string[1:]) + string[0]
a = str(... |
e74f97075b373d4777049e13e9917d4ea3a77f38 | jjbnunez/HW-CIS4361-Fuzzer | /defaults/runthrough.py | 3,062 | 4.125 | 4 | # Basics to know about Python from a C perspective:
#
# * Semicolons have been replaced by line breaks.
#
# * Whitespace matters if you don't want to get yelled at by the interpreter.
#
# * Python doesn't need to be compiled, hence why I'll call it an interpreter
# and not a compiler.
#
# * Most places that you would... |
1297359167ac925025a6676f080c2eb46e0180b8 | kwadrat/equ2 | /draw_eis.py | 3,032 | 3.734375 | 4 | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import sys
from turtle import (
backward,
back,
color,
down,
forward,
hideturtle,
left,
mainloop,
onclick,
right,
showturtle,
speed,
up,
)
width = 16
height = 11
edge_len = 30
debug_centering = 0
invisible_turtle =... |
db72b36df6e99f30537814406f3219f1239f481b | PAPION93/python-playground | /01_python_basic/05-2-loop.py | 1,212 | 3.890625 | 4 | # 반복문 실습
print("while")
v1 = 1
while v1 < 11:
print(v1)
v1 += 1
print()
print("for")
for v2 in range(10):
print(v2)
# 1 ~ 100 sum
sum1 = 0
cnt1 = 1
while cnt1 <= 100:
sum1 += cnt1
cnt1 += 1
print(sum1)
print(sum(range(1, 101)))
print(sum(range(1, 101, 2)))
# list loop
# iterable : ragne, revers... |
741b721ae7d56eb2fdc2ebe838d0584d3570fa36 | nopeless/perfectionist | /archived/gamev2.py | 3,170 | 3.609375 | 4 | # v7 revision
# this version tried to pair boards with branches
# but i quickly realized a memory waste
# and made path instance lists instead
import numpy as np
import math
VALID_MAX=2048
# max amount of valid returns
# X of the board
X=5
Y=4
# the logic is weird but ill just go with it anyway
class board:# ... |
d3f444921ee3732b33c71f61ddb6af15772e075e | TorinKeenan/Ecs36A | /study_programs/two_compliment.py | 738 | 3.5625 | 4 | #converts binary number to its two's compliment
def twos_compliment(binary_num):
compliment = ""
binary_list = [int(x) for x in list(binary_num)]
for i in range(len(binary_list)):
if binary_list[i] == 1:
binary_list[i] = 0
else:
binary_list[i] = 1
binary_list[len(... |
8405493330548f7b50fb83d061fe5716b6f0f456 | appletreeisyellow/cracking-the-coding-interview | /ch08_recursion_and_dynamic_programming/8.3_magic-index.py | 3,033 | 4.15625 | 4 | import unittest
"""
8.3 Magic Index
A magic index in an array A [1. .. n -1] is defined to be
an index such that A[i] = i. Given a sorted array of distinct
integers, write a method to find a magic index, if one exists,
in array A.
FOLLOW UP
What if the values are not distinct?
"""
# binary search
... |
2dfbea8ebfd076d8d7112a3b21ef5d7ebac743ff | mattshakespeare/generation_exercises | /exercise13.py | 2,302 | 4.375 | 4 | '''unit testing'''
#1. Write a unit test for the below function.
def add_two_numbers(a, b):
return a + b
def test_add_two_numbers():
#happy path
#arrange
a = 5
b = 5
expected = 10
#act
actual = add_two_numbers(a,b)
#assert
assert expected == actual
print(f'Test {... |
5a27ba5d6982c232fbdbb3e961c68dc41c75c38a | LucasSGomide/Python | /Códigos/Exercicios_estruturas_controle/ex35_mod7.py | 1,315 | 3.578125 | 4 | A = []
B = []
limite = 2
while len(A) < limite:
a = int(input('Digite um número: '))
if a < 0:
print('Numero inválido')
elif a > 10000:
print('Numero inválido')
else:
A.append(a)
for num in list(str(a)):
B.append(int(num))
print('A =', A)
print("B =", B)
C = []
pos... |
1281f05227fa04e5bf3cb0795d5850d54e17da8f | michaelcarlos3/Hangaroo-Problems1-4 | /getAvailableLetters.py | 608 | 4.09375 | 4 | secretWord = str(input("Enter the word to be guessed: "))
lettersGuessed = []
letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
def getAvailableLetters():
me=0
while me == 0:
lettersGuessed = input("Type a letter: ").lower()
... |
5998126d36649bd0fcd1df05e88e66b38d3c51b0 | galayko/euler-python | /problem3.py | 580 | 3.78125 | 4 | #!/usr/bin/env python
# The prime factors of 13195 are 5, 7, 13 and 29.
# What is the largest prime factor of the number 600851475143?
def isprime(num):
tmp = 2
while tmp<num:
if num%tmp==0:
return False
tmp+=1
return True
m = 600851475143
n = 3
while m/n>1:
... |
721604259a51061c8236e70ab9d53c50ae19d5de | 3to80/Algorithm | /Base/binarySearch.py | 1,309 | 4.03125 | 4 | def binarySearch(li, start, end, target):
"""
:param li: read only
:param start: start index in step
:param end: end index in step
:param target: read only
:return: int
"""
if end - start < 1: # 더이상 영역이 없음
return -1
mid = start + (int)((end- start) / 2)
if li[mid] == ta... |
39d3fedc84585cac995e25bfa39a611c253993ff | PRodenasLechuga/HackerRank | /Python/Tuples.py | 256 | 3.625 | 4 | def convertTupleToHash(tupleElement):
return hash(tupleElement)
if __name__ == '__main__':
n = int(input())
integer_list = map(int, input().split())
T = ()
for x in integer_list:
T = T + (x, )
print(convertTupleToHash(T)) |
56ea1fa1d8eacf5286485717b0a570fd4ae31fe1 | kunal12kaushik/calculator | /break and countinue.py | 113 | 3.765625 | 4 | # x = int(input("how much candies you want?"))
# #
# # i = 1
# # while i<=x:
# # print("candy")
# # i+=1
|
479a4c14355483fb27f0bbf979c7323d6ba1c412 | williamqin123/old-python | /Chat.py | 106 | 3.59375 | 4 | print("2013 Python User Chat 0.01pre")
count = 1
while count > 0:
print ">>>"
chat = input("")
|
3f16c0d1f704cc735a9a655dbaa46f95dfaa7869 | chrisxue815/leetcode_python | /problems/test_0233.py | 659 | 3.875 | 4 | import unittest
class Solution:
def countDigitOne(self, n):
"""
:type n: int
:rtype: int
"""
result = 0
m = 1
while m <= n:
m2 = m * 10
result += (n // m + 8) // 10 * m + (n // m % 10 == 1) * (n % m + 1)
m = m2
ret... |
6a835dd255969413594c861da5798d4178cafee6 | dlemusg/AnalisisNumerico | /metodos/multiplesVariables/LemusCanson/metodoGaussRelajado.py | 3,184 | 3.78125 | 4 | from numpy import *
from sympy import *
import math
def recolectarDatos():
n = int(input("Ingrese el numero de ecuaciones: "))
tolerancia = float(input("Ingrese la tolerancia: "))
niter = int(input("Ingrese el numero maximo de iteraciones: "))
omega = float(input("Ingrese el valor de omega: "))... |
d490aacc18405dc47c4c2c306147d9acadac5f3f | andrewnnov/tasks_py | /w3/date/dates.py | 187 | 3.578125 | 4 | import datetime
x = datetime.datetime.now()
print(x)
print(x.year)
print(x.strftime("%A"))
y = datetime.datetime(2021, 9, 21)
print(y)
print(y.strftime("%B"))
print(y.strftime("%x")) |
35b02a2ee5d4ba2db0dc66621515c0937a106bda | VAB-8350/Read_number-python- | /function.py | 1,440 | 3.75 | 4 | # >>>Victor Andres Barilin<<<
def grouper(n, iterable):
grouped_list = []
i = 0
while i <= len(iterable):
if iterable[i:i+3] != '':
grouped_list.append(iterable[i:i+3])
i += 3
return grouped_list
def clear_number(number):
number = number.strip()
posi = 1
... |
cccd21d7ca27dbd42bd0daa0052c20f4566296a6 | MrYangShenZhen/pythonstudy | /多线程/多线程队列.py | 638 | 3.625 | 4 | import queue
# # q=queue.Queue(3)#Queue()可传数字,表示该队列可存五组数据
# q=queue.LifoQueue(3)#后进先出模式
'''创建线程队列,默认先进先出'''
# q.put('你好')
# q.put(2)
# q.put({"lesson":"math"})
# q.put('test',False)#会提示满了的报错
# while 1:
# data=q.get()
# print(data)
#put,get在队列满了或者为空时去put,get会导致程序一直在运行中
'''优先级模式'''
# Q=queue.PriorityQueue(3)
# Q... |
00597ffe70d0e00990e4420d05ceac1d8dcdee3a | GMwang550146647/network | /0.leetcode/3.刷题/1.数据结构系列/1.线性结构/3.栈/1.单调栈/946.mid_验证栈序列(core).py | 783 | 3.59375 | 4 | from fundamentals.test_time import test_time
class Solution():
def __init__(self):
pass
@test_time
def validateStackSequences(self, pushed, popped):
"""
模拟法:一次push一个,一旦该个和pop中的是一样的,同时pop出来!
"""
stack = []
i = 0
for num in pushed:
stack.a... |
ba153dcca867fd84ccbc814d935a77d3d10a3e16 | nikkureev/bioinformatics | /ДЗ 4/Task6_7.py | 233 | 3.515625 | 4 | # функция проверяет тип коллекции и возвращает элемент
def search(collection, a):
if type(collection) == dict:
print(collection.get(a))
else:
print(collection[a])
|
181af1cd954557928354699c98196265ba3ae2fb | gransburyia/Gransbury-MATH361 | /IntroToProgramming/I9_PartialProd2_Gransbury.py | 629 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 26 08:53:55 2019
@author: grans
"""
import matplotlib.pyplot as plt
#function to change
a_n = lambda n:
#1 + b**n converges: 1 + (7/9)**n
#1 + b**n diverges: 1 + (3/2)**n
#1 + (f(n)/g(n)) converges: 1 + (n/n**4)
#1 + (f(n)/g(n)) diverges: 1 + (n**4/n**2)
def calculat... |
1e0f377724916267e50a3f9859ea78d61cbbb421 | yyzz1010/hackerrank | /sWAP_cASE.py | 230 | 3.90625 | 4 | def swap_case(s):
x = ''
word_list = []
for word in s:
if word == word.upper():
word_list.append(word.lower())
else:
word_list.append(word.upper())
return x.join(word_list)
|
0a32f68f8304f61f69f9e7e88b15733f6d405776 | arthurperng/eulerthings | /ehhhhhhhhhhhquickscopehhhhhhh35.py | 880 | 3.734375 | 4 | import math
primelist=[2]
bound = 3
from math import *
def primeornot(number):
global bound
if number < bound:
return number in primelist
for butt in primelist:
if butt<math.sqrt(number)+1:
if number%butt==0:
return False
else:
break
whil... |
94f686780677d8122c26aeb70613f75d2cb69d97 | DonggyuLee92/solving | /2020 Nov/1106/6323/6323.py | 202 | 3.8125 | 4 | num = int(input())
ans = "1, 1"
a = 1
b = 1
if(num==2):
print("[{}]".format(ans))
for i in range(num-2):
c = a + b
a = b
b = c
ans = ans + ', ' + str(c)
print("[{}]".format(ans)) |
e1c80fec4df39dc7dc736a79a8a624860adf3dbb | jacopo-j/advent-of-code-2017 | /day04/code.py | 987 | 3.59375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import itertools
def part1(in_data):
valids = 0
for line in in_data.split("\n"):
l_list = line.split(" ")
l_set = set(l_list)
if (len(l_list) == len(l_set)):
valids += 1
return valids
def part2(in_data):
valids = 0
... |
2a2c324aff48fd9e24d77248f07ed4a3d24d2451 | PetarSP/SoftUniFundamentals | /Lab5_List_Advanced/7.Group of 10's.py | 542 | 3.625 | 4 | import math
numbers = list(map(int, input().split(", ")))
group = 0
list_of_numbers = []
find_highest_num = max(numbers)
num_of_possible_groups = math.ceil(find_highest_num / 10)
current_group = 0
next_group = 11
while not num_of_possible_groups == 0:
for num in numbers:
if num in range(current_group, nex... |
971893dcea7b1b08d677bba9d730053a2e2bb77b | kotlyarovame/python_for_kids | /tasks/tasks_6.py | 2,964 | 4.0625 | 4 | #1. Цикл с приветом
# Как вы считаете, что делает эта программа?
# Сперва придумайте вариант ответа, а потом запустите код и проверьте, угадали ли вы.
for x in range(0, 20): # цикл от 0 до 19
print('привет %s' % x) # номер переменной
if x < 9: # если х меньше 9
break # остановиться
#2. Четные числ... |
6eaed8fa7755741ad30a31c0c422b3f7e3abf6ad | npatel37/Tflow_DL | /2_basics.py | 456 | 3.84375 | 4 | import tensorflow as tf
### -- this is called making a "graph" where you don't run anything!
x1 = tf.constant(5)
x2 = tf.constant(6)
result = tf.mul(x1,x2) ## multiplication
print(result)
## --- note: No computation has been done until now!
## -- To actually excecute the multiplication you have to run the session.
#... |
47cdf3bad889d8dbeca3fd0a19834edb31caa0dc | tkchris93/ACME | /Backup/test_module.py | 245 | 4.03125 | 4 | students = ["John", "Paul", "George", "Ringo"]
def add_numbers(a,b):
'''
Adds two numbers together
'''
return a+b
def print_students():
'''
Prints the names of each student in the student list
'''
for name in students:
print name
|
51e590a2999c906644f0e9ccbd06d618b4d59785 | khyasir/odoo-10 | /python program/task2.py | 514 | 3.53125 | 4 | import re
url_id=raw_input("enter the url with id")
id=map(int, re.findall(r'\d+', url_id))
abc=len(id)
print abc
or_len=abc-1
print or_len
print id[or_len][2]
print id[or_len][2]
if id[or_len][6]==True:
print id
else:
print "not found"
print url_id[1]
d = defaultdict(list)
for x in url_id:
d[type(x)].appe... |
9b981f431a8c7596696b526ab231e07abc9684f9 | jonasht/tkinter-aprendendo | /app25-lista1.py | 476 | 3.546875 | 4 | from tkinter import *
root = Tk()
root.title('listbox')
root.geometry('+600+200')
lista = Listbox(root, selectmode=EXTENDED)#selectmode=EXTENDED - p conseguir selecionr varios itens
lista.pack()
#inserir um item de cada vez
nomes =['jonas', 'lucas', 'carlos', 'pedro']
for nome in nomes:
lista.insert(END, nome)
... |
9b92a41cb933c55e716810d1023c7d7796a3f320 | ComputeCanada/dhsi-coding-fundamentals-2019 | /Programs/mapFlightsCSV.py | 1,151 | 3.796875 | 4 | # Google spreadsheet/map of hometowns and travel routes
# instructions on how to do this with Sheets instead of a CSV: https://www.twilio.com/blog/2017/02/an-easy-way-to-read-and-write-to-a-google-spreadsheet-in-python.html
# note: doing the mapping part with live Google API requires giving a credit card and being ch... |
088d031815c110a730da508822cb0feac80781eb | armandosrz/DataScience-343 | /KNN/main.py | 2,917 | 3.546875 | 4 | '''
Spirit Animal: generousIbex
Date: 19/10/16
Challenge #: 5
Sources:
- Dr. Jones Lecture
- http://www.cs.olemiss.edu/~jones/doku.php?id=csci343_nearest_neighbors
'''
import os, os.path, time
import matplotlib.pyplot as mplot
from PIL import Image
import numpy as np... |
983ddff7e51a990b44b1a9534414d68103d90f3c | mturpin1/CodingProjects | /Python/PiEncryption/listChars.py | 449 | 3.59375 | 4 | import os
array = []
def inputSubroutine():
inputVar = input('Please input the character you want added to the array(type \'end\' to end the program): ')
inputSubroutine()
while (inputVar != 'end'):
array.add(inputVar)
os.system('cls')
inputSubroutine()
print('Here is your array: ',)
arrayCounter = 0... |
540525bbd4a1f9aeba3c1f177af7f39370c09edb | MTDahmer/Portfolio | /fuckit.py | 2,759 | 3.734375 | 4 | def fillWithAT(grid, theRow, theCol, display):
print('ding')
def printGreeting():
print('Hello user')
print('This program will replace instances of "-" in a given file with the "@" symbol')
def testCharacter(fileData):
print('ding1')
charlist = list()
charList = set('-I')
... |
e343d54ebee0625b1029f708d25da2ffda3d3b1c | rizalpahlevii/learn-python | /praktikum6/kasus4.py | 179 | 3.703125 | 4 | a = int(input("Masukkan a : "))
sum = 0
i = 0
while i < a:
nilai = float(input("Inputkan nilai "))
sum = sum + nilai
i = i + 1
rata_rata = sum / a
print(rata_rata)
|
d2a1e811f70dcc14ffbed7964ced5d9eea2f8723 | joshf26/Personal-Website | /src/static/rocket-launch/scripts/stars.py | 380 | 3.625 | 4 | from random import randint
NUM_STARS = 100
IMAGE_SIZE = 1000
MIN_SIZE = 1
MAX_SIZE = 3
def main():
for _ in range(NUM_STARS):
radius = randint(MIN_SIZE, MAX_SIZE)
x = randint(0, IMAGE_SIZE - radius)
y = randint(0, IMAGE_SIZE - radius)
print(f'<circle cx="{x}" cy="{y}" r="{radius}... |
1a1268d3ab310a5fd2f841493aa3d6a20fee14f2 | Richardjames0289/JavaFiles | /python answers/challenge 2 answers/qa-assessment-example-2/programs/questions.py | 3,516 | 4.15625 | 4 | # <QUESTION 1>
# Given a word and a string of characters, return the word with all of the given characters
# replaced with underscores
# This should be case sensitive
# <EXAMPLES>
# one("hello world", "aeiou") → "h_ll_ w_rld"
# one("didgeridoo", "do") → "_i_geri___"
# one(... |
8260c0347e06210ac88d475d033723ee7a3871af | rrwt/daily-coding-challenge | /ctci/ch3/animal_shelter.py | 2,304 | 4.03125 | 4 | """
An animal shelter, which holds only dogs and cats, operates on a strictly
"first in, first out" basis. People must adopt either the "oldest"
(based on arrival time) of all animals at the shelter, or they can select whether
they would prefer a dog or a cat (and will receive the oldest animal of that type).
They cann... |
83cc1da1f92711e7cef737ac8bb27f9b54de64e1 | ThomasMatlak/tictactoe | /ticTacToe.py | 9,275 | 3.953125 | 4 | #Thomas Matlak
#CSCI100 Final Project
#22 November 2014
#This program runs the game Tic-Tac-Toe for one or two players
#TODO:
#Pretty up the game
#Refactor
from Tkinter import *
import random
import sys
#Draws the tic-tac-toe board
def drawBoard(window):
for i in range(2, 5, 2):
window.create_line(i * 100... |
2d26ec2aece3198533b0c6a4c2fbaee25030190f | DayNKnight/UnnamedCompanyCodeChallenges | /L3/level3.py | 8,208 | 4.1875 | 4 | """
Author: Zack Knight
Date: 5/5/2020
Raytheon Coding Challenges
Level 3
1.Create a command-line based user interface program that:
a.Accepts 3 command line parameters
i. Required: name and age
ii.Optional: phone number
b.Stores the data in a database
c.Supports the... |
90c1aca70fbce56ebea10f8af9a0a21eddae153f | jjivad/UoP_CS001 | /UoP_CS001/first_step.py | 743 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 19 15:31:50 2019
@author: VIJ Global
"""
#print 'Hello, World!'___ error message: syntaxError
#1/2
#type(1/2)
##print(01)____Error: SyntaxError: invalid token
#1/(2/3)
import turtle
import math
bob = turtle.Turtle()
#bob.fd(100)
#bob.lt(90)
#bob.fd(100)
#bob.lt(90)
#bob... |
37d6f9f429a9160b8848a67d0626a7db7532dc93 | honghyk/algorithm_study | /349. Intersection of Two Arrays.py | 346 | 3.828125 | 4 | from typing import List
# Hash Table, Two Pointers, Binary Search, Sort
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
interSet = set()
nums1Set = set(nums1)
for n in nums2:
if n in nums1Set:
interSet.add(n)
... |
3d71ff9638e3839f884fc0364d7a189a0a631707 | MrHamdulay/csc3-capstone | /examples/data/Assignment_9/grgvic001/question1.py | 1,174 | 3.875 | 4 | #program to calculate std andmean of file of marks and check the failures
#victor gueorguiev
#10 may 2014
import math
def calc_mean(marks):
total = 0
for i in marks:
total += i
return total/len(marks)
def calc_std(marks):
totalnum = 0
mean = calc_mean(marks)
for i in ma... |
70d4f20ffbce3e5ec812d0b2e342f68c9b9580cc | jerryzhang2019/VScode-git-leetcode | /Leetcode高频考题重中之重/Leetcode链表linkedlist/876. Middle of the Linked List.py | 925 | 3.96875 | 4 | # 求链表的中点:定一个带有头节点的非空单链表head,返回链表的中间节点。
# 如果有两个中间节点,则返回第二个中间节点。
# 范例1:输入:[1,2,3,4,5] 输出:此列表中的节点3(序列化:[3,4,5])
# 返回的节点的值为3。(此节点的法官序列化为[3,4,5])。
# 请注意,我们返回了ListNode对象ans,例如:
# ans.val = 3,ans.next.val = 4,ans.next.next.val = 5,ans.next.next.next = NULL。
# 范例2:输入:[1,2,3,4,5,6] 输出:此列表中的节点4(序列化:[4,5,6])
# 由于列表具有两个中间节点,其值分... |
41e92e13d355ce676ba61069f097d57e85bdd6cc | Macaque2077/DollyTheSheep | /saveBackup.py | 2,001 | 3.703125 | 4 | from shutil import copy2
import os
import sys
import json
#backup a file by passing {original file location} {folder for copied file to be placed in}
#passed files are stored in a dictionary text file
def main(args):
if len(args) > 0:
file_loc = args[0]
folder_name = args[1]
savefile(file_... |
7226763ef30f787382dd511cb3f66a18f1bf87ba | jvslinger/Year9Design01PythonJVS | /Sample Project 1/GUI1JVS.py | 1,455 | 3.96875 | 4 | #This opens the tkinter "tool box" containing all support material to make GUI Elements
#By including as tk we are giving a short name to use.
import tkinter as tk
#Main Window
root = tk.Tk() #creates the window
#Three stages to build elements
#1. Construct the Object: Building and Configuring it
#2. Configure the ... |
47432ab548574ecdbf7759e90c23f5a49f205cd0 | rafaelperazzo/programacao-web | /moodledata/vpl_data/158/usersdata/272/65875/submittedfiles/imc.py | 366 | 3.828125 | 4 | # -*- coding: utf-8 -*-
peso= float(input('Digite o peso:'))
altura= float(input('Digite a altura:'))
IMC=(peso/(altura**2))
if (IMC<20):
print('ABAIXO')
elif (IMC>=20) and (IMC<=25):
print('NORMAL')
elif (IMC>25) and (IMC<=30):
print('SOBREPESO')
elif (IMC>30) and (IMC<=40):
print('OBESIDADE')
... |
0fea85c1fe9190830c71d9104f40429f27e27d14 | RyanMoodGAMING/Python-School | /Flowchart.py | 576 | 4.21875 | 4 | '''
Function Name: flowChart()
Parameters: N/A
Return Value:
What it does:
'''
def flowChart():
age = input("Please input how old you are -> ")
gender = input("Please input your gender -> ")
if int(age) < 20:
dose = float(age) * 0.1
else:
dose = 2
if gender.lower() == "f... |
ad572777b8f454f725d5a4e2fe66188179049ed8 | ursu1964/Libro2-python | /Cap3/Programa 3_16.py | 460 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
@author: guardati
Problema 3.16
Quita de la lista aquellos elementos que no forman parte de
las tuplas que son claves de un diccionario.
"""
equipos = {('pat', 'lara'): 85, ('jorge', 'ines'): 80, ('luis', 'leti'): 103}
nombres = ['jose', 'pat', 'lara', 'alicia', 'ines']
solo_n... |
d70aba7130700a686ae5e9b4a434a3fb1f27ec9a | johnnymcodes/computing-talent-initiative-interview-problem-solving | /m05_search/merge_sorted_lists.py | 844 | 4.375 | 4 | # Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
#
# Note:
# The number of elements initialized in nums1 and nums2 are m and n respectively.
# You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
# Input... |
c85f735ca7b2768ed99b216e82fd8c8c83d1d5ac | saki45/CodingTest | /py/misc/perfectshuffle/permutationdecompose.py | 300 | 3.59375 | 4 | def permutationdecompose(N):
print(N)
seed = 1
while seed < N:
print(seed,end=',')
t = (seed*2)%(N+1)
while t != seed:
print(t,end=',')
t = (t*2)%(N+1)
print()
seed = 3*seed
if __name__ == '__main__':
permutationdecompose(8)
permutationdecompose(6)
permutationdecompose(0)
|
5f51484eb464a79cc1d4b49b8dd8475ee10bd203 | popshia/Algorithm_Homework_1 | /binarySearchTree.py | 1,994 | 3.90625 | 4 | # 演算法分析機測
# 學號: 10624370/10627130/10627131
# 姓名: 鄭淵哲/林冠良/李峻瑋
# 中原大學資訊工程系
# Preorder to Postorder Problem
# Build a binary tree from preorder transversal and output as postorder transversal
class Node():
def __init__(self, data): # initial node
self.data = data
self.left = None
self.right = None
self.isChar ... |
d66f65fb89910c4c51ea2694e7d4db8ae91149d0 | TJJTJJTJJ/leetcode | /105.construct-binary-tree-from-preorder-and-inorder-traversal.py | 2,471 | 3.828125 | 4 | #
# @lc app=leetcode id=105 lang=python3
#
# [105] Construct Binary Tree from Preorder and Inorder Traversal
#
# https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/
#
# algorithms
# Medium (39.61%)
# Total Accepted: 216.7K
# Total Submissions: 533.2K
# Testcase Exampl... |
81116d7840ce59680d2e39ad7132500b9b561482 | FunkyNoodles/DailyProgrammer | /PythonSolutions/2017-07-05/main.py | 939 | 3.71875 | 4 | import time
def is_palindrome(string):
for idx, char in enumerate(string):
if char != string[-idx-1]:
return False
return True
# n = input('n:\n')
n = 5
max_factor_i = 0
max_factor_j = 0
max_product = 0
found = False
print('n =', n)
start = time.time()
for i in reversed(list(range(1, 10... |
2fbeafbf055879c16aaa94633a8c20cfbdcad5ce | toshhPOP/SoftUniCourses | /Python-Advanced/Multidimentional_Lists/knight.py | 1,364 | 3.75 | 4 | def is_knight_placed(board, r, c):
board_size = len(board)
if r < 0 or c < 0 or r >= board_size or c >= board_size:
return False
return board[r][c] == "K"
def count_affected_knights(board, r, c):
result = 0
board_size = len(board)
if is_knight_placed(board, r - 2, c - 1):
resul... |
9fdcc4daa6fdbca5c906e4baa879ae43a36339d8 | avborup/Kat | /helpers/cli.py | 93 | 3.625 | 4 | def yes():
answer = input("(y/N): ").lower()
return answer == "y" or answer == "yes"
|
217645edebea012bf0f1694f3b277f885a03cf16 | xprime480/projects | /tools/new/python/keys.py | 342 | 3.5 | 4 | #!/usr/bin/python
import string
import random
keys = set([])
while len(keys) < 1000 :
keys.add(''.join([random.choice(string.ascii_lowercase) for x in range(3)]))
keys.add('aaa')
keys.add('aaa')
keys.add('aaa')
lkeys = list(keys);
lkeys.sort()
for k in lkeys :
print 'insert into key_names ( key_name ) val... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.