blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
87ce7ec9d948734a446a7cf0bb40ded7fd62da19 | tuseddomarcos/Python_Ahorcado_Basico | /manejoArchivo.py | 2,665 | 3.5 | 4 | import csv
import random
from tkinter import messagebox as mb
#Leo el archivo .csv y busco por nivel, luego busco una palabra ramdon y la retorno.
def seleccionoPalabrasPorNivel(nivel):
listPalabras = []
reader = csv.reader(open('ListaPalabras/ListaPalabras.csv'))
for row in reader:
listPalabras.ap... |
8b2c0a803a26329b184b7d41eb48ec8d7f65e221 | mauro-20/The_python_workbook | /chap2/ex50.py | 835 | 4.375 | 4 | # Richter Scale
magnitude = float(input('enter magnitude (from 0 to 10): '))
earthquake_description = ''
if magnitude < 2:
earthquake_description = 'micro'
elif magnitude < 3:
earthquake_description = 'very minor'
elif magnitude < 4:
earthquake_description = 'minor'
elif magnitude < 5:
ear... |
0ae274aed659eea48b376f0cdc99257cee82dc00 | brucehzhai/Python-JiangHong | /源码/Python课后上机实践源代码/ch10-模块和客户端/P10-prg-1-MyMath加减乘除幂.py | 523 | 3.90625 | 4 | #MyMath.py
def add(x, y): #定义函数
return x + y #加
def sub(x, y):
return x - y #减
def mul(x, y):
return x * y #乘
def div(x, y):
return x / y #除
def power(x, y):
return x ** y #幂
#测试代码
if __name__ == '__main__': #如果独立运行时,则运行测试代码
print('123 + 100 =', add(123, 100))
print('123 -... |
39b792b2760106b0e495e17f33a6b0a47824c349 | Feriow/Estacio-Python | /Tema 5 - Python em outros paradigmas/modulo 1/paradigmas.py | 791 | 4.125 | 4 | #Paradigma imperativo - O programador diz como fazer
print('### PARADIGMA IMPERATIVO ###')
numeros = [1,2,3,4]
total = 0
for numero in numeros:
total += numero
print('O total é', total)
print('\nsegundo exemplo')
if True:
print('Tudo certo')
else:
print('ops')
#Paradigma funcional - O que você quer fazer
pri... |
51a2c733609b056d0a79603e22b13f079628a47a | filipeclopes/courses | /AzeroPython/python-do-zero-master/python-do-zero-master/aulas/aula_1/problema_9.py | 762 | 4.09375 | 4 | """
Faça um programa que peça uma nota, entre zero e dez.
Mostre uma mensagem caso o valor seja inválido e
continue pedindo até que o usuário informe um valor válido.
"""
cond = False
# Olhar antes de saltar
while not cond:
nota = input('Insira uma nota entre 0 e 10: ')
if nota.isdigit():
if float... |
105ced869e3db43818e8b4cc6681435a2d670fb2 | dhirajgokuladas/PyGeo | /tests/test_objects.py | 2,769 | 3.90625 | 4 | from pygeo.objects import Point, Vector, Ray, Sphere
# Point.__eq__
def test__point_equal__given_two_equal_points__return_true():
assert (Point((1, 2, 3)) == Point((1, 2, 3))) is True
def test__point_equal__given_two_not_equal_points__return_false():
assert (Point((1, 2, 3)) == Point((4, 5, 6))) is False
#... |
f44298e2461fafc62425af390aa107fb7ea04670 | HappyRocky/pythonAI | /LeetCode/131_Palindrome_Partitioning.py | 1,027 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
给定一个字符串 s,将 s 进行划分,每个子串都是一个回文子串。
返回所有可能的 s 的回文划分。
Example:
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]
"""
def partition(s: str) -> list:... |
93b30072642e9170365fc62184aff381196b03f5 | gabrielizalo/jetbrains-academy-python-coffee-machine | /Problems/snake_case/task.py | 192 | 4.15625 | 4 | lower_camel_case = input()
snake_case = ""
for char in lower_camel_case:
if char.isupper():
snake_case += "_" + char.lower()
else:
snake_case += char
print(snake_case)
|
8cec4a945db8d8718e1782100db1481b45826fe9 | diegojfcampos/hashgame | /hash.py | 3,764 | 3.796875 | 4 | #HASH GAME
"Globals"
board = [0, 0, 0, 0, 0, 0, 0, 0, 0]
position = 0
game = True
player = 1
"""IMPORT´s"""
"""Def's"""
def DesignBoard(tabuleiro):
print(" GAME BOARD ")
tab = ""
for i in range(0, 9):
mark = " "
if board[i] == 1:
mark = "X"
elif board[i] == -1:
... |
d0b5904893f81cc3b0ad833bd0ee62ef6f3739dd | billjordan/walksf_flask | /walkSFapp/graph.py | 4,447 | 3.59375 | 4 | #!/usr/bin/python3.4
from edge import SF_street
from node import SF_intersection
class Digraph(object):
"""
directed graph
"""
def __init__(self):
self.nodes = set([])
self.edges = {}
def add_node(self, node):
if node in self.nodes:
raise ValueError('Duplicat... |
7c2ac8c6581a2ac2b1ebc659e8a4934a50882fe3 | teoespero/PythonStuff | /list-manip-03.py | 547 | 4.25 | 4 | # More Python list manipulation
# Teo Espero
# GIST I
# BOF
# initialize our vars
cars = ['bmw', 'audi', 'toyota', 'subaru']
# print the current list
print('print the current list')
print(cars)
# sort the elements on the list
print('sort the elements on the list')
cars.sort()
# print the sorted list
print('print t... |
65437f9f3062fe6b0c6f0730ce8e60690fae7410 | sigurdo/fysikklab | /x_til_index.py | 238 | 3.546875 | 4 |
def from_x_to_index(x,x_list):
diff_0 = abs(x_list[0]-x)
x_1 = 0
for num in range(1,len(x_list)):
diff = abs(x_list[num]-x)
if (diff < diff_0):
diff_0 = diff
x_1 = num
return x_1
|
5da9295713abe976debeacd3db949cb939e30b7d | mice73jp/completePython3Course | /readwriteFile.py | 317 | 3.765625 | 4 | newfile = open("newfile.txt", "w+")
string = "This is the content that will be written to the text file."
newfile.write(string)
newfile.close()
readfile = open("newfile.txt", "r")
getStr1 = readfile.readline(10)
getStr2 = readfile.readline()
print("content :", getStr1)
print("content :", getStr2)
readfile.close() |
9c3804b86338e4106b3d46b89c1db3532c260820 | Abdul-Nassar/Anand-Python-Class | /Chapter2/List/map.py | 92 | 3.5 | 4 | import sys
n = int(sys.argv[1])
def map(n):
return [ x*x for x in range(n)]
print map(n)
|
d0cf14b39ca7468ac3899ba8f178e09aecfb431a | prathik-kumar/python | /Fundamentals/func_overload.py | 641 | 3.59375 | 4 | class ServiceInfo(object):
def __init__(self, id, name, description):
self.id = id
self.name = name
self. description = description
#default arguments for omitting calling arguments
def alter(self, id, name = None, description = None):
self.id = id
if name != None:
self.name = name
if description !... |
8336bf6b9f6f08fce6ab5ad383530b8b6c31023c | pratik149/data-science-practice | /logistic Regression.py | 1,032 | 3.53125 | 4 | import pandas
iris=pandas.read_excel(r"C:\Users\Pratik\PycharmProjects\DS&ML\Iris.xls")
#print(iris)
column=iris.columns.values
print(column)
X=iris[column[0:4]] #0 to 3 columns
Y=iris[column[4]] #or column[-1] #last target column
#print(X)
#print(Y)
from sklearn.model_selection import train_test_spl... |
b8d95dda2fd1a3e31d266c3d870787328e5932b0 | sathishvinayk/Python-Advanced | /Inheritance_python.py | 336 | 3.984375 | 4 | #Creating a second class which inherits the superclass
from Class_in_python import FirstClass
class SecondClass(FirstClass):
def display(self):
print('Current value = "%s"' %self.data)
#make instances
z=SecondClass()
z.setdata(42)
z.display()
#calling firstClass instance again will show undistrupted va... |
1a7148a9336976efa4881ac1ebc01ab253196e81 | Ubastic/sts_simulator | /player.py | 1,315 | 3.5 | 4 | class Player:
def __init__(self, deck, health, energy = 3):
self.deck = deck
self.health = health
self.max_health = health
self.max_energy = energy
class Deck:
def __init__(self):
self.cards = []
def add_card(self, card):
self.cards.append(card)
def re... |
2e5fbca6379e124e9066fdda688b0b672035b73c | Rao-Varun/py_ds | /client_server_lock_implementation/utils/socket_handler.py | 6,031 | 3.84375 | 4 | """
Module to handle sockets of both Client and Server.
Author: Varun Rao
UTA id: 1001681430
"""
import socket
class SocketHandler(object):
def __init__(self, ip="127.0.0.1", port=12345):
self.ip = ip
self.port = port
self.client = False
self.server = False
self.py_socke... |
f0ca97bee5d37f0324b72f943b9edf5d135aa971 | MikeYeromenko/homework | /courier.py | 776 | 3.921875 | 4 |
def stage_entrance(number, stages, flats_stage):
num_entrance = number // (flats_stage * stages + 1) + 1
if number > flats_stage * stages:
number = number - (num_entrance - 1) * flats_stage * stages
num_stage = number // (flats_stage + 1) + 1
return num_stage, num_entrance
print('Enter the ... |
1501238572fdbc95c6e2fd6a1c972c2b29dcc9a8 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/meetup/1f04f464c3294c8fbcea4b7886f2c6fd.py | 1,464 | 3.578125 | 4 | # -*- coding: utf-8 -*-
from datetime import date
import calendar
def meetup_day(year, month, wd, order):
dict = {'Monday':0,'Tuesday':1,'Wednesday':2,'Thursday':3,'Friday':4, 'Saturday':5, 'Sunday':6}
lst = calendar.monthcalendar(year, month)
ret = date(1,1,1)
matchcnt = 0
bkflg = False
for ... |
67d6743cba7059af14ac61ef1a391fb660306586 | prateksha/Source-Code-Similarity-Measurement | /Datasets/py-if-else/Correct/073.py | 248 | 3.875 | 4 | #!/bin/python3
import sys
n = int(input().strip())
if (n % 2 == 1):
print ('Weird')
else:
if (2<= n <= 5):
print ('Not Weird')
elif (6<= n <= 20):
print ('Weird')
elif (n> 20):
print ('Not Weird')
|
1c9c568081340c999ce2852c1f092a9cc7b26a9a | JChinchilla91/Intro-Python-II | /src/player.py | 1,174 | 3.546875 | 4 | # Write a class to hold player information, e.g. what room they are in
# currently.
class Player:
def __init__(self, name, location, items = []):
self.name = name
self.location = location
self.items = items
def move(self, direction):
new_location = self.location.location_move(... |
257af5ac4152544c27c69f02c85e2d4c1c4c6aa9 | amstocker/aoc2019 | /day1.py | 357 | 3.90625 | 4 | def mass_to_fuel(m):
return max((m // 3) - 2, 0)
def total_fuel(m):
total = 0
while m > 0:
m = mass_to_fuel(m)
total += m
return total
with open("day1.txt") as f:
data = [int(l) for l in f.read().rstrip().split('\n')]
# part 1
print(sum(mass_to_fuel(m) for m in data))
# part 2
pr... |
52a4dd85acce041b5e30bdd3419e30c55953e3e1 | kevincrossgrove/Bananagrams-Solver | /server/board.py | 1,385 | 3.890625 | 4 | from tile import tile
class board:
banana_board = []
'''
To access dictionary
-> [length of word][first letter]
'''
banana_dictionary = []
@classmethod
def placeWord(cls, word, startX, startY, direction):
for index, letter in enumerate(word):
if direction == 'down... |
c8a82681027066fc775d866c9f9b163979fb46b3 | YashJain2/AP_LAB_WORK | /Application_programming(Lab_Work)/Q-9/9(python_programs)/tkinker.py | 1,029 | 3.5 | 4 | from tkinter import *
from tkinter import ttk
def get_sum(*args):
try:
num1_val=float(num1.get())
num2_val=float(num2.get())
solution.set(num1_val+num2_val)
except ValueError:
pass
root=Tk()
root.title("Calculator")
frame =ttk.Frame(root,padding="10 10 10 10")
... |
25360abe687c64fdb659982b035f0d92120ee247 | LukeLaScala/advent-of-code-2016 | /day3/solve1.py | 510 | 3.640625 | 4 | lengths = list()
possible = 0
impossible = 0
with open('in.txt') as f:
for line in f:
lengths.append(line.lstrip(' ').strip('\n').split(' '))
def check(l1, l2, l3):
return (l1 + l2) > l3 and (l2 + l3) > l1 and (l1 + l3) > l2
for length in lengths:
length = filter(lambda a: a != '', length)
i... |
63ab2b061ac1e2b5fff66840dd283d40dd7e21da | pomonykr/DataScience | /Python,Pandas,Mysql/Python_3일차/Python03_08_ForExp01_김병수.py | 272 | 4.15625 | 4 | a = [2*4,3*6,9*4,3*3]
#result = []
#for num in a:
# result.append(num*3)
#
#print(result)
#
#
#result = [num * 1]
#print(result)
#변수를 정수 말고 이름으로 해볼것
result = []
for num in a:
result.append(num*3)
print(result)
#[3, 6, 9, 12]
#[3, 6, 9, 12] |
206cbdcfad26c6a7f1d577c72faf53b677946fff | threegenie/algo_problem | /prefixsum.py | 1,334 | 3.546875 | 4 | import time, random
def prefixSum1(X, n):
# code for prefixSum1
for i in range(n):
S = 0
for j in range(i+1):
S += X[j]
def prefixSum2(X, n):
# code for prefixSum2
S = X[0]
for i in range(1, n):
S += X[i]
random.seed() # random 함수 초기화
n = int(inp... |
44d17f40e6f0e3b49d1b8fe305e19ff11d54d18c | jasper2326/HackerRank | /offer/_11.py | 896 | 3.578125 | 4 | class Solution:
def powerNormal(self, base, exponent):
if exponent == 0:
return 1
elif exponent == 1:
return base
if exponent < 0:
flag = 1
exponent = -exponent
else:
flag = 0
result = 1
temp = base
... |
02457e25a3e1322da15afd797241b8d6b3ca904f | haodonghui/python | /learning/py3/RuntimeError Set changed size during iteration解决方法/1.py | 659 | 3.75 | 4 | '''
参考:
https://blog.csdn.net/weixin_43848469/article/details/106470927
写代码的时候报了这样一个错,有一种非常简单的解决方法,因为一般是你 set 删除了一些东西,可以使用复制一个相同的集合进行循环,这样就不会报错了,比如
'''
order_delivery_no_set = set()
# 会报错 RuntimeError: Set changed size during iteration
for order_delivery_no in order_delivery_nos:
order_delivery_nos.discard(ord... |
eb16eeb0765d572d65b05b17f9cdc8a1dc5ff774 | pythonfoo/pythonfoo | /beginnerscorner/crashcourse-0/05_input.py | 495 | 3.921875 | 4 | #!/usr/bin/env python
# get user input
myInput = raw_input("enter some foo: ")
# THIS is BALLZ (in python 2.6/2.7), describe why!
#myInput = input("enter some foo: ")
print "you entered:", myInput
# do stuff ONLY if this the input is a digit
if myInput.isdigit() == True:
print 'yes we digit'
numberOne = 11
num... |
401135cd8985f8c777b666fc87e185bedfe94980 | namphung1998/Comp123_code | /untitled1/work.py | 805 | 3.5625 | 4 | from tkinter import *
class Yeller:
def __init__(self):
self.root = Tk()
self.inptVar = StringVar()
self.inpt = Entry(self.root, font = ("Bradley Hand", 30), textvariable = self.inptVar)
self.inpt.grid(row = 0, column = 0)
self.btn = Button(self.root, text = "yell now!", ... |
02514dc8173d54f03a86e681fb35b7a3da5a78cf | Gnurka/adventofcode-2017 | /day7/day7.py | 1,510 | 3.5625 | 4 | import re
class Node:
def __init__(self, root, weight, children):
self.root = root
self.weight = weight
self.children = children
#self.child_weights = []
def __repr__(self):
return self.root + "(" + str(self.weight) + ") -> " + str(self.children) # + ". Child weights: ... |
b9eccaf484d5bd0ce7631d54f1aa1e7fdf347308 | zhouf1234/untitled927 | /21点小游戏.py | 7,227 | 3.609375 | 4 | import random
import sys
import time
class Card:
"""定义扑克牌类。每个对象代表一张扑克牌。
"""
def __init__(self, card_type, card_text, card_value):
"""初始化方法。
card_type : str
牌的类型。(红桃,黑桃,梅花,方片)
card_text : str
牌面显示的文本。(A,K,Q,J)
card_value : int
牌面真实的点数。(如A为... |
1dfb83b0d0e9af206dfc81fdbe2fff8a48443e03 | ang027/r1-ticpy | /reto1.py | 316 | 3.609375 | 4 | Polacos= int (input("Candidatos Polacos: "))
Hungaros= int ((Polacos*2)+4)
Lituanos= int ((Polacos + Hungaros)/5)
print(Polacos, Hungaros, Lituanos)
if Lituanos in range(0,20):
print("Uno")
if Lituanos in range(21,30):
print("Dos")
if Lituanos in range(31,50):
print("Tres")
if (Lituanos>50):
print("Cuatro") |
5a8448913babbf7e385c003e23e02e531a088703 | aakin03/CS-115 | /lab3.py | 553 | 3.5625 | 4 | '''
Created on Feb 12, 2015
@author: Ayse Akin
'''
def minimum(x, y):
if x < y:
return x
return y
def change(amount, coins):
if amount == 0:
return 0
elif coins == []:
return float("inf")
else:
firstCoin = coins[0]
if firstCoin > amount:
... |
ad029472ea16da8948aba0742424b3b46ff28cae | FLINKBLINK/Curso-Python | /arquivos de python aleatorios/Exercicios/Exercicio006.py | 233 | 4.125 | 4 | numero = int(input('Digite aqui um número inteiro: '))
dobro = numero * 2
triplo = numero * 3
raiz = numero ** (1/2)
print('o dobro de {} é {}, seu triplo é {} e sua raiz quadrada é {}'.format(numero, dobro, triplo, raiz))
|
b0efb2143103655eae3a797f7d3ce0f7e3f34fae | JohnOyster/ComputerVision | /SpatialTransformations/spatial_transformations.py | 2,742 | 4.0625 | 4 | #!/usr/bin/env python3
"""CIS 693 - Spatial Transformations Homework.
Author: John Oyster
Date: May 22, 2020
Description:
List of Functions:
1. Convert to Grayscale
2. Negative Transformation
3. Logarithmic Transformation
4. Gamma Transformation
"""
import cv2
import numpy as np
def convert_to... |
7819fba779264926bb58176dd12c32cfbde42378 | ElmiraSargsyan/Machine_Learning | /Handwritten digit recognition/gradient_descent.py | 3,942 | 3.6875 | 4 | import numpy as np
def stochastic_gradient_descent(data, labels, gradloss,
learning_rate=1):
"""Calculate updates using stochastic gradient descent algorithm
:param data: numpy array of shape [N, dims] representing N datapoints
:param labels: numpy array of shape [N]
... |
453456830ed86cc790f41ccbdaf9831e6b18299a | PythonCoder8/python-174-exercises-wb | /Intro-to-Programming/exercise-7.py | 732 | 4.0625 | 4 | '''
Exercise 7: Sum of the first n positive integers
Write a program that reads a positive integer, n, from the user and then displays the
sum of all the integers from one to n. The sum of the first n positive integers can be
calculated using the formula:
sum = (n)(n + 1) divided by 2
(I didn't use the formula)... |
b9bee08964257334949d5b51e7d4a39fcd474cfb | Karenahv/holbertonschool-interview | /0x03-minimum_operations/0-minoperations.py | 472 | 3.78125 | 4 | #!/usr/bin/python3
"""Minumun operations"""
def minOperations(n):
"""num of operations for n H"""
if n < 2 or type(n) is not int:
return 0
num_op = 0
act = 1
cpy_all = 0
paste = 0
while act != n:
if n % act == 0:
cpy_all = act
paste = act + cpy_all
... |
864a70f00ef99f161fab4a212d3acbde87041eb6 | adebuyss/knapsack | /Waiter.py | 7,259 | 4.09375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Waiter.py
A waiter who looks at a customers financial situation and suggests a
menu
"""
from decimal import Decimal
import re
import collections
def _check_money(price):
"""Check that we don't have fractions of cent"""
price = Decimal(str(price))
retu... |
d4558b0be3d3f841ce448f0de89eaa9b6070eb30 | JinleeJeong/Algorithm | /20년 2월/1406.py | 67 | 3.734375 | 4 | enStr = str(input())
if(enStr == "love"):
print("I love you.") |
0354a62971df05b02b9c30824b5e29ce2f967c70 | Number1788/Python | /tutorial/lists/1.py | 3,934 | 3.96875 | 4 | L=[123,'123',1.23]
print(len(L)) #Длина строки
print(L[0]) #Возвращаем элемент по индексу
print(L[:1]) # делаем срез до второго элемента
print(L + [4,5,6]) # контатация сторк
print(L)
print(len([1,2,3])) ... |
412183a790a82a1e3aa9f98f849af688be90d939 | josephjose99/genskills | /wallis.py | 145 | 3.953125 | 4 | def wallis(n):
x=1
n=int(n)
i=1
while(i<=n):
x*=((2*i)**2)/(((2*i)**2)-1)
i+=1
return x*2
n=input("enter the n:")
print(wallis(n))
|
73dd1c5056ac871a92e1979443428f98504331d9 | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_3_neat/16_0_3_Haolan_cs.py | 1,485 | 4 | 4 | def isprime(n):
'''check if integer n is a prime'''
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return 0
# 2 is the only even prime number
if n == 2:
return 0
# all other even numbers are not primes
if not n & 1:
re... |
37ee56b2c9bfbbb7ab2b8b047543b0e8ae9d6692 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/leap/11128d9321e24cc185d83f165d0938f4.py | 313 | 3.875 | 4 | def is_leap_year(year):
divisible_by_4 = year % 4 == 0
divisible_by_100 = year % 100 == 0
divisible_by_400 = year % 400 == 0
if divisible_by_4:
if divisible_by_100 and not divisible_by_400:
return False
else:
return True
else:
return False
|
93d9e899a8ac54fc88f13f764fd894f5e0e967ea | bosonfields/MazeRunner | /Mazeclass.py | 3,562 | 3.6875 | 4 | import numpy as np
import random
import matplotlib.cm as cm
from matplotlib import pyplot as plt
#Generalize a maze with dimension and probability
class Maze:
def __init__(self, num, p = 0):
self.dim = num
self.M = np.random.rand(self.dim, self.dim)
blank = self.M >= p
blocked = se... |
6453cf86aaf67f828b46fe5991293c29197a27fb | kzh980999074/my_leetcode | /src/math/172. Factorial Trailing Zeroes.py | 315 | 4.125 | 4 | '''
Given an integer n, return the number of trailing zeroes in n!.
Example 1:
Input: 3
Output: 0
Explanation: 3! = 6, no trailing zero.
Example 2:
Input: 5
Output: 1
Explanation: 5! = 120, one trailing zero.
'''
def trailingZeros(n):
count=0
while n>0:
count+=n//5
n=n//5
return count
|
f03cd755ed946eefb1828173843c9861c33c3da0 | elshadow11/Prog | /ejercicios terminados/Python/Ejercicios programas/raices.py | 680 | 4.21875 | 4 | #Programa: raices.py
#Propósito: Calcular la raíz cuadrada y la raíz cúbica de un número
#Autor: Jose Manuel Serrano Palomo.
#Fecha: 13/10/2019
#
#Variables a usar:
# n1 es el numero que vamos a usar
# sq1 es la raíz cuadrada
# sq2 es la raíz cúbica
#
#Algoritmo:
# LEER n1
# sq1 <-- math.sqrt(n1)
# sq2 <-- n1 ** (1/3)... |
30c43127770096540cf10c087a9bc901b6dbb0ce | susanmpu/sph_code | /python-programming/learning_python/ascii_to_plain.py | 574 | 4.15625 | 4 | #!/usr/bin/env python
# by Samuel Huckins
def main():
"""
Print the plain text form of the ASCII codes passed.
"""
import sys
import string
print "This program will compute the plain text equivalent of ASCII codes."
ascii = raw_input("Enter the ASCII codes: ")
print "Here is the plainte... |
98b28d95edbd6bc1a60469775efa6004048ecc05 | ShiYujin/IntroductionToAlgorithms | /MergeSort.py | 728 | 3.6875 | 4 | # Merge sort.chapter2.3.1
__author__ = 'ShiYujin'
__date__ = '2015.5.24'
def merge(A, p, q, r):
import copy
L = copy.deepcopy(A[p:q])
R = copy.deepcopy(A[q:r])
L.append(float("inf")) # sentinel
R.append(float("inf"))
i = 0
j = 0
for k in range(p, r):
if L[i] <= R[j]:
... |
7fdaf297479afb9008a6d573e00c1b1fd8852624 | kurtrm/linear_algebra_pure | /src/matrix_multiplication.py | 1,041 | 3.984375 | 4 | """
Module supplying a function for matrix multiplication.
Numpy is way better, I'm strictly trying to solidify my understanding
by implementing it in Python.
"""
def multiply_matrices(m_1: list, m_2: list) -> list:
"""
Parameters
----------
m_1 : list of lists =>
[[1, 2, 3],
[4,... |
6e80d387ab8c3c50348300e1727df2b7d3575a71 | SimonFans/LeetCode | /OA/MS/Maximum Length of a Concatenated String with Unique Characters.py | 1,029 | 3.796875 | 4 | Example 1:
Input: arr = ["un","iq","ue"]
Output: 4
Explanation: All possible concatenations are "","un","iq","ue","uniq" and "ique".
Maximum length is 4.
Example 2:
Input: arr = ["cha","r","act","ers"]
Output: 6
Explanation: Possible solutions are "chaers" and "acters".
Example 3:
Input: arr = ["abcdefghijklmnopqr... |
b438ce2a54a301f4d7ac33b0fa70a13f87aab285 | Aasthaengg/IBMdataset | /Python_codes/p02712/s145621527.py | 93 | 3.578125 | 4 | n = int(input())
ans = sum(x for x in range(1, n+1) if x % 3 != 0 and x % 5 != 0)
print(ans)
|
06ba3f92ee3a1bfecd73d8b99f2978f3bac14aff | evanqianyue/Python | /day16/高阶函数-map与reduce/map和reduce.py | 515 | 4.0625 | 4 | # !/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@ Author :Evan
@ Date :2018/11/1 15:28
@ Version : 1.0
@ Description:
@ Modified By:
"""
# python内置map() 和 reduce()
# map(fn,lsd)
# fn是函数,lsd是序列
# 功能:将传入的函数依次作用在序列中的每一个元素,并把结果作为新的Iterator返回
def char2int(chr):
return {"0": 0, "1": 1, "2": 2, "... |
00721ac764c57a8d634221b2e282d1e724dc09e9 | harshit-dot/python-programs | /ga.py | 479 | 3.59375 | 4 | n=int(input())
s=list()
for i in range(0,n):
c=input().split()
if c[0]=='print':
print(s)
elif c[0]=='append':
b=int(c[1])
s.append(b)
elif c[0]=='insert':
b=int(c[1])
d=int(c[2])
s.insert(b,d)
elif c[0]=='remove':
b=int(c[1])
... |
b82cb382740964c8d14872c0333bde9ffb8ea19c | jagruti8/basic_algorithms | /dutch_national_flag.py | 3,311 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 31 07:50:52 2020
@author: JAGRUTI
"""
import random
def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
"""
# retur... |
0937d8d598e23fdafecc86265a0017beb1691ddd | phanrahan/magma | /magma/passes/tsort.py | 2,214 | 4.09375 | 4 | def tsort(graph):
"""
Repeatedly go through all of the nodes in the graph, moving each of
the nodes that has all its edges resolved, onto a sequence that
forms our sorted graph. A node has all of its edges resolved and
can be moved once all the nodes its edges point to, have been moved
from the ... |
536c2a23bfeedb497e941ec98f2fccf47723f094 | reberhardt7/sofa | /sofa/writers.py | 514 | 3.78125 | 4 | """
Contains common writer functions for converting information received via the
API into a format for database storage.
"""
from datetime import datetime
def boolean_writer(value):
if str(value).lower() in ['true', '1']:
return True
elif str(value).lower() in ['false', '0']:
return False
else:
raise ValueErr... |
01c0c081228f555be2498aaf1731367ff97e491d | Jiezhi/myleetcode | /src/128-LongestConsecutiveSequence.py | 1,132 | 3.609375 | 4 | #!/usr/bin/env python
"""
CREATED AT: 2022/3/3
Des:
GITHUB: https://github.com/Jiezhi/myleetcode
Difficulty: Medium
Tag:
See:
Time Spent: min
"""
from typing import List
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
"""
Ref: https://leetcode.com/problems/longest-con... |
e8e95b26fd35a1225b69bc15e850cd474ad57916 | caaden/python | /tkinter/tutorial/buttons.py | 804 | 3.609375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 21 11:01:29 2019
@author: caden
"""
import tkinter as tk
#%%
#Define master widget
class Window(tk.Frame): #Window inherits from frame... Window is a frame
def __init__(self,master):
tk.Frame.__init__(self,master=None)
self.mast... |
a93df82026d72cb7a5e375cc7a4a3bad9f595454 | tulans/LearnDataScience | /RegressionWithSKLearn/MultipleLinearRegressionSKLearn.py | 2,150 | 3.9375 | 4 | import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
sns.set()
data = pd.read_csv('../data/linear-regression/1.02.Multiple_linear_regression.csv')
print(data.head())
print(data.describe())
from sklearn.linear_model import LinearRegression
x = data[['SAT', 'Rand 1,2,3']]
y = data['GPA']
reg = L... |
4e5d217271c586257e78d304b22a69ae90c36518 | TMAC135/Pracrice | /intersection_of_two_linked_list.py | 5,101 | 3.796875 | 4 | #coding=utf-8
"""
Write a program to find the node at which the intersection of two singly linked lists begins.
Example
The following two linked lists:
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
begin to intersect at node c1.
Note
If the two linked lists have no interse... |
6b37f663e565158f647549961042902c3b71fdc6 | Srinvitha/python_classes | /Week_08/HW2.py | 292 | 3.984375 | 4 | # Loop through the above list (HW1) and print elements individually only if they are integers.
list = [1,12, 4.2, False,"Not imporant", True, "V.V.V.I.P", 42, 24.09, 63]
x = 0
for l in list:
if type(list[x]) == int:
print list[x]
x = x + 1
else:
x = x + 1
|
4b921f8ffa510f3ccc7de42a6e8620f18a4585b4 | hackettccp/CIS106 | /SourceCode/Module13/PartA/bicycle.py | 1,282 | 4.09375 | 4 | #Imports the Tire object
from tire import Tire
"""
Bicycle Object.
"""
#Class Header
class Bicycle :
#Initializer
def __init__(self) :
self.front_tire = Tire(45, 27)
self.back_tire = Tire(50, 27)
self.speed = 0
#Retrieves the front tire pressure
def getfrontpressure(self) :
return self.front... |
9bfba4dbe85b5988f07298be09de59eaae7830a2 | jordynojeda/sudoku_backtracking | /solver.py | 2,026 | 3.671875 | 4 |
board = [
[7,8,0,4,0,0,1,2,0],
[6,0,0,0,7,5,0,0,9],
[0,0,0,6,0,1,0,7,8],
[0,0,7,0,4,0,2,6,0],
[0,0,1,0,5,0,9,3,0],
[9,0,4,0,6,0,0,0,5],
[0,7,0,3,0,0,0,1,2],
[1,2,0,0,0,7,4,0,0],
[0,4,9,2,0,6,0,0,7]
]
def solve(the_board):
find = find_empty(the_board)
if not find:
... |
4e6edba4d8de64ee1d61b69dcd6f1a979b4e9277 | vsoch/algorithms | /reverse-without-special-char/reverse.py | 1,052 | 4.5625 | 5 | # Given a string, that contains special character together with alphabets
# (‘a’ to ‘z’ and ‘A’ to ‘Z’), reverse the string in a way that
# special characters are not affected.
def reverse_string(string):
# Idea: iterate through string from both sides
# First turn string into a list
lst = [x for x in st... |
2959676c2dbba1a65fccfd32b97083ef89d761fe | sanoojm/Python-Training | /psgen.py | 312 | 4.1875 | 4 | """
generators
-expression
-function
all generators are iterators
"""
items = [item for item in range(1, 10)]
print(items)
print()
items = (item for item in range(1, 3)) # generator
print(items)
"""print()
print(next(items))
print(next(items))
print(next(items))"""
for i in items:
print(i) |
f0e5646618a173eb2557fa7ef1fa228a4de47c80 | spinellimariana/OperadoresCondicionaisPython | /exeSucessorAntecessor.py | 355 | 4.21875 | 4 | '''
Exercício 5 - Aula 07
Faça um programa que leia um número inteiro e mostre na tela o seu sucessor e o seu antecessor.
'''
print('***MOSTRANDO O SUCESSOR E O ANTECESSOR DE UM NÚMERO INTEIRO***')
print()
n = int(input('Digite um número qualquer: '))
print('O antecessor de {} é {}; \nO sucessor de {} é {}.'.for... |
d27ad641ec739f25a2986929a0a209c7fe9ed2ea | liutongju/Fridolph | /python学习/python基础学习/08函数/8.3.2.py | 361 | 4.0625 | 4 | # 让实参变成可选的
def getFullname(firstName, lastName, middleName=''):
if middleName:
fullName = firstName + ' ' + lastName
else:
fullName = firstName + ' ' + middleName + ' ' + lastName
return fullName.title()
musician = getFullname('jimi', 'hendrix')
print(musician)
musician = getFullname('john', 'hooker'... |
ee536a862ca45990fa87167cc8bade7474e6b035 | nimanp/Project-Euler | /055.py | 390 | 3.59375 | 4 | def lychrelNumbers():
lychrels = 0
for i in range(1, 10001):
product = i
for j in range(0, 50):
reverse = int(str(product)[::-1])
product += reverse
if isPalindrome(product) == 1:
break
if j == 49:
lychrels += 1
print lychrels
def isPalindrome(num):
reverse = int(str(num)[::-1... |
e18f7bca40803c554768aa3790dccb6a4fc4d03f | SSBsoren/Python-Fundamentals | /elif02.py | 233 | 4 | 4 | num =int(input('Enter the number :'))
if 9 < num < 99:
print('Two digit number')
elif 99 < num < 999:
print('Three digit number')
elif 999 < num <9999:
print('Four digit number')
else:
print('Number is <=9 or >=9999') |
75c6f1b02f4204e1b5539d1bfe2e33c369c365f5 | hudy7/poker-game | /card.py | 629 | 3.625 | 4 | '''
This class could be built out to print out actual cards.
Also debating this turning into the Deck class and giving it the ability to
generate a deck.
'''
class Card:
def __init__(self, val, suit):
self.val = val
self.suit = suit
self.card_values = {
2 : '2',
3 ... |
6849e6a879d7f8d3d8b70824282b765b598c0fdd | MatanNadav/sudoku-bot | /sudoku-bot.py | 2,225 | 3.984375 | 4 | # This Project is a Sudoku Bot solving any 9x9 board using Backtracking Algorithm.
# board = [
# [7, 8, 0, 4, 0, 0, 1, 2, 0],
# [6, 0, 0, 0, 7, 5, 0, 0, 9],
# [0, 0, 0, 6, 0, 1, 0, 7, 8],
# [0, 0, 7, 0, 4, 0, 2, 6, 0],
# [0, 0, 1, 0, 5, 0, 9, 3, 0],
# [9, 0, 4, 0, 6, 0, ... |
a0c5d5274ca48198bdf1a15b5fbd52789f4104a5 | JaceTSM/Project_Euler | /euler034.py | 945 | 3.671875 | 4 | # !/Python34
# Copyright 2015 Tim Murphy. All rights reserved.
# Project Euler 034 - Digit Factorials
'''
Problem:
19 is a curious number, as 1! + 9! = 1 + 362880 = 362881 which is divisible by 19.
Find the sum of all numbers below N which divide the sum of the factorial of their digits.
Note: as 1!,2!, ... 9! are... |
436c883bda93139ca507904547bb324d5f60b1ba | saarikabhasi/Data-Structure-and-Algorithms-in-python | /queue/linked-list-implementation/circularQ-in-LL.py | 2,055 | 3.90625 | 4 | """
Implementing circular Q in Linked list
"""
class Node:
def __init__(self,data) -> None:
self.data = data
self.next = None
class cQueue:
def __init__(self,maxSize) -> None:
self.front = None
self.rear = None
self.maxsize = maxSize
self.size =0
def isFull... |
01a2f25fd91bcf7d4c2f739f412b16e6e2f4c75b | BoatInTheRiver/data_structure | /binaryTree.py | 5,187 | 3.8125 | 4 | # coding:utf-8
from collections import deque
class TreeNode(object):
def __init__(self, val, left=None, right=None):
self.val = val
self.left = None
self.right = None
class Tree(object):
'''
二叉树
add(item):往二叉树上加一个节点,满足完全二叉树
levelOrder1(root):层序遍历
levelOrder2(root):层序遍历
... |
99e12742a7b45e1c4a655ffbb87330f320a83e50 | wanghuafeng/lc | /剑指 Offer/33. 二叉搜索树的后序遍历序列.py | 703 | 3.765625 | 4 | #!-*- coding:utf-8 -*-
"""
https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。
如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。
参考以下这颗二叉搜索树:
5
/ \
2 6
/ \
1 3
示例 1:
输入: [1,6,3,2,5]
输出: false
示例 2:
输入: [1,3,2,6... |
2ab98c9d689dfd570d9741bbc478c690704278aa | estysdesu/exercism | /python/hamming/hamming.py | 282 | 4.0625 | 4 | def distance(strand_a: str, strand_b: str) -> int:
"""The Hamming distance of two equal length strings."""
if len(strand_a) != len(strand_b):
raise ValueError("strand_a and strand_b must be equal lengths")
return sum(a != b for a, b in zip(strand_a, strand_b))
|
60e36ee6b2d9941db8597f83f34b883f7967c847 | ankitomss/python_practice | /partitionList.py | 984 | 3.65625 | 4 | class ListNode(object):
def __init__(self,x):
self.val=x
self.next=None
class Solution(object):
def partition(self, head, x):
temp, second=head, head
count=0
while temp!=None:
if temp.val < x:
count+=1
second=second.next
... |
64ac2da9d780103a9041e6e5e3588734829e285b | kim-kiwon/Baekjoon-Algorithm | /삼성 기출/[5373]큐빙.py | 6,541 | 3.5625 | 4 | #그림 그려가며 구현.
#디버깅의 중요성
from collections import deque
cube = [[[0]* 3 for _ in range(3)] for _ in range(6)]
def init():
global cube
cube = [[['w', 'w', 'w'], ['w', 'w', 'w'], ['w', 'w', 'w']], #상
[['r', 'r', 'r'], ['r', 'r', 'r'], ['r', 'r', 'r']], #앞
[['g', 'g', 'g'], ['g', 'g', 'g'], ... |
7c407227405cbf58b85779608790e550fd106ec6 | leemarreros/Data-Analytics-for-Cyber-Security-Spam-Classification-by-R | /SMSSPAM.py | 11,209 | 3.671875 | 4 | #!/usr/bin/env python
# coding: utf-8
# ## Project Objective
# ##
#
# Spam detection is one of the major applications of Machine Learning in the interwebs today. Pretty much all of the major email service providers have spam detection systems built in and automatically classify such mail as 'Junk Mail'.
#
# In this... |
d635f631a0a5ebdf87c1be51ae59ea00d3d70ee3 | adam-barnett/LeetCode | /palindrome-number.py | 2,082 | 4.15625 | 4 | """
Determine whether an integer is a palindrome. Do this without extra space.
Problem found here:
http://oj.leetcode.com/problems/palindrome-number/
"""
import math
"""
my initial solution. This works and satisfies the requirement of using no
extra space, but it uses the math library which isn't available on leet... |
4efd541683b2df2d4ef87adcb42fd82ce9d844b9 | VijayEluri/ads | /python/optimization/simulatedannealing.py | 3,626 | 4.0625 | 4 | #!/usr/bin/env python
"""
The 0-1 knapsack problem resolved using the Simulated Annealing algorithm
"""
import math
import operator
import pprint
import random
import sys
COOLING_STEPS = 1000
TEMP_ALPHA = 0.8
random.seed()
def generate_items(n_items=100):
"Generate a list of items that could be stealed"
it... |
019625173c57d59fd7aa08942bb68763c51b4099 | skyfielders/python-skyfield | /skyfield/trigonometry.py | 2,208 | 3.78125 | 4 | """Routines whose currency is Angle objects."""
from numpy import arctan2, sin, cos, tan
from skyfield.constants import tau
from skyfield.units import Angle
def position_angle_of(anglepair1, anglepair2):
"""Return the position angle of one position with respect to another.
Each argument should be a tuple who... |
82781a27a46c1045a91c8019f1aa43010024ba3f | llanoxdewa/python | /Projek mandiri/save_pw.py | 682 | 3.828125 | 4 | import sys
def save_account():
if sys.argv[1] == '#help':
print('silahkan tulis seperti #<account> #<username> #<password>')
sys.exit()
else:
print('your user and password accoutn has been saved !!')
try:
# deklarai user dan password user
input_user_account = sys.argv[1].replace('#','')
input_user_name... |
c688c2939ca65f40d22e9ef885273aeb301088f9 | glissader/Python | /ДЗ Урок 2/main2.py | 777 | 4.21875 | 4 | # Для списка реализовать обмен значений соседних элементов.
# Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т. д.
# При нечётном количестве элементов последний сохранить на своём месте.
# Для заполнения списка элементов нужно использовать функцию input().
in_str = input("Введите элементы, разделенные про... |
0ce47a864a51d5c50333cbf874dc9a8b17461c9f | captainhcg/leetcode-in-py-and-go | /bwu/linked_list/147-insertion-sort-list.py | 1,393 | 3.984375 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def insertionSortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
ret... |
e2c37787e349cd43b2f7e5692f990c4cd2d366b2 | gadboisb5877/CTI110 | /M2T1_SalesPrediction_GadboisBrian.py | 271 | 3.765625 | 4 | # CTI-110
# M2T1 - Sales Prediction
# Brian Gadbois
# 9/19/2017
# Program made to figure out the annual profit
annualProfit = .23
totalSales = float (input ('What is the total sales:',))
profit = totalSales * annualProfit
print ('Your profit will be $',profit)
|
d1f4e9762fe7d1085b1dcb237bdc69c50d64b7f1 | kenji955/python_Task | /kadai_0/kadai0_6.py | 242 | 3.71875 | 4 | nameList=["たんじろう","ぎゆう","ねずこ","むざん"]
def nameCheck(checkName):
for name in nameList:
if name == checkName:
print(checkName+'は含まれます')
testName = 'ぎゆう'
nameCheck(testName) |
1ecb60ef067f1e18181711f2f06e470bb35dd381 | nduprincekc/papa | /student.py | 544 | 4.25 | 4 | #Write a function named readable_timedelta.
# The function should take one argument, an integer days, and return a string that says how many weeks and days that is.
# For example, calling the function and printing the result like this:
# print(readable_timedelta(10))
# should output the following:
# 1 week(s) and 3 ... |
9bd0fc0d6c4a2aa5da29e0eb6d68cf7b84d3d0e9 | mengnan1994/Surrender-to-Reality | /py/0339_nested_list_weight_sum.py | 2,043 | 4.15625 | 4 | """
Given a nested list of integers, return the sum of all integers in the list weighted by their depth.
Each element is either an integer, or a list -- whose elements may also be integers or other lists.
Example 1:
Input: [[1,1],2,[1,1]]
Output: 10
Explanation: Four 1's at depth 2, one 2 at depth 1.
Example 2:
Inpu... |
669b95b17e96bd9c0ba5c04124cb8a8165991855 | asouzajr/algoritmosLogicaProgramacao | /lingProgPython/cursoemVideo/desafio002.py | 101 | 3.71875 | 4 | nome = input('Qual é o seu nome? ')
print('Olá {}! É uma satisfação te conhecer!'.format(nome))
|
c550a1f6e75fab3373e8b3020184427856426db2 | topicus/musily | /server/models/people.py | 1,549 | 3.546875 | 4 | import csv
class People(object):
def __init__(self, file_path):
people_file = open(file_path, 'r')
self.people_reader = csv.DictReader(people_file, delimiter='|')
self.__people = {}
self.load()
def load(self):
for p in self.people_reader:
self.__people[p['usuario']] = p
def all(self)... |
3fe74a84b0fbe1b3d4b380574eaf166bdaba6bbb | GabrielNagy/Year3Projects | /AI/Project1.py | 7,004 | 3.515625 | 4 | #!/usr/bin/env python
from __future__ import print_function
import heapq
import logging
import sys
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
class Cell(object):
def __init__(self, x, y, reachable):
# Cell constructor
self.reachable = reachable # is cell reachable
self.x ... |
3616b072bd82250e68e8dc67b9840083ff18617f | hevervie/Python | /high.py | 156 | 3.921875 | 4 | #!/usr/bin/env python
#coding=utf-8
def max(a,b):
if a>b:
return a
return b
def MAX(a,b,c,f):
return f(f(a,b),c)
print(MAX(1,2,8,max))
|
8fbbb4f84e5776ed71c2d1a5ef1824766112772a | r0ckburn/d_r0ck | /The Modern Python 3 Bootcamp/4 - Boolean and Conditional Logic/getting_user_input.py | 562 | 4.40625 | 4 | # there is a built-in function in Python called "input" that will prompt the user and store the result to a variable
name = input("Enter your name here: ")
print(name)
# you can combine the variable that an end user input something to with a string
data = input("What's your favorite color?")
print("You said ... |
de338ad59cdbc44c528722475c5aca7bc0e9d381 | anitasandjaja/fundamental-python | /function.py | 3,949 | 4.125 | 4 | # Function
# Sekumpulan / block code yang dapat diberikan nama
# dan dapat digunakan berulang
# Dapat memiliki input, output, atau keduanya
# Contoh function tidak menerima inputan apapun
# def call():
# print("Hello, neighbour")
# # Menerima satu input
# def greet(name):
# print(f'Hello, (name)')
# # Men... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.