blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
f7b1305a7baa9b2e13c21a69f2229ea0a0026a7f
|
efecntrk/python_programming
|
/unit-1/problem1.py
| 219
| 4.1875
| 4
|
'''
for i in range(3):
print('Hello World ! ')
'''
statement = 'Homework is fun!!!'
num = 3
#loop to print statement num number of times
'''
for i in range(num):
print(statement)
'''
print(statement * num)
| false
|
14b215cd4bbf1eba8ad00724c8612941cf234650
|
efecntrk/python_programming
|
/unit-1/variables.py
| 786
| 4.1875
| 4
|
'''
#place a name and give a value
#integer
age = 27
#float
gpa = 3.0
#boolean
has_kids = True
#check the type of a variable
print(type(age)) #This function tell what type of data it is
print(type(gpa))
print(type(has_kids))
'''
#check if a number is even
'''
number = 10
if number % 2 == 0:
print('It is even!')
else:
print('It is odd!')
'''
'''
#comparison operators
# > - greater than
#< - less than
#>= greater than or equal to
#<= less than or equal to
#== - equal to
# != not equal to
#Truthiness
'''
x = 10 #a np zero value is truthy
y = 0 # zero or negative value is falsy
z = 'Python' # a string of non zero length is truth
p = '' # a string of zero length is falsy
q = [] #an empty list is falsy
if q:
print('yes')
else:
print('no')
| true
|
b3f654665c353ca0192af767791d9ed7375bae64
|
CharlesBird/Resources
|
/coding/Algorithm_exercise/Leetcode/0435-Non-overlapping-Intervals.py
| 1,208
| 4.34375
| 4
|
"""
Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Example 1:
Input: [[1,2],[2,3],[3,4],[1,3]]
Output: 1
Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.
Example 2:
Input: [[1,2],[1,2],[1,2]]
Output: 2
Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.
Example 3:
Input: [[1,2],[2,3]]
Output: 0
Explanation: You don't need to remove any of the intervals since they're already non-overlapping.
Note:
You may assume the interval's end point is always bigger than its start point.
Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other.
"""
from typing import List
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
# Time Complexity: O(n)
# Space Complexity: O(n)
if not intervals:
return 0
intervals.sort(key=lambda l: l[1])
res = 0
pre = intervals[0][1]
for v in intervals[1:]:
if v[0] < pre:
res += 1
else:
pre = v[1]
return res
| true
|
86f2e607b8f74fa172beaf6a893df66d4ce6c045
|
BaronDaugherty/DailyProgrammer
|
/Challenge 27/c27_easy.py
| 809
| 4.15625
| 4
|
'''
Daily Programmer Challenge 27 : Easy
@author: Baron Daugherty
@date: 2015-07-20
@desc: Write a program that accepts a year as input and outputs the
century the year belongs in (e.g. 18th century's year ranges are
1701-1800) and whether or not the year is a leapyear.
'''
from datetime import date
year = int(input("Please enter a year A.D.: "))
d = date(year, 1, 1)
print("Year: " +str(year))
if year % 100 == 0:
print(str(int(year/100)) + " Century")
else:
print(str(int(year/100 +1)) +" Century")
if year % 4 != 0:
print(str(year) +" is not a leap year.")
elif year % 100 != 0:
print(str(year) +" is not a leap year.")
elif year % 400 != 0:
print(str(year) +" is not a leap year.")
else:
print(str(year) +" is a leap year")
| false
|
17804be887ce906939cd1e20403c6057bfddd765
|
thatguy0999/PythonCodes
|
/Python2/Ex51.py
| 344
| 4.1875
| 4
|
grading = {
'A+':4.0,
'A':4.0,
'A-':3.7,
'B+':3.3,
'B':3.0,
'B-':2.7,
'C+':2.3,
'C':2.0,
'C-':1.7,
'D+':1.3,
'D':1.0,
'F':0.0,
}
while True:
grade = input('please enter a grade ')
try:
print(grading[grade.capitalize()])
break
except:
print('invalid input')
| false
|
ae6b40a94660f9b36a4e1954bd176acc098b8ca3
|
Airman-Discord/Python-calculator
|
/main.py
| 530
| 4.25
| 4
|
print("Python Calculator")
loop = True
while loop == True:
first_num = float(input("Enter your first number: "))
operation = input("Enter your operation: ")
second_num = float(input("Enter your second number: "))
if operation == "+":
print(first_num + second_num)
elif operation == "-":
print(first_num - second_num)
elif operation == "*":
print(first_num * second_num)
elif operation == "/":
print(first_num / second_num)
else:
print("invalid")
| true
|
96fb4e1c83c2c41d3e23f26da20a5c36af2383ea
|
alexmcmillan86/python-projects
|
/sum_target.py
| 729
| 4.125
| 4
|
# finding a pair of numbers in a list that sum to a target
# test data
target = 10
numbers = [ 3, 4, 1, 2, 9 ]
# test solution -> 1, 9 can be summed to make 10
# additional test data
numbers1 = [ -11, -20, 2, 4, 30 ]
numbers2 = [ 1, 2, 9, 8 ]
numbers3 = [ 1, 1, 1, 2, 3, 4, 5 ]
# function with O(n)
def sum_target(nums, target):
seen = {}
for num in nums:
remaining = target - num
if remaining in seen:
return num, remaining
else:
seen[num] = 1
return 'No pairs that sum to target'
print(sum_target(numbers, target))
print(sum_target(numbers1, target))
print(sum_target(numbers2, target))
print(sum_target(numbers3, target))
| true
|
4228d90052f5301e781e2ba2220051f5ea3cec64
|
shuoshuren/PythonPrimary
|
/15异常/xc_02_捕获错误类型.py
| 856
| 4.34375
| 4
|
# 捕获错误类型:针对不同类型的异常,做出不同响应
# 完整语法如下:
# try:
# 将要执行的代码
# pass
# except 错误类型1:
# 针对错误类型1,要执行的代码
# except (错误类型2,错误类型3):
# 针对错误类型2,3要执行的代码
# except Exception as result:
# print("未知错误%s" %result)
# else:
# 没有异常才会执行的代码
# pass
# finally:
# 无论是否有异常,都会执行的代码
try:
num = int(input("请输入一个整数:"))
result = 8/num
print(result)
except ValueError:
print("请输入一个整数")
# except ZeroDivisionError:
# print("不能输入0")
except Exception as result:
print("未知错误 %s" % result)
else:
print("正确执行")
finally:
print("无论是否出现错误都会执行")
| false
|
27b8e98acdd4c3e3a3eff0b4f131751a9a9c29db
|
jfbm74/holbertonschool-higher_level_programming
|
/0x0B-python-input_output/1-number_of_lines.py
| 440
| 4.28125
| 4
|
#!/usr/bin/python3
"""
Module that returns the number of lines of a text file:
"""
def number_of_lines(filename=""):
"""
function that returns the number of lines of a text file
:param filename: File to read
:type filename: filename
:return: integer
:rtype: int
"""
counter = 0
with open("my_file_0.txt", "r", encoding='utf8') as f:
for line in f:
counter += 1
return counter
| true
|
d5490fc4962001fdb36c4885e757827a11de0225
|
jfbm74/holbertonschool-higher_level_programming
|
/0x07-python-test_driven_development/4-print_square.py
| 679
| 4.4375
| 4
|
#!/usr/bin/python3
"""
Module print_square
This module prints a square with the character #
Return: Nothing
"""
def print_square(size):
"""
Function print_square
This function prints a square with the character #
Args:
size: is the size length of the square
Returns: Nothing
"""
if not isinstance(size, (int, float)):
raise TypeError("size must be an integer")
elif isinstance(size, float) and size < 0:
raise TypeError("size must be an integer")
elif size < 0:
raise ValueError("size must be >= 0")
for i in range(size):
for j in range(size):
print("#", end="")
print("")
| true
|
0022986af95ce6ad144c40436e54888205a2cdda
|
rraj29/Dictionaries
|
/game_challenge.py
| 1,826
| 4.21875
| 4
|
locations = {0: "You are sitting in front of a computer, learning python.",
1: "You are standing at the end of a road before a small brick building.",
2: "You are at the top of a hill.",
3: "You are inside a building, a well house for a small stream.",
4: "You are in a valley beside a stream.",
5: "You are in a forest."}
exits = {0: {"Q": 0},
1: {"W": 2,"E": 3,"N": 5,"S": 4,"Q": 0},
2: {"N": 5,"Q": 0},
3: {"W": 1,"Q": 0},
4: {"W": 1,"N": 2,"Q": 0},
5: {"W": 2,"S": 1,"Q": 0}}
vocabulary = {"QUIT": "Q",
"NORTH": "N",
"SOUTH": "S",
"WEST": "W",
"EAST": "E"}
loc = 1
while True:
available_exits = ", ".join(exits[loc].keys())
# available_exits = ""
# for direction in exits[loc].keys():
# available_exits += direction + ", "
print(locations[loc])
if loc==0:
break
direction = input("Available exits are " + available_exits).upper()
print()
#Parse the user input with vocabulary dictionary, if needed
if len(direction) > 1: #more than 1 letter, so check vocab
# for word in vocabulary: #does it contain a word that we know
# if word in direction:
# direction = vocabulary[word]
words = direction.split(" ")
for word in words: # this is more efficient as we are searching for the man word in user's input
if word in vocabulary: #rather than the whole dictionary,
direction = vocabulary[word] #coz if the dictionary was long, it would be very less efficient
break
if direction in exits[loc]:
loc = exits[loc][direction]
else:
print("You can't go in that direction.")
| true
|
0d2e5ff146429d2209e75b4531d833848ee66784
|
sandrahelicka88/codingchallenges
|
/EveryDayChallenge/fizzbuzz.py
| 855
| 4.3125
| 4
|
import unittest
'''Write a program that outputs the string representation of numbers from 1 to n.
But for multiples of three it should output Fizz instead of the number and for the multiples of five output Buzz. For numbers which are multiples of both three and five output FizzBuzz.'''
def fizzBuzz(n):
result = []
for i in range(1,n+1):
if i%3==0 and i%5==0:
result.append('FizzBuzz')
elif i%3==0:
result.append('Fizz')
elif i%5==0:
result.append('Buzz')
else:
result.append(str(i))
return result
class Test(unittest.TestCase):
def test_fizzBuzz(self):
output = fizzBuzz(15)
self.assertEqual(output, ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"])
if __name__ == '__main__':
unittest.main()
| true
|
8f12d5d67d13eba6f5efc1611e52118abeec7fd3
|
alex93skr/Euler_Project
|
/007.py
| 478
| 4.125
| 4
|
# !/usr/bin/python3
# -*- coding: utf-8 -*-
print(f'-----------------------7--')
def prost(n):
"""простые числа from prime"""
if n == 2 or n == 3: return True
if n % 2 == 0 or n < 2: return False
for i in range(3, int(n ** 0.5) + 1, 2): # only odd numbers
if n % i == 0:
return False
return True
limit = 10001
res = 0
n = 1
while not res == limit:
n += 1
if prost(n):
res += 1
print('>>', n, '♥')
| false
|
7b8004e2055f1db5c43aba0a6dc615af24127bb9
|
wcsten/python_cookbook
|
/data_structure/separate_variables.py
| 575
| 4.25
| 4
|
"""
Problema
Você tem uma tupla ou sequência de N elementos que gostaria de desempacotar em
uma coleçāo de N variáveis.
"""
"""
Soluçāo
Qualquer sequência (ou iterável) pode ser desempacotada em variáveis por meio de
uma operaçāo simples de atribuiçāo. O único requisito é que a quantidade de variáveis
e a estrutura correspondam à sequência. Por exemplo:
"""
def separate_variables():
data = ['ACME', 50, 91, (2012, 12, 21)]
name, shares, prices, date = data
print(name, shares, prices, date)
if __name__ == '__main__':
separate_variables()
| false
|
46a5f0c2e5618e80ed9aec030faf878e09a93e4e
|
grkheart/Python-class-homework
|
/homework_1_task_6.py
| 1,136
| 4.34375
| 4
|
# 6. Спортсмен занимается ежедневными пробежками. В первый день его результат составил
# a километров. Каждый день спортсмен увеличивал результат на 10 % относительно
# предыдущего. Требуется определить номер дня, на который общий результат
# спортсмена составить не менее b километров. Программа должна принимать
# значения параметров a и b и выводить одно натуральное число — номер дня.
# Например: a = 2, b = 3.
a = float(input("Введите количество км которые спортсмен пробегает каждый день: "))
b = float(input("Введите рубеж в км который необходимо побить: "))
days = 1
if a > b:
print(days)
while a < b:
a = a + 0.1 * b
days += 1
print(f"Спортсмен пробежит {b} км на {days} день")
| false
|
eb5f823180f5c69fafb99a9c0502f55045bf517b
|
RutujaMalpure/Python
|
/Assignment1/Demo10.py
| 335
| 4.28125
| 4
|
"""
. Write a program which accept name from user and display length of its name.
Input : Marvellous Output : 10
"""
def DisplayLength(name):
ans=len(name)
return ans
def main():
name=input("Enter the name")
ret=DisplayLength(name)
print("the length of {} is {}".format(name,ret))
if __name__=="__main__":
main()
| true
|
cdbaac13c9d4a49dd7c6fb425b6372929aab870d
|
RutujaMalpure/Python
|
/Assignment3/Assignment3_3.2.py
| 842
| 4.15625
| 4
|
"""
.Write a program which accept N numbers from user and store it into List. Return Maximum
number from that List.
Input : Number of elements : 7
Input Elements : 13 5 45 7 4 56 34
Output : 56
"""
def maxnum(arr):
#THIS IS ONE METHOD
#num=arr[0]
#for i in range(len(arr)):
#if(arr[i]>=num):
#num=arr[i]
#return num
#THIS IS THE SECOND METHOD I.E IN PYTHON
num=max(arr)
return num
def main():
arr=[]
print("Enter the number of elements")
size=int(input())
for i in range(size):
print("the element at position",i+1)
no=int(input())
arr.append(no)
print("the entered list is",arr)
ret=maxnum(arr)
print("The max element of list is",ret)
if __name__=="__main__":
main()
| true
|
8d320f16d9ab715efda548016fa5bc02e96e0588
|
zkevinbai/LPTHW
|
/ex34.quiz.py
| 2,904
| 4.46875
| 4
|
# my first app
# this is a quiz program which tests a novice programmer's ability to understand
# how indexing works with ordinal (0, 1, 2) and cardinal (1, 2, 3) numbers
# list of animals/answers, and indexes/questions
animal = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
List = [0, 1, 2, 3, 4, 5, 'first', 'second', 'third', 'fourth', 'fifth', 'sixth']
# imports the random interger function
from random import randint
# do not know how this works, imports the text to integer function
import sys
import os
sys.path.append(os.path.abspath("/Users/kevinbai/Exercises/Tools"))
from text_to_int import text2int
# imports the numbers
import numbers
# identifies the global list count as the number of items in the list
# starts problem count at one
list_count = len(List)
problem_count = 1
# opening lines, stylized
print'''
\t Welcome to the Python Index Understanding Quiz (PIUQ)
\t Your list for today: animal
'''
# while loop that comprises the majority of the code to be used
# I could have used a for loop here but that would lower the scalability of the code
# while loop allows me to run this with any list
# this while loop runs up to the point where problem_count = list_count
while problem_count <= list_count:
# I have a local list_count_updated to keep track
# of my eliminated, already-asked questions
list_count_updated = len(List)
# my random index generator allows me to randomly select the remaining prompts
number = randint(0, list_count_updated - 1)
# my list_item variable allows me to use the prompts I randomly generate
list_item = List[number]
# prints the list being tested so that the user will always have it for reference
print "animal = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']"
# prints the problem count and the current prompt
print "Problem #%d: What is the animal at %r?" % (problem_count, list_item)
# asks user for their answers
user_input = raw_input("> ")
# if the prompt is a number (which half of them are)
if isinstance(list_item, numbers.Number) == True:
# the correct animal can simply be accessed from the list
correct_animal = animal[list_item]
# if the prompt is a string(word)
else:
# the prompt is coverted into a number
list_int = text2int(list_item)
# the number is then used to access the correct animal
correct_animal = animal[list_int - 1]
# if the user is correct, print correct
if user_input == correct_animal:
print "correct\n"
# if the user is incorrect, print so and produce the correct answer
else:
print "incorrect, the answer is %s\n" % correct_animal
# removes an element from the prompt list after it is asked to prevent
# duplicate problems
List.remove(list_item)
# augements the problem count by 1
problem_count += 1
| true
|
c925b58fd1c717cd76feb44899fe65d3ac87722c
|
zkevinbai/LPTHW
|
/ex20.py
| 965
| 4.3125
| 4
|
# imports argument variables from terminal
from sys import argv
# unpacks argv
script, input_file = argv
# defines print_all() as a function that reads a file
def print_all(f):
print f.read()
# defines rewind() as a function that finds
def rewind(f):
f.seek(0)
# defines print_a_line as a function that prints one line
def print_a_line(line_count, f):
print line_count, f.readline(),
# identifies current_file as a variable which opens the input_file
current_file = open(input_file)
print "First let's print the whole file:"
# runs print_all on current_file
print_all(current_file)
print "Now let's rewind, kind of like a tape.\n"
# runs rewind on current_file
rewind(current_file)
print "Let's print 3 lines:"
# runs print a line 3 times for the 3 lines in the file
current_line = 1
print_a_line(current_line, current_file)
current_line += 1
print_a_line(current_line, current_file)
current_line += 1
print_a_line(current_line, current_file)
| true
|
1a78c13413ea3afdfc85f9d38600c34572b2dad8
|
ivanchen52/leraning
|
/ST101/mode.py
| 433
| 4.15625
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 1 11:36:09 2017
@author: ivanchen
"""
#Complete the mode function to make it return the mode of a list of numbers
data1=[1,2,5,10,-20,5,5]
def mode(data):
modecnt = 0
for i in range(len(data)):
icount = data.count(data[i])
if icount > modecnt:
mode = data[i]
modecnt = icount
return mode
print(mode(data1))
| true
|
a502a5919e592bfaf5580f83ff294cb866ca1742
|
EliMendozaEscudero/ThinkPython2ndEdition-Solutions
|
/Chapter 10/Exercise10-3.py
| 293
| 4.125
| 4
|
def middle(t):
"""It takes a list and return a new list with all but
the first and last elements."""
t1 = t[:]
del t1[0]
del t1[len(t1)-1]
return t1
if __name__=='__main__':
t = [True,'Hello world',431,None,12]
print('Original: ' + str(t))
print('Modified : ' + str(middle(t)))
| true
|
7760610b35f45b8ae1b9493a8e210aaa5a19f867
|
EliMendozaEscudero/ThinkPython2ndEdition-Solutions
|
/Chapter 6/palindrome.py
| 1,160
| 4.1875
| 4
|
#Exercise 6-3 from "Think python 2e"
def first(word):
"""It returns the first character of a string"""
return word[0]
def last(word):
"""It returns the last character of a string"""
return word[-1]
def midle(word):
"""It returns the string between the last and the first character of a stirng"""
return word[1:-1]
def is_palindrome(word):
"""It checks whether or not a word is palindrome"""
return is_palindrome_not_inclusive(word.upper())
def is_palindrome_not_inclusive(word):
"""It checks whether or not a word that only contains
upper case letters or only contains lower case letters is palindrome."""
if len(word)<2:
return True
elif first(word)==last(word) and is_palindrome(midle(word)):
return True
else:
return False
if __name__== "__main__":
print(midle("ab"))
print(midle("a"))
while(True):
word = input("Type a word to check whether or not it is palindrome or just press enter to exit:\n")
if len(word) > 0:
print(word + (" is palindrome." if is_palindrome(word) else " is not palindrome."))
else:
break
| true
|
7b22dbbe8673675d1ecfca185877c903899b4745
|
EliMendozaEscudero/ThinkPython2ndEdition-Solutions
|
/Chapter 10/Exercise10-5.py
| 363
| 4.125
| 4
|
def is_sorted(t):
"""It take a list and returns True if it's sorted in
ascending order and False otherwise."""
t1 = t[:]
t1.sort()
if t == t1:
return True
else:
return False
if __name__=='__main__':
t = [42,1,32,0,-2341,2]
t1 = [1,3,5,10,100]
print(str(t)+'\nSorted: '+str(is_sorted(t)))
print(str(t1)+'\nSorted: '+str(is_sorted(t1)))
| true
|
1475f834d657d0a4bd22927def4b5ec47f8f9b24
|
Chris-LewisI/OOP-Python
|
/week-7/set_assignment.py
| 1,043
| 4.375
| 4
|
# Author: Chris Ibraheem
# The following code below will use the random module to create a list of values from 1 to 10.
# Using the code below to create a random list of values, do the following:
# Count the number of times each number (1-10) appears in the list that was created. Print out a formatted string that lists the number and the count for that number Use a set object to remove the duplicates from the list. Confirm the set successfully removed the duplicates by printing out the length of the set.
# imports random library so that it can create a list with random variables
import random
random.seed(1)
list_of_numbers=[random.randint(1,10) for i in range(100)]
# counting and printing the amount of occurrences for each of the numbers 1 - 10
for x in range(1,11):
counter = 0
for y in list_of_numbers:
if x == y:
counter = counter + 1
print(f"{x}:\t{counter}")
# create a set to remove duplicates and display it to verify
set_of_numbers = set(list_of_numbers)
print(f"Set Of Numbers: {set_of_numbers}")
| true
|
8ce325259a74dff8fb76ded6fbbaca275aa86624
|
Chris-LewisI/OOP-Python
|
/week-1-&-2/exercise-1.py
| 267
| 4.1875
| 4
|
# author: Chris Ibraheem
# takes first name as input after prompt
first_name = input("First Name: ")
# takes last name as input after prompt
last_name = input("Last Name: ")
# prints a greeting using the string input from the user
print(f"Hello {first_name} {last_name}!")
| true
|
c2ca0fda6cce4e0a8461479fba4b2488dc930471
|
NickjClark1/PythonClass
|
/Chapter 5/rebuiltfromscratch.py
| 682
| 4.125
| 4
|
# Output program's purpose
print("Decimal to Base 2-16 converter\n")
def main():
print("Decimal to Base 2-16 converter\n")
number = int(input("Enter a number to convert: "))
for base in range(1, 17):
print (convertDecimalTo(number, base))
#end main function
def convertDecimalTo(number, base):
result = ""
number = number // base
while number > 0:
remainder = number % base
if remainder < 10:
result = (remainder) + number
return result
else:
result = 8
return result
main()
# while number > 0: remainder = number % base
| true
|
0a7603cd17344d5ac28c059209056bb6c98d7fa0
|
ibrahimhalilbayat/numpy-tutorials
|
/2_array_creation.py
| 1,321
| 4.21875
| 4
|
print("""
İbrahim Halil Bayat
Department of Electronics and Communication Engineering
İstanbul Technical University
İstanbul, Turkey
""")
import numpy as np
# First way
a = np.array([1, 2, 3])
print("With array command: \n", a)
# Second way
b = np.array([[1, 2], [3, 4]], dtype=complex)
print("Complex elements: \n", b)
# Array with zeros
c = np.zeros((3, 4), dtype='int')
print("Array with integer zeros: \n", c)
d = np.zeros((3, 4), dtype='float')
print("Array with float zeros: \n", d)
# 3 dimensional array with ones
e = np.ones((2, 3, 4), dtype='int')
print("3 dimensional array: \n", e)
print("Dimension of this array: ", e.ndim)
print("Shape of this 3 dimensional array: ", e.shape)
# Third way to create numpy array
f = np.arange(10, 30, 5, dtype = 'float')
print("Array with arange function: ", f)
# Creating an empty array
g = np.empty((2, 3), dtype='float', order='F')
print("An empty array with the shape 2, 3\n: ", g)
# with linspace
h = np.linspace(0, 2, 9)
print("Array with linspace: ", h)
print("The shape of linspaced array: ", h.shape)
from numpy import pi
j = np.linspace(0, 2*pi, 100)
k = np.sin(j)
print(k)
l = np.arange(0, 12).reshape(4, 3)
print("The array: ", l)
s = np.array(l<10)
print("The elemets of the l<10: \n", s)
| false
|
517d839fbbe4ad585393953f97487e2e34faedf1
|
gouyanzhan/daily-learnling
|
/class_08/class_03.py
| 1,627
| 4.15625
| 4
|
#继承
class RobotOne:
def __init__(self,year,name):
self.year = year
self.name = name
def walking_on_ground(self):
print(self.name + "只能在平地上行走")
def robot_info(self):
print("{0}年产生的机器人{1},是中国研发的".format(self.year,self.name))
#继承
class RobotTwo(RobotOne):
def walking_on_ground(self): #子类里面的函数名和父类函数名重复的时候,就叫重写
print(self.name + "可以在平地平稳地上行走")
def walking_avoid_block(self): #拓展
#我想在子类的函数里面调用父类的一个函数
self.robot_info()
print(self.name + "可以避开障碍物")
#继承的类 是否要用到初始化函数 请看是否从父类里面继承了
#1:父类有的,继承后,我都可以直接拿来用
#2:父类有,子类也有重名的函数,那么子类的实例就优先调用子类的函数
#3:父类没有,子类
r2= RobotTwo("1990","小王")
r2.robot_info()
r2.walking_on_ground()
r2.walking_avoid_block()
class RobotThree(RobotTwo,RobotOne): #第三代机器人继承第一代和第二代
def __init__(self,year,name):
self.year = year
self.name = name
def jump(self):
print(self.name + "可以单膝跳跃")
r3 = RobotThree("2000","大王")
r3.robot_info()
#多继承的子类具有两个父类的属性和方法,
# 如果两个父类具有同名方法的时候,子类调用函数就近原则,谁在前就继承谁的
# 初始化函数也包括在内(就近父类无,子类可以重写初始化函数)
| false
|
48638c406d2b678416dd75dd04b22814d061013a
|
C-CCM-TC1028-102-2113/tarea-4-CarlosOctavioHA
|
/tarea-4-CarlosOctavioHA/assignments/10.1AlternaCaracteresContador/src/exercise.py
| 323
| 4.125
| 4
|
#Alternar caracteres
num = int(input("Dame un numero"))
cont = 0
variable_1= "#"
while cont < num:
cont = cont + 1
if variable_1 == "#":
print(cont,"-", variable_1)
variable_1= "%"
else:
variable_1 == "%"
print (cont,"-", variable_1)
variable_1= "#"
| false
|
ed03cef20773b13070143965de70c7ae5bbff50e
|
aayush26j/DevOps
|
/practical.py
| 275
| 4.28125
| 4
|
num=int(input(print("Enter a number\n")))
factorial = 1
if num < 0:
print("Number is negative,hence no factorial.")
elif num ==0:
print("The factorial is 1")
else:
for i in range(1,num+1):
factorial=factorial*i
print("The factorial is ",factorial)
| true
|
ecb0fcd7b5843debc01afe56646dd0ad834db33b
|
jocassid/Miscellaneous
|
/sqlInjectionExample/sqlInjection.py
| 2,942
| 4.15625
| 4
|
#!/usr/bin/env python3
from sqlite3 import connect, Cursor
from random import randint
class UnsafeCursor:
"""Wrapper around sqlite cursor to make it more susceptible to a basic
SQL injection attack"""
def __init__(self, cursor):
self.cursor = cursor
def execute(self, sql, params=None):
"""Standard cursor.execute only allows a single SQL command to be run"""
if params is None:
for statement in sql.split(';'):
self.cursor.execute(statement)
return
print('string parameters get escaped to guard against sql injection')
print("resulting sql is " + \
sql.replace("?", "'" + params[0].replace("'", "''") + "'"))
self.cursor.execute(sql, params)
def executemany(self, sql, params):
self.cursor.executemany(sql, params)
def __iter__(self):
return self.cursor.__iter__()
with connect(':memory:') as conn:
cursor = conn.cursor()
# This is a hack to make it easy to perform the classic SQL injection hack
cursor = UnsafeCursor(cursor)
cursor.execute("CREATE TABLE Book(title text, author text)")
books = [
("Pattern Recognition", "William Gibson"),
("Hitchhiker's Guide to the Galaxy", "Douglas Adams"),
("Witches Abroad", "Terry Pratchett")
]
cursor.executemany("INSERT INTO Book VALUES(?, ?)", books)
cursor.execute("""CREATE TABLE User(username text, is_admin text)""")
cursor.execute("""INSERT INTO User VALUES('hacker', 'N')""")
conn.commit()
print("Starting Contents of database")
sql = "SELECT * FROM Book"
print(sql)
cursor.execute(sql)
for row in cursor:
print(row)
sql = "SELECT * FROM User"
print("\n" + sql)
cursor.execute(sql)
for row in cursor:
print(row)
print("\nA harmless query using author value provided by user")
author = 'William Gibson'
sql = "SELECT * FROM Book WHERE author='" + author + "'"
print(sql)
cursor.execute(sql)
for row in cursor:
print(row)
print("\nNow the hacker enters a value for author to inject a 2nd statement separated by a semicolon")
author = "'; UPDATE User SET is_admin='Y' WHERE username='hacker"
sql = "SELECT * FROM Book WHERE author='" + author + "'"
print(sql)
cursor.execute(sql)
print("\nThe hacker now has admin access")
cursor.execute("SELECT * FROM User")
for row in cursor:
print(row)
print("\nReset hacker account back to normal")
cursor.execute("UPDATE User SET is_admin='N' WHERE username='hacker'")
cursor.execute("SELECT * FROM User")
for row in cursor:
print(row)
print("\nQuery written the safe way")
cursor.execute(
"SELECT * FROM Book WHERE author=?",
(author,))
| true
|
3d9afb50aa377e790a19cdabd9db440969fae7a8
|
jkaria/coding-practice
|
/python3/Chap_9_BinaryTrees/9.2-symmetric_binary_tree.py
| 1,627
| 4.25
| 4
|
#!/usr/local/bin/python3
from node import BinaryTreeNode
def is_symmetric(tree):
def check_symmetric(subtree_0, subtree_1):
if not subtree_0 and not subtree_1:
return True
elif subtree_0 and subtree_1:
return (subtree_0.data == subtree_1.data
and check_symmetric(subtree_0.left, subtree_1.right)
and check_symmetric(subtree_0.right, subtree_1.left))
# else one is null i.e. not symmetric
return False
return not tree or check_symmetric(tree.left, tree.right)
if __name__ == '__main__':
print('Test if a binary tree is symmetric')
print("is_symmetric(None) ->", is_symmetric(None))
single_node = BinaryTreeNode(314)
print("is_symmetric(single_node) ->", is_symmetric(single_node))
symtree_1 = BinaryTreeNode(314, BinaryTreeNode(6), BinaryTreeNode(6))
symtree_1.left.right = BinaryTreeNode(2, right=BinaryTreeNode(3))
symtree_1.right.left = BinaryTreeNode(2, left=BinaryTreeNode(3))
print("is_symmetric(symtree_1) ->", is_symmetric(symtree_1))
symtree_2 = BinaryTreeNode(314, BinaryTreeNode(6), BinaryTreeNode(6))
symtree_2.left.right = BinaryTreeNode(561, right=BinaryTreeNode(3))
symtree_2.right.left = BinaryTreeNode(2, left=BinaryTreeNode(3))
print("is_symmetric(symtree_2) ->", is_symmetric(symtree_2))
symtree_3 = BinaryTreeNode(314, BinaryTreeNode(6), BinaryTreeNode(6))
symtree_3.left.right = BinaryTreeNode(561, right=BinaryTreeNode(3))
symtree_3.right.left = BinaryTreeNode(561)
print("is_symmetric(symtree_3) ->", is_symmetric(symtree_3))
| true
|
9a3c939c18e9c648a02710031af7e5da96cc3374
|
krunal16-c/pythonprojects
|
/Days_to_years.py
| 440
| 4.3125
| 4
|
# Converting days into years using python 3
WEEK_DAYS = 7
# deining a function to find year, week, days
def find(no_of_days):
# assuming that year is of 365 days
year = int(no_of_days/365)
week = int((no_of_days%365)/WEEK_DAYS)
days = (no_of_days%365)%WEEK_DAYS
print("years",year,
"\nWeeks",week,
"\ndays", days)
# driver code
no_of_days = int(input("Enter number of days.\n"))
find(no_of_days)
| true
|
80611801e607d18070c39d9313bbf51586980f16
|
fominykhgreg/SimpleAlgorithms
|
/ALG9.py
| 1,281
| 4.15625
| 4
|
"""
Вводятся три разных числа. Найти, какое из них является средним (больше одного, но меньше другого).
"""
print("Enter 'exit' for exit.")
def average_func():
a = input("First - ")
if a == "exit":
return print("Good bye!")
b = int(input("Second - "))
c = int(input("Third - "))
a = int(a)
z = []
z.append(a)
z.append(b)
z.append(c)
if a == b or a == c:
print(f"Average number - {a}")
print("+" * 100)
return average_func()
if c == b or c == a:
print(f"Average number - {c}")
print("+" * 100)
return average_func()
if b == a or b == c:
print(f"Average number - {b}")
print("+" * 100)
return average_func()
print("+" * 100)
print(f'List - {z}')
k = max(z)
l = min(z)
print(f'Max & min - {k} & {l}')
i = 0
while i <= len(z):
if z[i] != k:
if z[i] != l:
print(f"Average number - {z[i]}")
print("+" * 100)
return average_func()
else:
i = i+1
else:
i = i+1
average_func()
| false
|
130aee595a5c7aa78c89d5ee034129315afdbe10
|
mrkarppinen/the-biggest-square
|
/main.py
| 1,804
| 4.1875
| 4
|
import sys
def find_biggest_square(towers):
# sort towers based on height
towers.sort(key=lambda pair: pair[1], reverse = True)
# indexes list will hold tower indexes
indexes = [None] * len(towers)
biggestSquare = 0
# loop thorough ordered towers list
for tower in towers:
height = tower[1]
index = tower[0]
if (height <= biggestSquare):
# if already found square with size height * height
# return biggestSquare as towers are getting shorter
return biggestSquare
indexes[index] = index
# indexes list will contain towers taller than this tower
# check how many neighbour towers are already in the list
# so the biggestSquare after this tower is added to list is
# neighborougs * height
size = tower_sequence(indexes, index, height)
if ( size > biggestSquare ):
biggestSquare = size
return None
def tower_sequence(items, i, maxLength):
leftNeighbours = neighbours(items, i, -1, max(0, i-maxLength) )
if (leftNeighbours + 1 == maxLength):
return maxLength
rightNeighbours = neighbours(items, i, 1, min(len(items)-1, i + (maxLength - leftNeighbours) ) )
return (leftNeighbours + rightNeighbours + 1)
def neighbours(items, i, step, end):
if i == end:
return 0
start = i + step
end = end + step
for index in xrange(start, end, step):
if items[index] == None:
return abs(i-index)-1
return abs(start - end)
if __name__ == "__main__":
filename = sys.argv[1] if len(sys.argv) == 2 else 'input.txt'
input = open(filename)
towers = [ (index, int(line)) for index, line in enumerate(input)]
print 'Solution ' + str(find_biggest_square(towers))
| true
|
4239700e5be91ec7126fecc11dbc4ab405f22a3e
|
RHIT-CSSE/catapult
|
/Code/Raindrops/StevesObjectExamples/EmployeeClass.py
| 1,055
| 4.375
| 4
|
# First we define the class:
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)
# End of class definition
# Now we can use the class, either here, or in other python files in the same directory.
# In the latter case, we would say "import EmployeeClass" to get access to this class.
# Let's try a couple examples here:
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
emp1.age = 7 # Add an 'age' attribute.
emp1.age = 8 # Modify 'age' attribute.
print ("Employee 1 age is ",emp1.age)
# same kind of thing but usings lists
# lets give everbody a raise!
all_employees = [emp1, emp2]
for e in all_employees:
e.salary = e.salary + 100
e.displayEmployee()
| true
|
69e2a5128e5c34f2968e5bde4ea733630ef74134
|
RHIT-CSSE/catapult
|
/Code/DogBark/Session3FirstProgram.py
| 2,700
| 4.75
| 5
|
# This is an example of a whole program, for you to modify.
# It shows "for loops", "while loops" and "if statements".
# And it gives you an idea of how function calls would be used
# to make an entire program do something you want.
# Python reads the program from top to bottom:
# First there are two functions. These don't really "do"
# anything until they are called later.
# This function finds the prime divisors of a number.
# Nothing to do here, but it shows a function with a while-loop
# and an if-statement.
def divisorsOf(bigNumber):
listOfDivisors = [] # An empty list, to start building from
nextNumber = bigNumber
nextDivisor = 2
while (bigNumber > 1):
if (bigNumber % nextDivisor == 0):
#print(" "+str(nextDivisor))
bigNumber = bigNumber // nextDivisor
listOfDivisors.append(nextDivisor) # add to the list
else:
nextDivisor = nextDivisor+1
return listOfDivisors
# This function finds the season of a date, as in the Session 2 slides.
# The year parameter isn't used!
# This one has a "TODO" at the bottom:
def seasonOf(date): # The date is a "tuple" of month, day, year
month = date[0] # These commands separate the 3 parts of the tuple
day = date[1]
year = date[2]
season = "error" # in case a date is not assigned to a season
if (month == 10 or month == 11):
season = "fall"
elif (month == 1 or month == 2):
season = "winter"
elif (month == 4 or month == 5):
season = "spring"
elif (month == 7 or month == 8):
season = "summer"
elif (month == 12):
if (day < 21):
season = "fall"
else:
season = "winter"
elif (month == 3):
if (day < 21):
season = "winter"
else:
season = "spring"
return season
# TODO: You finish this function, for months 6 and 9, above the return!
# Then here's the part of the program which really causes
# something to happen. Code that includes calling the functions
# defined above:
print("Hello world!")
# Test cases:
print("Divisor tests:")
# The for-loop picks consecutive values from a Python "list":
for myDivisorTest in [2,3,4,5,6,7,8,9,12,13,24,35]:
print("Prime divisors of "+str(myDivisorTest))
print (divisorsOf(myDivisorTest))
print("Season tests:")
# This is a list of "tuples" representing dates:
myDateList = [ (1,1,2019), (2,1,2019), (3,1,2019), (3,25,2019),
(4,1,2019), (5,1,2019), (6,1,2019), (6,25,2019),
(7,1,2019), (8,1,2019), (9,1,2019), (9,25,2019),
(10,1,2019), (11,1,2019), (12,1,2019), (12,25,2019) ]
for myDateTest in myDateList:
print (seasonOf(myDateTest))
| true
|
69beb8bab0fe28d2e94cc6f12b60ecf73dba3852
|
dmaydan/AlgorithmsTextbook-Exercises
|
/Chapter4/exercise2.py
| 210
| 4.28125
| 4
|
# WRITE A RECURSIVE FUNCTION TO REVERSE A LIST
def reverse(listToReverse):
if len(listToReverse) == 1:
return listToReverse
else:
return reverse(listToReverse[1:]) + listToReverse[0:1]
print(reverse([1]))
| true
|
0cc02c8d3f8a59c29a8ef55ab9fee88a2f768399
|
Suiname/LearnPython
|
/dictionary.py
| 861
| 4.125
| 4
|
phonebook = {}
phonebook["John"] = 938477566
phonebook["Jack"] = 938377264
phonebook["Jill"] = 947662781
print phonebook
phonebook2 = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}
print phonebook2
print phonebook == phonebook2
for name, number in phonebook.iteritems():
print "Phone number of %s is %d" % (name, number)
del phonebook["John"]
print phonebook
phonebook2.pop("John")
print phonebook2
# Add "Jake" to the phonebook with the phone number 938273443, and remove Jill from the phonebook.
phonebook = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}
# write your code here
phonebook["Jake"] = 938273443
phonebook.pop("Jill")
# testing code
if "Jake" in phonebook:
print "Jake is listed in the phonebook."
if "Jill" not in phonebook:
print "Jill is not listed in the phonebook."
| true
|
864d0c93264da52d34c8b9e4fe263ca63b7efdda
|
daimessdn/py-incubator
|
/exercise list (py)/sorting/bubble.py
| 820
| 4.125
| 4
|
# Bubble Short
list = []
for i in range(0,25):
x = float(input(""))
list.append(x)
# swap the elements to arrange in order
# ascending
for iter_num in range(len(list)-1, 0, -1):
for index in range(iter_num):
if (list[index] > list[index+1]):
temp = list[index]
list[index] = list[index+1]
list[index+1] = temp
# descending
# for iter_num in range(len(list)-1, 0, -1):
# for index in range(iter_num):
# if (list[index] > list[index+1]):
# temp = list[index]
# list[index] = list[index+1]
# list[index+1] = temp
# with subprogram
# def bubblesort(list):
# for iter_num in range(len(list)-1, 0, -1):
# for index in range(iter_num):
# if (list[index] > list[index+1]):
# temp = list[index]
# list[index] = list[index+1]
# list[index+1] = temp
# bubblesort(list)
print(list)
| false
|
2fb640ca926f9769d4ee6f9c0de68e1de8b5729c
|
organisciak/field-exam
|
/stoplisting/__init__.py
| 1,421
| 4.1875
| 4
|
'''
Python code
Example of word frequencies with and without stopwords.
Uses Natural Language Toolkit (NLTK) - Bird et al. 2009
bush.txt is from http://www.bartleby.com/124/pres66.html
obama.txt is from http://www.whitehouse.gov/blog/inaugural-address
'''
from nltk import word_tokenize
from nltk.probability import FreqDist
from nltk.corpus import stopwords
from nltk.tokenize import sent_tokenize
def main():
# Number of words to display
count = 40
# Open files as strings
obama = open("obama.txt", "r").read()
bush = open("bush.txt", "r").read()
#Tokenize texts into words, then count frequencies for all words
top_obama = FreqDist(word.lower() for word in word_tokenize(obama))
top_bush = FreqDist(word.lower() for word in word_tokenize(bush))
#Return top {count} most occurring words
print "No stoplist".upper()
print "Obama/2009\t".upper(), " ".join(item[0] for item in top_obama.items()[:count])
print "Bush/2001\t".upper(), " ".join(item[0] for item in top_bush.items()[:count])
#Return most occurring words that are not in the NLTK English stoplist
print
print "Stoplisted".upper()
print "Obama/2009\t".upper(), " ".join([item[0] for item in top_obama.items() if not item[0] in stopwords.words('english')][:count])
print "Bush/2001\t".upper(), " ".join([item[0] for item in top_bush.items() if not item[0] in stopwords.words('english')][:count])
if __name__ == '__main__':
main()
| true
|
6d315993b7fe772ac2d2fe290db19438efad581e
|
sumittal/coding-practice
|
/python/print_anagram_together.py
| 1,368
| 4.375
| 4
|
# A Python program to print all anagarms together
#structure for each word of duplicate array
class Word():
def __init__(self, string, index):
self.string = string
self.index = index
# create a duplicate array object that contains an array of Words
def create_dup_array(string, size):
dup_array = []
for i in range(size):
dup_array.append(Word(string[i], i))
return dup_array
# Given a list of words in wordArr[]
def print_anagrams_together(wordArr, size):
# Step 1: Create a copy of all words present in
# given wordArr.
# The copy will also have orignal indexes of words
dupArray = create_dup_array(wordArr, size)
# Step 2: Iterate through all words in dupArray and sort
# individual words.
for i in range(size):
dupArray[i].string = ''.join(sorted(dupArray[i].string))
# Step 3: Now sort the array of words in dupArray
dupArray = sorted(dupArray, key=lambda k: k.string)
# Step 4: Now all words in dupArray are together, but
# these words are changed. Use the index member of word
# struct to get the corresponding original word
for word in dupArray:
print(wordArr[word.index])
# Driver program
wordArr = ["cat", "dog", "tac", "god", "act"]
size = len(wordArr)
print_anagrams_together(wordArr, size)
| true
|
39ac1ff3e0e7a78438a9015f83708fc95fdcf1b4
|
sumittal/coding-practice
|
/python/trees/diameter.py
| 930
| 4.1875
| 4
|
"""
Diameter of a Binary Tree
The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two end nodes.
"""
class Node:
def __init__(self,val):
self.data = val
self.left = None
self.right = None
def height(root):
if root is None:
return 0
return 1 + max(height(root.left), height(root.right))
def diameter(root):
if root is None:
return 0
# Get the height of left and right sub-trees
lh = height(root.left)
rh = height(root.right)
# Get the diameter of left and irgh sub-trees
ld = diameter(root.left)
rd = diameter(root.right)
return max(1 + lh + rh, max(ld, rd))
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print("Diameter of given binary tree is %d" %(diameter(root)))
| true
|
0b6eaf6f099c3b7197101b2d8892e3529f2f0c75
|
FabioOJacob/instruct_test
|
/main.py
| 2,136
| 4.1875
| 4
|
import math
class Point():
"""
A two-dimensional Point with an x and an y value
>>> Point(0.0, 0.0)
Point(0.0, 0.0)
>>> Point(1.0, 0.0).x
1.0
>>> Point(0.0, 2.0).y
2.0
>>> Point(y = 3.0, x = 1.0).y
3.0
>>> Point(1, 2)
Traceback (most recent call last):
...
ValueError: both coordinates value must be float
>>> a = Point(0.0, 1.0)
>>> a.x
0.0
>>> a.x = 3.0
>>> a.x
3.0
"""
def __init__(self, x, y):
self.x = x
self.y = y
if type(self.x) != float and type(self.y) != float:
raise ValueError('both coordinates value must be float')
def __repr__(self):
return f'{self.__class__.__name__}({str(self.x)}, {str(self.y)})'
def verifica(a, b):
if type(a) != Point:
raise ValueError('a must be a Point')
elif type(b) != Point:
raise ValueError('b must be a Point')
def euclidean_distance(a, b):
"""
Returns the euclidean distance between Point a and Point b
>>> euclidean_distance(Point(0.0, 0.0), Point(3.0, 4.0))
5.0
>>> euclidean_distance((0.0, 0.0), (3.0, 4.0))
Traceback (most recent call last):
...
ValueError: a must be a Point
>>> euclidean_distance(Point(0.0, 0.0), (3.0, 4.0))
Traceback (most recent call last):
...
ValueError: b must be a Point
"""
from math import sqrt
verifica(a, b)
dist = sqrt( (a.x - b.x)**2 + (a.y - b.y)**2 )
return dist
def manhattan_distance(a, b):
"""
Returns the manhattan distance between Point a and Point b
>>> manhattan_distance(Point(0.0, 0.0), Point(3.0, 4.0))
7.0
>>> manhattan_distance((0.0, 0.0), (3.0, 4.0))
Traceback (most recent call last):
...
ValueError: a must be a Point
>>> manhattan_distance(Point(0.0, 0.0), (3.0, 4.0))
Traceback (most recent call last):
...
ValueError: b must be a Point
"""
from math import fabs
verifica(a, b)
dist = fabs( a.x - b.x) + fabs( a.y - b.y)
return dist
if __name__ == "__main__":
import doctest
doctest.testmod()
| true
|
a2df6569fb7553f72667c03ae67ace637b9b9dbb
|
akaliutau/cs-problems-python
|
/problems/sort/Solution406.py
| 1,615
| 4.125
| 4
|
""" You are given an array of people, people, which are the attributes of some
people in a queue (not necessarily in order). Each people[i] = [hi, ki]
represents the ith person of height hi with exactly ki other people in front
who have a height greater than or equal to hi. Reconstruct and return the
queue that is represented by the input array people. The returned queue
should be formatted as an array queue, where queue[j] = [hj, kj] is the
attributes of the jth person in the queue (queue[0] is the person at the
front of the queue).
Example 1: Input: people =
[[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]] Output:
[[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]
Explanation: Person 0 has height 5 with
no other people taller or the same height in front. Person 1 has height 7
with no other people taller or the same height in front. Person 2 has height
5 with two persons taller or the same height in front, which is person 0 and
1. Person 3 has height 6 with one person taller or the same height in front,
which is person 1. Person 4 has height 4 with four people taller or the same
height in front, which are people 0, 1, 2, and 3. Person 5 has height 7 with
one person taller or the same height in front, which is person 1. Hence
[[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] is the reconstructed queue.
IDEA:
1) use sorting to track the shortest person
2) on each check compare (the number of people already in queue) with (number of needed persons to be ahead)
3) add the person at optimal position
"""
class Solution406:
pass
| true
|
657280e2cf8fbbc26b59ed7830b342713cac502b
|
akaliutau/cs-problems-python
|
/problems/hashtable/Solution957.py
| 1,240
| 4.15625
| 4
|
""" There are 8 prison cells in a row, and each cell is either occupied or
vacant.
Each day, whether the cell is occupied or vacant changes according to the
following rules:
If a cell has two adjacent neighbors that are both occupied or both vacant,
then the cell becomes occupied. Otherwise, it becomes vacant. (Note that
because the prison is a row, the first and the last cells in the row can't
have two adjacent neighbors.)
We describe the current state of the prison in the following way: cells[i] ==
1 if the i-th cell is occupied, else cells[i] == 0.
Given the initial state of the prison, return the state of the prison after N
days (and N such changes described above.)
Example 1:
Input: cells = [0,1,0,1,1,0,0,1], N = 7 Output: [0,0,1,1,0,0,0,0]
Explanation: The following table summarizes the state of the prison on each
day:
Day 0: [0, 1, 0, 1, 1, 0, 0, 1]
Day 1: [0, 1, 1, 0, 0, 0, 0, 0]
Day 2: [0, 0, 0, 0, 1, 1, 1, 0]
Day 3: [0, 1, 1, 0, 0, 1, 0, 0]
Day 4: [0, 0, 0, 0, 0, 1, 0, 0]
Day 5: [0, 1, 1, 1, 0, 1, 0, 0]
Day 6: [0, 0, 1, 0, 1, 1, 0, 0]
Day 7: [0, 0, 1, 1, 0, 0, 0, 0]
"""
class Solution957:
pass
| true
|
1ac4822dd02e34f946f4183122d8a6b5ec804d02
|
akaliutau/cs-problems-python
|
/problems/greedy/Solution678.py
| 1,937
| 4.25
| 4
|
""" Given a string containing only three types of characters: '(', ')' and '*',
write a function to check whether trightBoundarys string is valid. We define
the validity of a string by these rules:
Any left parenthesis '(' must have a corresponding right parenthesis ')'. Any
right parenthesis ')' must have a corresponding left parenthesis '('. Left
parenthesis '(' must go before the corresponding right parenthesis ')'. '*'
could be treated as a single right parenthesis ')' or a single left
parenthesis '(' or an empty string. An empty string is also valid.
Example 1: Input: "()" Output: True
( * ) )
l 1 0 -1 -2
t 1 2 1 0
When checking whether the string is valid, we only cared about the "balance":
the number of extra, open left brackets as we parsed through the string. For
example, when checking whether '(()())' is valid, we had a balance of 1, 2,
1, 2, 1, 0 as we parse through the string: '(' has 1 left bracket, '((' has
2, '(()' has 1, and so on. This means that after parsing the first i symbols,
(which may include asterisks,) we only need to keep track of what the balance
could be.
For example, if we have string '(***)', then as we parse each symbol, the set
of possible values for the balance is
[1] for '(';
[0, 1, 2] for '(*';
[0, 1, 2, 3] for '(**';
[0, 1, 2, 3, 4] for '(***', and
[0, 1, 2, 3] for '(***)'.
Furthermore, we can prove these states always form a contiguous interval.
Thus, we only need to know the left and right bounds of this interval. That
is, we would keep those intermediate states described above as [lo, hi] = [1,
1], [0, 2], [0, 3], [0, 4], [0, 3].
Algorithm
Let lo, hi respectively be the smallest and largest possible number of open
left brackets after processing the current character in the string.
"""
class Solution678:
pass
| true
|
f4248de8ff831fbb0103ccce3c0effde23ea28ad
|
akaliutau/cs-problems-python
|
/problems/backtracking/Solution291.py
| 830
| 4.4375
| 4
|
""" Given a pattern and a string s, return true if s matches the pattern. A
string s matches a pattern if there is some bijective mapping of single
characters to strings such that if each character in pattern is replaced by
the string it maps to, then the resulting string is s. A bijective mapping
means that no two characters mapping to the same string, and no character maps to
two different strings.
Example 1: Input: pattern = "abab", s =
"redblueredblue" Output: true
Explanation: One possible mapping is as
follows: 'a' -> "red" 'b' -> "blue"
IDEA:
1) start with smallest cut, then expanding initial string
2) apply this process recursively to the rest part of the string
Example:
pattern = aba, s = bluewhiteblue
"""
class Solution291:
pass
| true
|
9369936045f15e39fe607e57906f4811c519fde6
|
akaliutau/cs-problems-python
|
/problems/bfs/Solution1293.py
| 1,001
| 4.28125
| 4
|
""" Given a m * n grid, where each cell is either 0 (empty) or 1 (obstacle). In
one step, you can move up, down, left or right from and to an empty cell.
Return the minimum number of steps to walk from the upper left corner (0, 0)
to the lower right corner (m-1, n-1) given that you can eliminate at most k
obstacles. If it is not possible to find such walk return -1.
Example 1:
Input: grid =
[
[0,0,0],
[1,1,0],
[0,0,0],
[0,1,1],
[0,0,0]
],
k = 1 Output: 6
Explanation: The shortest path without eliminating any obstacle is 10. The
shortest path with one obstacle elimination at position (3,2) is 6. Such path
is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2).
IDEA:
1) use a classical BFS - which is ALWAYS return the shortest path due to its nature
2) track a current number of overcome obstacles - and traverse this value along with coords on next cell to process
"""
class Solution1293:
pass
| true
|
41acdd2f91669a03c8ab44e35ea7a7b786be3454
|
anettkeszler/ds-algorithms-python
|
/codewars/6kyu_break_camel_case.py
| 508
| 4.4375
| 4
|
# Complete the solution so that the function will break up camel casing, using a space between words.
# Example
# solution("camelCasing") == "camel Casing"
import re
def solution(s):
result = ""
for char in s:
if char.isupper():
break
result += char
result += " "
splitted = re.findall('[A-Z][^A-Z]*', s)
result += " ".join(splitted)
return result
hello = solution("camelCasing")
print(hello)
hello = solution("helloNettiHowAreYou")
print(hello)
| true
|
ea2ca3bce7b4b158415eddae8169b3832ff39908
|
guilhermeG23/AulasPythonGuanabara
|
/Pratico/Desafios/desafio17.py
| 812
| 4.15625
| 4
|
#Meu método
#So o: from math import sqrt
#Ou: from math import hypot
import math
a = float(input("Entre com o Cateto Adjacente A do triangulo retangulo: "))
b = float(input("Entre com o Cateto Oposto B do triangulo retangulo: "))
hipotenusa = (a**2) + (b**2)
print("A Hipotenusa é {:.2f}".format(math.sqrt(hipotenusa)))
#Método Guanabara(Equação na raça)
adjacente = float(input("Entre com o Adjacente do triangulo retangulo: "))
oposto = float(input("Entre com o oposto do triangulo retangulo: "))
hipotenusa = (adjacente ** 2 + oposto ** 2) ** (1/2)
print("Valor da Hipotenusa: {:.2f}".format(hipotenusa))
#Segundo método guanabara muito util
adj = float(input("Entre com o Adjacente: "))
opos = float(input("Entre com o Oposto: "))
hip = math.hypot(opos, adj)
print("Hipotenusa: {:.2f}".format(hip))
| false
|
c406d32dfc1dbf1e07ea73fddf9c10d160d47dc1
|
guilhermeG23/AulasPythonGuanabara
|
/Pratico/Exemplos/AnalisandoVariaveis.py
| 657
| 4.28125
| 4
|
#trabalhando com métodos
entrada = input("Entrada: ")
print("Saida: {}".format(entrada))
#Tipo da entrada
print("Tipo: {}".format(type(entrada)))
#Entrada é Alpha-numero?
print("AlphaNumerico: {}".format(entrada.isalnum()))
#Entrada é alfabetica
print("Alpha: {}".format(entrada.isalpha()))
#Estrada é numerica
print("Numerico: {}".format(entrada.isnumeric()))
#Entrada é espaço vazio
print("Espaço: {}".format(entrada.isspace()))
#Entrada é minuscula
print("Minusculo: {}".format(entrada.islower()))
#Maiuscula
print("Maiusculo: {}".format(entrada.isupper()))
#Capitalizada(maiusculo e minusculo)
print("Capitalizada: {}".format(entrada.istitle()))
| false
|
b5b4ebc84d31f10c982dfc65275c44cf9d6a6703
|
saraatsai/py_practice
|
/number_guessing.py
| 928
| 4.1875
| 4
|
import random
# Generate random number
comp = random.randint(1,10)
# print (comp)
count = 0
while True:
guess = input('Guess a number between 1 and 10: ')
try:
guess_int = int(guess)
if guess_int > 10 or guess_int < 1:
print('Number is not between 1 and 10. Please enter a valid number.')
else:
# Guess is too big
if int(guess) > comp:
count += 1
print('Too big, guess again')
# Guess is too small
elif int(guess) < comp:
count += 1
print('Too small, guess again')
else:
print('You win!')
print('Number of guesses: ', count+1)
break
except ValueError:
try:
float(guess)
break
except ValueError:
print('Invalid input. Please enter a valid number.')
| true
|
bb20892c11b9fedb0fe35696b45af31451bbe7e8
|
Devbata/icpu
|
/Chapter3/Fexercise3-3-1.py
| 594
| 4.25
| 4
|
# -*- coding: utf-8 -*-
#Bisecting to find appproximate square root.
x = float(input('Please pick a number you want to find the square root of: '))
epsilon = 1*10**(-3)
NumGuesses = 0
low = 0.0
high = max(1.0, abs(x))
ans = (high + low)/2.0
while abs(ans**2 - abs(x)) >= epsilon:
print('low =', low, 'high =', high, 'ans =', ans)
NumGuesses += 1
if ans**2 < abs(x):
low = ans
else:
high = ans
ans = (high + low)/2.0
if x < 0:
ans = str(ans)+'i'
print('NumGuesses =', NumGuesses)
print(ans, 'is hella close- to the square root of', x)
| true
|
6858af583e1ad4657650d185b87f289aec26a1a4
|
Anvin3/python
|
/Basic/divisor.py
| 261
| 4.15625
| 4
|
'''
Create a program that asks the user for a number and then prints out a list of all the divisors of that number.
'''
num=int(input("Please enter a number of your choice:"))
subList=[i for i in range(2,num) if num%i==0 ]
print("All the divisors are",subList)
| true
|
382dbb2572586d26f9f335e004f6886f74abdc07
|
anjana-analyst/Programming-Tutorials
|
/Competitive Programming/DAY-29/metm.py
| 323
| 4.15625
| 4
|
def time(hh,mm,ss):
return hh+(mm/60)+(ss/60)/60
def distance():
m=int(input("Enter the meters"))
hh=int(input("Enter the hours"))
mm=int(input("Enter the minutes"))
ss=int(input("Enter the seconds"))
miles=(m*0.000621372)/time(hh,mm,ss);
print("Miles per hour is ",miles)
distance()
| true
|
63d10fa7f02ba38539f03a49c09dccb6d36dbc70
|
MiguelBim/Python_40_c
|
/Challenge_31.py
| 1,250
| 4.1875
| 4
|
# CHALLENGE NUMBER 31
# TOPIC: Funct
# Dice App
# https://www.udemy.com/course/the-art-of-doing/learn/lecture/17060876#overview
import random
def dice_app(num_of_dice, roll_times):
total_count = 0
print("\n-----Results are as followed-----")
for rolling in range(roll_times):
val_from_rolling = random.randint(1, num_of_dice)
print("\t\t{}".format(val_from_rolling))
total_count += val_from_rolling
print("The total value of your roll is {}.".format(total_count))
return
if __name__ == '__main__':
print("Welcome to the Python Dice App")
run_app = True
while run_app:
dice_sides = int(input("\nHow many sides would you like on your dice: ").strip())
dice_number = int(input("How many dice would you like to roll: "))
print("\nYou rolled {} {} side dice.".format(dice_number, dice_sides))
dice_app(dice_sides,dice_number)
play_again = input("\nWould you like to roll again (y/n): ").lower().strip()
if play_again == 'n':
run_app = False
print("Thank you for using the Python Dice App.")
elif play_again != 'y':
run_app = False
print('\nThat is not a valid option. Exiting from app.')
| true
|
18a56761663e1202e10e77d40b4a6cfb5cd47763
|
JordiDeSanta/PythonPractices
|
/passwordcreator.py
| 1,600
| 4.34375
| 4
|
print("Create a password: ")
# Parameters
minimunlength = 8
numbers = 2
alphanumericchars = 1
uppercasechars = 1
lowercasechars = 1
aprobated = False
def successFunction():
print("Your password is successfully created!")
aprobated = True
def printPasswordRequisites():
print("The password requires:")
print(minimunlength, "characters minimum")
print(numbers, "numbers")
print(alphanumericchars, "alpha numeric characters")
print(uppercasechars, "uppercase characters")
print("Please write other password: ")
# While the password is not aprobated, ask to the user again
while aprobated == False:
# USername ask
password = input()
# Check character per character if the password pass the security test
uppercaseCount = 0
lowercaseCount = 0
numberCount = 0
alphanumericCount = 0
for i in range(len(password)):
# Uppercase check
if(password[i].isupper()):
uppercaseCount += 1
# Lowercase check
if(password[i].islower):
lowercaseCount += 1
# Numbers check
if(password[i].isnumeric()):
numberCount += 1
# Aphanumeric check
if(password[i].isalnum()):
alphanumericCount += 1
pass
# Final check with the requirements
if(len(password) >= minimunlength and uppercaseCount >= uppercasechars and lowercaseCount >= lowercasechars and numberCount >= numbers and alphanumericCount >= alphanumericchars):
successFunction()
else:
printPasswordRequisites()
pass
pass
| true
|
736fbfee5775cb351f4ee8acabeb5321c0a38c84
|
SinglePIXL/CSM10P
|
/Homework/distanceTraveled.py
| 451
| 4.3125
| 4
|
"""
Alec
distance.py
8-21-19
Ver 1.4
Get the speed of the car from the user then we calculate distances traveled for
5, 8, and 12 hours.
"""
mph = int(input('Enter the speed of the car:'))
time = 5
distance = mph * time
print('The distance traveled in 5 miles is:', distance)
time = 8
distance = mph * time
print('The distnace traveled in 8 miles is:', distance)
time = 12
distance = mph * time
print('The distance traveled in 12 miles is:', distance)
| true
|
e7acd1abad675af9ccd1b1b8bddc11884020ea8b
|
SinglePIXL/CSM10P
|
/Testing/10-7-19 Lecture/errorTypes.py
| 982
| 4.125
| 4
|
# IOError: if the file cannot be opened.
# ImportError: if python cannot find the module.
# ValueError: Raised when a built in operation or function recieves an argument
# that has the right type but an inapropriate value
# KeyboardInterrupt: Raised when the user hits the interrupt key
# EOFError: Raised one of the builtin functions (like input()) hits an end
# of file condition (EOF) without reading any
# forty = ValueError
# Using "assert" statement ou ca initially create your own exception
# assert statement checks for a condition. If the condition is not met(false)
# then it will throw exception error.
def input_age(age):
try:
assert int(age)>18
except ValueError:
return 'ValueError: cannot convert to int'
else:
return 'Age is saved succesfully.'
def main():
age = int(input('Enter your age'))
print(input_age(age))
print(input_age('23'))
print(input_age(25))
print(input_age('nothing'))
main()
| true
|
288f685744aa6609b795bf433a18ea2ffbb24008
|
SinglePIXL/CSM10P
|
/Testing/9-13-19 Lecture/throwaway.py
| 489
| 4.1875
| 4
|
def determine_total_Grade(average):
if average <= 100 and average >= 90:
print('Your average of ', average, 'is an A!')
elif average <= 89 and average >= 80:
print('Your average of ', average, 'is a B.')
elif average <= 79 and average >= 70:
print('Your average of ', average, 'is a C')
elif average <= 69 and average >= 70:
print('Your average of ', average, 'is a D')
else:
print('Your average of ', average, 'is an F')
| true
|
6e1fb9392f9533ac4803cc93cb122d4ddd85ab52
|
SinglePIXL/CSM10P
|
/Lab/fallingDistance.py
| 874
| 4.21875
| 4
|
# Alec
# fallingDistance.py
# 9-21-19
# Ver 1.3
# Accept an object's falling time in seconds as an argument.
# The function should return the distance in meters that the object has fallen
# during that time interval. Write a program that calls the function in a loop
# that passes the values 1 through 10 as arguments and displays the return
# value
# Display calculation for distance of a falling object
def main():
# Seconds: Range is 1 second to 10
for i in range(1,11):
# Print the calculation
print('Object has traveled', format (falling_distance(i),',.2f'),\
'meters per', i, 'second/s.')
# Define variables gravity and distnace
# Time is passed into this function through the timeTraveled arguement
def falling_distance(timeTraveled):
gravity = 9.8
distance = 0.5 * gravity * (timeTraveled ** 2)
return distance
main()
| true
|
d1f1e3c5760e32f745a2d798bba26f1c1abb3ca2
|
MyloTuT/IntroToPython
|
/Homework/HW1/hw1.py
| 1,213
| 4.25
| 4
|
#!/usr/bin/env python3
#Ex1.1
x = 2 #assign first to variable
y = 4 #assign second to variable
z = 6.0 #assign float to variable
vsum = x + y + z
print(vsum)
#Ex1.2
a = 10
b = 20
mSum = 10 * 20
print(mSum)
#Ex1.3
var = '5'
var2 = '10'
convert_one = int(var) #convert var into an int and assign to a variable
convert_two = int(var2) #convert var2 into an int and assign to a variable
var_total = convert_one + convert_two
print(var_total) #print the total of var and var2 as converted integers
#Ex1.4
user_var = input('Please enter an integer: ') #request a integer from a user
user_doubled = int(user_var) * 2
print(user_doubled)
#Ex1.5
user_place = input('Name your favorite place: ')
print('Hello,' + ' ' + user_place + '!')
#Ex1.6
multi_exclamation = input('Please enter your excitement level: ')
print('Hello,' + ' ' + user_place + '!' * int(multi_exclamation))
#Ex1.7
thirty_five = 35.30
tf_output = round(thirty_five)
print(tf_output)
#Ex1.8
tf_super_float = 35.359958
tf_rounded_two = round(tf_super_float, 2)
print(tf_rounded_two)
#Ex1.9
var = "5"
var2 = "4"
var_conversion = int(var)
var2_conversion = int(var2)
var_sum = var_conversion / var2_conversion
print(var_sum)
| true
|
ce5015940881770acdbb6fd87af458b35d99c86b
|
GingerBeardx/Python
|
/Python_Fundamentals/type_list.py
| 908
| 4.40625
| 4
|
def tester(case):
string = "String: "
adds = 0
strings = 0
numbers = 0
for element in case:
print element
# first determine the data type
if isinstance(element, float) or isinstance(element, int) == True:
adds += element
numbers += 1
elif isinstance(element, basestring) == True:
# if string - determine if string is short or long
string += element + " "
strings += 1
if strings > 0 and numbers > 0:
print "The list you entered is of mixed types"
elif strings > 0:
print "The list you entered is of string type"
elif numbers > 0:
print "The list you entered is of integer type"
print string
print "Sum:", adds
case_1 = ['magical unicorns', 19, 'hello', 98.98, 'world']
case_2 = [2, 3, 1, 7, 4, 12]
case_3 = ['magical', 'unicorns']
tester(case_2)
| true
|
a2c485ba03991204912d6dd23b32d8d17daa3c25
|
GingerBeardx/Python
|
/Python_Fundamentals/loops.py
| 340
| 4.34375
| 4
|
for count in range(0, 5):
print "looping - ", count
# create a new list
# remember lists can hold many data-types, even lists!
my_list = [4, 'dog', 99, ['list', 'inside', 'another'], 'hello world!']
for element in my_list:
print element
count = 0
while count < 5: # notice the colon!
print 'looping - ', count
count += 1
| true
|
5538252bcd657f22538ee14632a806d237d54790
|
jahosh/coursera
|
/algorithms1/week2/two_stack.py
| 1,094
| 4.125
| 4
|
OPERATORS = {'*', '+', '-', '/'}
""" Djikstra's Two Stack Arithmetic expression evaluation algorithm """
def two_stack(arithmetic_expression):
value_stack = []
operator_stack = []
for string in arithmetic_expression:
try:
if isinstance(int(string), int):
value_stack.append(int(string))
except:
if string in OPERATORS:
operator_stack.append(string)
if string == ')':
operator = operator_stack.pop()
value_1 = value_stack.pop()
value_2 = value_stack.pop()
result_value = 0
if operator == '*':
result_value = value_1 * value_2
elif operator == '+':
result_value = value_1 + value_2
elif operator == '-':
result_value = value_1 - value_2
elif operator == '/':
result_value = value_1 / value_2
value_stack.append(result_value)
return value_stack.pop()
arithmetic = '(1 + ((2 + 3) * ( 4 * 5)))'
print(two_stack(arithmetic))
| false
|
49d87afe33dc3036b23b86692dc71248917878c7
|
MonilSaraswat/hacktoberfest2021
|
/fibonacci.py
| 345
| 4.25
| 4
|
# 0 1 1 2 3 5 8 13
"""a , b = 0 , 1
n = int(input("Enter Number of Terms"))
print(a,b , end = " ")
for x in range(1 , n-1):
temp = a+b
a=b
b=temp
print(temp , end = " ")
"""
def fibonacci(n):
a, b = 0, 1
while b < n:
print(b, end=' ')
a, b = b, a + b
n = int(input("Enter the end term"))
fibonacci(n)
3
| false
|
780c24fd5b63cab288383303d3ac8680691afd18
|
MicheSi/code_challenges
|
/isValid.py
| 1,421
| 4.34375
| 4
|
'''
Sherlock considers a string to be valid if all characters of the string appear the same number of times. It is also valid if he can remove just character at index in the string, and the remaining characters will occur the same number of times. Given a string , determine if it is valid. If so, return YES, otherwise return NO.
For example, if , it is a valid string because frequencies are . So is because we can remove one and have of each character in the remaining string. If however, the string is not valid as we can only remove occurrence of . That would leave character frequencies of .
Function Description
Complete the isValid function in the editor below. It should return either the string YES or the string NO.
isValid has the following parameter(s):
s: a string
Input Format
A single string .
Constraints
Each character
Output Format
Print YES if string is valid, otherwise, print NO.
Sample Input 0
aabbcd
Sample Output 0
NO
'''
def isValid(s):
visited = []
for i in s:
if i not in visited:
visited.append(i)
s = s.replace(i, '', 1)
print(visited, s)
if i in visited:
s = s.replace(i, '', 1)
print(len(s))
if len(s) == 0:
return 'YES'
else:
return 'NO'
isValid('aabbcd')
isValid('aabbccddeefghi')
isValid('abcdefghhgfedecba')
| true
|
aa2e42c78db54ca867c25ce2113b7914bcc666ee
|
Keshav1506/competitive_programming
|
/Bit_Magic/004_geeksforgeeks_Toggle_Bits_Given_Range/Solution.py
| 2,703
| 4.15625
| 4
|
#
# Time :
# Space :
#
# @tag : Bit Magic
# @by : Shaikat Majumdar
# @date: Aug 27, 2020
# **************************************************************************
# GeeksForGeeks: Toggle bits given range
#
# Description:
#
# Given a non-negative number N and two values L and R.
# The problem is to toggle the bits in the range L to R in the binary representation of n,
# i.e, to toggle bits from the rightmost Lth bit to the rightmost Rth bit.
# A toggle operation flips a bit 0 to 1 and a bit 1 to 0.
# Print n after the bits are toggled.
#
#
# Example 1:
#
# Input:
# n = 17 , L = 2 , R = 3
# Output:
# 23
# Explanation:
# (17)10 = (10001)2. After toggling all
# the bits from 2nd to 3rd position we get
# (10111)2 = (23)10
# Example 2:
#
# Input:
# n = 50 , L = 2 , R = 5
# Output:
# 44
# Explanation:
# (50)10 = (110010)2. After toggling all
# the bits from 2nd to 3rd position we get
# (101100)2 = (44)10
#
#
# Your Task:
# You don't need to read input or print anything. Your task is to complete the function toggleBits()
# which takes 3 Integers n, L and R as input and returns the answer.
#
#
# Expected Time Complexity: O(1)
# Expected Auxiliary Space: O(1)
#
#
# Constraints:
# * 1 <= n <= 105
# * 1 <= L<=R <= Number of Bits in n
#
# **************************************************************************
# Source: https://practice.geeksforgeeks.org/problems/toggle-bits-given-range0952/1 (GeeksForGeeks - Toggle bits given range)
# **************************************************************************
#
# **************************************************************************
# Solution Explanation
# **************************************************************************
# Refer to Solution_Explanation.md
#
# **************************************************************************
#
import unittest
class Solution(object):
def toggleBitsFromLtoR(self, n: int, L: int, R: int) -> bool:
# calculating a number
# 'num' having 'r'
# number of bits and
# bits in the range l
# to r are the only set bits
num = ((1 << R) - 1) ^ ((1 << (L - 1)) - 1)
# toggle bits in the
# range l to r in 'n'
# Besides this, we can calculate num as: num=(1<<r)-l .
# and return the number
return n ^ num
class Test(unittest.TestCase):
def setUp(self) -> None:
pass
def tearDown(self) -> None:
pass
def test_toggleBitsFromLtoR(self) -> None:
sol = Solution()
for n, L, R, solution in ([17, 2, 3, 23], [50, 2, 5, 44]):
self.assertEqual(solution, sol.toggleBitsFromLtoR(n, L, R))
# main
if __name__ == "__main__":
unittest.main()
| true
|
31f5a45e28ccb77adff1f5f3761e9297a121f0cd
|
Keshav1506/competitive_programming
|
/Tree_and_BST/021_leetcode_P_366_FindLeavesOfBinaryTree/Solution.py
| 2,439
| 4.25
| 4
|
#
# Time : O(N) [ We traverse all elements of the tree once so total time complexity is O(n) ] ; Space: O(1)
# @tag : Tree and BST ; Recursion
# @by : Shaikat Majumdar
# @date: Aug 27, 2020
# **************************************************************************
#
# LeetCode - Problem - 366: Find Leaves of Binary Tree
#
# Description:
#
# Given a binary tree, you need to compute the length of the diameter of the tree.
# The diameter of a binary tree is the length of the longest path between any two nodes in a tree.
# This path may or may not pass through the root.
#
# Example:
# Given a binary tree
# 1
# / \
# 2 3
# / \
# 4 5
# Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
#
# Note: The length of path between two nodes is represented by the number of edges between them.
#
# **************************************************************************
# Source: https://leetcode.com/problems/find-leaves-of-binary-tree/ (Leetcode - Problem 366 - Find Leaves of Binary Tree)
#
from typing import List
import unittest
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def findLeavesHelper(self, root, results):
"""
push root and all descendants to results
return the distance from root to farthest leaf
"""
if not root:
return -1
ret = 1 + max(
self.findLeavesHelper(child, results) for child in (root.left, root.right)
)
if ret >= len(results):
results.append([])
results[ret].append(root.val)
return ret
def findLeaves(self, root: TreeNode) -> List[List[int]]:
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
ret = []
self.findLeavesHelper(root, ret)
return ret
class Test(unittest.TestCase):
def setUp(self) -> None:
pass
def tearDown(self) -> None:
pass
def test_findLeaves(self) -> None:
s = Solution()
root = TreeNode(1)
root.left = TreeNode(2)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right = TreeNode(3)
self.assertEqual([[4, 5, 3], [2], [1]], s.findLeaves(root))
if __name__ == "__main__":
unittest.main()
| true
|
0fff29228279abcae6d9fa67f111602e0423db66
|
hakepg/operations
|
/python_sample-master/python_sample-master/basics/deepcloning.py
| 757
| 4.15625
| 4
|
import copy
listOfElements = ["A", "B", 10, 20, [100, 200, 300]]
# newList= listOfElements.copy() -- list method- performs shallow copy
newList = copy.deepcopy(listOfElements) # Deep copy -- method provided by copy module
newList1 = copy.copy(listOfElements) # Shallow copy -- method provided by copy module
print("Before modification: \n\nOriginal List: ", listOfElements)
print("Copied List due to shallow cloning: ", newList1)
print("Copied List due to deep cloning: ", newList)
# Modification
listOfElements[1] = 100
newList[4][0] = 200
newList1[4][2] = 100
print("\n\nAfter modification: \n\nOriginal List: ", listOfElements)
print("Copied List due to shallow cloning: ", newList1)
print("Copied List due to deep cloning: ", newList)
| true
|
10841b4db43d984e677eec6a8dcd00415bc8c098
|
hakepg/operations
|
/python_sample-master/python_sample-master/basics/listExample.py
| 525
| 4.15625
| 4
|
# Sort in the list
# Two ways: list method -- sort and built in function -- sorted
listOfElements = [10,20,30,45,1,5,23,223,44552,34,53,2]
# Difference between sort and sorted
print(sorted(listOfElements)) # Creates new sorted list
print(listOfElements) # original list remains same
print(listOfElements.sort()) # Return None, make changes in the given list
print(listOfElements)
print(listOfElements.sort(reverse=True)) # Reverese sorting, Return None, make changes in the given list
print(listOfElements)
| true
|
b6c2ab37074be1587dd53185c93632471dbf213a
|
rajatmishra3108/Daily-Flash-PYTHON
|
/17 aug 2020/prog5.py
| 253
| 4.21875
| 4
|
"""
Question : Write a Python program which accepts your name,
like("Rajat Mishra") and print output as
My--name--is--Rajat--Mishra.
"""
name = input("Enter Your Name : ")
output = "--".join(f"My name is {name}".split())
print(output)
| false
|
5e49178aa33566d2e953913f919101f8a2bc1e93
|
akjadon/HH
|
/Python/Python_Exercise/Python_Exercise1/ex38.py
| 569
| 4.28125
| 4
|
"""Write a program that will calculate the average word length of a text
stored in a file (i.e the sum of all the lengths of the word tokens in the
text, divided by the number of word tokens)."""
from string import punctuation
def average_word_length(file_name):
with open(file_name, 'r') as f:
for line in f:
# Clean each line of punctuations, we want words only
line = filter(lambda x: x not in punctuation, line)
# We get only the length of the words
words = map(len, line.split())
print sum(words) / len(words)
average_word_length('hapax.txt')
| true
|
f50269a35eb4da827425795badc0ba7eab421a92
|
akjadon/HH
|
/Python/Python_Exercise/Python_Exercise1/ex46.py
| 2,938
| 4.4375
| 4
|
"""An alternade is a word in which its letters, taken alternatively in a
strict sequence, and used in the same order as the original word, make up at
least two other words. All letters must be used, but the smaller words are not
necessarily of the same length. For example, a word with seven letters where
every second letter is used will produce a four-letter word and a three-letter
word. Here are two examples:
"board": makes "bad" and "or".
"waists": makes "wit" and "ass".
Using the word list at http://www.puzzlers.org/pub/wordlists/unixdict.txt,
write a program that goes through each word in the list and tries to make two
smaller words using every second letter. The smaller words must also be members
of the list. Print the words to the screen in the above fashion."""
import re
from collections import defaultdict
# I'm still not sure if this is the best solution.
# But I think it does what the problem asks for :/
# But my, my, my, it takes around 2 minutes to finish building.
# Please, help!
def alternade_finder(file_name):
# Get our words
with open(file_name, 'r') as f:
words = re.findall(r'\w+', f.read())
# Prepare our dictionary
foundalternades = defaultdict(list)
# For each word in the list
for word in words:
# We make a copy of the words list and prepare our variables
wordlist, smallerwordeven, smallerwordodd = words[:], '', ''
# We remove the word from the list so it doesn't choose itself
# as an alternade
wordlist.remove(word)
# We only do that for words that are longer than 1 letter
if len(word) > 1:
for letters in word: # For each letter in the word
# Get the position of this letter
letter_pos = word.index(letters)
# If the letter is at an even position
if letter_pos % 2 == 0:
smallerwordeven += letters # Add this letter to the variable
# If the smaller word is in the words list and is not yet
# in the dictionary for the current word, add it to the dict
if smallerwordeven in wordlist and \
smallerwordeven not in foundalternades[word]:
foundalternades[word].append(smallerwordeven)
# If the letter is at an odd position
if letter_pos % 2 != 0:
smallerwordodd += letters # Add this letter to the variable
# If the smaller word is in the words list and is not yet
# in the dictionary for the current word, add it to the dict
if smallerwordodd in wordlist and \
smallerwordodd not in foundalternades[word]:
foundalternades[word].append(smallerwordodd)
# For each word in the dictionary
for word, alternades in foundalternades.items():
# Make a string out of all the alternades
alt = reduce(lambda x, y: x + y, alternades)
# If all the letters in the word have been used to create all
# the alternades, print this word and its alternades
if sorted(alt) == sorted(word):
print '"%s": makes %s' % (word, alternades)
#test
alternade_finder('unixdict.txt')
| true
|
2a5f3f611ca53f2e173c3ec12fba914a98480d6f
|
gmastorg/CSC121
|
/M2HW1_NumberAnalysis_GabrielaCanjura(longer).py
| 1,275
| 4.1875
| 4
|
# gathers numbers puts them in a list
# determines correct number for each category
# 02/12/2018
# CSC-121 M2HW1 - NumberAnalysis
# Gabriela Canjura
def main():
total = float(0)
numOfNumbers = int(20) # decides loop count and used for average
total,numbers = get_values(numOfNumbers)
get_lowest(numbers)
get_highest(numbers)
get_total(total)
get_average(total, numOfNumbers)
def get_values(numOfNumbers):
values = [] # holds list of numbers
total = float(0)
for x in range (numOfNumbers): #creates loop
num = float(input("Enter a number: "))
total += num; # holds the total as numbers are entered in loop
values.append(num) # creates list
return total, values
def get_lowest(numbers):
lowest = min(numbers) # gets lowest number
print("The lowest number in the list is: " , lowest)
def get_highest(numbers):
highest = max(numbers) # gets highest number
print("The highest number in the list is: " , highest)
def get_total(total):
print("The total of the numbers is: ", total)
def get_average(total, numOfNumbers):
ave = total/numOfNumbers
print("The average of the numbers is: ", ave)
main()
| true
|
1f9f2c05bffaf755d40164b3704909532d50243a
|
motaz-hejaze/lavaloon-problem-solving-test
|
/problem2.py
| 1,451
| 4.1875
| 4
|
print("***************** Welcome ********************")
print("heaviest word function")
print("python version 3.6+")
print("run this script to test the function by yourself")
print("or run test_problem2 for unittest script ")
# all alphabets
alphabet_dict = {
"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, "g": 7, "h": 8, "i": 9, "j": 10, "k": 11, \
"l": 12, "m": 13, "n": 14, "o": 15, "p": 16, "q": 17, "r": 18, "s": 19, "t": 20, "u": 21,\
"v": 22, "w": 23, "x": 24, "y": 25, "z": 26
}
def heaviest_word(sentence):
# a dict to put all calculated words
all_words_sums = {}
# split sentence into list of words
words_list = sentence.split(" ")
# loop through all words in words_list
for word in words_list:
# split current word into a list of characters
chars_list = [c for c in word]
word_weight = 0
# loop through all characters of current word
for c in chars_list:
# calculate each character and add to word_weight
word_weight += alphabet_dict[c]
# add key , value to all words dictionary
all_words_sums[word] = word_weight
# return the (first) key with maximum weight
first_max_word = max(all_words_sums, key=all_words_sums.get)
return first_max_word
if __name__ == '__main__':
sentence = input("Please enter a sentence of words : ")
print("The Heaviest word is ({})".format(str(heaviest_word(sentence))))
| true
|
e78997ec31b258f44532ee3066938f4aa3e2826b
|
silasfelinus/PythonProjects
|
/9_8_privileges.py
| 1,189
| 4.28125
| 4
|
class User():
"""A basic user to explore Classes"""
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
self.full_name = self.first_name.title() + " " + self.last_name.title()
def describe_user(self):
print("User's name is " + self.full_name)
def greet_user(self):
print("Hello, " + self.full_name + "!")
class Admin(User):
#User with elevated access
def __init__(self, first_name, last_name):
super().__init__(first_name, last_name)
self.privileges = Privileges()
class Privileges():
#privileges of users
def __init__(self, privileges=[]):
self.privileges = privileges
def show_privileges(self):
#stolen from answer page
#otherwise would have done
#print(self.privileges)
print("\nPrivileges:")
if self.privileges:
for privilege in self.privileges:
print("- " + privilege)
else:
print("- This user has no privileges.")
ronin = Admin('ronin', 'knight')
ronin.describe_user()
ronin.greet_user()
ronin.privileges.show_privileges()
ronin.privileges.privileges = ["can delete posts", "can see home addresses", "can access webcams remotely",]
ronin.privileges.show_privileges()
| false
|
5e727dfead901603bd7972ae63c92bdc68467516
|
silasfelinus/PythonProjects
|
/9_7_admin.py
| 732
| 4.15625
| 4
|
class User():
"""A basic user to explore Classes"""
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
self.full_name = self.first_name.title() + " " + self.last_name.title()
def describe_user(self):
print("User's name is " + self.full_name)
def greet_user(self):
print("Hello, " + self.full_name + "!")
class Admin(User):
def __init__(self, first_name, last_name):
super().__init__(first_name, last_name)
self.privileges = ["can delete posts", "can see home addresses", "can access webcams remotely"]
def show_privileges(self):
print(self.privileges)
ronin = Admin('ronin', 'knight')
ronin.describe_user()
ronin.greet_user()
ronin.show_privileges()
| false
|
c86115e76fc305660d014f1579e65ecffa2b4c33
|
silasfelinus/PythonProjects
|
/9_5_login_attemps.py
| 787
| 4.21875
| 4
|
class Restaurant():
"""A basic restaurant to explore Classes"""
def __init__(self, name, cuisine):
self.name = name
self.cuisine = cuisine
self.number_served = 0
def describe_restaurant(self):
print(self.name.title() + ": " + self.cuisine)
def set_number_served(self, number):
self.number_served = number
def increment_number_served(self, increment):
self.number_served += increment
def open_restaurant(self):
print(self.name.title() + " is open!")
my_restaurant = Restaurant('mcdonalds', "fine dining")
my_restaurant.describe_restaurant()
my_restaurant.open_restaurant()
print(my_restaurant.number_served)
my_restaurant.set_number_served(20)
print(my_restaurant.number_served)
my_restaurant.increment_number_served(30)
print(my_restaurant.number_served)
| false
|
0c62ff7ab5bf7afeb43db3d74580deb06abe89a2
|
rohit2219/python
|
/decorators.py
| 1,068
| 4.1875
| 4
|
'''
decorator are basically functions which alter the behaviour/wrap the origonal functions and use the original functions
output to add other behavious to it
'''
def add20ToaddFn(inp):
def addval(a,b):
return inp(a,b) + 20
addval.unwrap=inp # this is how you unwrap
return addval
@add20ToaddFn
def addFn(x,y):
return x+y
d = {}
def decorFn(addFn):
def decorInnerFn(a,b):
if (a,b) in d:
print('return from cache')
return d((a,b))
else:
print('return from fn')
d[(a,b)]= addFn(a,b)
return addFn(a,b)
return decorInnerFn
@decorFn
def add(x,y):
return x+y
print(add(7,2))
#print(addFn(2,3),addFn.unwrap(2,3))
#generators
def numberGen(x):
for i in range(x):
yield i
for i in numberGen(5):
print(i)
file="./data.txt"
try:
fileObj=open(file,'r')
except FileNotFoundError:
print('File not found')
else:
i=file.readline()
print(i)
fileObj.close()
finally:
print('The above set of statemnets done with/without erro')
| true
|
069de02a13505fa4c356308b8ed189446807612c
|
BondiAnalytics/Python-Course-Labs
|
/13_list_comprehensions/13_04_fish.py
| 333
| 4.25
| 4
|
'''
Using a listcomp, create a list from the following tuple that includes
only words ending with *fish.
Tip: Use an if statement in the listcomp
'''
fish_tuple = ('blowfish', 'clownfish', 'catfish', 'octopus')
fish_list = list(fish_tuple)
print([i for i in fish_list if i[-4:] == "fish"])
# fishy = []
# for i in fish_tuple:
#
| true
|
cd318be0b06227fc766e910ea786fb792c02fced
|
BondiAnalytics/Python-Course-Labs
|
/14_generators/14_01_generators.py
| 245
| 4.375
| 4
|
'''
Demonstrate how to create a generator object. Print the object to the console to see what you get.
Then iterate over the generator object and print out each item.
'''
gen = (x**2 for x in range(1,6))
for i in gen:
print(i)
print(gen)
| true
|
9c198707d630b0b99ccc73294ae2249f8e52582b
|
Tavial/cursophyton
|
/ALFdatosSimples/ejercicio09.py
| 576
| 4.15625
| 4
|
'''
Escribir un programa que pida al usuario su peso (en kg) y estatura (en metros),
calcule el índice de masa corporal y lo almacene en una variable, y muestre por
pantalla la frase Tu índice de masa corporal es <imc> donde <imc> es el índice
de masa corporal calculado redondeado con dos decimales.
IMC = peso(kg) /Estatura al cuadrado (en metros)
'''
peso = float (input("Introduce tu peso en kg.: "))
estatura = float (input("Introduce tu estatura en metros: "))
imc = round((peso/pow(estatura,2)),2)
print ("Tu índice de masa corporal es: "+str(imc))
| false
|
7ea4ad1d64edd040b9572c615f550c3488dde131
|
Tavial/cursophyton
|
/ALFcondicionales/ejercicio06.py
| 1,291
| 4.375
| 4
|
'''
Los alumnos de un curso se han dividido en dos grupos A y B de acuerdo al sexo y
el nombre. El grupo A esta formado por las mujeres con un nombre anterior a la M
y los hombres con un nombre posterior a la N y el grupo B por el resto. Escribir
un programa que pregunte al usuario su nombre y sexo, y muestre por pantalla el
grupo que le corresponde.
'''
print (" ******************************************************************* ")
print (" Este grupo te clasifica en un grupo o otro según tu nombre y sexo ")
print (" ******************************************************************* ")
print ("")
print ("Introduce tu nombre: ")
nombre = input ()
print ("Introduce tu sexo (H/M): ")
sexo = input ()
if nombre.isdigit() or sexo.isdigit() or nombre.isspace() or sexo.isspace() or nombre =="" or sexo =="":
print ("Alguno de los valores introducido no es correcto")
else:
sexo = sexo.lower()
nombre = nombre.lower()
if (sexo != "h") and (sexo != "m"):
print ("El valor introducido para el sexo no es el correcto")
else:
if ((nombre < "m") and (sexo =="m")) or ((nombre > "n") and (sexo == "h")):
print ("Perteneces al grupo A")
else:
print ("Perteneces al grupo B")
| false
|
2418436b66812d56c024f62600b64f4fda325e60
|
Tavial/cursophyton
|
/ALFdatosSimples/ejercicio10.py
| 608
| 4.53125
| 5
|
'''
Escribir un programa que pida al usuario dos números enteros y muestre por
pantalla la <n> entre <m> da un cociente <c> y un resto <r> donde <n> y <m> son
los números introducidos por el usuario, y <c> y <r> son el cociente y el resto
de la división entera respectivamente.
'''
print ("Vamos a obtener el cociente y el resto de dos números enteros")
print("")
n = int (input("Introduce un número entero: "))
m = int (input("Introduce otro número entero: "))
c = int (n / m)
r = n % m
print ("El cociente de la división es: "+str(c))
print ("El resto de la división es: "+str(r))
| false
|
b728aafc4536358c55c802932a6352874f2cb782
|
baddener/PYTHON
|
/urok1.py
| 834
| 4.1875
| 4
|
import math
op = input("operation")
x = float(input("Number one"))
y = float(input("Number two(при sqr и sqrtx - не учитывается, введите любую цифру)"))
z = float(input("Stepen'"))
result = None
if op == "+":
result = x+y
print(result)
elif op == "-":
result = x-y
print(result)
elif op == "*":
result = x *y
print(result)
elif op == "/":
result = x / y
print(result)
elif op == "sqrtx":
result = math.sqrt(x)
print(result)
elif op == "sqr":
result = x**z
print(result)
elif op == "cosx":
result = math.cos(x)
print(result)
elif op == "sinx":
result = math.sin(x)
elif op == "log":
result = math.log(x,y)
print(result)
input(" ")
#elif op == "-":
# result = x - y
| false
|
6de2ac2bbde9274df1540b29f9c983a39253bd57
|
the-matrixio/ml_competition_didi
|
/preprocess_data/get_weekday.py
| 630
| 4.1875
| 4
|
'''
Given absolute time, return weekday as an integer between 0 and 6
Arguments:
Absolute time (integer)
Returns:
Integer between 0 and 6 inclusive. Monday is 0, Sunday is 6.
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import calendar
def get_weekday(absolute_time):
# First determine the year, month, day
# NOTE: Below code only works for Jan/Feb 2016, it's not scalable but OK for this competition
year = 2016
month = absolute_time // (144*31) + 1
day = (absolute_time - (144*31) * (month - 1)) // 144 + 1
return calendar.weekday(year, month, day)
| true
|
77db9841cf16c96919bf770b7f01e9a2e9abd864
|
tegamax/ProjectCode
|
/Common_Questions/TextBookQuestions/PythonCrashCourse/Chapter_8/8_11.py
| 1,260
| 4.21875
| 4
|
'''
8-11. Archived Messages: Start with your work from Exercise 8-10.
Call the function send_messages() with a copy of the list of messages.
After calling the function, print both of your lists to show that the original list has retained its messages.
'''
'''
def send_messages(short_list):
sent_messages = []
current_message = short_list.pop()
sent_messages.append(current_message)
#print(sent_messages)
messages = ['monitor','mouse','laptop','keyboard']
send_messages(messages)
print(messages)
'''
'''
def send_messages(short_list):
sent_messages = []
current_message = short_list.pop()
sent_messages.append(current_message)
return sent_messages
messages = ['monitor', 'mouse', 'laptop', 'keyboard']
#sent_messages = []
#send_messages(messages[:])
print(messages[:])
'''
def show_messages(messages):
print("Printing all messages")
for message in messages:
print(message)
def send_messages(messages,sent_messages):
while messages:
removed_messages = messages.pop()
sent_messages.append(removed_messages)
print(sent_messages)
messages = ['monitor', 'mouse', 'laptop', 'keyboard']
show_messages(messages)
sent_messages = []
send_messages(messages[:], sent_messages)
| true
|
4a6aa2ffcf88c2e4a38ce56fab7d316f6d4e0114
|
tegamax/ProjectCode
|
/Common_Questions/TextBookQuestions/PythonCrashCourse/Chapter_9/Ex_9_4.py
| 1,639
| 4.28125
| 4
|
'''
9-4. Number Served: Start with your program from Exercise 9-1 (page 162). Add an attribute called number_served with a default value of 0.
Create an instance called restaurant from this class. Print the number of customers the restaurant has served,
and then change this value and print it again.
Add a method called set_number_served() that lets you set the number of customers that have been served.
Call this method with a new number and print the value again.
Add a method called increment_number_served() that lets you increment the number of customers who’ve been served.
Call this method with any number you like that could represent how many customers were served in, say, a day of business.
'''
class Restaurant:
def __init__(self):
self.number_served=0 #Attribute
def number_of_customers(self): #Method
print(f"The Number of customers served today was {self.number_served}.")
def set_number_served(self):
print(f"We served {self.number_served} clients this week")
def increment_number_served(self,served_customers):
self.number_served += served_customers
return self.number_served
#print(self.number_served)
#print(served_customers) num_of_customers_served
#a,
restaurant = Restaurant() #Instance
#print(restaurant.number_of_customers)
restaurant.number_of_customers()
#b,
restaurant.number_served=23
restaurant.number_of_customers()
restaurant.number_served=90
restaurant.set_number_served()
total=restaurant.increment_number_served(20)
print(f"In total we served {total} customers today")
| true
|
b2def23578d639e50d6eea882e5b9a8246edb01b
|
Pajke123/ORS-PA-18-Homework07
|
/task2.py
| 469
| 4.1875
| 4
|
"""
=================== TASK 2 ====================
* Name: Recursive Sum
*
* Write a recursive function that will sum given
* list of integer numbers.
*
* Note: Please describe in details possible cases
* in which your solution might not work.
*
* Use main() function to test your solution.
===================================================
"""
# Write your function here
def main():
# Test your function here
pass
if __name__ == "__main__":
main()
| true
|
077e070ecddeedee387a0a9b9b658262af4eccaf
|
AMfalme/OOP-python-Furniture-sales
|
/OOP_file.py
| 1,182
| 4.1875
| 4
|
from abc import ABCMeta, abstractmethod
class Electronics(object):
"""docstring for Electronics
This is an abstract Base class for a vendor selling Electronics of various types.
"""
__metaclass__ = ABCMeta
def __init__(self, make, year_of_manufacture, sale_date, purchase_price, selling_price, purchase_date):
super(Electronics, self).__init__()
self.make = make
self.year_of_manufacture = year_of_manufacture
self.sale_date = sale_date
self.purchase_price = purchase_price
self.selling_price
def profit_after_sale(self):
profit = self.selling_price - self.purchase_price
return profit
def make(self):
return self.make
@abstractmethod
def type_of_electronic(self):
return self.make
class computer(Electronics):
"""docstring for computer"""
def __init__(self, model):
self.model = model
def type_of_electronic(self):
return "Computer"
def insert_ram_capacity(self):
ram_in_gb = raw_input("What is the ram of this computer")
self.ram = ram_in_gb
return self.ram
def Insert_processor_capacity(self):
processor = raw_input("kindly input the processor capacity on this computer")
laptop = computer("HP")
print(laptop.make)
| true
|
61123681d1a35d9a00b4cfba76103fc78ca105e5
|
dionysus/coding_challenge
|
/leetcode/088_MergeSortedArray.py
| 1,297
| 4.1875
| 4
|
'''
88. Merge Sorted Array
URL: https://leetcode.com/problems/merge-sorted-array/
Given two sorted integer arrays nums1 and nums2,
merge nums2 into nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is equal to m + n) to hold
additional elements from nums2.
Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
'''
from typing import List
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
'''
two index
'''
if n == 0:
return nums1
i = 0
j = 0
# while nums1 has elements larger than nums2
while i < m and j < n:
if nums1[i] > nums2[j]:
nums1[i+1:] = nums1[i:m]
nums1[i] = nums2[j]
j += 1
m += 1
i += 1
# copy rest of nums2
if j < n:
nums1[i:] = nums2[j:]
if __name__ == "__main__":
# nums1 = [1,2,3,0,0,0]
# m = 3
# nums2 = [2,5,6]
# n = 3
nums1 = [2,0]
m = 1
nums2 = [1]
n = 1
nums1 = [4,5,6,0,0,0]
m = 3
nums2 = [1,2,3]
n = 3
test = Solution()
test.merge(nums1, m, nums2, n)
print(nums1)
| true
|
05d0485e40117cf2b4e8063942e6cb4154569ac6
|
MankaranSingh/Algorithms-for-Automated-Driving
|
/code/exercises/control/get_target_point.py
| 981
| 4.125
| 4
|
import numpy as np
def get_target_point(lookahead, polyline):
""" Determines the target point for the pure pursuit controller
Parameters
----------
lookahead : float
The target point is on a circle of radius `lookahead`
The circle's center is (0,0)
poyline: array_like, shape (M,2)
A list of 2d points that defines a polyline.
Returns:
--------
target_point: numpy array, shape (,2)
Point with positive x-coordinate where the circle of radius `lookahead`
and the polyline intersect.
Return None if there is no such point.
If there are multiple such points, return the one that the polyline
visits first.
"""
# Hint: A polyline is a list of line segments.
# The formulas for the intersection of a line segment and a circle are given
# here https://mathworld.wolfram.com/Circle-LineIntersection.html
raise NotImplementedError
| true
|
5a129e2a8a4dd86d3d295899ff3cf8e015afd5fb
|
calvinstudebaker/ssc-scheduling
|
/src/core/constants.py
| 2,840
| 4.28125
| 4
|
"""Hold values for all of the constants for the project."""
class Constants():
"""This is a class for managing constants in the project."""
STRINGS = {}
@classmethod
def get_string(cls, val, dictionary=None):
"""Get the string representation of the given constant val.
Looks in the subclass's dictionary called STRINGS. If there is none,
returns the empty string.
Parameters
----------
cls: class
Name of the class in this file
val: string
value to retrieve
dictionary: dictionary
dictionary to use. default is cls.STRINGS
Returns the value from the dictionary.
"""
if not dictionary:
dictionary = cls.STRINGS
if val in dictionary:
return dictionary[val]
return ""
@classmethod
def string_to_val(cls, string_rep):
"""Find which constant value the STRING_REP is associated with.
Given a string STRING_REP, find which constant value
it is associated with.
Parameters
----------
cls: class
Name of the class in this file
string_rep: string
String representation of the constant value to look up
Returns int.
"""
for pair in cls.STRINGS.iteritems():
const = pair[0]
string = pair[1]
if string == string_rep:
return const
return -1
class Days(Constants):
"""Constants for days of the week."""
SUNDAY = 0
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
THURSDAY = 4
FRIDAY = 5
SATURDAY = 6
STRINGS = {}
STRINGS[SUNDAY] = "Sunday"
STRINGS[MONDAY] = "Monday"
STRINGS[TUESDAY] = "Tuesday"
STRINGS[WEDNESDAY] = "Wednesday"
STRINGS[THURSDAY] = "Thursday"
STRINGS[FRIDAY] = "Friday"
STRINGS[SATURDAY] = "Saturday"
class Jobs(Constants):
"""Constants for the different possible jobs."""
MUNCHKINS = 0
SNOOPERS = 1
MENEHUNES = 2
YAHOOS = 3
MIDOREES = 4
SUAVES = 5
TEENS = 6
SKI_DOCK = 7
TENNIS = 8
HIKING = 9
OFFICE = 10
CRAFTS = 11
ART = 12
PHOTO = 13
KIDS_NAT = 14
ADULT_NAT = 15
THEATER = 16
MUSIC = 17
KGC = 18
STAPH_D = 19
STRINGS = {}
STRINGS[MUNCHKINS] = "Munchkins"
STRINGS[SNOOPERS] = "Snoopers"
STRINGS[MENEHUNES] = "Menehunes"
STRINGS[YAHOOS] = "Yahoos"
STRINGS[MIDOREES] = "Midorees"
STRINGS[SUAVES] = "Suaves"
STRINGS[TEENS] = "Teens"
STRINGS[SKI_DOCK] = "Ski Dock"
STRINGS[TENNIS] = "Tennis"
STRINGS[HIKING] = "Hiking"
STRINGS[OFFICE] = "Office"
STRINGS[CRAFTS] = "Crafts"
STRINGS[ART] = "Art"
STRINGS[PHOTO] = "Photo"
STRINGS[KIDS_NAT] = "Kids Naturalist"
STRINGS[ADULT_NAT] = "Adult Naturalist"
STRINGS[THEATER] = "Theater"
STRINGS[MUSIC] = "Music Director"
STRINGS[KGC] = "Kids Group Coordinator"
STRINGS[STAPH_D] = "Staph Director"
class ShiftCategory(Constants):
"""Constants for the different types of shifts."""
SPECIAL = 0
OFF_DAY = 1
PROGRAMMING = 2
STRINGS = {}
STRINGS[SPECIAL] = "Special"
STRINGS[OFF_DAY] = "Off Day"
STRINGS[PROGRAMMING] = "Programming"
| true
|
94f4d5e0d095afe3077243be4706ff9135672ccd
|
dwillis/django-rmp-data
|
/rmp/utils.py
| 394
| 4.1875
| 4
|
"""
General-purpose utility functions.
"""
import re
def camelcase_to_underscore(camelcase_str):
"""
Replace CamelCase with underscores in camelcase_str (and lower case).
"""
underscore = re.sub(r'(.)([A-Z][a-z]+)', r'\1_\2', camelcase_str)
lower_underscore = re.sub(r'([a-z0-9])([A-Z])', r'\1_\2', underscore).lower()
return re.sub(r'_{1,}', '_', lower_underscore)
| false
|
a6da2062585d75edf9643bdac2f9df4619211327
|
vijaypatha/python_sandbox
|
/numpie_mani.py
| 2,173
| 4.375
| 4
|
'''
pretty simple:
1) Create a array
2) Manipylate the arary: Accessing, deleting, inserting, slicing etc
'''
#!/usr/bin/env python
# coding: utf-8
# In[10]:
import numpy as np
#Step 1: Create a array
x = np.arange(5,55,5).reshape(2,5)
print("Array X is:")
print(x)
print("Attrubute of Array X is:")
print("# of axis of x: ", x.ndim)
print("# row and columns in X:", x.shape)
print("Data type of X:",x.dtype)
print("# of elements in the array X:", x.size)
# In[11]:
#Step 2: Access a element in the array
x[1,3] #expecting 2 row, 4th colum element -> 45
print(x[1,3])
# In[12]:
#Step 3: Changing 45 to 95
x[1,3] = 95
print(x)
# In[13]:
#Step 4: Changing 95 to 45
x[1,3] = 45
print(x)
# In[32]:
#Step 5: delete something along Axis 1
print("array x is: ")
print(x)
y = np.delete(x,[1,3],1) # deleting array's index 1 and 3 along the axis 1 -> a columnwise opreation
print("modified x after deleting index [0,4] along axis 1 is:")
print(y)
# In[33]:
#Step 5: delete something along Axis 1
print("array x is: ")
print(x)
z = np.delete(x,[0,4]) # deleting array's index 1 and 3 along the axis 0 -> a rowwise operation
print("modified x after deleting index [0,4] is",z)
# In[38]:
print("z = ", z)
t = np.delete(z, [0,2], axis=0)
print("modifed z =",t)
# In[45]:
# Step 6: Appending rows and columns
print("y", y)
print("appended new column:")
print(np.append(y, [[55],[60]], axis = 1)) #notice the difference between appending a row vs. Column.
#The new rows and columns match the shapes arrays
# In[49]:
print("y", y)
print("appended new row:")
print(np.append(y, [[55,60,65]], axis = 0)) #notice the difference between appending a row vs. Column.
#The new rows and columns match the shapes arrays
# In[ ]:
# Step 7: Inserting rows and colummns np.insert(ndarray, index, elements, axis)
print("y array is",y)
w = np.insert(y, 2, [55,60,65],axis = 0)
print ("Inserted Y array is:")
print(w)
print("y array is")
print(y)
w = np.insert(y, 3, [[55],[60],[65]],axis = 1)
print ("Inserted Y array is:")
print(w)
# STep 8: Vstack and Hstack
print("y array is")
print(y)
w = np.hstack(y)
print ("hstacked Y array is:")
print(w)
| true
|
86f2268590847d4f99e6899e8049b7a2abe72ac4
|
anjalak/Code-Archive
|
/Python_Code/python code/bitOperator.py
| 892
| 4.21875
| 4
|
# Create a function in Python called bitOperator that takes two bit strings of length 5 from the user.
# The function should return a tuple of the bitwise OR string, and the bitwise AND string
# (they need not be formatted to a certain length, see examples).
def bitOperator(int1, int2):
num1 = int(int1,2);
num2 = int(int2,2);
str1 = format(num1|num2,'b');
str2 = format(num1&num2,'b');
ans = (str1,str2);
return ans;
# Test cases
# 1.
# result = bitOperator('01001','00100')
# possible_solution_1 = ('1101', '0')
# possible_solution_2 = ('01101', '00000')
# print (result==possible_solution_1 or result==possible_solution_2)
# True
# 2.
# result = bitOperator('10001', '11011')
# solution = ('11011', '10001')
# print (result==solution)
# True
# 3.
# result = bitOperator('11001', '11100')
# solution = ('11101', '11000')
# print (result==solution)
# True
| true
|
8782817b87ac1f819b078b3c773778f2c72a93ee
|
davide-coccomini/Algorithmic-problems
|
/Python/steps.py
| 988
| 4.15625
| 4
|
# Given the number of the steps of a stair you have to write a function which returns the number of ways you can go from the bottom to the top
# You can only take a number of steps based on a set given to the function.
# EXAMPLE:
# With N=2 and X={1,2} you can go to the top using 2 steps or you can use a single step (valued 2) so return 2
# Easy example with constant X
# def numWays(n):
# if n== 0 or n == 1:
# return 1
# else:
# return numWays(n-1) + numWays(n-2)
# We can notify that the result of the N case is the result of the sum of the 2 previosly results
# N output
# 0 1
# 1 1
# 2 2
# 3 3
# 4 5
# ...
# So we can just remember the previously 2 results and sum them
def numWays(n, x):
if n == 0 or n == 1:
return 1
nums = n+1 * [0]
nums[0] = 1
for i in range(1, n):
total = 0
for j in x:
total += nums[i - j]
nums[i] = total
return nums[n]
# Asked by Amazon
| true
|
d0a3332f64adf879f38cbb8b105851357287772f
|
KrzysztofKarch/Python-Programming-for-the-absolute-beginner
|
/chapter 4/exercise 2.py
| 518
| 4.1875
| 4
|
# "Python Programming for the Absolute Beginner", Michael Dawson
#
# chapter 4, exercise 2
print("Program wypisujący komunikat wspak. \n")
statement=input("Wprowadź komunikat: ")
# Pythonic way to get backwards
backward=statement[::-1]
print("Komunikat wspak utworzony za pomocą wycinka [::-1]:",backward)
# Using 'for' loop and indexes
backward2=''
for i in range(-1,(-len(statement)-1),-1):
backward2+=statement[i]
print("Komunikat wspak utworzony za pomocą ujemnych indeksów i pętli for:",backward2)
input()
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.