blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
9f7a5977df4e57f7c7c5518e4e3bc42f517d1856 | matthew-lu/School-Projects | /CountingQueue.py | 1,823 | 4.125 | 4 | # This program can be called on to create a queue that stores pairs (x, n) where x is
# an element and n is the count of the number of occurences of x.
# Included are methods to manipulate the Counting Queue.
class CountingQueue(object):
def __init__(self):
self.queue = []
def __repr__(s... | true |
421acdd0c0bd12526592bed9d95c9578552f188e | Daoud-Hussain/Python-Rock-Paper-Scissor-game | /game.py | 1,112 | 4.28125 | 4 | while True:
print( "*****Rock Paper Scissor Game****")
import random
comp = random.randint(1,3)
if comp == 1:
computer = 'r'
elif comp == 2:
computer = 'p'
else:
computer = 's'
player = input("Enter 'r' for rock, 's' for scissor, 'p' for paper: ")
if player == 'r'... | false |
8464016eb57ab1d72628555c417586a544038d0d | Dennysro/Python_DROP | /8.5_DocStrings.py | 880 | 4.3125 | 4 | """
Documentando funções com Docstrings
- Serve para deixar o código mais claro para que for ler.
- Podemos ter acesso à documentação de uma função em Python utilizando 2 formas:
1. __doc__ como no exemplo:
print(diz_oi.__doc__)
2. print(help(diz_oi))
"""
def diz_oi():
"""Uma função s... | false |
c698040822bc3cdec690b166ad4a930bba3207bf | Dennysro/Python_DROP | /10.0_Utilizando_Lambdas.py | 1,720 | 4.875 | 5 | """
Utilizando Lambdas
Conhecidas por expressões Lambdas ou simplesmente lambdas, são funções sem nome.
Ou seja, anônimas.
#Função em Python:
def soma(a, b):
return a+b
def funcao(x):
return 3 * x + 1
print(funcao(4))
"""
# Expressão Lambda
lambda x: 3 * x + 1
# E como utilizar ... | false |
717e07ce6e76ff6606bf902af61dd31db3457ffb | vgswn/lab_codes | /SIX/COD/Lab/Q1.py | 959 | 4.125 | 4 | _end = '_end_'
def make_trie(*words):
root = dict()
for word in words:
current_dict = root
for letter in word:
current_dict = current_dict.setdefault(letter, {})
current_dict[_end] = _end
return root
def in_trie(trie, word):
current_dict = trie
for lette... | false |
8949fd91df9d848465b03c7024e7516738e72c8e | jtew396/InterviewPrep | /linkedlist2.py | 1,651 | 4.21875 | 4 | # Linked List Data Structure
# HackerRank
#
#
# Node class
class Node:
# Function to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
# LinkedList class
class LinkedList:
# Function to initialize the LinkedList class
def __init__(self):
s... | true |
a624e3d14acd2154c5dc156cfaa092ab1767d6a5 | jtew396/InterviewPrep | /search1.py | 1,154 | 4.25 | 4 | # Cracking the Coding Interview - Search
# Depth-First Search (DFS)
def search(root):
if root == None:
return
print(root)
root.visited = True
for i in root.adjacent:
if i.visited == false:
search(i)
# Breadth-First Search (BFS) - Remember to use a Queue Data Structure
def ... | true |
78e04dee445264cd06b68053f1944def79f1746d | jtew396/InterviewPrep | /mergesort3.py | 1,617 | 4.15625 | 4 | # Python program for implementation of MergeSort
# Merges two subarrays of arr[].
# First subarray is arr[l..m]
# Second subarray is arr[m+1..r]
def merge(arr, left, middle, right):
n1 = middle - left + 1
n2 = right - middle
# create temp arrays
LeftArr = [0] * (n1)
RightArr = [0] * (n2)
# Copy data to temp ar... | false |
b288d4d0bb10fe3fa47c578349f5070afcd1282c | maryb0r/geekbrains-python-hw | /lesson05/example01.py | 539 | 4.34375 | 4 | # Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем.
# Об окончании ввода данных свидетельствует пустая строка.
with open("file01.txt", "w") as f_obj:
line = None
while line != '':
line = input("Type your text >>> ")
f_obj.write(f"{line... | false |
1e94eb4654f5f61e11fbc61a382904a4ab393828 | maryb0r/geekbrains-python-hw | /lesson04/example05.py | 828 | 4.125 | 4 | # Реализовать формирование списка, используя функцию range() и возможности генератора.
# В список должны войти четные числа от 100 до 1000 (включая границы).
# Необходимо получить результат вычисления произведения всех элементов списка.
# Подсказка: использовать функцию reduce().
from random import randint
from ... | false |
ffbd1535e7f9c25e817c10e31e0e6812a7645724 | knpatil/learning-python | /src/dictionaries.py | 686 | 4.25 | 4 | # dictionary is collection of key-value pairs
# students = { "key1":"value1", "key2": "value2", "key3": "value3" }
# color:point
alien = {} # empty dictionary
alien = {"green":100}
alien['red'] = 200
alien['black'] = 90
print(alien)
# access the value
print(alien['black'])
# modify the value
alien['red'] = 500
p... | true |
7b3f5e98d0ec4f94764e65e70a68c542f44ea966 | knpatil/learning-python | /src/lists2.py | 2,077 | 4.46875 | 4 |
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
# sort a list by alphabetical order
# cars.sort()
# print(cars)
#
# cars.sort(reverse=True) # reverse order sort
# print(cars)
print(sorted(cars)) # temporarily sort a list
print(cars)
cars.reverse()
print(cars)
print(len(cars))
# print(cars[4]) # exception... | true |
a87bf15fb1e4f742f5f31be7a1af84276ffe6fc2 | MaxAttax/maxattax.github.io | /resources/Day1/00 - Python Programming/task4.py | 808 | 4.40625 | 4 | # Task 4: Accept comma-separated input from user and put result into a list and into a tuple
# The program waits until the user inputs a String into the console
# For this task, the user should write some comma-separated integer values into the console and press "Enter"
values = input() # Use for Python 3
# After ... | true |
2823dce222d6d18b8e901786b78aa696d53effd4 | ek17042/ORS-PA-18-Homework02 | /task1.py | 872 | 4.25 | 4 | def can_string_be_float(user_value):
allowed_characters = ["0","1","2","3","4","5","6","7","8","9",".","-"]
for x in user_value:
if x not in allowed_characters:
return False
nr_of_dots = 0
for x in user_value:
if x == ".":
nr_of_dots = nr_of_dots + 1
if n... | false |
e829a743405b49893446c705272db2f7323bb329 | Sharanhiremath02/C-98-File-Functions | /counting_words_from_file.py | 281 | 4.375 | 4 | def count_words_from_file():
fileName=input("Enter the File Name:")
file=open(fileName,"r")
num_words=0
for line in file:
words=line.split()
num_words=num_words+len(words)
print("number of words:",num_words)
count_words_from_file() | true |
7c821b9a5102495f8f22fc21e29dd9812c77b3bd | chetanDN/Python | /AlgorithmsAndPrograms/02_RecursionAndBacktracking/01_FactorialOfPositiveInteger.py | 222 | 4.125 | 4 | #calculate the factorial of a positive integer
def factorial(n):
if n == 0: #base condition
return 1
else:
return n * factorial(n-1) #cursive condition
print(factorial(6))
| true |
9bbcd87d994a200ebe11bc09ff79995dd74eac0a | GBaileyMcEwan/python | /src/hello.py | 1,863 | 4.5625 | 5 | #!/usr/bin/python3
print("Hello World!\n\n\n");
#print a multi-line string
print(
'''
My
Multi
Line
String
'''
);
#concatinate 2 words
print("Pass"+"word");
#print 'Ha' 4 times
print("Ha" * 4);
#get the index of the letter 'd' in the word 'double'
print("double".find('d'));
#print a lower-case version of the stri... | true |
34ad45e897f4b10154ccf0f0585c29e1e51ad2f8 | EwarJames/alx-higher_level_programming | /0x0B-python-input_output/3-to_json_string.py | 315 | 4.125 | 4 | #!/usr/bin/python3
"""Define a function that returns a json."""
import json
def to_json_string(my_obj):
"""
Function that convert json to a string.
Args:
my_obj (str): Object to be converted.
Return:
JSON representation of an object (string)
"""
return json.dumps(my_obj)
| true |
431384abd81af78ff79355d261528645cf9c100b | pi408637535/Algorithm | /com/study/algorithm/daily/diameter-of-binary-tree.py | 1,370 | 4.15625 | 4 | '''
树基本是递归。
递归:四要素
本题思路:left+right=diameter
https://www.lintcode.com/problem/diameter-of-binary-tree/description
'''
#思路:
#Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
class Solution:
"""
@param root: a r... | true |
8661d933bf731b111cda9345752a0307ff4adca8 | rodrigomanhaes/model_mommy | /model_mommy/generators.py | 1,794 | 4.34375 | 4 | # -*- coding:utf-8 -*-
__doc__ = """
Generators are callables that return a value used to populate a field.
If this callable has a `required` attribute (a list, mostly), for each item in the list,
if the item is a string, the field attribute with the same name will be fetched from the field
and used as argument fo... | true |
6c036ab3ae9e679019d589fbd8de8be45486773f | gbrough/python-projects | /palindrome-checker.py | 562 | 4.375 | 4 | # Ask user for input string
# Reverse the string
# compare if string is equal
# challenge - use functions
word = None
def wordInput():
word = input("Please type a word you would like to see if it's a palindrome\n").lower()
return word
def reverseWord():
reversedWord = word[::-1]
return reversedWord
def palin... | true |
881d9ba1f1dea7860a6fd2f30f62ed0f8246bea3 | marcelinoandre/python-logica-para-data-science | /07-listas-pacotes-funcoesexternas/7.10.Atividade3.py | 407 | 4.125 | 4 | from math import sqrt
lista = list(range(0,5))
for n in range(0, 5):
print("Informe o número da posição ", n+1, " da primeira lista")
lista[n] = float(input())
for n in range(0, 5):
print("Raiz quadrada: "sqrt(lista[n]))
if sqrt(lista[n]) % 1 == 0 :
print("Raiz quadrada é um valo... | false |
5ebe1f88e466c99ba52f3dd43a17e692b30c96b2 | chena/aoc-2017 | /day12.py | 2,625 | 4.21875 | 4 | """
part 1:
Each program has one or more programs with which it can communicate, and they are bidirectional;
if 8 says it can communicate with 11, then 11 will say it can communicate with 8.
You need to figure out how many programs are in the group that contains program ID 0.
For example, suppose you go door-to-door... | true |
6e33fd4e81dcfdce22916bd20d4230e472490dae | chena/aoc-2017 | /day05.py | 1,882 | 4.53125 | 5 | """
part 1:
The message includes a list of the offsets for each jump.
Jumps are relative: -1 moves to the previous instruction, and 2 skips the next one.
Start at the first instruction in the list. The goal is to follow the jumps until one leads outside the list.
In addition, these instructions are a little strange;... | true |
d42ecceedf925c992c64ad311cbf801eb3757f84 | yasukoe/study_python | /comprehension.py | 253 | 4.375 | 4 | # comprehension 内包表記
# print([i for i in range(10)])
# print([i*3 for i in range(10)])
# print([i*3 for i in range(10) if i % 2 ==0])
print(i*3 for i in range(10) if i % 2 ==0) #Generator
print({i*3 for i in range(10) if i % 2 ==0}) #set type
| false |
164dda3ecb9d27c153dbc9d143ba05437c47f656 | luisprooc/data-structures-python | /src/bst.py | 1,878 | 4.1875 | 4 | from binary_tree import Node
class BST(object):
def __init__(self, root):
self.root = Node(root)
def insert(self, new_val):
current = self.root
while current:
if new_val >= current.value:
if not current.right:
current.right = Node(new_... | true |
757cfb65fc22c1f8f9326a25018defb7aafbad56 | 2FLing/CSCI-26 | /codewar/camel_case.py | 531 | 4.25 | 4 | # Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case).
# Examples
# to_camel_case("the-stealth-warrior") # r... | true |
5a5581ad8604d9d61d579ab1661be5c7d70cdcb6 | rodrigocamarena/Homeworks | /sess3&4ex4.py | 2,915 | 4.5 | 4 | print("Welcome to the universal pocket calculator.")
print("1. Type <+> if you want to compute a sum."
"\n2. Type <-> if you want to compute a rest."
"\n3. Type <*> if you want to compute a multiplication."
"\n4. Type </> if you want to compute a division."
"\n5. Type <quit> if you want to exit.... | true |
7536d2a8c16cc9bda41d4a4d3894c0a8a0911446 | artemis-beta/phys-units | /phys_units/examples/example_2.py | 1,160 | 4.34375 | 4 | ##############################################################################
## Playing with Measurements ##
## ##
## In this example the various included units are explored in a fun and ##
## ... | true |
3c419f360e36ed45af7d7935aa2f824bb2dc472a | Cleancode404/ABSP | /Chapter8/input_validation.py | 317 | 4.1875 | 4 | import pyinputplus as pyip
while True:
print("Enter your age:")
age = input()
try:
age = int(age)
except:
print("Please use numeric digits.")
continue
if age < 0:
print("Please enter a positive number.")
continue
break
print('Your age is', age) | true |
bf005c98b3c7beabc0e2000cfd0cfd404010a9a9 | AlexRoosWork/PythonScripts | /delete_txts.py | 767 | 4.15625 | 4 | #!/usr/bin/env python3
# given a directory, go through it and its nested dirs to delete all .txt files
import os
def main():
print(f"Delete all text files in the given directory\n")
path = input("Input the basedir:\n")
to_be_deleted = []
for dirpath, dirnames, filenames in os.walk(path):
for... | true |
8ae3f309e572b41a3ff5205692f0ae4c90f11962 | Trenchevski/internship | /python/ex6.py | 867 | 4.21875 | 4 | # Defining x with string value
x = "There are %d types of people." % 10
# Binary variable gets string value with same name
binary = "binary"
# Putting string value to "don't"
do_not = "don't"
# Defining value of y variable using formatters
y = "Those who know %s and those who %s." % (binary, do_not)
# Printing value of... | true |
6cd204d47bb1937a024c1afa0c25527316453468 | Soares/natesoares.com | /overviewer/utilities/string.py | 633 | 4.5 | 4 | def truncate(string, length, suffix='...'):
"""
Truncates a string down to at most @length characters.
>>> truncate('hello', 12)
'hello'
If the string is longer than @length, it will cut the
string and append @suffix to the end, such that the
length of the resulting string is @length.
... | true |
066bcfb00c4f01528d79d8a810a65d2b64e8a8a2 | bchaplin1/homework | /week02/03_python_homework_chipotle.py | 2,812 | 4.125 | 4 | '''
Python Homework with Chipotle data
https://github.com/TheUpshot/chipotle
'''
'''
BASIC LEVEL
PART 1: Read in the data with csv.reader() and store it in a list of lists called 'data'.
Hint: This is a TSV file, and csv.reader() needs to be told how to handle it.
https://docs.python.org/2/library/csv.html
'''
... | true |
0982d07b0af6e12ee34a1bad96af8d9e7730bc8c | andrericardoweb/curso_python_cursoemvideo | /exercicios/ex008.py | 287 | 4.1875 | 4 | # Exercício Python 008: Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros.
m = eval(input('Uma distância em metros: '))
print('CONVERTENDO MEDIDAS')
print(f'{m/1000}km | {m/100}hm | {m/10}dam | {m}m | {m*10}dm | {m*100}cm |{m*1000}mm')
| false |
81ad7ff791adaf6dfad0b90fbb9f60c56139be6c | MagomedNalgiev/Ozon-New-Skills | /DZ_3-1.py | 609 | 4.375 | 4 | string1 = 'Съешь ещё этих мягких французских булок ДА выпей же чаю'
#Преобразуем текст в список
string1_list = string1.split()
#Выводим четвертое слово в верхнем регистре
print(string1_list[3].upper())
#Выводим седьмое слово в нижнем регистре
print(string1_list[6].lower())
#Выводим третью букву восьмого слова
print... | false |
90af163267b8d485c28169c9aeb149df021e3509 | hemenez/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 423 | 4.3125 | 4 | #!/usr/bin/python3
def add_integer(a, b):
"""Module will add two integers
"""
total = 0
if type(a) is not int and type(a) is not float:
raise TypeError('a must be an integer')
if type(b) is not int and type(b) is not float:
raise TypeError('b must be an integer')
if type(a) is fl... | true |
dbb83d0461e2f93fb463380da950cf83a61eeee4 | 28kayak/CheckIO_TestFile | /BooleanAlgebra/boolean_algebra.py | 1,299 | 4.15625 | 4 |
OPERATION_NAMES = ("conjunction", "disjunction", "implication", "exclusive", "equivalence")
def boolean(x, y, operation):
return operation(x,y)
def conv(x):
if x == 1:
x = True
else:
x = False
def conjunction(x,y):
if x == y and x == 0:
#print "T"
return 1
elif x == y and x == 1:
#print "F x and y are ... | false |
ba2c8e1e768b24f7ad7a4c00ee6ed4116d31a21a | kjigoe/Earlier-works | /Early Python/Fibonacci trick.py | 866 | 4.15625 | 4 | dic = {0:0, 1:1}
def main():
n = int(input("Input a number"))
## PSSST! If you use 45 for 'n' you get a real phone number!
counter = Counter()
x = fib(n,counter)
print("Fibonacci'd with memoization I'd get",x)
print("I had to count",counter,"times!")
y = recursivefib(n, counter)
print("And with recusion I stil... | true |
e996c9bff605c46d30331d13e44a49c04a2e29be | Kaylotura/-codeguild | /practice/greeting.py | 432 | 4.15625 | 4 | """Asks for user's name and age, and greets them and tells them how old they'll be next year"""
# 1. Setup
# N/A
# 2. Input
name = input ("Hello, my name is Greetbot, what's your name? ")
age = input(name + ' is a lovely name! How old are you, ' + name + '? ')
# 3. Transform
olderage = str(int(age) + 1)
# 4. Output... | true |
922c0d74cf538e3a28a04581b9f57f7cfb7377e4 | BstRdi/wof | /wof.py | 1,573 | 4.25 | 4 | from random import choice
"""A class that can be used to represent a wheel of fortune."""
fields = ('FAIL!', 'FAIL!', 100, 'FAIL!', 'FAIL!', 500, 'FAIL!', 250, 'FAIL!', 'FAIL!', 'FAIL!', 'FAIL!', 1000, 'FAIL!', 'FAIL!', 'FAIL!', 'FAIL!', 'FAIL!', 'FAIL!')
score = []
class WheelOfFortune:
"""A simple at... | true |
22349e2b8bc3f99956fb293d14463d71420ad45c | gustavocrod/vrp | /util.py | 1,619 | 4.21875 | 4 | from graph import *
def cost(route, graph):
"""
Funcao que computa a soma das demandas dos clientes de uma rota
:param route: rota a ser computada
:param graph: grafo
:return:
"""
cost = 0
for i in route:
edge = graph.findEdge(i)
cost += edge.demand
return cost
def... | false |
b63879f6a16ae903c1109d3566089e47d0212200 | idahopotato1/learn-python | /01-Basics/005-Dictionaries/dictionaries.py | 1,260 | 4.375 | 4 | # Dictionaries
# A dictionary is an associative array (also known as hashes).
# Any key of the dictionary is associated (or mapped) to a value.
# The values of a dictionary can be any Python data type.
# So dictionaries are unordered key-value-pairs.
# Constructing a Dictionary
my_dist = {'key1': 'value1', 'key2': 10... | true |
b5dbb2bc21aca13d23b3d3f87569877ce9951eec | idahopotato1/learn-python | /04-Methods-Functions/001-methods.py | 736 | 4.34375 | 4 | # Methods
# The other kind of instance attribute reference is a method.
# A method is a function that “belongs to” an object.
# (In Python, the term method is not unique to class instances:
# other object types can have methods as well.
# For example, list objects have methods called append, insert, remove, sort, an... | true |
abb45102966579d6e8efcc54af764ae78c20bccb | QuickJohn/Python | /test/recursion.py | 1,287 | 4.34375 | 4 | # Author: John Quick
# Recursion demonstration
def main():
print()
print('RECURSION WITH PYTHON')
print('Choose option:')
print('[1] Find factorial')
print('[2] Convert to binary')
print('[3] Fibonacci')
print()
# get choice from user
option = int(input('Pick option: \n'))
... | false |
4afb88e53ccddb16c631b2af181bb0e607a2b37b | Evakung-github/Others | /381. Insert Delete GetRandom O(1).py | 2,170 | 4.15625 | 4 | '''
A hashmap and an array are created. Hashmap tracks the position of value in the array, and we can also use array to track the appearance in the hashmap.
The main trick is to swap the last element and the element need to be removed, and then we can delete the last element at O(1) cost.
Afterwards, we need to update ... | true |
c57eab0302c15814a5f51c2cbc0fa104910eef08 | hihihien/nrw-intro-to-python | /lecture-06/solutions/exponent.py | 261 | 4.28125 | 4 | base = float(input('What is your base?'))
exp = float(input('What is your exponent?'))
num = exp
result = 1
while num > 0:
result = result * base
num = num - 1
print(f'{base} raised to the power of {exp} is: {result}. ({base} ** {exp} = {base**exp})')
| true |
ef2e1747c49dca4e17fe558704d05d50b2a11506 | kengbailey/interview-prep | /selectionsort.py | 1,507 | 4.28125 | 4 | # Selection Sort Implementation in Python
'''
How does it work?
for i = 1:n,
k = i
for j = i+1:n, if a[j] < a[k], k = j
→ invariant: a[k] smallest of a[i..n]
swap a[i,k]
→ invariant: a[1..i] in final position
end
What is selection sort?
The selection sort algorithm is a combination of searching ... | true |
0ff6efa124129922594e4e996dd1b2955e6002b8 | BethMwangi/python | /rock_paper_scissors.py~ | 1,165 | 4.21875 | 4 | #!/usr/bin/python
# Rock, paper ,scissors game
# The rules apply, i.e ,
# * Rock beats scissors
# * Paper beats rock
# * Scissors beats paper
import sys
print "Let's get started!"
player1 =raw_input("Enter your name please:") #prompts the user to input their name
player2 = raw_input("Enter your name please:")
play... | false |
6c612b3a3904a9710b3f47c0174edf1e0f15545b | spots1000/Python_Scripts | /Zip File Searcher.py | 2,412 | 4.15625 | 4 | from zipfile import ZipFile
import sys
import os
#Variables
textPath = "in.txt"
outPath = "out.txt"
## Announcements
print("Welcome to the Zip Finder Program!")
print("This program will take a supplied zip file and locate within said file any single item matching the strings placed in an accompanying text... | true |
77ee96c305f1d7d21ddae8c1029639a50627382b | SamuelHealion/cp1404practicals | /prac_05/practice_and_extension/electricity_bill.py | 1,317 | 4.1875 | 4 | """
CP1404 Practice Week 5
Calculate the electricity bill based on provided cents per kWh, daily use and number of billing days
Changed to use dictionaries for the tariffs
"""
TARIFFS = {11: 0.244618, 31: 0.136928, 45: 0.385294, 91: 0.374825, 33: 0.299485}
print("Electricity bill estimator 2.0")
print("Which tariff a... | true |
823282e7460b9d11b4d4127fa68a87352a5543ce | SamuelHealion/cp1404practicals | /prac_02/practice_and_extension/word_generator.py | 2,154 | 4.25 | 4 | """
CP1404/CP5632 - Practical
Random word generator - based on format of words
Another way to get just consonants would be to use string.ascii_lowercase
(all letters) and remove the vowels.
"""
import random
VOWELS = "aeiou"
CONSONANTS = "bcdfghjklmnpqrstvwxyz"
def first_version():
"""Requires c and v only"""
... | true |
d2539727c20ffae59e81cccadb78648b10797a5d | SamuelHealion/cp1404practicals | /prac_06/guitar.py | 730 | 4.3125 | 4 | """
CP1404 Practical 6 - Classes
Define the class Guitar
"""
VINTAGE_AGE = 50
CURRENT_YEAR = 2021
class Guitar:
"""Represent a Guitar object."""
def __init__(self, name='', year=0, cost=0):
"""Initialise a Guitar instance."""
self.name = name
self.year = year
self.cost = cost... | true |
7ed8c1c53c80c4740739308c7768e5cb65fe92e5 | SamuelHealion/cp1404practicals | /prac_02/practice_and_extension/random_boolean.py | 854 | 4.25 | 4 | """
Three different ways to generate random Boolean
"""
import random
print("Press Q to quit")
print("What random function do you want to run: A, B or C? ")
user_input = str(input("> ")).upper()
while user_input != 'Q':
if user_input == 'A':
if random.randint(0, 1) == 0:
print("False")
... | false |
6339d40839889e191b3ef8dae558cf3266b08ba8 | jamieboyd/neurophoto2018 | /code/simple_loop.py | 407 | 4.46875 | 4 | #! /usr/bin/python
#-*-coding: utf-8 -*-
"""
a simple for loop with conditionals
% is the modulus operator, giving the remainder of the
integer division of the left operand by the right operand.
If a number divides by two with no remainder it is even.
"""
for i in range (0,10,1):
if i % 2 == 1:
print (str ... | true |
86dec63990bd3ae55a023380af8ce0f38fcdf3e2 | CQcodes/MyFirstPythonProgram | /Main.py | 341 | 4.25 | 4 | import Fibonacci
import Check
# Driver Code
print("Program to print Fibonacci series upto 'n'th term.")
input = input("Enter value for 'n' : ")
if(Check.IsNumber(input)):
print("Printing fibonacci series upto '" + input + "' terms.")
Fibonacci.Print(int(input))
else:
print("Entered value is not a valid inte... | true |
e2f55129c04745dd81793e7d6867af117c988661 | rinogen/Struktur-Data | /Perkenalan List.py | 1,569 | 4.25 | 4 | # parctice with list in phyton and falsh back in first alpro 1
colors = ["red", "green" , "blue" , "yellow" ]
for i in range (len(colors)) :
print (colors[i])
print()
for i in range (len(colors) -1 , -1 , -1): # --> (panjangnya , sampai ke berapa , mundurnya berapa) #
print (colors[i])
print ()
print ()
pri... | false |
f193bf10635f1b1cc9f4f7aa0ae7a209e5f041db | Yashs744/Python-Programming-Workshop | /if_else Ex-3.py | 328 | 4.34375 | 4 | # Nested if-else
name = input('What is your name? ')
# There we can provide any name that we want to check with
if name.endswith('Sharma'):
if name.startswith('Mr.'):
print ('Hello,', name)
elif name.startswith('Mrs.'):
print ('Hello,', name)
else:
print ('Hello,', name)
else:
print ('Hello, St... | true |
012cc0af4adbfa714a4f311b729d89a9ba446d35 | Tagirijus/ledger-expenses | /general/date_helper.py | 1,213 | 4.1875 | 4 | import datetime
from dateutil.relativedelta import relativedelta
def calculateMonths(period_from, period_to):
"""Calculate the months from two given dates.."""
if period_from is False or period_to is False:
return 12
delta = relativedelta(period_to, period_from)
return abs((delta.years * 12) ... | true |
b5a66fd0978895aaabb5cb93de5a7cfabd57ad8e | yosef8234/test | /python_simple_ex/ex28.py | 477 | 4.3125 | 4 | # Write a function find_longest_word() that takes a list of words and
# returns the length of the longest one.
# Use only higher order functions.
def find_longest_word(words):
'''
words: a list of words
returns: the length of the longest one
'''
return max(list(map(len, words)))
# test
print(fin... | true |
b787971db2b58732d63ea00aaac8ef233068b822 | yosef8234/test | /python_simple_ex/ex15.py | 443 | 4.25 | 4 | # Write a function find_longest_word() that takes a list of words and
# returns the length of the longest one.
def find_longest_word(words):
longest = ""
for word in words:
if len(word) >= len(longest):
longest = word
return longest
# test
print(find_longest_word(["i", "am", "python... | true |
9b22d6e5f777384cd3b88f9d44b7f2711346fc74 | yosef8234/test | /pfadsai/07-searching-and-sorting/notes/sequential-search.py | 1,522 | 4.375 | 4 | # Sequential Search
# Check out the video lecture for a full breakdown, in this Notebook all we do is implement Sequential Search for an Unordered List and an Ordered List.
def seq_search(arr,ele):
"""
General Sequential Search. Works on Unordered lists.
"""
# Start at position 0
pos = 0
# Targ... | true |
720f5fa949f49b1fa20d7c0ae08ae397fc6fc225 | yosef8234/test | /pfadsai/03-stacks-queues-and-deques/notes/implementation-of-stack.py | 1,537 | 4.21875 | 4 | # Implementation of Stack
# Stack Attributes and Methods
# Before we implement our own Stack class, let's review the properties and methods of a Stack.
# The stack abstract data type is defined by the following structure and operations. A stack is structured, as described above, as an ordered collection of items where ... | true |
5d1b9a089f9f4c0e6b8674dafffa486f4698cdb4 | yosef8234/test | /toptal/python-interview-questions/4.py | 1,150 | 4.5 | 4 | # Q:
# What will be the output of the code below in Python 2? Explain your answer.
# Also, how would the answer differ in Python 3 (assuming, of course, that the above print statements were converted to Python 3 syntax)?
def div1(x,y):
print "%s/%s = %s" % (x, y, x/y)
def div2(x,y):
print "%s//%s = %s" % (x, ... | true |
3c39888213a9dcc78c1c0a641b9ab70c87680c0a | yosef8234/test | /pfadsai/04-linked-lists/questions/linked-list-reversal.py | 2,228 | 4.46875 | 4 | # Problem
# Write a function to reverse a Linked List in place. The function will take in the head of the list as input and return the new head of the list.
# You are given the example Linked List Node class:
class Node(object):
def __init__(self,value):
self.value = value
self.nextnode = None
#... | true |
9041e5cb16518965f170e82bdac4929e93ab0273 | yosef8234/test | /hackerrank/30-days-of-code/day-24.py | 2,826 | 4.375 | 4 | # # -*- coding: utf-8 -*-
# Objective
# Check out the Tutorial tab for learning materials and an instructional video!
# Task
# A Node class is provided for you in the editor. A Node object has an integer data field, datadata, and a Node instance pointer, nextnext, pointing to another node (i.e.: the next node in a lis... | true |
756868b809716f135bb1a27a9c35791e116a902a | yosef8234/test | /pfadsai/04-linked-lists/questions/implement-a-linked-list.py | 952 | 4.46875 | 4 | # Implement a Linked List - SOLUTION
# Problem Statement
# Implement a Linked List by using a Node class object. Show how you would implement a Singly Linked List and a Doubly Linked List!
# Solution
# Since this is asking the same thing as the implementation lectures, please refer to those video lectures and notes for... | true |
6eb333b658f76812126d0fefdb33a39e66f608bf | yosef8234/test | /pfadsai/10-mock-interviews/ride-share-company/on-site-question3.py | 2,427 | 4.3125 | 4 | # On-Site Question 3 - SOLUTION
# Problem
# Given a binary tree, check whether it’s a binary search tree or not.
# Requirements
# Use paper/pencil, do not code this in an IDE until you've done it manually
# Do not use built-in Python libraries to do this, but do mention them if you know about them
# Solution
# The f... | true |
0d349d0708bdb56ce5da09f585eaf41d8f9952c3 | yosef8234/test | /python_essential_q/q8.py | 2,234 | 4.6875 | 5 | # Question 8
What does this stuff mean: *args, **kwargs? And why would we use it?
# Answer
# Use *args when we aren't sure how many arguments are going to be passed to a function, or if we want to pass a stored list or tuple of arguments to a function. **kwargs is used when we dont know how many keyword arguments wi... | true |
ec8296cf056afef1f3ad97123c852b66f25d75cb | yosef8234/test | /pfadsai/04-linked-lists/notes/singly-linked-list-implementation.py | 1,136 | 4.46875 | 4 | # Singly Linked List Implementation
# In this lecture we will implement a basic Singly Linked List.
# Remember, in a singly linked list, we have an ordered list of items as individual Nodes that have pointers to other Nodes.
class Node(object):
def __init__(self,value):
self.value = value
self.ne... | true |
09da1340b227103c7eb1bc9800c714907939bfde | yosef8234/test | /python_ctci/q1.4_permutation_of_palindrom.py | 1,097 | 4.21875 | 4 | # Write a function to check if a string is a permutation of a palindrome.
# Permutation it is "abc" == "cba"
# Palindrome it is "Madam, I'm Adam'
# A palindrome is word or phrase that is the same backwards as it is forwards. (Not limited to dictionary words)
# A permutation is a rearrangement of letters.
import string... | true |
c117f5f321a25493ee9c3811a51e6c28d6487392 | imjching/playground | /python/practice_python/11_check_primality_functions.py | 730 | 4.21875 | 4 | # http://www.practicepython.org/exercise/2014/04/16/11-check-primality-functions.html
"""
Ask the user for a number and determine whether the number
is prime or not. (For those who have forgotten, a prime number
is a number that has no divisors.). You can (and should!)
use your answer to
[Exercise 4](/exercise/2014/02... | true |
8f13963a5059a9cbb14790645f86ff0415398108 | imjching/playground | /python/practice_python/14_list_remove_duplicates.py | 764 | 4.1875 | 4 | # http://www.practicepython.org/exercise/2014/05/15/14-list-remove-duplicates.html
"""
Write a program (function!) that takes a list and returns a new
list that contains all the elements of the first list minus all
the duplicates.
Extras:
Write two different functions to do this - one using a loop and
constructing a... | true |
35c0ab9c2e6bfb4eea6f3750b208495ce1407d03 | imjching/playground | /python/practice_python/18_cows_and_bulls.py | 1,813 | 4.21875 | 4 | # http://www.practicepython.org/exercise/2014/07/05/18-cows-and-bulls.html
"""
Create a program that will play the 'cows and bulls' game with the user.
The game works like this:
Randomly generate a 4-digit number. Ask the user to guess a 4-digit number.
For every digit that the user guessed correctly in the correct p... | true |
53937a32b059e4e9613be47b492f586eff09a06d | bkhuong/LeetCode-Python | /make_itinerary.py | 810 | 4.125 | 4 | class Solution:
'''
Given a list of tickets, find itinerary in order using the given list.
'''
def find_route(tickets:list) -> str:
routes = {}
start = []
# create map
for ticket in tickets:
routes[ticket[0]] = {'to':ticket[1]}
try:
... | true |
70cc3581b224daa3beadfc0150d31b52c30f6284 | Gachiman/Python-Course | /python-scripts/hackerrank/Medium/Find Angle MBC.py | 603 | 4.21875 | 4 | import math
def input_length_side(val):
while True:
try:
length = int(float(input("Enter the length of side {0} (0 < {0} <= 100): ".format(val))))
if 0 < length <= 100:
return length
else:
raise ValueError
except ValueError:
... | true |
a1b6391a773b23a0f5fe8e0b0a4d36bc7e03b9b0 | hobsond/Computer-Architecture | /white.py | 1,788 | 4.625 | 5 | # Given the following array of values, print out all the elements in reverse order, with each element on a new line.
# For example, given the list
# [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
# Your output should be
# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# 10
# You may use whatever programming language you'd like.
# Verbalize... | true |
2718e25886a29226c5050afe0d83c6459bd6747b | Twest19/prg105 | /Ch 10 HW/10-1_person_data.py | 1,659 | 4.71875 | 5 | """
Design a class that holds the following personal data: name, address, age, and phone number.
Write appropriate accessor and mutator methods (get and set). Write a program that creates three instances
of the class. One instance should hold your information and the other two should hold your friends' o... | true |
b33b65d4b831bcd41fac9f4cd424a65dc4589d39 | Twest19/prg105 | /3-3_ticket.py | 2,964 | 4.3125 | 4 | """
You are writing a program to sell tickets to the school play.
If the person buying the tickets is a student, their price is $5.00 per ticket.
If the person buying the tickets is a veteran, their price is $7.00 per ticket.
If the person buying the ticket is a sponsor of the play, the price is $2.00 per ticket.
... | true |
20a0d53d34ba73884e14d026030289475bb6275e | Twest19/prg105 | /chapter_practice/ch_9_exercises.py | 2,681 | 4.4375 | 4 | """
Complete all of the TODO directions
The number next to the TODO represents the chapter
and section in your textbook that explain the required code
Your file should compile error free
Submit your completed file
"""
import pickle
# TODO 9.1 Dictionaries
print("=" * 10, "Section 9.1 dictionaries",... | true |
666efab8a625d46543dab413aadd15936594a5dd | Twest19/prg105 | /4-1_sales.py | 862 | 4.5625 | 5 | """
You need to create a program that will have the user enter in the total sales amount for the day at a coffee shop.
The program should ask the user for the total amount of sales and include the day in the request. At the end of
data entry, tell the user the total sales for the week, and the average sa... | true |
a3ace412c840aac7ff86999020c0d765a5062a5d | Twest19/prg105 | /5-3_assessment.py | 2,467 | 4.21875 | 4 | """
You are going to write a program that finds the area of a shape for the user.
"""
# set PI as a constant to be used as a global value
PI = 3.14
# create a main function then from the main function call other functions to get the correct calculations
def main():
while True:
menu()
... | true |
52dd577610c57f96e36b41ee06982c873f0d55af | dougiejim/Automate-the-boring-stuff | /commaCode.py | 753 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#Write a function that takes a list value as an argument and returns
#a string with all the items separated by a comma and a space, with
#and inserted before the last item. For example, passing the previous
#spam list to the function would return 'apples, bananas, tofu, ... | true |
732a68dc8a28c98ecc93001de996919759778a2c | sakamoto-michael/Sample-Python | /new/intro_loops.py | 727 | 4.28125 | 4 | # Python Loops and Iterations
nums = [1, 2, 3, 4, 5]
# Looping through each value in a list
for num in nums:
print(num)
# Finding a value in a list, breaking upon condition
for num in nums:
if num == 3:
print('Found!')
break
print(num)
# Finding a value, the continuing execution
for num in nums:
if n... | true |
701ea9976f04c66564962c3bc7f64d89e1314120 | vivekyadav6838/Data-Structures-and-Algorithms-for-Interviews | /Python/BinaryTree/NumberOfNonLeafNodes.py | 1,524 | 4.3125 | 4 | # @author
# Aakash Verma
# Output:
# Pre Order Traversal is: 1 2 4 5 3 6 7
# Number Of non-Leaf Nodes: 3
# Creating a structure for the node.
# Initializing the node's data upon calling its constructor.
class Node:
def __init__(self, data):
self.data = data
self.right = self.left = None
# Def... | true |
8878c006639c546777ff2af254a979033560c15a | vivekyadav6838/Data-Structures-and-Algorithms-for-Interviews | /Python/LinkedList/StartingOfLoop.py | 1,519 | 4.34375 | 4 | #
#
#
# @author
# Aakash Verma
#
# Start of a loop in Linked List
#
# Output:
# 5
#
# Below is the structute of a node which is used to create a new node every time.
class Node:
def __init__(self, data):
self.data = data
self.next = None # None is nothing but null
# Creating a class for implementing ... | true |
96ca87b2c6191ffd17b5571581f5dec816529ef2 | SgtHouston/python102 | /sum the numbers.py | 249 | 4.21875 | 4 | # Make a list of numbers to sum
numbers = [1, 2, 3, 4, 5, 6]
# set up empty total so we can add to it
total = 0
# add current number to total for each number iun the list
for number in numbers:
total += number
# print the total
print(total)
| true |
b318bf9bc8d0760352b2b551697b45f24117dcb3 | starsCX/Py103 | /chap0/Project/ex12-3.py | 557 | 4.1875 | 4 | #在Python 3.2.3中 input和raw_input 整合了,没有了raw_input
age = input("How old are you?")
height = input("How tall are you?")
weight = input("How much do you weigh?")
print ("so you are %r old ,%r tall and %r heavy." %(age,height,weight))
print ("so you are %r old ,%r tall and %r heavy." %(age,height,weight))
#python2.7 的话,pri... | false |
25ceca21258ebec39c3bb51f308a1e5f136aaca4 | urmajesty/learning-python | /ex5.py | 581 | 4.15625 | 4 | name = 'Zed A Shaw'
age = 35.0 # not a lie
height = 74.0 # inches
weight = 180.0 #lbs
eyes = 'Blue'
teeth = 'White'
hair = 'Brown'
print(f"Let's talk about {name}.")
print(f"He's {height} pounds heavy.")
print("Actually that's not too heavy.")
print(f"He's got {eyes} eyes and {hair} hair.")
print(f"His teeth are usua... | true |
74ac90a14c752bbb7f61db09150bb3df3cdb7d94 | antoinemadec/test | /python/codewars/middle_permutation/middle_permutation.py | 1,069 | 4.1875 | 4 | #!/usr/bin/env python3
f = {}
def factorial(n):
if n==0:
f[n] = 1
elif n not in f:
f[n] = n*factorial(n-1)
return f[n]
def factoradics(n):
for k in range(n+2):
if factorial(k) > n:
break
r = []
for k in range(k-1,-1,-1):
d = n//factorial(k)
r... | false |
53c52d5fb29d5f8f28c56ead8f8c31dfd6f06d98 | antoinemadec/test | /python/codewars/simplifying/simplifying.py | 2,602 | 4.5 | 4 | #!/usr/bin/env python3
'''
You are given a list/array of example formulas such as:
[ "a + a = b", "b - d = c ", "a + b = d" ]
Use this information to solve a formula in terms of the remaining symbol such as:
"c + a + b" = ?
in this example:
"c + a + b" = "2a"
Notes:
Variables names are case sensitive
There ... | true |
1d5eba8fd2834bb2375016ec7ed9e8cc686f1991 | antoinemadec/test | /python/programming_exercises/q5/q5.py | 662 | 4.21875 | 4 | #!/usr/bin/env python3
print("""https://raw.githubusercontent.com/zhiwehu/Python-programming-exercises/master/100%2B%20Python%20challenging%20programming%20exercises.txt
Question:
Define a class which has at least two methods:
getString: to get a string from console input
printString: to print the string ... | true |
7f17dd1d0b9acc663a17846d838cbd79998bb79b | antoinemadec/test | /python/programming_exercises/q6/q6.py | 840 | 4.21875 | 4 | #!/usr/bin/env python3
print("""https://raw.githubusercontent.com/zhiwehu/Python-programming-exercises/master/100%2B%20Python%20challenging%20programming%20exercises.txt
Question:
Write a program that calculates and prints the value according to the given formula:
Q = Square root of [(2 * C * D)/H]
Follow... | true |
c1679cb04b4e70b555eaf1c35f5dd7ee8d5927f8 | antoinemadec/test | /python/asyncio/coroutines_and_tasks/coroutines.py | 1,304 | 4.40625 | 4 | #!/usr/bin/env python3
import asyncio
import time
# coroutine
async def main():
print('hello')
await asyncio.sleep(1)
print('world')
# coroutine
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
# coroutine
async def main_after():
print(f"started at {time.strftime('%X'... | false |
d057707ccd873e895d2caf5eec45a19e0473da84 | antoinemadec/test | /python/codewars/find_the_divisors/find_the_divisors.py | 708 | 4.3125 | 4 | #!/usr/bin/env python3
"""
Create a function named divisors/Divisors that takes an integer and returns an
array with all of the integer's divisors(except for 1 and the number itself).
If the number is prime return the string '(integer) is prime' (null in C#) (use
Either String a in Haskell and Result<Vec<u32>, String>... | true |
81cc9b7d03933d990e1a90129929d1eb78ffb108 | antoinemadec/test | /python/cs_dojo/find_mult_in_list/find_mult_in_list.py | 526 | 4.1875 | 4 | #!/bin/env python3
def find_multiple(int_list, multiple):
sorted_list = sorted(int_list)
n = len(sorted_list)
for i in range(0,n):
for j in range(i+1,n):
x = sorted_list[i]
y = sorted_list[j]
if x*y == multiple:
return (x,y)
elif x>mu... | true |
ce349e0d877be430c57a4a11990ac1cdf6096847 | GreatRaksin/Saturday3pm | /1505_functions_p4/01_functional_programming.py | 639 | 4.25 | 4 | '''Функциональный код отличается тем, что у него отсутствуют побочные эффекты.
Он не полагается на данные вне функции и не меняет их.
'''
a = 0
def increment1():
'''Вот это НЕ функциональный код'''
global a
a += 1
def increment2(a):
'''А это функциональный'''
return a + 1
nums = ['0', '1', '2',... | false |
1cbd89b34fc28fdfc949fc7b48b363df817adf71 | GreatRaksin/Saturday3pm | /1704_functions_2/02_stars_and_functions.py | 844 | 4.25 | 4 | def multiply(n, n1, n2):
print(n * n1 * n2)
fruits = ['lemon', 'pear', 'watermelon', 'grape']
# ТАК НЕ НАДО: print(fruits[0], fruits[1], fruits[2], fruits[3])
# НАДО ВОТ ТАК:
print(*fruits)
def insert_into_list(*numbers):
l = []
l.append(numbers)
return numbers
'''
*args - * позволяет передать фу... | false |
d6aabcb1f4476a9d8dbb13844e29227df4db6426 | GreatRaksin/Saturday3pm | /task1.py | 428 | 4.4375 | 4 | '''
Создать словарь со странами и их столицами
Вывести предложение:
{столица} is a capital of {страна}.
'''
countries = {
'USA': 'Minsk',
'Brazil': 'Brasilia',
'Belarus': 'Washington',
'Italy': 'Rome',
'Spain': 'Madrid'
}
for country, capital in countries.items():
print(f'{capital} is a Capital of {coun... | false |
ca298fbbff9313d62c867a6a8b5cc9e3511d7e05 | pedroinc/hackerhank | /staircase.py | 280 | 4.15625 | 4 | #!/bin/python3
import sys
def staircase(n):
for x in range(1, n + 1):
if x < n:
remain = n - x
print(remain * " " + x * "#")
else:
print(x * "#")
if __name__ == "__main__":
n = int(input().strip())
staircase(n)
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.