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 |
|---|---|---|---|---|---|---|
787ed93ff1e4a2d30965e1e4cd593d2e31f42ffc | AhhhHmmm/Project-Euler | /Problem 14/problem14.py | 414 | 3.828125 | 4 |
def collatz_count(num):
count = 1
while num != 1:
if num % 2 == 0:
num = num / 2
else:
num = 3*num+1
count += 1
return(count)
current_max = 0
best_val = 0
current_value = 1
highest_val = 1000000
while current_value < highest_val:
collatz_val = collatz_count(current_value)
if collatz_val > current_ma... |
6af69bfa50ce71a5726548aed0577e088ee69c9a | nsodium/GEOG481 | /Student.py | 1,298 | 3.546875 | 4 | class Student:
def __init__ (self, faculty, schedule, residence, infected, infectionRate, infectRoom):
self.faculty = faculty
#Schedule used to determine what building Student is in, TBD based on information
#from Waterloo API
self.schedule = schedule
self.residence = residence
#Infected status (tru... |
94e86854351e391131814ac466c822d8c6f11a4d | jedzej/tietopythontraining-basic | /students/semko_krzysztof/lesson_07_strings_manipulation/to_swap_the_two_words.py | 377 | 3.984375 | 4 | """
Given a string consisting of exactly two words separated
by a space. Print a new string with the first and second
word positions swapped (the second word is printed first).
This task should not use loops and if.
"""
def main():
line = input()
line = line[line.find(' ') + 1:] + ' ' + line[:line.find(' ')]... |
25ec56572ae3b9f2cfa4f96b3f76b1535f5b99c3 | Kawser-nerd/CLCDSA | /Source Codes/AtCoder/abc070/A/4885846.py | 58 | 3.640625 | 4 | a = input()
b = a[::-1]
print("Yes" if a == b else "No") |
3395c8a5f5de7a85525d9868fcf8cecce9d6121c | DanielFHermanadez/Readme | /Trabajo#2/Python/Trabajo#10.py | 215 | 3.8125 | 4 | n1 = int(input("ingrese la temperatura: "))
if n1>35:
print("Que semana tan calurosa: ",n1)
elif n1<15:
print ("Que semana tan fria: ",n1)
else:
print("Que semana tan deliciosa: ",n1)
|
fd2be0db4571685f637dca40db0faef3c6adabfc | u982025/test | /contact.py | 464 | 3.765625 | 4 | from phone_number import PhoneNumber
class Contact:
def __init__ (self, f_name, l_name, company):
self.first_name = f_name
self.last_name = l_name
self.company = company
self.phone_number = PhoneNumber()
def add_phone_number(self, number, type):
self.phone_number.number ... |
4542e521626e5e048bfddd5d39f8900e594f01cf | white1107/Python_for_Competition | /Python_for_Competition/PLab/S-2.py | 645 | 3.59375 | 4 | import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-3,7,0.5)
y = 10*np.random.rand()+x * np.random.rand() + 2*np.random.rand()*x**2 +x**3
plt.scatter(x,y)
plt.show()
coef_1 = np.polyfit(x,y,1)
y_pred_1 = coef_1[0]*x+ coef_1[1]
# coef_2 = np.polyfit(x,y,2)
# y_pred_2 = coef_2[0]*x**2+ coef_2[1]... |
33f7355c390e5c9f5777a2a38943c6599c67bf3b | changtc8/salt-proj | /vagrant-u/mongotest.py | 582 | 3.5625 | 4 | #!/usr/bin/env python
""" mongodb installation test
add three records to the database,
test the count to indicate test passed or failed
remove the records
"""
from pymongo.connection import Connection
connection = Connection("localhost")
db = connection.mydb
doc1 = {"timestamp":001, "msg":"Hello 1"}
do... |
924fb702dbb9aa0eb6aade9caa8f86f086c854f3 | mkurde/the-coding-interview | /problems/spiral/spiral.py | 859 | 3.8125 | 4 | def board(h, w):
board = []
for row in range(h):
row = [row*w + col for col in range(1,w+1)]
board.append(row)
return board
def spiral(h, w, r, c):
b = board(h, w)
# up left down right
directions = [(0,-1),(-1,0),(0,1),(1,0)]
# step: 1 1 2 2 3 3 4 4 5 5 ...
step = 1
... |
e6629ff7e021c9c1d0709a463d327652f4afdf14 | karthikapresannan/karthikapresannan | /for looping/range checking.py | 137 | 4 | 4 | num=int(input("enter the number"))
for i in range(20,50):
if (num >=20)& (num<=50):
print("true")
else:
print("false")
|
6e2c85c20e9c130852758039613e852a388ad530 | Dawn-Test/InterfaceTest | /Basics/text18_事务提交与回滚.py | 1,209 | 3.984375 | 4 | """
目标:pymysql完成新增数据操作
案例:
新增一条图书数据
sql:insert into t_book(title,pub_date) values("西游记",“1980-1-3”)
新增一条英雄人物
sql:insert into t_hero(name,gender,book_id) values("孙悟空",1,4)
方法:
自动提交事务方法 连接对象.autocommit(True)
手动提交事务方法 连接对象.commit()
事务回滚方法 连接对象.rollback()
"""
# 导包
import pym... |
3cef810dc21231a7f7f5538f6cf093a1f1c4aa0e | ValenYamamoto/Raffle | /run_raffle.py | 2,068 | 3.859375 | 4 | import csv as csv
import random as random
OUTPUT_FILE_NAME = "RaffleWinners.csv"
MAX_WINS = 1
def read_file(file_name: str):
with open(file_name) as f:
reader = csv.reader(f)
prize_numbers = [int(i) for i in next(reader)[4:-1]]
prize_names = next(reader)[4:-1]
entries = {row[0] :... |
8689ba172e6dbe813e062c084f596b70824783a8 | michaelore/cpre492-algorithm | /python/planar/optimal/naive/interval.py | 6,656 | 4.28125 | 4 | from math import *
class Interval:
"""Represents real intervals."""
def __init__(self, left, right, left_closed=False, right_closed=False):
if left < right:
self.left = left
self.right = right
self.left_closed = left_closed
self.right_closed = right_clos... |
d2852790496cb8ffc25bdc93220735c4b6f1d773 | jake221/algorithm008-class01 | /Week_02/637.average_of_levels_in_binary_tree.py | 581 | 3.5625 | 4 | # -*- coding: utf-8 -*-
__author__ = 'jack'
class Solution:
def averageOfLevels(self, root):
res = []
res = self.helper(root, 0, res)
return [sum(l) / len(l) for l in res]
def helper(self, root, level, traverse):
if root:
if len(traverse) == level:
t... |
0c6dabcf1857ad821395c80c4c2db573d8078ec8 | AlesyaKovaleva/IT-Academy-tasks | /tasks_4/negative_elements_6.py | 1,030 | 3.921875 | 4 | """
Задача 6
Преобразовать массив так, чтобы сначала шли все отрицательные
элементы, а потом положительные (0 считать положительным).
Порядок следования должен быть сохранен.
"""
list_numbers = []
while True:
try:
num = int(input("Введите число: "))
except ValueError:
break
list_numbers.a... |
26f92f18990ce32227121e8b0bc88ef7a28d5e6a | kazuma-shinomiya/leetcode | /58.length-of-last-word.py | 463 | 3.515625 | 4 | #
# @lc app=leetcode id=58 lang=python3
#
# [58] Length of Last Word
#
# @lc code=start
class Solution:
def lengthOfLastWord(self, s: str) -> int:
words = []
word = ''
for c in s:
if c == ' ':
if word == '': continue
words.append(word)
... |
295650de0994fd9ccd5cb1d38514584f45f5bc7e | chdharm/amity-room-allocation | /employees/model.py | 2,270 | 3.9375 | 4 | # !/usr/bin/python
# title :amity/alloc.py
# description :An algorithm which randomly allocates
# persons to rooms in a building.
# author :Jee Githinji
# email :githinji.gikera@andela.com
# date :20151218
# version :0.0.1
# python_version :2.7.10
# ========... |
89caceb5c703e6e89553d5f755827d30edcf8db0 | afeefebrahim/anand-python | /chap3/wget.py | 375 | 4.0625 | 4 | #Write a program wget.py to download a given URL. The program should accept a URL as argument, download it and save it with the basename of the URL. If the URL ends with a /, consider the basename as index.html.
import urllib,sys,os
url = urllib.urlopen(sys.argv[1])
p = sys.argv[1]
n = p.split('/')
if n[len(n)-1] == ... |
a7637d715cb99a28a9cfb5c6fc64a98c86a61ecf | eclairsameal/TQC-Python | /第2類:選擇敘述/PYD208.py | 448 | 3.6875 | 4 | num = eval(input())
# solution 1
print('{0:X}'.format(num))
# solution 2
hex = ['A', 'B', 'C', 'D', 'E', 'F']
if num <= 9:
print(num)
else:
print(hex[num-10])
# solution 3
num = int(input())
if num <= 9:
print(num)
elif num == 10:
print('A')
elif num == 11:
print('B')
elif... |
108816f5b4aba66ef5e2c424c43791036676cb94 | jackiejone/AttendanceProject | /test2.py | 151 | 3.703125 | 4 | x = [5, 2, 5, 7, 9, 'a', 2, 'b', 'd', 'c', 5 , 10, 3, 9, 6, 3, 'a', 'b', 'e', 'f']
def sortKey(elem):
return int(elem)
print(x.sort(key=sortKey)) |
6af50bf3ee48cd4a09a72d6c7647413100b84d41 | justinYarrington/WineMaking | /autoWiner.py | 4,440 | 3.5 | 4 | import math
from random import randint, uniform, choice, random
import sys
import time
import numpy as np
import pyautogui as pag
from itertools import chain
import os
def rightclickIcon(item):
"""Will use special if image is provided"""
if not item:
print('inif')
return False
... |
5b6a38c7e645d47e1b18b8316b7cdc77dca0cdde | Interview-study/algosalza | /프로그래머스/완전탐색/모의고사/subway.py | 722 | 3.625 | 4 | def solution(answers):
answer = []
one_count = 0
two_count = 0
three_count = 0
one = [1, 2, 3, 4, 5]
two = [2, 1, 2, 3, 2, 4, 2, 5]
three = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]
for i in range(len(answers)):
if one[i % len(one)] == answers[i]:
one_count += 1
if two... |
887f0f1453fb2750aee5d976af08657498308366 | anthonysof/python_puzzle_week | /ex1-8Queens/queens.py | 1,603 | 3.90625 | 4 | import random
from random import randint
class Queen:
name = ""
threatened = False
def __init__(self, name, location):
self.name = name
self.location = location
self.threatened = False
def checkHorizontal(queen, board):
j = queen.location[0]
for i in range(8):
if board[j][i] != " * " and board[j][i] !... |
aa92df37748e85c2cab4ab040e39b3f0c7f54931 | xexugarcia95/LearningPython | /CodigoJesus/Listas/Ejercicio6.py | 640 | 4.34375 | 4 | """Escribir un programa que almacene las asignaturas de un curso
(por ejemplo Matemáticas, Física, Química, Historia y Lengua) en una lista,
pregunte al usuario la nota que ha sacado en cada asignatura y elimine de la
lista las asignaturas aprobadas. Al final el programa debe mostrar por pantalla
las asignaturas que el... |
19f8f1aa25fc8836519f3907eef6c40255361ead | emrahnl/Odevler-Hafta-3 | /3.5 FIZZBUZZ.py | 237 | 3.953125 | 4 | for number in range(1,101):
if number %5==0 and number %3==0:
print("FIZZBUZZ")
elif number %3==0:
print("FIZZ")
elif number %5==0:
print("BUZZ")
else:
print(number)
|
6a775778e7f1f8f2bb00f09d41124b1091ccc64f | RenanBertolotti/Python | /Curso Udemy/Modulo 04 - Pyhton OO/Aula17 - Metodos Magicos/main.py | 854 | 3.71875 | 4 | # https://rszalski.github.io/magicmethods/
class A:
def __new__(cls, *args, **kwargs):
return super().__new__(cls)
def __init__(self):
print("Eu sou o Init")
def __call__(self, *args, **kwargs):
resultado = 0
for i in args:
resultado += i
return resul... |
0dbea2da47cbf09ea8b885d480dcf09a986d9566 | jdhouse1/Knights | /main.py | 1,668 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 25 00:48:46 2019
@author: Owner
"""
from itertools import product
import numpy as np
class position(tuple):
def __add__(self,other):
return (self[0]+other[0],self[1]+other[1])
def square(x,y):
n = max(abs(x),abs(y))
s = (2*n+1)**2
if y==n:
... |
4281ec45cc456c211fe2eaefd46ba0826f5e63e9 | yuzumei/leetcode | /662.py | 667 | 3.609375 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def widthOfBinaryTree(self, root: TreeNode) -> int:
import collections
memo=collections.defaultdict(li... |
439f0067ee46a8dc51afb93675750c267ec6a54a | kimhyunkwang/algorithm-study-02 | /2주차/김윤주/숫자 나라 특허 전쟁.py | 107 | 4.09375 | 4 | num = int(input())
sum=0
for i in range(num):
if i % 3 ==0 or i % 5 ==0:
sum = sum+i
print(sum) |
41013e420632b789761f28b656a5e6371b4a940c | duckasaur/fizzbuzz | /fizzbuzz.py | 466 | 4.4375 | 4 | #!/usr/bin/python
# on numbers divisible by 3, it fizzes. on numbers divisible by 5, it buzzes. on numbers
# divisible by both, it fizzbuzzes.
# max fizzbuzz number input
fizzbuzz_max = input("How high do you want to fizzbuzz to? > ")
num = 0
while num < fizzbuzz_max:
num = num + 1
if (num%3)==0 and (num%5... |
3fb67aba961466e64eb2efa79b17a66019df6a1f | aywang71/PythonKattis | /code/pieceofcake2.py | 297 | 3.53125 | 4 | #https://open.kattis.com/problems/pieceofcake2
square, length, width = input().split(' ')
square = int(square)
length = int(length)
width = int(width)
pieces = [length*width,(square-width)*length,(square-length)*width,(square-length)*(square-width)]
#print('pieces:', pieces)
print(max(pieces)*4) |
bbc2e49917b7daadd79ae38831c2e0d9cf00ddd6 | endlessseal/Python | /series.py | 967 | 4 | 4 | given_series = #random series
def maybe_fib(series):
#solve the fib
throw error if wrong
def rule_add_iterating_numbers(series):
diff_between_first_set = sub_numbers(get_first_n_number(series,2)[::-1])
def get_first_n_number(series, n, reversed=0):
if reversed == 0:
return series[0:n]
retur... |
444d04942fee8be4a63f317be3cd4bd31e77c971 | afreensana/Regular_Expressions | /example4.py | 346 | 3.703125 | 4 | # using"^","$" to get first and last string
import re
e4 = input("enter a string:")
res = re.findall(r"^\w+",e4) #['java']
#res = re.findall(r"^\w",e4) ['j']
print(res)
print("==============================================================")
rt = re.findall(r"\w+$",e4) #['python']
#rt = re.findall(r"\w... |
05e0cd1ce685f22703b72df42349be12c5c75e1e | cbayonao/holbertonschool-higher_level_programming | /0x0B-python-input_output/2-read_lines.py | 569 | 4.0625 | 4 | #!/usr/bin/python3
"""
Function that reads n lines of a text file (UTF8)
and prints it to stdout
Read the entire file if nb_lines is lower or equal
to 0 OR greater or equal to the total number of lines of the file
"""
def read_lines(filename="", nb_lines=0):
with open(filename) as f:
if nb_lines <= 0 or n... |
7042ab996ddfeeb0693368ff98476b66a843ab7f | laura-barluzzi/Learn-Python-hard-way | /ex3.py | 897 | 4.28125 | 4 | # This line states the obvious
print "I will now count my chickens:"
# This line counts the Hens
print "Hens", 25 + 30 / 6
#This line counts the Roosters
print "Roosters", 100 - 25 * 3 % 4
# This line states the obvious (again)
print "Now I will count the eggs:"
# this line counts the eggs
print 3 + 2 + 1 - 5 + 4 % 2 -... |
3a703488ffa1bfc3f4dfc8e9a64212c78d77c8a9 | jnoc/python | /random/mb_convert.py | 785 | 4.1875 | 4 | def megabyteConvert():
#this converts megabytes into bits, bytes, kilobytes, gigabytes and terrabytes
# written well before I knew how to actually do python!
megabyte = float(input("How many MB's do you have? "))
terabyte = float(megabyte) / 1048576
gigabyte = float(megabyte) / 1024
kilobyte = float(megaby... |
f48696e37c9f0158ea4fe754c85325e8b75800de | hayeonk/leetcode | /sols/binary_tree_zigzag_level_order_traveral.py | 723 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def zigzagLevelOrder(self, root):
ret = []
def zigzag(root, level):
if not root:
... |
686cb17b52368386739a0ae4f9a4d866e6cd89cd | lopezjronald/Python-Crash-Course | /part-1-basics/ch_6/practice.py | 2,752 | 3.953125 | 4 | alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
# adding position
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
# adding speed
alien_0['speed'] = 'medium'
print(alien_0)
alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print(f"Original ... |
6f46e8998b3c99209d0221a253128cbe6d78af10 | Rabbi50/python-books-practice | /PythonCrashCourse/user_input_while_loop/dream_vacation.py | 467 | 4.03125 | 4 | vaction_poll = {}
while True:
user = input('Enter your name: ')
place = input('If you could visit one place in the world, where would you go?')
vaction_poll[user] = place
repeate = input('Would you like to let another person respond? (yes/ no)')
if repeate == 'no':
break
# Polling is com... |
44c0295687516ea5118ad3aaad1a8ff29597af14 | solomonli/PycharmProjects | /Stepik_Adaptive_Python/adaptive-python-en-master/Step 043 Sum of numbers, divisible by 6.py | 100 | 3.671875 | 4 | numbers = [int(input()) for _ in range(int(input()))]
print(sum(i for i in numbers if i % 6 == 0))
|
7b36fadb2a4f8836fdfe8d3f66ddf3958a630600 | ZSWA/Python-Projects-Protek | /Praktikum 8/Project 5.py | 478 | 3.640625 | 4 | def kuadrat(bil):
for i in range(len(bil)):
bil[i] **= 2
return bil
try:
hitung = int(input("Banyak input : "))
data = []
perulangan = 0
while perulangan < hitung :
bilangan = int(input("Masukkan bilangan bulat : "))
print("Angka", bilangan, "dimasukkan")
... |
26eabe8d90e6378cb47cf0a75bc0cf160613fd2e | ManasHarbola/EPI_solutions | /Chapter8/8-1.py | 545 | 3.6875 | 4 | class Stack:
def __init__(self):
self.stack = []
self.size = 0
def empty(self) -> bool:
return self.size == 0
def max(self) -> int:
if self.size > 0:
return self.stack[-1][1]
def pop(self) -> int:
if self.size > 0:
self.size -= 1
... |
8ace0d54e3be292fce6dfb822dccec70f09dcdd0 | itgsod-Carl-Bernhard-Hallberg/Uppgift---ShoppingListPrinter | /lib/shopping_list_printer.py | 334 | 3.578125 | 4 | def format_shopping_list(products):
if(products):
to_return = str(len(products)) + "item" + ("s" if len(products) != 1 else "") + ""
for i in range(len(products)):
to_return += "\n" + str(i) + ": " + str(products[i]).capitalize()
return to_return
else:
return "No ... |
31015086cb3c4c905af5db3e7c2ca5c376ff75d5 | Akavov/PythonDss | /HandleIt/Handle_It.py | 1,065 | 4.46875 | 4 | #demonstrate handling exceptions
try:
num=float(input("Type the number:"))
except ValueError:
print("Seems like not a number!")
#handling different kinds of exceptions
print()
for value in (None,"Hello!"):
try:
print("Trying transform into the the number:",value,"-->",end="")
print(float(va... |
59716471d696a61fd52201e41849ecd217197f01 | zheshilixin/TCP_DNS_Diff_py | /.idea/json_split_calss.py | 49,807 | 3.796875 | 4 | # -*- coding: utf-8 -*-
false = False
true = True
class find_path():
def find_value_path(self,target, value, tmp_list ):
'''输入字典的值/列表的元素,以list返回所对应的key/posi,跟所在的字典/列表
[key,dict,posi,list,key,dict........]
'''
if isinstance(target, dict): #判断... |
32dbd6c8cff24b2011695ad4e874a70d8f4c48b6 | alminhataric/Python_Basic | /17_default_parameter_values/code.py | 266 | 4.125 | 4 | """ def add(x, y=8):
print(x + y)
add(x=5) """
#############################################################################################################
default_y = 3
def add(x, y=default_y):
sum = x + y
print(sum)
add(2)
default_y = 4
add(2) |
429086a3bfa67542c8167e8a1fb15afd9b4e7e7b | sushmita119/pythonProgramming | /sorting/quickSort.py | 614 | 3.65625 | 4 | def partition(arr, start, end):
pivot = arr[end]
p_index = start
for i in range(start, end):
if arr[i] <= pivot:
arr[i], arr[p_index] = arr[p_index], arr[i]
p_index += 1
arr[p_index], arr[end] = arr[end], arr[p_index]
return p_index
def quick_sort(arr, start, end):
... |
7b1d0d467c35d045652c4bcc2b7309342a25a91b | nikkster311/turtle_proj_01 | /turtleproject.py | 1,126 | 4.34375 | 4 | import turtle
#draw basic shapes
#use those to make more complex shapes
#run whole thing in a function
def tri(name): # draws individual triangle
name.begin_fill()
for i in range(3):
name.speed(1)
name.forward(50)
name.left(120)
name.end_fill()
def tri_cubed(name):... |
b993f295423e5c6792b0af4a978e5ccfc30103de | MasterOrange/Python | /Learning/forLoop2.py | 326 | 3.9375 | 4 | #!/usr/bin/python3.5
# stops at third T
sequence = input('input your sequence: \n')
counter = 0
proc = list(sequence)
for item in proc:
print(str(item)+', ', end='')
if item == 't':
counter = counter + 1
if counter == 3:
print('\nThe third T is reached')
break
print('Do... |
5a38263f85e235ef78607d1f850a7797d04da767 | SpringCheng/Python--practice | /day7/类与对象/封装2.py | 1,209 | 4.09375 | 4 | """
-*- coding: UTF-8 -*-
@date: 2019/9/9 15:55
@author:Spring
"""
# class Rectangle:
#
# def __init__(self, width, height):
# self.__width = width
# self.__height = height
#
# def get_width(self):
# return self.__width
#
# def set_width(self, width):
# self.__width = wi... |
bc04cebc93c88678c8190df618641e85de89ba0c | charlie1kimo/leetcode_judge | /153_find_minimum_in_rotated_sorted_array.py | 1,020 | 3.796875 | 4 | """
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
You may assume no duplicate exists in the array.
"""
class Solution(object):
"""
Idea:
- Binary search: O(log(n))
- eliminate half possibl... |
e27572f1ac642ff161c2786cd8e84f5514064803 | cphurley82/sandbox-py | /trees.py | 2,986 | 3.984375 | 4 | from typing import List
# TODO(cphurley): Add comments.
class Node:
def __init__(self, key):
self.data = key
self.children = []
def list_tree_breadth_first_queue(self) -> List:
data_list = []
queue = [self]
while len(queue) > 0:
data_list.append(queue[0].... |
101edc28053b0f0bf76312b2377d7cab7bcaf912 | gedo147/Python | /Sorting/sorting.py | 640 | 4.21875 | 4 | nums = [3,4,51,2,3]
nums.sort()
print(nums)
# to sort in desc order
nums.sort(reverse=True)
print(nums)
# sorting using specific condition like all even numbers should come first
# for this we can use helper function
def sorting_helper(x):
if x % 2 == 0:
return (0,x)
return (1,x)
num... |
35d9e9597993619029df2aed6101050e0b903f88 | mattjp/leetcode | /practice/medium/0287-Find_the_Duplicate_Number.py | 586 | 3.609375 | 4 | class Solution:
def findDuplicate(self, nums: List[int]) -> int:
"""
do tortise and hare using the value of each index as a singly-linked list
since nums is [1,n-1] 0 is the entrace to the list containing the cycle
"""
tortise = hare = 0
tortise = nums[tortise]
hare = nums[nums[hare]]
... |
750eb9a89abbe91d680b0acb163d2c4e33efbd33 | sheilatabuena/django-sudoku | /games/sections.py | 8,666 | 3.5 | 4 | """ This module returns various chunks of the grid """
import math
def get_horz(grid, square, unsolved=False):
""" get row minus reference square """
related = []
for square2 in grid.grid[square.row]:
if square2 != square:
if not unsolved:
related.append(square2)
... |
e5321f0f7d4148854955b9e59c81c018e5de015a | Olanetsoft/SimpleShapeCalculator | /my simple shape calculator.py | 3,007 | 4.15625 | 4 | print("")
print("")
import time
print(time.asctime())
print("")
#A SIMPLE AREA CALCULATOR.... JUST CHOOSE YOUR SHAPE
print("WELCOME TO A SIMPLE AREA CALCULATOR BUILT BY OLANETSOFT")
def the_main():
anyShape=input("PLEASE SELECT ANY SHAPE OF YOUR CHOICE? \n \n(a) TRIANGLE \n \n(b) CIRCLE \n \n(c) RECTANGLE \n \n(d)... |
d63e4962d0315f21555dd7ab16887e1fcd573087 | evanwangxx/leetcode | /python/72_Edit_Distance.py | 2,903 | 3.9375 | 4 | # Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.
# You have the following 3 operations permitted on a word:
# Insert a character
# Delete a character
# Replace a character
#
# Example 1:
# Input: word1 = "horse", word2 = "ros"
# Output: 3... |
bf0b706daec81e2816b038b941edfef40c585a32 | DDR7707/Final-450-with-Python | /Linked Lists/155.Splitting Circular Linked List into 2 Halves.py | 673 | 3.578125 | 4 | '''
class Node:
def __init__(self):
self.data = None
self.next = None
'''
class Solution:
def splitList(self, head, head1, head2):
#code here
slow = head
fast = head
while fast.next != head.data and fast.next.next != head.data:
fast = fast.ne... |
22041e85bed9f4a0b4d36f36d70f2e5487145b1e | cat4er/geeklearning | /start_python/lesson4/itertool_script.py | 866 | 4 | 4 | # Реализовать два небольших скрипта:
# а) бесконечный итератор, генерирующий целые числа, начиная с указанного,
# б) бесконечный итератор, повторяющий элементы некоторого списка, определенного заранее.
# Подсказка: использовать функцию count() и cycle() модуля itertools.
from itertools import count, cycle
# задание a... |
16fdeaed56f2a9d4776089e4bd409277805a561d | OlehPalka/First_semester_labs | /Lab work 6/ratosfen_resheto.py | 873 | 3.546875 | 4 | # from CMU 15-112
# http://www.cs.cmu.edu/~112
# Sieve of Eratosthenes
# This function returns a list of prime numbers
# up to n (inclusive), using the Sieve of Eratosthenes.
# See http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
def sieve_flavius(n):
lucky_num = 3
list_of_nums = list()
for i in range(n... |
70e8a0e537fb29b3534d53326b28faff30a1a429 | yuanfang2017/python_demo | /jj.py | 404 | 3.984375 | 4 | # coding=<encoding name> 例如,可添加# coding=utf-8
# 返回函数
# 写一个求和的函数demo
# def function(*x):
# sum = 0
# for n in x:
# sum = sum +x
# return sum
# 把function 作为函数返回
def myfunction(*x):
def function():
sum = 0
for n in x:
sum = sum + n
return sum
return func... |
474b855cbb5247cc07f7476960eb6be820b6b7b3 | SunatP/ITCS425_Algorithm | /HW2/question_14.py | 528 | 3.625 | 4 | V = 1234 # Tarsget number
coins = [1,5,10,25,50,100]
coins_all_types = len(coins)
print("We have coins",coins_all_types,"types")
answer = []
traversal = coins_all_types - 1 # Do a traversal all of coin types
while traversal >= 0 :
while V >= coins[traversal]: # Find the minimum coins
V = V - coins[traversa... |
146272bb26519157983d6be5baea2d56518f5a54 | damien1994/Some_coding_exercises | /mytraffic/utils.py | 3,745 | 4.40625 | 4 | import json
def sum_input_file(filename: str) -> int:
"""
Read a file and returns the sum of each line
:param filename: a string which specifies the name of the file to load
:return: an integer which is the sum of each line (if integer)
"""
with open(filename) as f:
return sum(int(line... |
3e18be30df426abc8a87422b647795056b10addd | LuanaDeMoraes/code | /functions_python.py | 1,695 | 4.4375 | 4 | '''
#--- function with no parameters ---
print("--- function with no parameters ---")
def sayHello():
print ("Hello! I am a function")
sayHello()
#--- function with parameters ---
print("--- function with parameters ---")
def sum(a, b):
s=a+b
print ("sum "+ str (s) )
#using constants as parameters
sum(3... |
92de0210a3191d1abf5843544d579e91c15ae1fc | sendurr/spring-grading | /submission - Homework1/KAYLA S REVELLE_2237_assignsubmission_file_Homework 1/Homework 1/Question 5.py | 293 | 3.8125 | 4 | #Question 5
X = {1, 3, 8, 10, 14, 20, 25}
Y = {3, 3, 8, 10, 15, 20, 33, 55, 88}
intersection = X & Y
print ("intersection: ", intersection)
union = X | Y
print ("union: ", union)
noty = X - Y
print ("In X but not in Y (X-Y): ", noty)
notx = Y - X
print ("In Y but not in X (Y-X): ", notx) |
a1bbaca13f03109c2be2b2d4cc2fc65d33254d39 | datnguyenX/b-i-t-p-th-c-h-nh | /c3 bai 9.py | 652 | 4.125 | 4 | def add(x,y):
return x + y
def subtract(x,y):
return x - y
def multiply(x,y):
return x * y
def divide(x,y):
return x / y
print("1.add")
print("2.subtract")
print("3.muliply")
print("4.divide")
choice=input("entre choice(1/2/3/4):")
num1 = int(input("enter first number:"))
num2 = int(inpu... |
d803d43e51002469c9ebf1ea5186718a226eec81 | MahdiPyPro/Calculate-the-exam | /calculature.py | 1,597 | 3.6875 | 4 | def my_final_grade_calculation(filename):
fp = open(filename, "r")
data = fp.readlines()
my_dictionary = {}
for x in range(0, len(data)):
stripped = data[x].strip().split(',')
for x in range(1, len(stripped)):
stripped[x] = int(stripped[x].strip())
# extract various ... |
7f80ce7787f63f0a479e0008ab4c6b8dbb2be839 | yagavardhini/python--program | /biggest among 3 no.py | 206 | 4.09375 | 4 | a=int(input("enter the 1 no:"))
b=int(input("enter the 2 no:"))
c=int(input("enter the 3 no:"))
if a>b and a>c:
print("a is greater")
elif b>a and b>c:
print("b is greater")
else:
print("c is greater")
|
fa736fe20fafc4b0290d9700222bbb356285f431 | mourafc73/PythonApplication | /PythonApplication1/Tuples_Lists.py | 483 | 3.59375 | 4 |
#MySequence = (1, 3, 6, 4, 1, 2)
#print (MySequence[-2])
#for countseq=0 to len(MySequence)
#next countseq
#B=["a","b","c"]
#print (B[1:])
#tuple1 = ("disco",10,1.2 )
#print (type(tuple1))
album_set1 = set(["Thriller", 'AC/DC', 'Back in Black'])
album_set2 = set([ "AC/DC", "Back in Black", "The Dark Side of the... |
380dc5ceb9d674a64a6f986d94fea75250d426fe | decorouz/Google-IT-Automation-with-Python | /using-python-to-interact-with-operating-sys/week4_managing_data_processes/advance_subprocess.py | 843 | 3.5 | 4 | import os
import subprocess
'''
So in this code, we start by calling the copy method of the OS environ dictionary
that contains the current environment variables.
Calling 'copy' method of the os.environ dictionary will copy the current environment
variables to store and prepare a new environment.
'''
my_env = os.en... |
70edc38f29efbda2ed2e5c2b05ae6ef80fe45f38 | sathibabunaidu58/Pytno_Problems | /palindrome.py | 89 | 3.96875 | 4 | a = input('enter a word : ')
b=("Palindrome" if a==a[::-1] else 'Not Palindrom')
print(b) |
52f490ed2cbfc8803acce3cdd9155640532b5961 | haradahugo/cursoemvideopython | /ex054res.py | 366 | 3.8125 | 4 | from datetime import date
maior = 0
menor = 0
atual = date.today().year
for i in range(1,8):
p = int(input('Digite aqui o {}º ano de nascimento: '.format(i)))
idade = atual - p
if idade >= 21:
maior += 1
else:
menor += 1
print('{} pessoas já alcançaram a maior idade.\n{} ainda não alcanç... |
690504999c114ba27523277fb0848a89cedb438e | srividyavn/Python-DL | /ICP/ICP2/Source/list.py | 351 | 3.625 | 4 |
lis = []
for i in range(4):
lis.append(input("enter element"))
print(lis)
print(lis.pop())
print(lis.pop())
print(lis)
from collections import deque
queue = deque(["himalayas", "1", "beautiful", "2"])
print(queue)
queue.append("Akbar")
print(queue)
queue.append("Birbal")
print(queue)
print(queue.popleft())
prin... |
3c736e6e75b2c5b11e329018e43332cb01d1c742 | darshankrishna7/NTU_reference | /NTU/CZ1012 Engineering Mathematics II/trapezoidal_rule.py | 518 | 3.734375 | 4 | def fx(xi):
return xi / (1 + xi*xi)
def getDiff_x(a, b, n):
return (b - a) / n;
print("Trapezoidal rule")
a = int(input("Input a = "))
b = int(input("Input b = "))
n = int(input("Input n = "))
while n <= 50:
count = n
x_diff = getDiff_x(a, b, n)
xi_left = a;
xi_right = b;
total = 0;
... |
ec202f97e13f47126cb08e9465e4dfbc4729903d | tristan2077/howtopy | /datetime_/timestamp.py | 237 | 3.5 | 4 | from datetime import datetime
import pytz
ts1 = datetime.utcnow().timestamp() # 错误写法
ts2 = datetime.now().timestamp()
ts3 = datetime.utcnow().replace(tzinfo=pytz.timezone('UTC')).timestamp()
print(int(ts1), int(ts2), int(ts3)) |
460cb45f045fe19f6624e15155dd5e2afca4b0a9 | efnine/learningPython | /python_crash_course/lists.py | 1,340 | 4.5 | 4 | motorbikes = ["honda","yamaha","susuki"]
print(motorbikes)
print("\n")
motorbikes[0]="ducati"
print(motorbikes)
print("\n")
motorbikes = ["honda","yamaha","susuki"]
motorbikes.append("ducati")
print(motorbikes)
print("\n")
motorbikes = ["honda","yamaha","susuki"]
motorbikes.insert(2,"bwm")
print(motorbi... |
758ddffef336745bf3f3bd77e015fc46cf27dcac | DataScienceOrg/MITx-6.00.1x | /Programs/ccdebtpayoff.py | 1,513 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 27 18:01:40 2017
Write a program to calculate the credit card balance after one year if a
person only pays the minimum monthly payment required by the credit card
company each month.
@author: z001hmb
"""
#balance - the outstanding balance on the credit card
#annualInte... |
eb5e0608a3e1b09ebd7b03b6caf1179ccd5cfaf3 | 995586041/python_base | /02io/04序列化.py | 1,362 | 3.671875 | 4 | import pickle
#pickle.loads()方法反序列化出对象,也可以直接用pickle.load()方法从一个file-like Object中直接反序列化出对象
d = dict(name='zs', age=12, weight=75)
print(pickle.dumps(d))
f = open('aa.text','wb')
pickle.dump(d,f)
f.close()
f2 = open('aa.text', 'rb')
print(pickle.load(f2))
f2.close()
import json
# 用loads()或者对应的load()方法,前者把JSON的字符串反序列化... |
587c27cb193a0be89ab9f6d4f4a40d3e5671e94c | reubenmackey/Learning-Code | /Fizz-Buzz/fizzbuzz.py | 1,310 | 4.28125 | 4 | # Find Multiples of two separate numbers within a start and end range.
# Multiples of Number 1 prints "FIZZ"
# Multiples of Number 2 prints "BUZZ"
# Multiples of both Number 1 and 2 prints "FIZZ-BUZZ"
def fizzbuzz(start, end, num1, num2):
for num in range(start,end+1):
if num % num1 == 0 and num % num2 == ... |
27b0520fa250ebda9b6bbb5c3180abd1a4f6c601 | SushilShrestha/NepaliTransliteralDataset | /src/NepaliTokenizer.py | 1,293 | 3.75 | 4 | '''
Taken from https://github.com/sushil79g/Nepali_nlp/blob/master/Nepali_nlp
under MIT license
'''
import string
class Tokenizer:
def __init__(self):
pass
def sentence_tokenize(self, text):
"""This function tokenize the sentences
Arguments:
text {string} -- Sent... |
7399e374dae71d576c74e9bb865a537f2a081067 | fishjord/devnet | /scripts/dn.py | 16,361 | 3.65625 | 4 | #!/usr/bin/python
import sys
import math
import numpy
import dn_utils
from dn_utils import preresponse, activation_function, rescale, amnesic
#Tell numpy to show us more of the arrays
numpy.set_printoptions(threshold=100, linewidth=10000)
"""
Neuron class, holds weights and learning rates for each individual neuron ... |
e15a752b52b7a08168b91d99de559213ff38bcd0 | deepanshutayal/python | /6.py | 177 | 4 | 4 | m=int(input('enter minutes'))
if m > 60 or m == 60 :
t=m/60
r=m%60
print('it contains ',t, 'hours and ',r, 'minutes' )
else :
print('it contains 0 hours and ',m, 'minutes' ) |
ac3008cec7f6ecd15f08a6582446b42fb0f2d6ea | lan956/sorting-project | /sorts.py | 479 | 4.03125 | 4 | def insertion_sort(ar):
for i in range(1, len(ar)):
for j in range(i):
if (ar[i]<ar[j]):
k = ar[i]
ar[i] = ar[j]
ar[j] = k
print(ar)
def bubble_sort(ar):
for i in range(len(ar),0,-1):
for j in range(i-1):
if... |
89d5123dbcbef3bbd32bd3965c092caa82a91d3d | Lucyxxmitchell/PythonOOCardGames | /src/BlackJack.py | 7,197 | 3.640625 | 4 | import random
from PlayingCard import PlayingCard
class BlackJack:
"""Constant values to be references in the functions and methods below."""
winning_score = 21
face_card_score = 10
max_ace_score = 11
min_ace_score = 1
good_number_of_cards = 5
playing_card = PlayingCard()
def score_h... |
8d68c270d23b429fc251ee51bd31c76f63e6b364 | unclemedia0/Tao-GUI | /tao2.py | 377 | 3.5625 | 4 | import turtle
import random
tao = turtle.Turtle()
tao.shape('turtle')
color = ['red','blue','yellow','green']
tao.pensize(4)
for i in range(10):
c = random.choice(color)
tao.color(c)
x = random.randint(-200,200)
y = random.randint(-200,200)
tao.penup()
tao.goto(x,y)
tao.pendown()
size = random.randint(50,10... |
589b7f20e604a241db56059155a4ee9d1179c2b2 | andresguaita/Codigos-de-prueba | /FP_Calificacion_Estudiante.py | 1,267 | 3.96875 | 4 | ## Nombre de un estudiante ,Leer las notas de los tres parciales, el acumulado de inasistencia y calcular
## La nota definitiva sabiendo que PP tiene un porcentaje del 35% , SP tiene % del 35 % y el restante 30% es para el TP .
## Imprimir la nota definitiva mas un concepto:
## Gano academicamente fallas < 12 y ... |
49cc00c709a3e6991d29dbc5ba229ee3177c8d20 | Charlesyyun/data-structure-and-algorithm | /select_sort.py | 558 | 3.796875 | 4 | def select_sort_simple(li):
li_new = []
for i in range(len(li)):
min_val = min(li)
li_new.append(min_val)
li.remove(min_val)
return li_new
def select_sort(li):
for i in range(len(li)-1):# i是第几趟
min_loc = i #初始化最小值位置是无序区的第一个位置
for j in range(i+1,len(li)... |
153c30669caa65f19580cba71ff9de3b0965809b | panditdandgule/Pythonpractice | /P03_MonkTeachesPalindrome.py | 1,318 | 4.1875 | 4 | # Monk introduces the concept of palindrome saying,"A palindrome is a sequence of characters which reads the s
# ame backward or forward."
# Now, since he loves things to be binary, he asks you to find whether the given string is palindrome or not.
# If a given string is palindrome, you need to state that it is even... |
aa7192bde49460e975401ae9f556e427afb7d76b | Yasmin-Alhajjaj/python.day | /day5.py | 2,337 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 25 09:52:39 2019
@author: owner
class hello:
def hi(self):
print("hello")
p= hello()
p.hi()
class Person:
def __init__(self, name):
self.name = name
def whoami( self ):
... |
2a311afa9680505e7e413dd651593989e6864776 | KostyaTyurin/programming_practice_2020 | /Lab2 turtles part2/turtle2_modelirovanie_tochki_4.py | 553 | 3.703125 | 4 | import turtle as tr
tr.shape('circle')
tr.turtlesize(1)
tr.width(2)
tr.penup()
tr.hideturtle()
tr.goto(-200, 0)
tr.pendown()
tr.fd(705)
tr.penup()
tr.hideturtle()
tr.goto(-200, 0)
tr.showturtle()
tr.pendown()
Vx = 60 # скорость по иксу
Vyk = 300 # скорость по ординате
ay = -100 # ускорение
dt = 0.01
x = -200
y = 0
for... |
cd4b537198b57a6426230f31cee47b3b7b65b2fd | madsbk/hidden-markov-model-example | /bob_alice_hmm.py | 1,132 | 3.703125 | 4 | # The Wikipedia Bob Alice HMM example using hmmlearn
# Based on <http://sujitpal.blogspot.se/2013/03/the-wikipedia-bob-alice-hmm-example.html> and <https://en.wikipedia.org/wiki/Hidden_Markov_model#A_concrete_example>
import numpy as np
from hmmlearn import hmm #From <http://hmmlearn.readthedocs.io/>
np.random.seed(4... |
97c21bf921a36a72176d80af3c8a631d67d99141 | travisb98/SpotifySongAnalysisProject | /Test work/pullCSVSample.py | 1,573 | 3.53125 | 4 | import requests
from bs4 import BeautifulSoup
import csv
#The purpose of this code is to pull a list of possible regions for spotify charts.
region_codes=[]
region_names=[]
Original_url="https://spotifycharts.com/regional/global/daily/latest"
list_response=requests.get(Original_url)
soup=BeautifulSoup(list_response.te... |
8ab5f7b0bf848ae0776dd657ea5cc806afa7365a | MineDenis/Computer-programming-2-lab-tasks | /12.2/decode_123.py | 233 | 3.5 | 4 | import sys
vowels = "aeiou"
for lines in sys.stdin:
line = lines.strip()
newword = []
i = 0
while i < len(line):
newword.append(line[i])
i += 3 if line[i] in vowels else 1
print(''.join(newword))
|
8527aa296bbfab40a119c653ac4fc6a6ee756030 | Narengowda/algos | /v2/long_increase_subseq.py | 318 | 3.5 | 4 | # not correct
x = [3,4,-1,0,6,2,3]
results = []
n = len(x)
i = 0
j = 1
local_res = []
for i in range(n):
local_res = []
last_data = x[i]
for j in range(i, n):
if last_data <= x[j]:
local_res.append(x[j])
last_data = x[j]
results.append(local_res)
print(results)
|
8b824e7ba1f13669b10e0b47b8642a9462956145 | davidsmoreno/Computaci-n-en-la-Nube | /TCPservidor.py | 1,968 | 3.625 | 4 |
def saldo():
file=open("saldo.txt")
x=file.read()
x=int(x)
file.close()
return x
def debitar(y):
file=open("saldo.txt")
x=file.read()
x=int(x)
file.close()
m=x-y
if m >=0:
m=str(m)
file1=open("saldo.txt","w")
file1.write... |
3cf4538725ffacb51cd65c7b8ae68f72b1e2677b | hasant99/Python-Class-Projects | /bank.py | 4,187 | 4.53125 | 5 | ###Author: Hasan Taleb
###Class: CSc110
###Description: A program that creates a simple
### banking system. It creates a certain
### number of accounts based on the user input
### and then can recieve several different
### commands to either display the account
### ... |
038bf17bee0ca77e2b664558bbb8eadddc8f6bd5 | Esme01/TXQneural-network | /generator.py | 181 | 3.859375 | 4 | def generator(n):
i = 0
while i<n:
yield i
i = i+1
l = list(generator(10))
print(l)
# zip是一个generator类型,必须用list才能把数据放到内存
|
cef680e4c1243e2c51d49be41f13af72e1a1630b | pvbhanuteja/CSCE636_DL | /HW1/code/LogisticRegression.py | 7,185 | 3.65625 | 4 | import numpy as np
import sys
"""This script implements a two-class logistic regression model.
"""
class logistic_regression(object):
def __init__(self, learning_rate, max_iter):
self.learning_rate = learning_rate
self.max_iter = max_iter
def fit_GD(self, X, y):
"""Train perceptron... |
c28e91d061b3a34ce31e620b82066c653ef63620 | RainyLi/LeetCode | /101_Symmetric Tree.py | 810 | 3.859375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isOpposite(self, roota, rootb):
if roota==None and rootb==None:
return True
if roota==Non... |
e033a80858e4388885065396d1bed5bca5db2c5b | nobody1570/lclpy | /lclpy/localsearch/acceptance/abstract_acceptance_function.py | 939 | 3.984375 | 4 | from abc import ABC, abstractmethod
class AbstractAcceptanceFunction(ABC):
"""Template to create acceptance functions.
Acceptance functions determine if a worse state than the current
state is accepted as the new current state.
"""
def __init__(self):
super().__init__()
@abstractme... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.