blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
2bc497d9e1a1a89d48a6f9c684febbd65074d200 | jameszhan/hotchpotch_pythons | /builtin/lang_features/desciptor.py | 825 | 3.578125 | 4 | #!/usr/bin/env python
class mydescriptor(object):
def __call__(cls):
print('new me')
#i'm going to be bound!!!
def __get__(self, new_self, Type = None):
#let us bind it!!!
print('__get__')
return self.__call__
#oh no.... i'm being override..
def __set__(self, new_... |
c5409bbe6d655ee6e95b99e80cd02b997b5d02ed | saulquispe/My-Solutions-to-The-Python-Workbook-By-Ben-Stephenson-122-of-174- | /Introduction to Programming Exercises/ex15.py | 572 | 4.4375 | 4 | '''
Exercise 15: Distance Units
In this exercise, you will create a program that begins by reading a measurement
in feet from the user. Then your program should display the equivalent distance in
inches, yards and miles. Use the Internet to look up the necessary conversion factors
if you don’t have them memorized.... |
0bd204847851f9006a893dd354c738a4412bfae4 | tickhcj/mystuff | /ex3.py | 706 | 4.03125 | 4 | # What to do
print "I will now count my chickens:"
# The number of chickens
print "Hens", 25.0 + 30.0 / 6.0
print "Roosters", 100 - 25.0 * 3.0 % 4.0
# cout the eggs
print "Now I will count the eggs:"
# The calculation results
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
# To determine the size
print "Is it true that 3 +... |
61fddbaafa4fbe3e2d1e72eb0b2f1289d99d5819 | kellystroh/Word_Ladder | /game_app/init_db.py | 560 | 3.9375 | 4 | #imports sqlite
import sqlite3
#connects it to the books-collection database
conn = sqlite3.connect('game-records.db')
#creates the cursor
c = conn.cursor()
#executes the query which inserts values in the table
c.execute("INSERT INTO game VALUES( 1, '[dinner, time, machine, learning, experience, required, reading, m... |
88c960b1337389666ce1c86a8a52720a7c734278 | SarthakSharma660/Python_Practice | /BIll_Splitter.py | 438 | 4.21875 | 4 | print("Welcome to the tip calculator")
# asking for total bill
bill=float(input("What is the total bill :\n"))
# asking for tip %
percent=int(input("What percentage tip would you like to give? 10,12 or 15\n"))
#asking for number of people
no_people=int(input("How many people to split bill ?\n"))
# calculations
total_bi... |
fcce75d3d358a2e83b76ecc2d52f7cf15bb22776 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/3858/codes/1644_2704.py | 97 | 3.6875 | 4 | nt = float(input())
m = input()
m = m.upper()
if(m == "S"):
print(nt+(nt*0.10))
else:
print(nt) |
f279abd7c1b0453d127b5e2fa729e0e4fa081cc7 | ethanjpkamus/zoo-o-mathematics | /animals.py | 682 | 3.90625 | 4 | # Arithmetic Computational Game - Zoo-o-mathematics!
# set of arrays - animals for each corresponding level of difficulty
from arithmeticFunc import *
listOfAnimals = [
"hare",
"lion",
"camel",
"koala",
"lemur",
"otter",
"panda",
"sloth",
"tiger",
"zebra",
"dragon",
"go... |
739684680bc6e4a66c985b1f576ee3fbb0c8f794 | 44378/Iteration | /Itteration rev ex - python school 4.py | 260 | 4.03125 | 4 | #Jack Scaife
#31/10/14
#Rogue cancel for addition
total = 0
value = int(input("Enter a number to add to the total: "))
while value > 0 :
value = int(input("Enter a number to add to the total: "))
total = total+value
print("The total is {0}".format(total))
|
3989b665f074cfc3132eef0397f0febe9103d7bf | manpreetsran93/movies_db | /find.py | 1,798 | 4.40625 | 4 | import printcol
def find(dict1):
"""Finds movie/s from collection based attribute searched by user
:param dict1: dictionary contains movies as keys and their attributes in a nested dictionary
:return:
"""
if dict1 != {}:
search = input("Which attribute would you like to search by? Enter: ... |
8516132ce3cbb26fff2360bc5d522403387c569a | simran0963/python | /search.py | 551 | 3.984375 | 4 | li = list(map(int,input("enter the list elements separated by spaces in a non decreasing order: ").split())) # to enter a list
key = int(input("enter the key : "))
# print('List is ' , li)
# print('Key is ', key)
# print(key in li)
def linearSearch(li,key)->bool:
for i in li:
if i == key:
return True
return F... |
a591fa25b377692e64340ec17750f55b41bdb68d | kiranmahi2593/Projects | /dictonary_module.py | 865 | 4.15625 | 4 | def Add(x):
Udict = dict()
for i in range(x):
DKey = input("Enter the Key:")
DValue = input("Enter the Value:")
Udict[DKey] = DValue
print("Dictionary",Udict)
return Udict
def Remove(x):
val = input("enter the key name to remove dict... |
fd6ed5bdc98130b9d4b876f8253f1204ab749540 | Dearyyyyy/TCG | /data/3920/AC_py/519774.py | 195 | 3.65625 | 4 | # coding=utf-8
line = input()
number = int(line)
number_list = list(line)
cal = 0
for i in range(3):
cal += int(number_list[i]) ** 3
if cal == number:
print("YES")
else:
print("NO") |
2e354d494a3b76c0a6811628e5a238770f5c324a | pippylam/python | /dientich.py | 233 | 3.625 | 4 | chieudai = int(input("Nhap chieu dai hinh chu nhat: "))
chieurong = int(input("Nhap chieu rong hinh chu nhat: "))
print ("Chu vi hinh chu nhat la: ", (chieudai+chieurong)*2)
print ("Dien tich hinh chu nhat la: ", chieudai*chieurong)
|
b1f55ae6cce0a19be382d81a116aadda9ad8c4e7 | Shivani3012/PythonPrograms | /conditional ass/ques32.py | 215 | 4.21875 | 4 | #Write a Python program to check whether an alphabet is a vowel or consonant.
ch=input("Enter the character:")
if ch=='a' or ch=='e' or ch=='i' or ch=='o' or ch=='u':
print("Vowel")
else:
print("Consonent")
|
6af428efd7c0a97ff30ca3bf2d37444a3d236e95 | saurav188/python_practice_projects | /bianary_tree_iterative_inorder_traversal.py | 805 | 3.953125 | 4 | class Node(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def inorder(self):
stack=[]
current=self
result=""
while True:
if current!=None:
stack.append(current)
current=c... |
d4d536e733df1a149691d7e9b0cce9b7649cc7ab | bFraley/python-examples | /jason_mize.py | 1,136 | 3.828125 | 4 | print ("=" * 10)
#This module allows you to ouput calendars.
#It has built in functions to help.
import calendar
def calendar_example ():
#prints the day you have set to be the start of the week
#in this case the default is 0 for Monday
print (calendar.firstweekday())
#prints what day of the week the date was ... |
83449302e04e40941dbf5ffc8e16996186203e9c | hariharanragothaman/codeforces-solutions | /contests/339/339A-Helpful-Maths.py | 99 | 3.765625 | 4 | string = input().split('+')
string = sorted(c for c in string)
print('+'.join(c for c in string))
|
d792e0c8b5964c2b4c8590dc124b27112184fc45 | mebarile02/Python- | /explode_seq.py | 449 | 4 | 4 | """
This is a function that takes in a natural number n. It assumes the user will
enter an integer, but not necessarily a natural number.
"""
def explode_seq(n):
cond = True
while cond:
if n > 0:
cond = False
else:
n = int(input('Enter an integer greater than... |
130fa7cc423067efacecf6dbe66590772ae94e18 | tanx16/blindfold-chess | /user_input.py | 2,641 | 4 | 4 | from pieces import *
from game import *
import sys
new_chessboard = Chessboard()
new_game = Game(new_chessboard)
column_names = {"a": 0, "b": 1, "c": 2, "d": 3, "e": 4, "f": 5, "g": 6, "h": 7}
def start():
print("Hi! Welcome to Blind Chess, a challenging game where neither side can see the chessboard!\n")
... |
af6f41cc78f216617bb43df6b87192ac916adf98 | ptsiampas/Exercises_Learning_Python3 | /07_Iteration/Exercise_7.26.15.py | 1,338 | 4.09375 | 4 | # Write a function num_even_digits(n) that counts the number of even digits in n. These tests should pass:
#
# test(num_even_digits(123456), 3)
# test(num_even_digits(2468), 4)
# test(num_even_digits(1357), 0)
# test(num_even_digits(0), 1)
import sys
def test(actual, expected):
""" Compare the actual to the expec... |
20635e7f48d2ed356a5d6eb749db95e35e97bf0a | tomasmariconde/EDA_with_Python | /EDA.py | 8,785 | 4 | 4 | #Analisis exploratorio (EDA) de protestas de campesinos sudamericanos con Python
#PASO 1 - Carga de librerias
#Importamos las librerias que utilizaremos para generar nuestro analisis
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#PASO 2 - Carga de datos
#Cargamos nuestra base de datos a un ... |
256d2fe77046027509078e5c1c990b40466bfa67 | ejrinkus/netris | /game/gameover.py | 2,518 | 3.765625 | 4 | ################################################################################
#
# Contains the Pause class. This class is responsible for displaying and
# removing the pause screen overlay during a game (will not be needed in modes
# with more than one human player, since pausing won't be allowed).
#
###########... |
40588e030ac43c8883bd039a9569d38305b5eb46 | salotz/boar | /macrotests/txtmatch.py | 2,821 | 3.578125 | 4 | #!/usr/bin/env python3.7
# -*- coding: utf-8 -*-
# Copyright 2012 Mats Ekberg
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... |
cec09409b89fcd3dcc844731a5a000b380bfd5c8 | guildenstern70/PythonLearn | /src/pydiskutils/filesdeleter.py | 1,323 | 3.84375 | 4 | """
FilesDeleter.py
Usage: python FilesDeleter.py [initial_dir] [string]
Walks every subdirectory starting from
[initial_dir] and deletes every file in it that
contains in its file name 'string'
Example: python FilesDeleter.py . .class
Deletes every .class file in all subdir... |
72ce8099acb5cc296426a23eb4f9bd5c9ca9b754 | zeylanica/programmers | /Level1_수박수박수박수박수박수.py | 260 | 3.671875 | 4 | #https://programmers.co.kr/learn/courses/30/lessons/12922?language=python3
def solution(n):
string = "수박"
if(n % 2 == 0):
answer = string * (n//2)
else:
answer = string * (n//2+1)
answer = answer[0:-1]
return answer |
253654fc55a5a161b731d27044a34c9dc5ef0378 | akhildraju/cs-module-project-recursive-sorting | /src/searching/searching.py | 1,069 | 4.34375 | 4 | # TO-DO: Implement a recursive implementation of binary search
def binary_search(arr, target, start, end):
# Your code here
if len(arr) == 0:
return -1
if target < arr[start] or target > arr[end]:
return -1
slice = arr[start:end]
minIndex = 0... |
22bf75f98127604df26dac5c4a3bf674b48bf3a1 | DavidHan6/Week2 | /Week2/ImageProcessing.py | 4,275 | 3.515625 | 4 | from PIL import Image
from PIL import ImageFilter
print(" What is your request? ")
print(" a is invert")
print(" b is darken")
print(" c is brigten")
print(" d is greyscale")
print(" e is posterize")
print(" f is solarize")
print(" g is denoi... |
0e513decfbab90b4bfca5e57e25bce946c6bae22 | ethan-haynes/coding-problems | /python/src/isunique.py | 705 | 4.25 | 4 | """
implement algorithm to determine if string has all unique
characters with no additional data structurs.
"""
def isunique(s):
last = ''
for i in sorted(s):
if i == last: return False
else: last = i
return True
print(isunique('abcde'))
print(isunique('abcdee'))
print(isunique('aaa... |
89473bafaa239848b24ca170eec55d3044a747cf | yiss13/CursoDeMatematicasParaDataScience-CalculoBasico_Platzi | /piecewise_function.py | 651 | 3.84375 | 4 | import numpy as np
import matplotlib.pyplot as plt
def piecewiseFunction(x):
y = np.zeros(len(x))
for idx, x in enumerate(x):
if x >= 0:
y[idx] = 1.0
return y
def plot(x, y):
fig, ax = plt.subplots()
plt.xlim(-10, 10)
plt.ylim(-1, 2)
ax.plot(x, y)
ax.grid()
... |
d84f80020e3a44bf7a026e250f3bf1706eebb11a | Letian-Wang/CS61A-Structure-and-Interpretation-of-Computer-Programs | /2.2-4-iteration.py | 634 | 4.0625 | 4 | ''' iteration '''
def fib(n):
""" Compute fibonachi number """
pred, curr = 0, 1
k = 1
while k < n:
pred, curr = curr, pred + curr
k = k + 1
return curr
Function:
1. exactly one job
2. no repeatation
3. generally
python -i file.py
assert 3 > 2, "Math is broken"
''' Use a function... |
8f719280695ac658200268046789953812fff787 | rmayherr/python | /list_recursion.py | 219 | 3.734375 | 4 | def list_sum(some_list):
if some_list == []:
return 0
elif len(some_list) == 1: # base case
return some_list[0]
else:
return some_list.pop() + list_sum(some_list) # recursive case
|
6d41d3acfdb15c9c299e7aad22c64dd100548ac5 | andresilmor/Python-Exercises | /Ficha N7/ex05___.py | 578 | 3.953125 | 4 | #Crie um ficheiro com o nome “texto.txt”. Escreva nesse ficheiro um qualquer conteúdo
#com um número de linhas entre 20-30 (Pode ser um copy de um texto qualquer). De
#seguida, implemente e teste uma função capaz de retornar o número de vezes que
#uma dada palavra, fornecida pelo utilizador, aparece no referido text... |
0787a5c88d909f876f1da3155a976075ba59c611 | robinsxdgi/Machine-Learning | /Spell-Checking-System-by-K-Nearest-Neighbor/costTest.py | 4,293 | 3.78125 | 4 | # EECS 349 Machine Learning, Spell Checking System, P3.1
# Ding Xiang
# October,1,2017
#########################
# python spellcheck.py '/Users/Rockwell/PycharmProjects/MLHW2/3esl.txt' 3esl.txt
# python spellcheck.py '/Users/Rockwell/PycharmProjects/MLHW2/wrongwords.txt' 3esl.txt
# python spellcheck.py '/Users/Rockwell... |
0a801023a32ce773a46fe7aef6b5c78c817a3939 | forkcodeaiyc/skulpt_parser | /run-tests/t185.py | 301 | 3.671875 | 4 | class Wee:
def __init__(self):
self.called = False
def __iter__(self):
return self
def __next__(self):
print("in next")
if not self.called:
self.called = True
return "dog"
raise StopIteration
for i in Wee():
print(i)
|
836c8621791565038fe44c60168be5ec0d14df0b | CMWelch/Python_Projects | /Python/General_Projects/Black Jack/Game.py | 3,752 | 3.9375 | 4 | import Classes
def wager(player):
'''
:param player: Player that is placing the bet
:return: The bet amount
'''
while True:
try:
b = int(input("Place a bet: "))
if b <= player.chips:
player.bet(b)
return b
el... |
51ce3e629ef73d65d4d948afa1373dd2fb1565e3 | maxwelldantas/learning-python3 | /aprendendo_a_sintaxe/dicionarios.py | 575 | 3.90625 | 4 | # Listas tipo chave:valor - dict(dicionário)
# Criando um dicionário vazio
livros = {}
# Forma de adicionar chave e valor no dicionário
livros['titulo'] = 'Aprenda a programar em python em 6hs'
livros['ano'] = 2018
# Criando um dicionário com chaves e valores
pessoa = {'nome': 'José da Silva', 'idade': 30, 'altura':... |
47556b713b2b0c01a9febd413ab6a26d5cc4fa3d | filipmalecki94/Python | /Task_lists/pazdziernik/pazdz32.py | 827 | 3.671875 | 4 | import math
wybor = int(input("1. Kartezjanskie -> Sferyczne\n2. Sferyczne -> Kartezjanskie\n-> "))
def sfer2kart(r,theta,phi):
#return (x,y,z)
return r*math.sin(theta)*math.cos(phi),r*math.sin(theta)*math.sin(phi),r*math.cos(theta)
def kart2sfer(x,y,z):
#return (r,theta,phi)
return math.sqrt(x**2+y**2+z**2),(... |
10774f733307c6b9f0bf9a5859f5f907cea688a7 | krajeshkumar11/Test | /cspp1-practice/m4/p2/bob_counter.py | 629 | 4.03125 | 4 | '''Assume s is a string of lower case characters.
Write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then your program should print
Number of times bob occurs is: 2'''
def main():
s = raw_input()
# the input string is in s
# remove pass and start y... |
221a1b13d353885119ce598638e506d9764a6f8f | WilliamKulha/learning_python | /files_and_exceptions/addition.py | 649 | 4.15625 | 4 | def add_two_digits(num1, num2) :
"""Add two numbers"""
try :
num1 = int(num1)
num2 = int(num2)
except ValueError :
print("Hey, one of those isn't a number!")
else :
result = num1 + num2
print(f"The result is: {result}")
print("enter 'q' to quit at anytime.")
pr... |
1dbe8f2ed6518b3eb02bde221300924d671eae20 | gautam4941/Machine_Learning_Codes | /Pre Processing/Topic 3 - MatPlotLib/3. Histogram.py | 4,416 | 3.828125 | 4 | #When we work with histogram then we need to have only one data which will be x-axis data
#and y will be the freq. occurance of each element in x-axis data
import matplotlib.pyplot as plt
import random
import pandas as pd
# Syntax for Random,
# random.randrange(start_value, End_value, incrementation)
# r... |
6382d54128664403ed41f6dca96ecf8e34d621e8 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2447/60738/313279.py | 383 | 3.65625 | 4 | a=input()
b=input()
c=input()
try:
d=input()
except:
string=""
if a=="10 2":
print("7 26 ",end="")
elif a=="10 3":
if d=="3 9" and c=="2 7":
print("2 3 1 ",end="")
elif d=="3 6":
print("2 3 1 ",end="")
elif d=="6 6":
print("4 6 5 ",end="" )
elif a=="10 5":
print("4 4 ... |
61da7894fefae38ddb2e4d514779a14aa22a7b55 | nolderosw/estdados | /prova1/q1.py | 1,732 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 10 09:35:14 2017
@author: wesley150
"""
class Lista:
def __init__(self):
self.referencia = None
def inserirFim(self,valor):
novoNo = no(valor)
if(self.referencia == None):
self.referencia = novoNo
else:
... |
5a5da05a2c56aa5b59174e38aa51741e33294514 | stepheneldridge/Advent-of-Code-2019 | /Day 03.py | 1,981 | 3.515625 | 4 | # Day 3
import math
INPUT = open('Day 03.txt', 'r')
data = []
directions = {
"D": [0, -1],
"U": [0, 1],
"L": [-1, 0],
"R": [1, 0]
}
for line in INPUT:
p = line.split(",")
current = [0, 0]
path = [(0, 0)]
for i in range(len(p)):
d = directions[p[i][0]]
dist... |
3c03df5ae872c1b03b1d3061cb7adff1abbb5404 | nileshzend/PythonNZ | /8_calc.py | 1,468 | 4.28125 | 4 | # print("2+3") dont use ""
print(2+3) # ANS : 5
print(2+3*4) # ANS : 14
print(2+3*4-1) # ANS : 13
print(4/2) # ANS : 2.0 # floting print devision
print(2/4) # ANS : 0.5
print(4//2) # ANS : 2 # integre division
print(2//4) # ANS : 0
print(2**3) # ANS : 8 # double multipl... |
dfbfa7405a6b4f80ab61db86d87e027fc03d3d2e | cipher813/dsp | /python/hackerrank/35set.py | 179 | 3.71875 | 4 | def intersect_lists_2(list1, list2):
for e in list2:
list1.append(e)
print(list1)
s = set(list1)
print(s)
return s
intersect_lists_2([1,2,3],[3,4,5])
|
79208fd23e131d46ccc1034c01bb5900dd0437e5 | xblh2018/LeetcodePython | /longest_valid_parentheses.py | 1,585 | 4.09375 | 4 | #!/usr/bin/env python
'''
Leetcode: Longest Valid Parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
For "(()", the longest valid parentheses substring is "()", which has length = 2.
Another example is ")()())", where the long... |
ee8352a3ddef6e59b4b2e0b1102de0f1f0b8d3ef | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | /students/MicahBraun/Lesson 10/Great_Circle/great_circle_v0.py | 956 | 3.703125 | 4 | # -------------------------------------------------------------------------------------
# PROJECT NAME: great_circle_v0.py
# NAME: Micah Braun
# DATE CREATED: 11/30/2018
# UPDATED:
# PURPOSE: Lesson 10 final
# DESCRIPTION: Function is left un-optimized for the C/static language (no type dec-
# -larations ... |
ee6f4d725081191d530c477fc2033eece319db04 | nao37/Project_Euler | /0-9/problem4.py | 873 | 3.5625 | 4 | def main():
a, b, c = '9', '8', '9'
while True:
division_num = 999
num_array = [a, b, c, c, b, a]
integer = ''
for i in num_array:
integer += i
while division_num >= 100:
if int(integer) / division_num >= 1000:
break
eli... |
5daaee1a7da1a224c9fcb5f18a168416833b4e20 | zhanghuihb/python | /python/test/Test4.py | 239 | 3.9375 | 4 | import time;
# 判断现在是这一年的第几天?
print(time.localtime(time.time()))
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())))
print("it is the ", time.strftime("%j", time.localtime(time.time())), " day") |
1ff936d07c46b4ca5f258df76bc0cb982d269c7c | carlosafdz/pensamiento_computacional_python | /primitivos/ciclos.py | 304 | 3.953125 | 4 |
a = int(input("primer numero: "))
b = int(input("numero maximo: "))
while a<=b:
print(a)
a=a+1
frutas = ['manzana', 'pera', 'nanranja', 'sandia']
objeto = {'nombre':'carlos', 'apellido':'alberto','edad':21}
print(objeto.keys())
for i in range(b):
print(i)
for i in frutas:
print(i)
|
5b21e204906659200bbee803d444f7f4dfcec2f6 | huangj485/binary-division | /main.py | 668 | 3.625 | 4 | import argparse
import division
# Initialize parser
parser = argparse.ArgumentParser(description = "Multiply A and B with Booth's Algorithm")
# Define args
parser.add_argument("-A", type=int, required=True, help = "dividend")
parser.add_argument("-B", type=int, required=True, help = "divisor")
parser.add_argument(... |
4eed52830cbd94e693731e549bfb9e7f69f06d0d | jdavisson87/Udemy_AutomatedTesting | /PythonRefresher/01_variables/code.py | 152 | 3.625 | 4 | # x = 15
# price = 9.99
# discount = 0.2
# result = price * (1 - discount)
# print(result)
a = 25
b = a
print(a)
print(b)
a = 16
print(a)
print(b) |
346c2d07ac34b1ef307df0fe1fe64f96572968db | bio-chris/Python | /LeetCode/LongestCommonPrefix.py | 400 | 3.5 | 4 | """"
Write a function to find the longest common prefix string amongst an array of strings.
"""
array = ["endanger", "irregulgar", "undo", "tricycle", "triangle"]
from difflib import SequenceMatcher
from difflib import get_close_matches
"""
def similar(a, b):
return SequenceMatcher(None, a, b).ratio()
prin... |
22c95200d48d0fb6f8c9ae09d27c5894bbe58085 | olyzhang/leetcode_python | /array/888 Fair Candy Swap.py | 417 | 3.640625 | 4 | class Solution:
def fairCandySwap(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: List[int]
"""
diff = (sum(A) - sum(B)) / 2
A = set(A)
for b in set(B):
if int(diff + b) in A:
return (int(diff + b), b)
if __... |
68eb31e2915b3aaeee8f89939d95c6e81c960703 | JakaMale/p1 | /Naloge/Dnrazredi.py | 977 | 3.65625 | 4 |
class Rezalnik:
def __init__(self):
self.s = []
self.dol = 2
def razrezi(self,s):
new = []
self.s=s
for i in range(0, len(s), self.dol):
new.append(s[i: i + self.dol])
return new
def nastavi_dolzino(self,dol):
self.dol=dol
##########... |
e0120bf76359dabbe71f7cae8d6b5594e5f744b0 | DhruvBhagadia/Tic-Tac-Toe-Python- | /Tic-Tak-Toe.py | 2,313 | 4.03125 | 4 | import random
def drawOnBoard(whatToDraw):
k = 0
index = -1
while(k<=6):
if(k%2 == 0):
i = 1
while(i<=3):
print(" --- ", end="")
i = i+1
print(" ", end="\n")
else:
j = 1
while(j<=4):
... |
edd562ec214a7c70d94b4f0ce63852e049d69912 | minimum-hsu/tutorial-python | /lesson-06/02/without_exception.py | 401 | 3.59375 | 4 | #!/usr/bin/env python3
import sys
def throw_exception():
names = ['Alice', 'Bob', 'Charlie']
for i in range(3):
print(names[i])
if __name__ == '__main__':
try:
throw_exception()
except IndexError as err:
print('[Error]', err, file = sys.stderr)
else:
print('no exc... |
59e7f2e078328eac5c25f2a05c74bc95c6a63ccf | siikamiika/scripts | /filename-fix.py | 1,010 | 3.609375 | 4 | #!/usr/bin/env python3
import os
import sys
REPLACEMENTS = {}
for c in 'öäåÖÄÅ':
REPLACEMENTS[c.encode('utf-8').decode('latin-1')] = c
def fix_path(path):
for r in REPLACEMENTS:
path = path.replace(r, REPLACEMENTS[r])
return path
def rename_path(path, subdir):
new_path = fix_path(path)
... |
cf51d34419ce3108ecdcb4e87b757d6a174d4173 | pranavj1001/CompetitiveProgramming | /Python/queensAttack2.py | 3,161 | 3.5625 | 4 | # The question for this solution can be found at https://www.hackerrank.com/challenges/queens-attack-2/problem
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the queensAttack function below.
def queensAttack(n, k, r_q, c_q, obstacles):
count = 0
if n == 1:
return... |
dc2be5e32f1185d6f40a8a583dfd5b29ecc89970 | Covax84/CodeWars | /alphabet_position.py | 299 | 3.921875 | 4 | def alphabet_position(text: str) -> str:
""" Input: text as string
Output: string with every letter replaced with its position in the alphabet
replaced characters separated by one space
"""
return ' '.join([str(ord(x.lower()) - 96) for x in text if x.isalpha()])
|
846a3fe03af5caddc7a2f8091e4fe1f8ea6fde3f | harrisonheld/SystemsOfEquations | /solvingSystemsOfEquations.py | 806 | 4 | 4 | from sympy import *
from sympy.plotting import (plot, plot_parametric)
import mpmath
# declare your variables
a,b = symbols('a,b')
# set up your equations. these are assumed to be equal to zero
# so if you wanted a = 2b, you would rearrange it into a - 2b (= 0)
# and if you wanted a + b = 12, you would rearra... |
e8be94c1326674aab4ca141591f04e85fcc5588b | acttx/Python | /Comp Fund 2/Project1/sort_search_funcs.py | 5,064 | 4.3125 | 4 | def bubble_sort(obj_list):
sorted = False
n = len(obj_list) - 1
while not sorted and n > 0:
sorted = True
for i in range(n):
if obj_list[i].compare(obj_list[i + 1]) > 0:
sorted = False
obj_list[i], obj_list[i + 1] = obj_list[i + 1], obj_list[i]
... |
f850aed56b0f8dacf57616dee5ea10716692dc02 | CraxY-Codes/cmp104 | /assignment.py | 1,593 | 3.953125 | 4 | import math
msg = input('what shape would you like to find the area?')
#msg triangle
if msg == 'triangle':
base = int(input('what is the base?'))
height = int(input('what is the height?'))
area = 1/2 * (base * height)
print('the area of {}= {}'.format(msg, area))
#msg rectangle
elif msg =... |
073b6c9873aee4c8a7c4464c881a5c3d9a89b25c | chansen736/sudokudo | /src/solver.py | 1,041 | 3.53125 | 4 | import sudoku
class Solver:
def __init__(self):
self._puzzle = sudoku.Sudoku()
def load(self, filename):
"""
Reads a puzzle from a file. The file is of the format:
<size of puzzle: N>
<row1 of puzzle>
...
<rowN of puzzle>
"""
... |
812b4baa153affb542468c72640cc7093de8853e | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_3_neat/16_0_3_shubhamkrm_coin.py | 1,187 | 3.609375 | 4 | import math
def convert(num,base):
rev=1
output=0
while(num>0):
digit = num%base;
rev = rev*10+digit
num/=base
while (rev>0):
digit = rev%10
output = output*10+digit
rev/=10
output/=10
return output
def interpret(num,base):
i=0
output = 0
while (num>0):
output+=(num%10)*(base**i)
i+=1
num/=... |
ffaa1a2f8115310f0d622da6553003d3bc45628e | cookie223/startingtocode | /strStr.py | 256 | 3.5625 | 4 | import sys
def strStr(haystack,needle):
try:
return haystack.index(needle)
except:
return -1
if __name__=="__main__":
if len(sys.argv)==3:
print strStr(sys.argv[1],sys.argv[2])
else :
print "Invalid input" |
162ed23153a6921e9e1f17934269efc5848f0fe6 | Alvin2580du/alvin_py | /business/stepTwo/blocking/comparision/comparison.py | 12,913 | 3.53125 | 4 | """ Module with functionalities for comparison of attribute values as well as
record pairs. The record pair comparison function will return a dictionary
of the compared pairs to be used for classification.
"""
Q = 2 # Value length of q-grams for Jaccard and Dice comparison function
# =======================... |
9b0e7daceb49492e0894e8ba34d58715c5127edb | kj808/2019Probably-Interesting-Data | /libraries/kmeans.py | 1,628 | 3.5625 | 4 | def assign(data,centroids):
import numpy as np
#print("----ASSIGN----")
#for all points
for point in data:
#create an array with all the distances from the point to the centroids
dist=np.sqrt(np.sum((point[1:]-centroids)**2, axis=1))
#Grab the centorid that's closest
clus... |
c08367d0545f2db93efbf5aee2c972133fbadec5 | VYatharth/Algorithms-N-DS | /DataStructures/Linked Lists/Implementation.py | 5,018 | 4.1875 | 4 | class Node():
def __init__(self, data): #When instantiating a Node, we will pass the data we want the node to hold
self.data = data #The data passed during instantiation will be stored in self.data
self.next = None #This self.next will act as a pointer to the next node in the list. When creating a n... |
28175fd121a7e73d76cd12eaa473afbb3013cc96 | RadkaValkova/SoftUni-Web-Developer | /Programming Advanced Python/Tuples and sets exercise/04 count_symbols.py | 381 | 3.6875 | 4 | def get_unique_symbols(text):
symbols_dict = {}
for symbol in text:
if symbol not in symbols_dict:
symbols_dict[symbol] = 0
symbols_dict[symbol] += 1
return symbols_dict
def print_results(result):
for key,value in sorted(result.items()):
print(f'{key}: {value} time/... |
3e9355354b7c3e3c5cc209bf74b659bb8e2dc4f0 | honghen15/checkio_ | /number-radix.py | 1,134 | 3.75 | 4 | def checkio(str_number, radix):
dict_base = { '0':0, '1':1,'2':2,'3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9,
'A':10, 'B':11, 'C':12, 'D':13, 'E':14, 'F':15, 'G':16, 'H':17,
'I':18, 'J':19, 'K':20, 'L':21, 'M':22, 'N':23, 'O':24, 'P':25,
'Q':26, 'R':27, 'S':... |
eeae916ba4ba7c625dd42484a6205362083b1034 | uit-no/python-course-2016 | /notebooks/data_in_python/pet_1.py | 620 | 3.640625 | 4 | class Pet:
def __init__(self, name):
self.name = name
self.hunger = 0
self.age = 0
self.pets_met = set()
def advance_time(self):
self.age += 1
self.hunger += 1
def feed(self):
self.hunger = 0
def meet(self, other_pet):
... |
92d4564d0af80fa4637de470af47832927458f6f | atomr3/389Rfall18 | /week/4/writeup/stub.py | 2,681 | 3.5 | 4 | """
Use the same techniques such as (but not limited to):
1) Sockets
2) File I/O
3) raw_input()
from the OSINT HW to complete this assignment. Good luck!
"""
import socket
import re
host = "cornerstoneairlines.co" # IP address here
port = 45 # Port here
# I like color in my shell
clas... |
3b92ce9e509bcff38f87806b4abc41dbe72b3ee6 | JagadeeshmohanD/PythonTutorials | /loopsDemo/forloopDemo4.py | 180 | 3.53125 | 4 | l1=["Rahul","Rajeev","Raji"]
l2=["python","java","js"]
l3=["India","Australia","USA"]
for a in l1:
for b in l2:
for c in l3:
print(a + " " + b + " " + c)
|
f7f2ff3f23557a7a1844ec21ea84fadd0fdfa104 | agungap22/Latihan | /6_task.py | 993 | 3.78125 | 4 |
# def factorial(n) :
# if n == 0:
# return 1
# elif n == 1:
# return 1
# else:
# i = n
# hasil = 1
# while i != 1:
# hasil *= i
# i -= 1
# return hasil
# n = int(input("Nilai "))
# print (factorial(n))
# def fizz(n):
... |
6ac43b6bc7ff61430f95d47efac1ba44abd38688 | ramohse/dsp | /math/matrix_algebra.py | 2,133 | 3.546875 | 4 | # Matrix Algebra
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 5 18:26:06 2016
@author: ramohse
Defines matrices and vectors and uses Python/numpy to check the hand-written
work done on linear algebra
"""
import numpy as np
A = np.matrix([[1, 2, 3], [2, 7, 4]])
B = np.matrix([[1, -1], [0, 1]])
C = np.matrix([[5, ... |
3a2fe3959d5a522b7da2992cf41b81206482b54f | PhilipeRLeal/Classes_and_Objects_in_Python | /Classes/Classes_e_funcoes_1.py | 3,002 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 20 11:29:24 2018
@author: Philipe Leal
"""
class Point: # definicao de classe
def __init__(self, x=0, y=0): # funcao de iinicializacao da classe criada
self.x = x # self.x e self.y são atributos do objeto Point
self.y = y # self.x e self.y s... |
efe9b7a7dda2a3d2a983f008e67171bf547a14c3 | Bertram-Liu/Note | /NOTE/02_PythonBase/day11/exercise/mysum_recursion.py | 378 | 3.796875 | 4 | # 练习:
# 用递归的方式求和
# def mysum_recursion(n):
# ...
# print(mysum_recursion(100)) # 5050
# def mysum_recursion(n):
# if n == 1:
# return 1
# r = n + mysum_recursion(n - 1)
# return r
def mysum_recursion(n):
if n == 1:
return 1
return n + mysum_recursion(n - 1... |
be5d0976fa48799d3cba7aa30a49f347d70f4611 | tensorbro400/learning-python | /fizzbuzz.py | 355 | 3.765625 | 4 | #This code is best for future use of this program
for i in range(1, 101):
fizz = 3
buzz = 5
fizzbuzz = fizz * buzz
if i % fizzbuzz == 0:
print("FizzBuzz")
continue
elif i % fizz == 0:
print("Fizz")
continue
elif i % buzz == 0:
print("Buzz")
co... |
94aed0ec5e9abcc1b6882fedf44c3858d4940bbb | thminh179/TruongHoangMinh-Fundamental-C4E18 | /Session 3/add_and_update_list.py | 509 | 4.0625 | 4 | hobby=["car", "tech", "grill"]
# #add
# add = input("Name one thing you want to add. ")
# hobby.append(add)
# print("here are your favorite things so far:", end='')
# print((*hobby), sep=', ')
# #update
for index, item in enumerate(hobby):
print("{0}. {1}".format(index+1, item))
position = int (input("Which po... |
439b7c67ff065f42d883402fe60b1221fcba56be | shweta2425/ML-Python | /Week2/List12.py | 250 | 3.8125 | 4 | # Write a Python program to get the difference between the two lists
from Week2.Utilities import utility
class List12:
lst1 = [1, 2, 3, 4, 5, 6]
lst2 = [32, 2, 4, 65, 2, 1]
obj = utility.User.Diff(lst1, lst2)
print(obj)
|
c4732d63492c06e01dbf9868ec7caaa1720a6817 | mikeodf/Python_Graphics_Animation | /ch2_prog7_ball_collisions_class_1.py | 4,682 | 4.0625 | 4 | """
Program name: ball_collisions_class_1.py
Objective: Two balls moving under the influence of gravity.
Keywords: canvas, class, ball, bounce, gravity, time, movement
============================================================================79
Explanation: A simplified equation of motion that inclused the infl... |
e2b144b45b79ad1c89b68aded6591661ae2aa37c | nahgnaw/data-structure | /exercises/string/anagram_grouping.py | 945 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
Note:
For the return value, each inner list's elements must follow the lexicographic order.
All inputs will b... |
9d7ef7fa81faa988232f153a145cdf9155ced240 | big-wave-dave/basics4fun | /08_fileIO.py3 | 1,259 | 4.5 | 4 | # Basically, file input is reading from a file and output is writing to one.
# To start, we need a file to read from and one to write to.
# input.txt is what we read from and output.txt is what we write to.
# There are a few flags that can be used when opening files for io that
# tell python what to do with the file:
... |
b8d3e09130ad36f8f647c9f1f5b391a24b263f11 | abhro/exercism-solutions | /python/pangram/pangram.py | 179 | 4.09375 | 4 |
from string import ascii_lowercase
def is_pangram(s):
s = s.lower()
for letter in ascii_lowercase:
if letter not in s:
return False
return True
|
06d77135dda0129709f3d692b3fe5e1224c3d5ff | Mahalinoro/python-ds-implementations | /linked lists/singly_linked_list.py | 7,309 | 4.34375 | 4 | # Linked Lists (with a tail reference) + relevant primary methods
# Node Class
class Node:
def __init__(self, value = None):
self.value = value
self.next = None
# Method which returns the value of a node
# Time Complexity => O(1)
# Space Complexity => O(1)
def getValue(self):
... |
1713aa6e0fa02384f155054f2d3c42252efcc206 | helenaj18/Gagnaskipan | /Tímadæmi/Tímadæmi 4/power.py | 130 | 3.703125 | 4 |
def power(base, exp):
if exp == 0:
return 1
else:
return base * power(base, exp-1)
print(power(2,-3))
|
3f56c9edefcef6a49582a6edab900dc5de4a0bac | Utkarshmalik99/DSA-GeeksforGeeks | /Recursion/Possible Words From Phone Digits.py | 975 | 4.03125 | 4 | #User function Template for python3
phone = ["abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"]
def printString(digits,n,res,string="",index=0):
if index == n:
res.append(string)
return
for i in range(len(phone[digits[index]-2])):
string += phone[digits[index]-2][i]
printString(... |
1ce7d65bba75e56d076e2d9fffceed6d882d76d9 | hschilling/dln_rover | /dln_rover.py | 1,614 | 3.625 | 4 | '''
This is the file that defines all the objects the
students will create and call methods on.
The methods, in turn, will send BlueTooth messages
to the NXT
'''
import nxt.locator
class Robot(object):
'''The driving part of the rover'''
def __init__(self, brick):
self.brick = brick
def timeDrive(self... |
6eab42cb6a6ebefe0e49cd3c61be957dad172eae | wuruchi/nand2tetris1 | /assembler/symboltable.py | 1,447 | 3.734375 | 4 | #!/usr/bin/python
class SymbolTable():
"""
Stores memory addresses and variable values
"""
def __init__(self):
self._table = {"SP": 0,
"LCL": 1,
"ARG": 2,
"THIS": 3,
"THAT": 4,
"R... |
e1b1dc5a3e6c62da8869015f8ef3e88777d1cfec | MilanaShhanukova/programming-2021-19fpl | /shapes/square.py | 268 | 3.65625 | 4 | """
Programming for linguists
Implementation of the class Square
"""
from shapes.rectangle import Rectangle
class Square(Rectangle):
"""
A class for squares
"""
def __init__(self, uid: int, length: int):
super().__init__(uid, length, length)
|
08a0d7b77bf11da438467dd2f5d32ac3b5a2a40a | janakuz/Project-Euler | /P9.py | 503 | 3.671875 | 4 | #a=m**2-n**2, b=2mn, c=m**2+n**2
#m**2+mn=tripleSum/2, m and n coprime, m-n odd
import math
def gcd(a,b):
while (a != b):
if (a > b):
a -= b
else:
b -= a
return a
def pythagoreanTriples(tripleSum):
m = int(round(math.sqrt(tripleSum/2)))
while (m>0):... |
a960bca7ff17a16b60e58796bd7e3f04d9de3920 | jocelinoFG017/IntroducaoAoPython | /01-Cursos/GeekUniversity/Seção07-Coleções/Collections_Deque.py | 500 | 3.890625 | 4 | """
Módulo Collections - Deque
Podemos dizer que o Deque é uma lista de alta performance
"""
# Fazendo o import
from collections import deque
# Criando deques
deq = deque('geek')
print(deq)
# Adicionando elementos no deque
deq.append('y') # Adiciona no final da lista
print(deq)
deq.appendleft('k') # Adiciona no ... |
227024d1547c354e5c3ad2c130409bfdd86c51a4 | huntermthws/advent-of-code-2018 | /day1.py | 761 | 3.875 | 4 |
#Part 1
#Open file input.txt and read line by line. Adding the value of the line to frequency. Print frequency.
def part1(values):
frequency = 0
for value in values:
frequency += value
print(frequency)
def part2(values):
individual_frequency = set()
frequency = 0
while ... |
4c84bc0f21edc9c36b3e30dd70663c011259825a | maciejwieczorek/python | /lekcja_1/zad_5.py | 662 | 3.8125 | 4 | print('Podaj ilosc liczb :')
n = int(input())
i = 0
j = 0
tablica=[]
for i in range((n)):
liczba = input()
tablica.append(int(liczba))
print('Wpisz 1 posortuje rosnaco')
print('Wpisz 2 posortuje malejaco')
wybor = int(input())
print('wybierz zakres sortowania')
print('Zakres od : ')
zakres ... |
879ec38f74a20936b74f9f1f0d9b019eb14ab698 | wzz482436/python_Text | /07day/03-输入一个数判断大小.py | 227 | 3.578125 | 4 | number = int(input("请输入一个数字"))
'''
= 赋值运算符 a = 1
== 条件判等 a == 1
'''
if number == 50:#判断你输入进来的数是不是等于50
print("哈哈哈")
else:
print("呵呵呵")
|
74a31d4a315675d62614630aac25ffb3a9822682 | howeltri/miscrepo-howeltri | /dictComprehensionExamples.py | 723 | 3.765625 | 4 | new_dict = {num: num**2 for num in [1,2,3,4,5]}
instructor = {'name': "sam", 'city': 'ashburn', 'pal': 'scout'}
yelling_instructor = {key.upper():val.upper() for key, val in instructor.items()}
yelling_instructor_logic = {(key.upper() if key == "pal" else key):val.upper() for key, val in instructor.items()}
answer = {l... |
2c7eff7af6d5fce54d88c03f85fc291f0c2676d1 | ms-shakil/52-problems-and-solve | /problem_eighteen.py | 167 | 3.9375 | 4 | # word count by input sentence
value = input("Enter the sentence:")
def MyFunction(val):
value = val.split(" ")
print("count = ",len(value))
MyFunction(value)
|
ed122ddfaa239f9a2b617a743bf44e00369055d2 | eazow/leetcode | /405_convert_a_number_to_hexadecimal.py | 461 | 3.546875 | 4 | class Solution(object):
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0:
return "0"
map = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"]
hex = ""
for i in range(8):
hex = map[num & 0xf] + ... |
da9db7611acb298e917383a038f1187b55ad32af | rwehner/rl | /homework/Python2_Homework03/src/countext.py | 850 | 3.671875 | 4 | """
Examine the contests of CWD and print out how may files
of each extension are there.
"""
import glob
import os
def countext():
files = glob.glob('*')
extensions = {}
for file in files:
name, ext = os.path.splitext(file)
extensions[ext] = extensions.get(ext, 0) + 1
retur... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.