blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
f2ec17a815493ee02a2719a193f13f13072e1dae | mauroindigne/Python_fundementals | /04_conditionals_loops/04_00_star_loop.py | 443 | 4.625 | 5 | '''
Write a loop that for a number n prints n rows of stars in a triangle shape.
For example if n is 3, you print:
*
**
***
'''
n = 5
# outer loop to handle number of rows
for i in range(0, n):
# inner loop to handle number of columns
# values is changing according to outer loop
for j in range(0, i + 1... | true |
e358b650105e95f0ab0a8d3ced40804d66fe7605 | Tuzosdaniel12/learningPython | /pythonBasics/if.py | 567 | 4.1875 | 4 | first_name = input("What is your first name? ")
print("Hello,", first_name)
if first_name == "Daniel":
print(first_name, "is learning Python")
elif first_name == "Dan":
print(first_name, "is learning with fellow student in the community! Me too!")
else:
#ask if user is under or equal the age of 6
age ... | true |
ce9097e61112db7ffe0aff654197eaf7b5c3b523 | thatvictor7/Python-Intro | /chapter7/chp7-solution3.py | 1,611 | 4.5 | 4 | '''
Victor Montoya
Chapter 7 Solution 3
Fat Gram Calculator
7 July 2019
'''
MULTIPLIER = 9
MIN = 0
TO_PERCENT = 100
LOW_FAT_LIMIT = 29
def main():
print("This program calculates the % of calories from fat in a food,\n"
"and signals when a food is low fat.\n",
"When asked,...\n",
"enter the number of f... | true |
3948e50e14e929686ac4bd5be841110740e37e45 | thatvictor7/Python-Intro | /chapter5/chp5-solution9.py | 1,458 | 4.25 | 4 | # Victor Montoya
# Chapter 5 Solution 9
# Pennies for Pay
# Declared constants
DAY_ADDITION = 1
PAY_DOUBLER = 2
STARTING_POINT = 1
# Declared variables that will hold input, current pay getting doubles and the addition of salary
days = 0
current_pay = .01
running_total = .01
def main():
display_program_and_obta... | true |
f373e03756c50870dbd58f0ebecf4c85b4fe7d77 | thatvictor7/Python-Intro | /chapter5/chp5-solution8.py | 933 | 4.3125 | 4 | # Victor Montoya
# Chapter 5 Solution 8
# Celcius to Farenheit Table
# Declared constants for celcius to farenheit formula and the number of times t]the loop will be executed
FARENHEIT_MULTIPLIER = 1.8
FARENHEIT_ADDITION = 32
MAX_CELCIUS = 21
def main():
iterator()
def iterator():
# for loop will iterate fro... | true |
a0848d243527fa1cf17542b9c5fc6d1e34a78cfc | maknetaRo/python-exercises | /definition/def3.py | 273 | 4.34375 | 4 | """3. Write a Python function to multiply all the numbers in a list.
Sample List : (8, 2, 3, -1, 7)
Expected Output : -336
"""
def multiply_all(lst):
total = 1
for num in lst:
total *= num
return total
lst = [8, 2, 3, -1, 7]
print(multiply_all(lst))
| true |
7db1b5ac4431d1aaeb4594ae6c001f2820814d14 | s1s1ty/Learn-Data_Structure-Algorithm-by-Python | /Data Structure/Linked List/linked_list.py | 1,548 | 4.15625 | 4 | class Node:
def __init__(self, item, next):
self.item = item
self.next = next
class LinkedList:
def __init__(self):
self.head = None
# Add an item to the head of the linked list
def add(self, item):
self.head = Node(item, self.head)
# Delete the first item of the l... | true |
893663f7761aa2739091d0bbeac4dadbfc913e88 | Billdapart/Py3 | /nestedFORLOOPpattern.py | 380 | 4.125 | 4 | # Write a Python program to construct the following pattern, using a nested for loop.
# *
# * *
# * * *
# * * * *
# * * * * *
# * * * *
# * * *
# * *
# *
num=5;
for star in range(num):
for repeat in range(star):
print ('* ', end="")
print('')
for star in range(num,0,-1):
for repe... | true |
c6c19165d5a3b173c8f70261bfd76b088e5303f8 | wasimusu/Algorithms | /sorting/mergeSort.py | 1,409 | 4.34375 | 4 | """
Implement merge sort using recursion
Time complexity O(n*log(n))
Space complexity O(n)
"""
import random
def merge(L, R):
"""
:param L: sorted array of numbers
:param R: sorted array of numbers
:return: L and R merged into one
"""
L = sorted(L)
R = sorted(R)
output = []
while... | true |
7bfa89d3b9a120e66b12658ae499a42a9c5b6e82 | TiagoTitericz/chapter2-py4e | /Chapter6/exercise3.py | 456 | 4.125 | 4 | '''Exercise 3: Encapsulate this code in a function named count, and generalize it so that it accepts
the string and the letter as arguments.
word = 'banana'
count = 0
for letter in word:
if letter == 'a':
count = count + 1
print(count)
'''
def count(word, letter):
count = 0
for l in word:
if l == let... | true |
66fa6baf13c984638065754b49a5e36b299a8e38 | TiagoTitericz/chapter2-py4e | /Chapter6/exercise5.py | 536 | 4.5 | 4 | '''Exercise 5: Take the following Python code that stores a string:
str = 'X-DSPAM-Confidence:0.8475'
Use find and string slicing to extract the portion of the string after the
colon character and then use the float function to convert the extracted
string into a floating point number.'''
#First way
str = 'X-DSPAM-Con... | true |
e58425d79803ac7c48ddd3f3376cfe660d2b8ad3 | TiagoTitericz/chapter2-py4e | /Chapter2/fourth.py | 272 | 4.34375 | 4 | # Write a program which prompts the user for a Celsius temperature, convert the temperature to Fahrenheit,
# and print out the converted temperature.
tcelsius = float(input("Enter temp in Celsius: "))
tfahr = (tcelsius * (9 / 5)) + 32
print("Temp in Fahrenheit:", tfahr)
| true |
c51f7510238e8d65b83540fa0e1d975913ad4b60 | a19131100/260201084 | /lab7/exercise5.py | 532 | 4.21875 | 4 | password = input("Please enter the password: ")
upper_count = 0
lower_count = 0
number_count = 0
if len(password)<8:
print("Password is not valid")
else:
for element in password:
if element.isdigit():
number_count += 1
else:
if element.isalpha():
if element.isupper():
upper_c... | true |
931f3f69d1a04c6dea7df3e5d252c235f28f8ddc | chrddav/CSC-121 | /CSC121_Lab02_Lab02_Problem2.py | 534 | 4.125 | 4 | Lab1 = float(input('Enter the score for Lab 1: '))
Lab2 = float(input('Enter the score for Lab 2: '))
Lab3 = float(input('Enter the score for Lab 3: '))
Test1= float(input('Enter the score for Test 1: '))
Test2= float(input('Enter the score for Test 2: '))
LabAverage = (Lab1 + Lab2 + Lab3) / 3
TestAverage = (Test1 + Te... | true |
13b039ed807ac7a7d98cca0fa3cd9c97c3241cf4 | chrddav/CSC-121 | /CSC121_Lab12_Lab12P2.py | 1,480 | 4.40625 | 4 | print('Converting US Dollar to a foreign currency')
def main():
foreign_currency, dollar_amount = get_user_input()
currency_calculator(foreign_currency, dollar_amount)
def get_user_input():
"""Prompts user to determine which currency they want to convert to and how much money they are converting"""
... | true |
67b11455fa9442605617caa1e4d8927b0de22daf | raihanrms/py-practice | /sqr_sum-vs-sum_sqr.py | 398 | 4.21875 | 4 | '''
The difference between the squared sum and the sum
of squared of first n natural numbers
'''
def sum_difference(n=2):
sum_of_squares = 0
square_of_sum = 0
for num in range(1, n+1):
sum_of_squares += num * num
square_of_sum += num
square_of_sum = square_of_sum ** 2... | true |
0eeaf290bdaea1e8b28ca1aefa174acb35151313 | TiscoDisco/Python-codes | /Collatz Length.py | 925 | 4.28125 | 4 |
# collatz_length (n) produces the number of steps that is required to get to one
# using the Collatz method
# collatz_length: Num -> Num
# required: n != float n has to be positive
# Examples: collatz_length(2) => 1
# collatz_length(42) => 8
import math
import check
def collatz_length (n):
... | true |
e52d780ec9dd8967ec05ae1cd5ec39bcc8b70114 | TiscoDisco/Python-codes | /Check by Queen.py | 2,075 | 4.125 | 4 |
## check_by_queen (queen_pos, king_pos) prduces "Check!!!" if king's position can be
## attacked by the queen. Queen can moving infinite positions horizontally, vertically
## diagonally
## check_by_queen: Str Str -> None
## print (anyof "Check!!!" nothing)
## Required: quee... | true |
fabbf7c356274e3deebe666c50592d92610d889c | JetimLee/DI_Bootcamp | /pythonlearning/week1/listsMethods.py | 724 | 4.15625 | 4 | basket = [1, 2, 3, 4, 5]
print(len(basket))
basket.append('hello')
print(basket)
basket.pop()
print(basket)
basket.insert(3, 'gavin')
# here insert takes the index and then the thing you want to insert
# list methods do not give a new list, they just change the list
# this means you cannot reassign the changed list ... | true |
f2004af1ad010067a47f3489ffa5b485bbe918ea | JetimLee/DI_Bootcamp | /pythonlearning/week1/tuples.py | 260 | 4.25 | 4 | # A tuple is like a list, but you cannot modify them - they're immutable
my_tuple = (1, 2, 3, 4, 5)
# my_tuple[1] = 'z' can't do this
print(my_tuple[1])
print(4 in my_tuple)
new_tuple = my_tuple[1:2]
print(new_tuple)
# only has 2 methods - count and index
| true |
b1c34dfcd2f1c0ccedc19b71f18f56d8868a6543 | jeffclough/handy | /patch-cal | 2,605 | 4.34375 | 4 | #!/usr/bin/env python3
import argparse,os,sys
from datetime import date,timedelta
def month_bounds(year,month):
"""Return a tuple of two datetime.date instances whose values are the
first and last days of the given month."""
first=date(year,month,1)
if month==12:
last=date(year+1,1,1)
else:
last=da... | true |
b30026b349867c47c5b5b3624b8445847228de29 | AbhinavAshish/ctci-python | /Data Structures/solution1_2.py | 499 | 4.28125 | 4 |
#Implement a function which reverses a string
#Approach use a temporary variable and replace. Solution in n
def reverseString (inputStr) :
inputString= list(inputStr)
for index in range(0,len(inputString)/2):
temp = inputString[index]
inputString[index]= inputString[len(inputString)-1-index]
inputString[len... | true |
bb56d7c2c701f8a8526438cc68f97078a9bb2b66 | smksevov/Grokking-the-coding-interview | /two pointers/comparing strings containing backspaces.py | 1,397 | 4.3125 | 4 | # Given two strings containing backspaces (identified by the character ‘#’),
# check if the two strings are equal.
# Example:
# Input: str1="xy#z", str2="xzz#"
# Output: true
# Explanation: After applying backspaces the strings become "xz" and "xz" respectively.
# O(M+N) where ‘M’ and ‘N’ are the lengths of the two ... | true |
4958f912d9d158a4bec20790b7d608a9c018f68a | smksevov/Grokking-the-coding-interview | /bitwise XOR/two single numbers.py | 771 | 4.15625 | 4 | # In a non-empty array of numbers, every number appears exactly twice except two numbers that appear only once.
# Find the two numbers that appear only once.
# Example 1:
# Input: [1, 4, 2, 1, 3, 5, 6, 2, 3, 5]
# Output: [4, 6]
# Input: [2, 1, 3, 2]
# Output: [1, 3]
# O(N) space: O(1)
def find_two_single_numbers(ar... | true |
d3ea31721c808160ccb18f5b5f7616d0399927ff | Oroko/python-project | /pay.py | 428 | 4.1875 | 4 | # A program to prompt the user for hours and rate per hour to compute gross pay
hours = input('Enter Hours:')
hourly_rate = input('Enter Hourly Rate:')
overtime_hrs = input('Enter Overtime hours:')
regular_pay = float(hours) * float(hourly_rate)
if float(overtime_hrs)==0:
print(regular_pay)
elif float(overtime_hrs)>... | true |
cda5bd086248bd8cb906e6a7f7af16d0cdc98b2c | bretonne/workbook | /src/Chapter6/ex128.py | 1,404 | 4.53125 | 5 | # Exercise 128: Reverse Lookup
# (Solved—40 Lines)
# Write a function named reverseLookup that finds all of the keys in a dictionary
# that map to a specific value. The function will take the dictionary and the value to
# search for as its only parameters. It will return a (possibly empty) list of keys from
# the dicti... | true |
fb5f09e30b07839d8dc63a0a28eb89ce1372e85c | bretonne/workbook | /src/Chapter6/ex136.py | 1,305 | 4.1875 | 4 | # Exercise 136:Anagrams Again
# (48 Lines)
# The notion of anagrams can be extended to multiple words. For example, “William
# Shakespeare” and “I am a weakish speller” are anagrams when capitalization and
# spacing are ignored.
# 66 6 Dictionary Exercises
# Extend your program from Exercise 135 so that it is able to c... | true |
95be2a49b9ada465c8495de39c0149eb490d6699 | covcom/122COM_sorting_algorithms | /lab_sorting.py | 2,636 | 4.15625 | 4 | #!/usr/bin/python3
def bubble_sort( sequence ):
# COMPLETE ME - Green task
return sequence
def selection_sort( sequence ):
# COMPLETE ME - Yellow task
return sequence
def quick_sort( sequence ):
# COMPLETE ME - Yellow task
return sequence
def quick_sort_inplace( sequence, start=None, end=... | true |
61d5bc282770b82855ad904bc889e1eb64d09087 | pranayvwork/mypy | /stringsDemo.py | 775 | 4.25 | 4 | message = 'My Wolrd'
print(message)
#apostrophe
myString = "Cat's world"
print(myString)
#multi line string literal
longString = """This is a multi line string
spanning to the second line. """
print(longString)
#find the length of string
print(len(myString))
#upper or lower
print(myString[6:].upper())
#count method
pr... | true |
592c5a195ee4892d0f59525431184e53b40c7d54 | Muhammad-Salman-Hassan/Python_Basic | /DSA_2.py | 2,315 | 4.1875 | 4 | class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Structure to store node pair onto stack
class snode:
def __init__(self, l, r):
self.l = l
self.r = r
''' Helper functio... | true |
ac18bb5814d50470d24a021c012c39f6cce5e813 | judecafranca/PYTHON | /PALINDROME.py | 318 | 4.3125 | 4 | def isPalindrome():
string = input('Enter a string: ')
string1 = string[::-1]
if string[0] == string[(len(string)-1)]\
and string[1:(len(string)-2)] == string1[1:(len(string)-2)]:
print('It is a palindrome')
else:
print('It is not a palindrome')
isPalindrome()
| true |
ef431b986c659ee6943577f8606b75db0ca1e8d5 | leonardotdleal/python-basic-course | /primitive-variables/primitive-variables.py | 428 | 4.15625 | 4 | # PRIMITIVE VARIABLES IN PYTHON #
# String
name = 'Leonardo Leal'
# Integer
age = 25
# Float
height = 1.68
# Boolean
student = True
print(name)
print(age)
print(height)
print(student)
# None (is similar to null in others languages)
working = None
print(working)
# OPERATIONS #
new_age = age + 2
name_and_city = ... | true |
968ec4600f28007d7a84b5068b7d2b185f6f684f | olafironfoot/CS50_Web | /Lectures/Lecture4/src4/Testing and questions for classes4.py/TestingClass.py | 2,009 | 4.4375 | 4 | # class User:
# def __init__ (self, full_name, birthday):
# self.name = full_name
# self.birthday = birthday
#
# #Can assign a variable to store infomation within a class User()
# Thisperson = User("Dave", 192832)
#
# print(Thisperson.name, Thisperson.birthday)
#
# #this needs to be assigned, otherw... | true |
c501f289e485673870ab507cde6938e037fd20ee | gerardogtn/matescomputacionales | /matescomputacionales/project02/recursive_definitions.py | 1,790 | 4.21875 | 4 | """ All strings used as patterns in a recursive definition"""
patternStrings = ['u', 'v', 'w', 'x', 'y', 'z']
def getAllCombinationsForStep(step, combinations, out):
"""" Given a single recursive definition and all possible combinations to fill
each pattern with, return all possible combinations
Keyword a... | true |
5a6110d12a5f4882796302209952a91cfc3d43b1 | IvanJeremiahAng/cp1404practicals | /prac_03/lecture ex.py | 488 | 4.15625 | 4 | min_age = 0
max_age = 150
valid_age = False
while not valid_age:
try:
age = int(input("Enter your age: "))
if min_age <= age <= max_age:
valid_age = True
else:
print("Age must be 0 - 150 inclusive.")
except ValueError as e:
print("Age must be an integer")
... | true |
f22ee0714af9a4727ee3311b5a15ee083e004c76 | urjits25/leetcode-solutions | /LC92.py | 1,880 | 4.125 | 4 | '''
REVERSE LINKED LIST II
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
'''
def reverseBetween(head: ListNode, m: int, n:int) -> ListNode:
'''
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
'''
# Function to rever... | true |
cd4f1bd46e15ca494d59ca9650839d313f51847b | urjits25/leetcode-solutions | /LC53.py | 758 | 4.1875 | 4 | '''
MAXIMUM SUBARRAY
Given an integer array nums, find the contiguous subarray (containing at least one number)
which has the largest sum and return its sum.
'''
# Dynamic Programming, Time : O(N); Space: O(N)
# Better solution (O(1) space): https://leetcode.com/problems/maximum-subarray/discuss/20194, Explanation:... | true |
58c93fd24db3aadf5899654ba7f63b724ae96bd3 | rubleen1903/Python-BubbleSort | /sort.py | 413 | 4.28125 | 4 | # Creating a bubble sort function
def bubblesort(lista):
#outer for loop
for i in range(0,len(lista)-1):
for j in range(len(lista)-1):
if(lista[j]>lista[i]):
temp = lista[j]
lista[j]=lista[j+1]
lista[j+1]=temp
return lista
lista=[12,42,8... | true |
0d79d97a228c8e133511f3d6d10a4fa9af1c7a12 | LeenaKH123/Python2 | /02_more-datatypes/02_14_char_count_dict.py | 347 | 4.25 | 4 | # Write a script that takes a text input from the user
# and creates a dictionary that maps the letters in the string
# to the number of times they occur. For example:
#
# user_input = "hello"
# result = {"h": 1, "e": 1, "l": 2, "o": 1}
x = input("type your string without spaces ")
freq = {}
for c in set(x):
freq[c... | true |
6c01755380160bfc34cb1067e9c2d05546b336d9 | LeenaKH123/Python2 | /02_more-datatypes/02_10_pairing_tuples.py | 871 | 4.40625 | 4 | # The import below gives you a new random list of numbers,
# called `randlist`, every time you run the script.
#
# Write a script that takes this list of numbers and:
# - sorts the numbers
# - stores the numbers in tuples of two in a new list
# - prints each tuple
#
# If the list has an odd number of items,... | true |
21f4c5fdebc4f4ecb80f42d20e364ca29b276377 | LeenaKH123/Python2 | /04_functions-and-scopes/04_10_type_annotations.py | 692 | 4.21875 | 4 | # Add type annotations to the three functions shown below.
# type annotations are also known as type signatures and they are used to indicate the data type of variables and the input
# and output of functions and methods in a programming language
# static type: performs type checking at compile-time and requires datatt... | true |
9bfea5d550eb6f62ad3dff93d63fa4f6058f28ee | uabua/rosalind | /bioinformatics-stronghold/rabbits-and-recurrence-relations/fib.py | 689 | 4.25 | 4 | """
ID: FIB
Title: Rabbits and Recurrence Relations
URL: http://rosalind.info/problems/fib/
"""
def count_rabbits(month, pair):
"""
Counts the total number of rabbit pairs that will be present after n(month) months, if we begin with 1 pair and
in each generation, every pair of reproduction-age rabbits pr... | true |
7153eecf22609652b057f756a8aff5bd17c931a1 | NoroffNIS/Python_Examples | /src/week 2/day 2/while_loop_exit.py | 385 | 4.25 | 4 | what_to_do = ''
while what_to_do != 'Exit':
what_to_do = input('Type in Exit to quit, '
'or something else to continue: ')
if what_to_do == 'Exit':
print('You typed in Exit, program stopped')
elif what_to_do == 'exit':
print('You typed in Exit, loop break, program stop... | true |
22048e72c64345b993e87c6183c1b0a31c257d7a | NoroffNIS/Python_Examples | /src/week 2/day 3/letter_count.py | 257 | 4.125 | 4 | word = input('Type in a word:').upper()
letter = input('Type in a letter you want to count:').upper()
count = 0
for l in word:
if l == letter:
count += 1
else:
pass
print('In you word', word, 'there is', count, 'letters of', letter) | true |
09d3553282f07aebe1220d22a9a614eea96c470d | maizzuu/ot-harjoitustyo | /src/entities/user.py | 534 | 4.15625 | 4 | class User:
"""Class that depicts a User.
Attributes:
username: String that represents the users username.
password: String that represents the users password.
"""
def __init__(self, username:str, password:str):
"""Class constructor that creates a new user.
Args:
... | true |
af23b5795bbb6d606222cc34ea0dc4088e9a81f0 | Salman42Sabir/Python3-Programming-Specialization | /Tuples_course_2_assessment_5.py | 1,704 | 4.40625 | 4 | # 1. Create a tuple called olympics with four elements: “Beijing”, “London”, “Rio”, “Tokyo”.
olympics = ("Beijing", "London", "Rio", "Tokyo")
print(olympics)
# 2. The list below, tuples_lst, is a list of tuples. Create a list of the second elements of each tuple and assign this list to the variable country.
tuples_l... | true |
8ca4330f75344811b46435ec2b92cabdaf601e89 | omwaga/Python-loop-programs | /Factorial_of_a_Number.py | 501 | 4.1875 | 4 | """
Factorial is a non-negative integer.
It is the product of all positive integers less than or equal to that number for which you ask for factorial.
It is denoted by exclamation sign (!).
"""
num = int(input("Enter a number:"))
factorial = 1
if num < 0:
print("Sorry, factorial does not exist for negative numb... | true |
b1739be0b25eb2d1d4ec11c915e6243f2d51b242 | tedmik/classwork | /python-workbook/37.py | 613 | 4.375 | 4 | num_sides = int(input("How many sides does your shape have?: "))
if(num_sides == 3):
print("Your shape is a triangle")
elif(num_sides == 4):
print("Your shape is a square or rectangle")
elif(num_sides == 5):
print("Your shape is a pentagon")
elif(num_sides == 6):
print("Your shape is a hexagon")
elif(num_sides ... | true |
34b2cc012e22fc7015c4058c2534e7be382a91b0 | imharshr/7thSemCSEnotes | /ML Lab/Sample Programs Assignment/samplePrograms.py | 263 | 4.3125 | 4 | tuplex = "w", 3, "r", "s", "o", "u", "r", "c", "e"
print(tuplex)
#tuples are immutable, so you can not remove elements
#using merge of tuples with the + operator you can remove an item and it will create a new tuple
tuplex = tuplex[:2] + tuplex[3:]
print(tuplex)
| true |
e12ab5d88436f7882b3a3d5891f48b5d4a16a63f | tylerharter/caraza-harter-com | /tyler/cs301/fall18/materials3/code/lec-06-functions/example12.py | 261 | 4.25 | 4 | # show global frame in PythonTutor
msg = 'hello' # global, because outside any function
def greeting():
print(msg)
print('before: ' + msg)
greeting()
print('after: ' + msg)
# LESSON 5: you can generally just use
# global variables inside a function
| true |
ad15dbee9408784ef55eb62222df7b892febf92d | GitRAK07/my_python_programs_learning | /Documents/python/dictionary.py | 714 | 4.25 | 4 | ####### Dictionary ########
user = {
'name': 'Anand',
'Age': 26,
'occupation': 'Software Engineer'
}
print(user['name'],user['Age'])
print(user.get('age')) #Use get method to avoid the program throwing the errors.
print(user.get('Age', 90)) #Returns value 90 if Age value is not found in the dict.
print( 'n... | true |
1d2df47f0beaf079e3e79b40ece8905592eb71bd | jblanco75/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/4-print_square.py | 474 | 4.40625 | 4 | #!/usr/bin/python3
"""Function: print_square"""
def print_square(size):
"""Prints a square with '#'
'size' is the size length of the square
'size' must be an integer"""
if type(size) != int:
raise TypeError("size must be an integer")
if size < 0:
raise V... | true |
7e5f9e75db1723f379b360afb8ed88937b3783e3 | RSP123/python_puzzles | /minus_duplicates.py | 436 | 4.21875 | 4 | # Program for removing duplicate element in tthe list using set
# function to remove the duplicates
def duplicate(input):
result = []
res = set(input) # Converting list to set
for i in res:
result.append(i)
return result
# Main
if __name__=="__main__":
input = [1, 2, 2, 3, 4, 8, 8, 7,... | true |
c2eff0cf6036a8e991ff80e7acd9b69cac631a40 | RSP123/python_puzzles | /prime_num.py | 846 | 4.40625 | 4 | # This program check weather the given number is prime or not
# Function to check prime number
def prime_number(number):
# Returning False for number 1 and less then 1
if number == 2 or number == 1:
return True
elif number < 1 or number%2 == 0:
return False
else:
# Iterating from 2 to check the number is pri... | true |
87e0ace6902aca39ce6e71a3c4b3ddb3456df7d0 | Yaseen315/pres-excercise | /yq-grace-exercise-logic1.py | 932 | 4.25 | 4 | """This is my random number generator, I have a few problems with it. The turns don't seem to be working properly- I want them to start from 1
and increase each turn. Also the print statements seem to not be coming out the way I want them. I also can't make the game finish."""
print "Random number generator"
from ran... | true |
f6f15763778e1c9adbeddba0956c1ab04fb40259 | alyson1907/CodeWars | /6-kyu/python/IsIntegerArray.py | 892 | 4.125 | 4 | # https://www.codewars.com/kata/52a112d9488f506ae7000b95/train/python
# Write a function with the signature shown below:
# def is_int_array(arr):
# return True
# returns true / True if every element in an array is an integer or a float with no decimals.
# returns true / True if array is empty.
# returns false / F... | true |
aa54193adecee918fa5762535ffda5dd8470d6e1 | dancaps/python_playground | /cw_titleCase.py | 2,296 | 4.40625 | 4 | #!/use/bin/env python3
'''https://www.codewars.com/kata/5202ef17a402dd033c000009/train/python
A string is considered to be in title case if each word in the string is either (a) capitalised (that is, only the first letter of the word is in upper case) or (b) considered to be an exception and put entirely into lower c... | true |
1736446a61e22d6c931fd7ea09648771e545b743 | dancaps/python_playground | /cw_summation.py | 455 | 4.375 | 4 | #!/usr/bin/env python3
'''
https://www.codewars.com/kata/grasshopper-summation/train/python
Summation
Write a program that finds the summation of every number between 1 and num. The number will always be a positive
integer greater than 0.
For example:
summation(2) -> 3
1 + 2
summation(8) -> 36
1 + 2 + 3 + 4 + 5 + ... | true |
7602a619d5f9c3f16c886f59c1c70fdd134f2de3 | sonofmun/FK-python-course | /pyhum/pig_latin.py | 891 | 4.40625 | 4 | #! /usr/bin/env python3
# -*- coding: utf8 -*-
VOWELS = 'aeiouAEIOU'
def starts_with_vowel(word):
"Does the word start with a vowel?"
return word[0] in VOWELS
def add_ay(word):
"Add 'ay' at the end of the word."
return word + 'ay'
def convert_word(word):
"Convert a word to latin (recursive styl... | true |
c86ebebbe6eb2c4b51b731ffb8d49cd5679528bd | mstoiovici/module2 | /Codingbat/String_1/String_1_first_half.py | 437 | 4.34375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 18 15:52:31 2018
@author: maria
"""
"""
Given a string of even length, return the first half. So the string "WooHoo" yields "Woo".
first_half('WooHoo') → 'Woo'
first_half('HelloThere') → 'Hello'S
first_half('abcdef') → 'abc'
"""
def first_half(st... | true |
e057e238d978fb2b6043f1810963e3f86a5b03cf | HugoPhibbs/COSC262_lab_work | /Lab_11/binary_search_tree.py | 1,187 | 4.15625 | 4 | # Do not alter the next two lines
from collections import namedtuple
Node = namedtuple("Node", ["value", "left", "right"])
# Rewrite the following function to avoid slicing
def binary_search_tree(nums, is_sorted=False, start=None, end=None):
"""Return a balanced binary search tree with the given nums
at t... | true |
92e483d42f1b5deba9df5b7efce92ccd22bbf551 | HugoPhibbs/COSC262_lab_work | /Lab_2/fib_matrix.py | 1,787 | 4.125 | 4 | def fib(n, matrix=None):
"""finds the nth fibonacci sequence using divide and conquer and
fast exponentiation"""
#how to use martix multiplication in python??
#how can i implement 2x2 matrix multiplicatoin in python, look at the general formula.
# fib matrix = [[fn+1, fn], [fn, fn-1]]
if n == 1 ... | true |
0e48158e10ae5c8672c3c4b58cd1679a6afdaec1 | HugoPhibbs/COSC262_lab_work | /Lab_4/dijkstras.py | 1,825 | 4.1875 | 4 | def dijkstra(adj_list, next_node):
"""does dijkstras algorithm on a graph"""
parent_array = [None for i in range(0, len(adj_list))]
distance_array = [float('inf') for i in range(0, len(adj_list))]
in_tree = [False for i in range(0, len(adj_list))]
distance_array[next_node] = 0
true_array = [Tr... | true |
8ca7053bbf67d2a95481a4cd7dc58e54defb37e0 | failedpeanut/Python | /day1/MoreAboutFunctions.py | 1,137 | 4.28125 | 4 | #Default Argument Values
#can give default argument values for functions.
def defaultArguments(name, age=18, gender='Not Applicable',somethingelse=None):
print("name",name)
print("age",age)
print("gender",gender)
print("somethingelse", somethingelse)
defaultArguments("Peanut",20,"Male","Nothing!")
defau... | true |
489444bb8d5a6526728879c779bba58c35b45534 | Christinaty/holbertonschool-higher_level_programming-1 | /0x0B-python-input_output/7-add_item.py | 584 | 4.3125 | 4 | #!/usr/bin/python3
"""Write a script that adds all arguments to a Python list, and then save
them to a file:
*If the file doesnt exist, it should be created
"""
from sys import argv
from os import path
save_to_json_file = __import__('5-save_to_json_file').save_to_json_file
load_from_json_file = __import__('6... | true |
aae741e19ab69d1b916ad414e0b6db207f5dc3e0 | tyriem/PY | /CISCO/CISCO 33 - Tax Calc.py | 2,193 | 4.28125 | 4 | ### AUTHOR: TMRM
### PROJECT: CISCO DevNet - Tax Calc
### VER: 1.0
### DATE: 05-XX-2021
### OBJECTIVE ###
# Your task is to write a tax calculator.
# It should accept one floating-point value: the income.
# Next, it should print the calculated tax, rounded to full dollars. There's a function named round() which wil... | true |
ffbfc2d58564e2cad36dac052f517cb9632f4d4d | tyriem/PY | /Intro To Python/14 -While Loop - Password TMRM.py | 322 | 4.15625 | 4 | ### AUTHOR: TMRM
### PROJECT: INTRO TO PYTHON - While Loop Password
### VER: 1.0
### DATE: 05-XX-2020
##Declare CALLs
##LOOPs and VARs
password = ''
while password != 'test':
print('What is the password?')
password = input()
##OUTPUTs
print('Yes, the password is ' + password + '. You may enter.'... | true |
339ac9fc350ddedccd8667e9288dc25facda7c82 | tyriem/PY | /Intro To Python/25 - Function - Param-Default-Return TMRM.py | 1,542 | 4.8125 | 5 | ### AUTHOR: TMRM
### PROJECT: INTRO TO PYTHON - FUNCTIONS
### VER: 1.0
### DATE: 05-28-2020
##Declare CALLs & DEFs
### PARAMETERS ###
# Parameters are used to pass information to functions
# Parameters are specified after the function name, inside the parentheses. You can add as many parameters as you want, just s... | true |
c4613f6ad8a571db354d428c78a9f5441cdc62a0 | tyriem/PY | /Intro To Python/41 - GUI - Radio Button SelectGet - TMRM.py | 1,047 | 4.25 | 4 | ### AUTHOR: TMRM
### PROJECT: INTRO TO PYTHON - GUI: Radio Buttons Select & Get
### VER: 1.0
### DATE: 06-06-2020
#####################
### GUIs ###
#####################
### OBJECTIVE ###
#Code a basic GUI for user
#
### OBJECTIVE ###
##Declare CALLs & DEFs
from tkinter import*
#First, we import the t... | true |
a39b5eec1a8262f0e693f662b6664a79e42a7888 | tyriem/PY | /Intro To Python/6 - Perform CALCs using Formulae.py | 1,985 | 4.34375 | 4 | ### AUTHOR: TMRM
### PROJECT: Perform Calculations using Formulas
### VER: 1.0
### DATE: 05-18-2020
#Task #1: Find the area of a circle
print ("\n [TASK #1: Find the area of a circle using the formula pi(3.14) x radius^2]")
#Declare STRINGs & VALs
rad = float(input("\n Enter the Radius of The Circle = "))
measure... | true |
8c5f731509903fbfe23c7fa8e09b304218cdad80 | vaylon-fernandes/simple-python-projects | /guess_the_number/guess_the_number_with_levels.py | 2,677 | 4.375 | 4 | #Number Guessing Game Objectives:
# Include an ASCII art logo.
# Allow the player to submit a guess for a number between 1 and 100.
# Check user's guess against actual answer. Print "Too high." or "Too low." depending on the user's answer.
# If they got the answer correct, show the actual answer to the player.
# Trac... | true |
d3e11df9c61642894bc613cebf4f9a2f7b4e7360 | lt393/pythonlearning | /s5_data_structure/dict/dict_create.py | 670 | 4.25 | 4 |
# Python's dictionaries are kind of hash table type which consist of key-value pairs of unordered elements.
# Keys : must be immutable data types ,usually numbers or strings.
# Values : can be any arbitrary Python object.
d = {} # empty dict
d = {
1: 1,
2: 2,
3: 3
}
# Python Dictionaries are mutabl... | true |
b6aabafceb7b1b07d5952b5e48a959e1100821fc | lt393/pythonlearning | /s7_python_functions/lambda.py | 1,260 | 4.21875 | 4 |
"""
The lambda’s general form is the keyword lambda,
followed by one or more arguments (exactly like the arguments list you enclose in parentheses in a def header),
followed by an expression after a colon:
lambda argument1, argument2,... argumentN :expression using arguments
"""
def sum(x, y ,z):
return x + y + ... | true |
c82d806ab02b2e467699dab1d57461474f8e9bce | Czbenton/HelloPython | /src/Main.py | 1,377 | 4.21875 | 4 | accountList = {"zach": 343}
def login():
global userName
print("Welcome to The Bank of Python. Please enter your name.")
userName = input()
print("Hi ", userName, "!! How much would you like to deposit to start your account?", sep="")
initDeposit = float(input())
accountList[userName] = initDe... | true |
95af735aa251c5d148acf1b04761d7f7eec5851d | emanuelvianna/algos | /algo/sorting/heapsort.py | 2,914 | 4.21875 | 4 | import heapq
from algo.utils.list_utils import swap
def _min_heapify_at_a_range(numbers, left, right):
"""
Build max-heap in a range of the array.
Parameters
----------
numbers: list
List of numbers to be sorted.
left: int
Initial index.
right: int
Final index.
... | true |
dce86aff42a17c01304f326cb7a55574fcd2b097 | mkhalil7625/hello_sqlite_python | /sqlite/db_context_manager_error_handling.py | 1,673 | 4.21875 | 4 | """
sqlite3 context manager and try-except error handling
"""
import sqlite3
def create_table(db):
try:
with db:
cur = db.cursor()
cur.execute('create table phones (brand text, version int)')
except sqlite3.Error as e:
print(f'error creating table because {e}')
def ... | true |
f3b56bd393ca33e532baa4e4eaacbae7fd9ebe9c | sakshimaan/Python | /palindrome.py | 590 | 4.3125 | 4 | #python code to check whether the given string is palindrome or not
def check(string):
n=len(string)
first=0
mid=(n-1)//2
last=n-1
flag=1
while(first<mid):
if (string[first]==string[last]):
first=first+1
last=last-1
else:
flag=0
... | true |
1ee0023d2c872565e5405a8d850b11094b392fe4 | LachezarKostov/SoftUni | /01_Python-Basics/functions/Password Validator.py | 1,161 | 4.15625 | 4 | def is_six_to_ten_char(password):
valid = False
if 6 <= len(password) <= 10:
valid = True
return valid
def is_letters_and_digits(password):
valid = True
for char in password:
ascii = ord(char)
if (ascii < 48) or (57 < ascii < 65) or (90 < ascii < 97) or (ascii > 122):
... | true |
d4c79eb2a3a0673e078c907808a187a25853d825 | phibzy/InterviewQPractice | /Solutions/LongestCommonPrefix/solution.py | 1,002 | 4.25 | 4 | #!/usr/bin/python3
"""
@author : Chris Phibbs
@created : Wednesday Sep 16, 2020 17:07:49 AEST
@file : solution
"""
"""
The "column" approach
Compare each sequential character of each string.
Return as soon as a character in one string is not the same.
Complexity:
Time: O( N * M) - Where ... | true |
be104d8d168f501796507c6b58a15bb49d2c9314 | phibzy/InterviewQPractice | /Solutions/DistributeCandies/candies.py | 1,124 | 4.4375 | 4 | #!/usr/bin/python3
"""
@author : Chris Phibbs
@created : Thursday Mar 04, 2021 12:00:57 AEDT
@file : candies
"""
"""
Questions:
- Range of number of candies?
- Will number of candies always be even? Need to floor if odd?
- Will candy types just be ints >= 0?
- Neg ints?
- Em... | true |
85938d4ff2bad05052c6158c29525d45d74a9428 | naumanurrehman/ekhumba | /problem3/recursion/reverseString.py | 1,012 | 4.1875 | 4 | '''
Given a string, Write recursive function that reverses the string.
Input Format
A String.
Constraints
x
Output Format
Reverse of Strings.
Sample Input
Being
Sample Output
gnieB
Explanation
Self explanatory.
'''
def recur(content, num, length):
if num >= length:
return ''
return recur(c... | true |
4050182c72685750fd92c6fb0bdca5c5879db964 | JanakSharma2055/Cryptopals | /challenge6.py | 613 | 4.5 | 4 | def find_hamming_distance(string1: bytes, string2: bytes) -> int:
"""
Find hamming distance between two strings.
The Hamming distance is just the number of differing bits.
:param string1: The first string to be compared, as bytes
:param string2: The second string to be compared, as bytes
:retur... | true |
16a17fc8a65afedb33d9cd32c49b27f2d12559b8 | jermcmahan/ATM | /ATM/simulator/tree.py | 1,546 | 4.4375 | 4 |
"""
Tree --- class to represent an accepting computation tree of an Alternating Turing Machine
:author Jeremy McMahan
"""
class Tree:
"""
Creates the tree from the root data and a list of subtrees. A leaf is denoted by having the empty list
as its children
:param root the data associated with the tre... | true |
70cbc8e51a38048c50c5bdd0cc765b97ecbe0fa2 | dylanplayer/ACS-1100 | /lesson-7/example_4.py | 337 | 4.1875 | 4 | # This while loop prints count until 100, but it breaks when
# the counter reaches 25
counter = 0
while counter < 100:
print(f"Counter: {counter}")
counter += 1
# If counter is 25, loop breaks
if counter == 25:
break
# Write a for loop that counts backwards from 50 to
# 0.
for num in range(50, 0, ... | true |
92ece88144930e7c5988738c24ca00c903a09d1c | dylanplayer/ACS-1100 | /lesson-10/example-3.py | 808 | 4.59375 | 5 | '''
Let's practice accessing values from a dictionary!
To access a value, we access it using its key.
'''
# Imagine that a customer places the following order
# at your empanada shop:
'''
Order:
1 cheese empanada
2 beef empanadas
'''
menu = {"chicken": 1.99, "beef":1.99, "cheese":1.00, "guava": 2.50}
# Get the p... | true |
90c220bac3f0f604e7ad0352859940d1729c40f9 | dylanplayer/ACS-1100 | /lesson-7/example_2.py | 403 | 4.25 | 4 | '''
Use while loops to solve the problems below.
'''
# TODO - Exercise 1: Repeatedly print the value of the variable price,
# decreasing it by 0.7 each time, as long as it remains positive.
from typing import Counter
price = 5
while price > 0:
print(price)
price -= 1
print("--------------")
# TODO - Exe... | true |
7fe979cb792ebdf4ccaf4f199c7a43466da3a7c4 | dylanplayer/ACS-1100 | /lesson-2/example-4.py | 905 | 4.125 | 4 | # Types
# Challenge: Guess the type for each of these and define a value
# write the type as a comment then define a value.
# Then test your work
# For example
height_in_inches = 72
print("int")
print(type(height_in_inches))
# Your age: type and value
age = 15
print("int")
print(type(age))
# Your shoe size: Type an... | true |
714c14a6b333ab2ac08deb00a132cf5a9dbccc20 | dylanplayer/ACS-1100 | /lesson-2/example-10.py | 399 | 4.625 | 5 | print("Welcome to the snowboard length calculator!")
height = input("Please enter your height in inches: ")
height = float(height) # Converts str to float!
# Input sees the user input as a string
# Before we can calculate it, we need to convert it to the correct
# data type... in this case, height should be an float... | true |
01b2a5e8659fedd193ada2f2bdf3869eab30f2ed | moritzemm/Ch.09_Functions | /9.7_BB8.py | 1,968 | 4.34375 | 4 | '''
BB8 DRAWING PROGRAM
-------------------
Back to the drawing board! Get it? Let's say we want to draw many BB8 robots
of varying sizes at various locations. We can make a function called draw_BB8().
We've made some basic changes to our original drawing program. We still have the
first two lines as importing arcade a... | true |
8fcfa372d51f99068336f9896d44edd6255c8d1f | rynoschni/python_dictionaries | /dictionary.py | 603 | 4.15625 | 4 | meal = {
"drink": "Beer",
"appetizer": "chips & salsa",
"entree": "fajita's",
# "dessert": "churros"
}
#print(meal["drink"])
#print("This Thursday, I will have a %s and %s for dinner!") % (meal("drink"), meal("entree"))
# if "dessert" in meal:
# print("Of course, Ryan had a dessert!! He ate %s" % (... | true |
e10ec57bd111df03b31fb9482c64fc39d5f1d0dd | thaimynguyen/Automate_Boring_Stuff_With_Python | /regrex_search.py | 1,578 | 4.25 | 4 | #! python 3.8
"""
Requirement:
_ Write a program that opens all .txt files in a folder and searches for any line that matches a user-supplied regular expression.
_ The results should be printed to the screen.
Link: https://automatetheboringstuff.com/2e/chapter9/#calibre_link-322
"""
import os, re
d... | true |
3e5075d3b68fd8d52eda91cc7c122d56951af2cb | codecherry12/Python_for_EveryBody | /AccessingFileData/filelist.py | 657 | 4.40625 | 4 | """8.4 Open the file romeo.txt and read it line by line. For each line,
split the line into a list of words using the split() method.
The program should build a list of words. For each word on each line check to see
if the word is already in the list and if not append it to the list.
When the program completes, so... | true |
8901f47cf34579292368352c41e9a5c0436883ce | rehan252/Axiom-Pre-Internship | /Learn-Python3-from-Scratch/05-Data-Structure/04-sets.py | 752 | 4.34375 | 4 | """
This doc provide detailed overview of sets in Python.
These are basically unordered collection of data items. Can't contain repeated values
Mutable data structures like lists or dictionaries can’t be added to a set.
However, adding a tuple is perfectly fine.
"""
# Syntax:
data_set = set()
data_set.add(5)
print(da... | true |
bb36bc53737c632b2113a43934c59f5fc461363c | rehan252/Axiom-Pre-Internship | /Learn-Python3-from-Scratch/07-Classes/01-python-classes.py | 521 | 4.40625 | 4 | """
In this Doc we'll cover all details about classes in Python.
Class Inheritance e.t.c.
"""
# start by creating a simple example of Person
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("David", 25)
print(p1.name)
# let's create a new class name Te... | true |
7c8c15582d92d04bf10ec58f1886a2fe54903edf | rehan252/Axiom-Pre-Internship | /Learn-Python3-from-Scratch/01-Introduction/writing-first-code.py | 449 | 4.25 | 4 | """
This file is created for practicing Python
Print statement
"""
# printing string
print("First Lesson")
# printing integers/float
print(300)
print(102.5784)
#using format
print('Data: {}'.format(10))
# Printing Multiple Pieces of Data
print('Integer: {}\nFloat: {}\nString: {}\nList: {}'.format(120, 14.25, 'Hello... | true |
8a6f54f6ea0c18c4bfda517406ee9b30c2566f0d | c4llmeco4ch/eachDayInYear | /main.py | 1,339 | 4.6875 | 5 | #see attached jpg
'''
* @param day The day of the month we want to print
* @param month The string of the month we want to print
* i.e. "Jan"
* Given a "day" and "month", this function prints out
* The associated calendar day. So, passing 1 and "Feb"
* Prints "Feb 1st"
'''
def printDay(day, month):
ending = "... | true |
fd384b8b89d722b99c77963f49a4d35ef3402341 | ananyasaigal001/Wave-1 | /Units_Of_Time_2.py | 437 | 4.21875 | 4 | #obtaining seconds
time_seconds=input("Enter the time in seconds: ")
time_seconds=int(time_seconds)
#computing the days,hours,minutes,and seconds
days="{0:0=2d}".format(time_seconds//86400)
hours="{0:0=2d}".format((time_seconds% 86400)//3600)
time_remaining=((time_seconds% 86400)%3600)
minutes="{0:0=2d}".format(time... | true |
8f257a0493eb3fd85030f0bdab42e973271ab95d | kgermeroth/Code-Challenges | /lazy-lemmings/lemmings.py | 2,027 | 4.3125 | 4 | """Lazy lemmings.
Find the farthest any single lemming needs to travel for food.
>>> furthest(3, [0, 1, 2])
0
>>> furthest(3, [2])
2
>>> furthest(3, [0])
2
>>> furthest(6, [2, 4])
2
>>> furthest(7, [0, 6])
3
>>> furthest_optimized(7, [0, 6])
3
>>> furthest_opt... | true |
4a499c580419ba601df9f6540540aa3342fcbb5b | saswat0/catalyst | /catalyst/contrib/utils/misc.py | 1,471 | 4.125 | 4 | from typing import Any, Iterable, List, Optional
from itertools import tee
def pairwise(iterable: Iterable[Any]) -> Iterable[Any]:
"""Iterate sequences by pairs.
Examples:
>>> for i in pairwise([1, 2, 5, -3]):
>>> print(i)
(1, 2)
(2, 5)
(5, -3)
Args:
i... | true |
b6ee3ae1c6ffa6db1546c8dd7bd12d5e0cfaf4eb | jonmckay/Python-Automate | /Section-6-Lists/lists-and-strings.py | 945 | 4.40625 | 4 | list('Hello')
name = 'Zophie'
name = [0]
print(name)
# Taking a section of a string
name[1:3]
print(name)
# Create a new string using slices
name = 'Zophie a cat'
newName = name[0:7] + 'the' + name[8:12]
print(newName)
# References
spam = 42
cheese = spam
spam = 100
print(spam)
# When you assign a list to a variab... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.