blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
e31e1faec48a064176ad9dba34ed13ba8d263272 | SaratM34/CSEE5590-490-Python-and-DL-SP2018 | /Python Lab Assignment 1/Source/Q2.py | 771 | 4.4375 | 4 | # Taking input from the user
list1 = input("Enter Sentence: ").split(" ")
# Function for evaluating the sentence
def give_sentence(list1):
# Declaring empty list
list2 = []
#Print middle words in a sentence
print("Middle Words of the Sentence are: "+list1[len(list1)//2], list1[(len(list1)//2)+1])
# Printing Longest Word in the sentence
for item in list1:
list2.append(len(item))
print("Longest Word in the Sentence: "+list1[list2.index(max(list2))] +" "+"("+str(max(list2)) + " letters"+ ")")
# Printing Sentence in Reverse
# item[::-1] to reverse the string
# end = " " is to print side by side
print("Reversed Sentence: ", end= " ")
for item in list1:
print(item[::-1],end = " ")
give_sentence(list1) | true |
b66e53fcea2e0232c032ed701e780a9846377322 | ashiifi/basic-encryption | /encryption.py | 2,527 | 4.40625 | 4 | """
Basic Encryption Project:
encryption(S,n) takes in a string and a number. It then moves each letter in the string
n amount of times through the alphabet. In this way, 'encrypting' the string
then decryption(W) takes in the encrypted string with the n at the end of it. like "helloworld1"
"""
def encryption(S, n):
#this is actually quite basic, I am simply listing the entire alphabet as a starting point
letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
initial = [] #initiate an empty list for the initial characters
encrypted = []
for char in S: #adds each character to the list initial
initial.append(char)
#Now if you noticed that you could also simply just use list(S) to get initial, you are right!
a = 0
while a < len(initial): #starts a while loop until a is no longer smaller than the lenght if initial
for i in range(len(initial)):
if initial[a] == " ": #if the element is a space " ", then add it as well
encrypted.append(" ")
elif initial[a] in letters:
encrypted.append(letters[(letters.index(initial[a])+n)%26])
a = a + 1
T = "".join(encrypted)
W = T+str(n) #ouputs the encrypted string as well as the n attached to the end
return W
def decryption(W): #takes in W which is an encrypted string and decrypts
letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
numbers = ['1','2','3','4','5','6','7','8','9','0','-']
initial = []
decrypted = []
num = []
for char in W:
initial.append(char)
a = 0
b = 0
while b < len(initial):
if initial[b] in numbers:
num.append(initial[b])
n = "".join(num)
b = b + 1
while a < len(initial):
for i in range(len(initial)):
if initial[a] == " ":
decrypted.append(" ")
elif initial[a] in letters:
decrypted.append(letters[(letters.index(initial[a])-int(n))%26])
a = a + 1
d = "".join(decrypted)
return d
def main():
print("\nAre you looking to encrypt or decrypt? \n\nType exactly as shown: encrypt OR decrypt")
to_run = str(input())
if to_run == "encrypt":
print('Word to encrypt:')
S = str(input())
print('\nProvide n:')
n = int(input())
W = encryption(S, n)
print('\nEncrypted phrase:')
print(W)
elif to_run == "decrypt":
print('Encrypted phrase to decrypt(with n at end):')
W = str(input())
print("\nDecrypted word:")
print(decryption(W))
else:
print('unknown method entered')
main() | true |
b2a7a14ccf32ece134f0d20b577fc3fcb6b4a132 | brittCommit/lab_word_count | /wordcount.py | 831 | 4.21875 | 4 | # put your code here.
import sys
def get_word_count(file_name):
"""Will return word count of a given text file.
user will enter python3 wordcount.py 'anytextfilehere' on the command
line to run the code
"""
text_file = open(sys.argv[1])
word_count = {}
special_characters = [',', '?', '.', '/', ':', '(',')', '!']
for line in text_file:
line = line.strip()
words = line.split(' ')
for word in words:
# for letter in word:
# if letter in special_characters:
# new_word = [word]
# new_word = word.remove([-1])
# word = new_word
word_count[word] = word_count.get(word,0) + 1
return word_count
print(get_word_count(sys.argv)) | true |
b8397d36b580077337a794991bf083c2003222a6 | EgorKurito/little_projects | /NumberGame.py | 1,228 | 4.1875 | 4 | import random
# главная функция игры
def game():
# генерация случайного числа от 1 до 10
secret_num = random.randint(1, 10)
# Список чисел пользователя
guesses = []
while len(guesses) < 3:
# проверка того, что пользователь ввел число
try:
# считывание числа пользователя
guess = int(input("Guess a number between 1 and 10: "))
except ValueError:
print("{} isn't a number!".format(guess))
else:
# проверка числа пользователя
if guess == secret_num:
print("You got it! My number was {}".format(secret_num))
break
elif guess > secret_num:
print("Your number is too high")
else:
print("Your number is too low")
guesses.append(guess)
else:
print("You didnt get it. My number was {}".format(secret_num))
play_again = input("Do you want to play again? Y/n")
if play_again.lower() != 'n':
game()
else:
print("Bye!")
game()
| false |
22f8f3f61f63a9c1a0c174761c56bfd621a4c915 | AnabellJimenez/SQL_python_script | /data_display.py | 1,395 | 4.34375 | 4 | import sqlite3
'''Python file to enter sql code into command line and generate a csv file with the information from the: fertility SQL DB '''
from Database_model import Database
import requests
import csv
#open sqlite3 connection
def db_open(filename):
return sqlite3.connect(filename)
#close sqlite3 connection
def db_close(conn):
conn.close()
#function takes an SQL command as a parameter and returns what is in the table
def db_select(conn, SQL_cmd):
c = conn.cursor()
c.execute(SQL_cmd)
return c.fetchall()
#function opens file, taking in filename and data list as paramter and writes to a CSV
def open_file(filename, data_list):
with open(filename, "wb") as f:
csv_writer = csv.writer(f)
for data in data_list:
csv_writer.writerow(data)
'''function calls
***BUG: HEADER IN CSV FILE!!!!
'''
conn = db_open("fertility")
filename = raw_input("Enter file you want to create: ")
SQL_cmd = raw_input("Enter SQL command you want to execute: \n")
data_list = db_select(conn, SQL_cmd)
open_file(filename, data_list)
# def read_file(filename):
# with open(filename, "r") as f:
# lines = f.readlines()
# # print lines
# array = []
# for line in lines:
# # line.split(",")
# # print line
# line.split(",")
# line[0].strip("\n")
# line[1].strip("\n")
# new_hash = {}
# new_hash["x"]=line[0]
# new_hash["y"]=line
# array.append(new_hash)
# return array
| true |
f95eb88f8b5ae743155b8d3b55389c6d8686cfe2 | ravisjoshi/python_snippets | /Array/SearchInsertPosition.py | 801 | 4.15625 | 4 | """
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Input: [1,3,5,6], 5 / Output: 2
Input: [1,3,5,6], 2 / Output: 1
Input: [1,3,5,6], 7 / Output: 4
Input: [1,3,5,6], 0 / Output: 0
"""
class Solution:
def searchInsert(self, nums, target):
if nums == []:
return 0
elif target in nums:
return nums.index(target)
else:
position = 0
for num in nums:
if num < target:
position += 1
return position
if __name__ == '__main__':
s = Solution()
nums = [1, 3, 5, 6]
target = 5
print(s.searchInsert(nums, target))
| true |
0334ea3d2d970823df4f5b66f1cfc5855d972206 | ravisjoshi/python_snippets | /Basics-3/ConstructTheRectangle.py | 2,118 | 4.15625 | 4 | """
For a web developer, it is very important to know how to design a web page's size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:
1. The area of the rectangular web page you designed must equal to the given target area.
2. The width W should not be larger than the length L, which means L >= W.
3. The difference between length L and width W should be as small as possible.
You need to output the length L and the width W of the web page you designed in sequence.
Input: 4 / Output: [2, 2]
Explanation: The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1].
But according to requirement 2, [1,4] is illegal; according to requirement 3, [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2.
Note:
The given area won't exceed 10,000,000 and is a positive integer
The web page's width and length you designed must be positive integers.
"""
import sys
from itertools import combinations, permutations
from math import sqrt
class Solution:
def constructRectangle(self, area):
for index in range(int(sqrt(area)), 0,-1):
if area % index == 0:
return [area//index, index]
def constructRectangle_BruteForce(self, area):
if area == 1:
return [1, 1]
factors = [area]
for index in range(1, area//2+1):
if area % index == 0:
factors.append(index)
factors.append(int(sqrt(area)))
output = {}
for l, w in permutations(factors, 2):
if l*w == area and l >= w:
output.update({l: w})
min_value, result = sys.maxsize, [0, 0]
for l, w in output.items():
if (l - w) < min_value:
result[0] = l
result[1] = w
min_value = l - w
return result
s = Solution()
area = 10
print(s.constructRectangle(area))
area = 4
print(s.constructRectangle(area))
area = 9
print(s.constructRectangle(area))
| true |
272a9925a7e7c9fa671779a87354cac682c8e379 | ravisjoshi/python_snippets | /Strings/validateParenthesis.py | 1,217 | 4.40625 | 4 | """
Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this 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.
Input: "()" / Output: True
Input: "(*)" / Output: True
Input: "(*))" / Output: True
Input: ")(" / Output: False
Input: "(((****))" / Output: True
"""
class Solution(object):
def checkValidString(self, parenthesisString):
leftP = rightP = 0
for parenthesis in parenthesisString:
leftP += 1 if parenthesis == '(' else -1
rightP += 1 if parenthesis != ')' else -1
if rightP < 0: break
leftP = max(leftP, 0)
return leftP == 0
if __name__ == '__main__':
s = Solution()
parenthesisString = "***)"
print(s.checkValidString(parenthesisString)) | true |
3a2ab445be28e3da8491cc57473ba43252435d4a | ravisjoshi/python_snippets | /Strings/LongestUncommonSubsequenceI.py | 1,496 | 4.21875 | 4 | """
Given two strings, you need to find the longest uncommon subsequence of this two strings. The longest uncommon subsequence is defined as the longest subsequence of one of these strings and this subsequence should not be any subsequence of the other string.
A subsequence is a sequence that can be derived from one sequence by deleting some characters without changing the order of the remaining elements. Trivially, any string is a subsequence of itself and an empty string is a subsequence of any string.
The input will be two strings, and the output needs to be the length of the longest uncommon subsequence. If the longest uncommon subsequence doesn't exist, return -1.
Input: a = "aba", b = "cdc" / Output: 3
Explanation: The longest uncommon subsequence is "aba",
because "aba" is a subsequence of "aba",
but not a subsequence of the other string "cdc".
Note that "cdc" can be also a longest uncommon subsequence.
Input: a = "aaa", b = "bbb" / Output: 3
Input: a = "aaa", b = "aaa" / Output: -1
Constraints:
Both strings' lengths will be between [1 - 100].
Only letters from a ~ z will appear in input strings.
"""
class Solution:
def findLUSlength(self, strA, strB):
if strA == strB:
return -1
elif len(strA) == len(strB):
return len(strA)
return len(strA) if len(strA) > len(strB) else len(strB)
if __name__ == '__main__':
s = Solution()
strA = "aaa"
strB = "bbb"
print(s.findLUSlength(strA, strB))
| true |
dc52061454014fea26d67bd88c9c4a34f5bdd17c | ravisjoshi/python_snippets | /DataStructure/sorting/quickSort.py | 854 | 4.1875 | 4 | """
Quick Sort: https://en.wikipedia.org/wiki/Quicksort
Ref:
https://www.youtube.com/watch?v=1Mx5pEeTp3A
https://www.youtube.com/watch?v=RFyLsF9y83c
"""
from random import randint
def quick_sort(arr):
if len(arr) <= 1: return arr
left, equal, right = [], [], []
pivot = arr[randint(0, len(arr)-1)]
for element in arr:
if element < pivot: left.append(element)
elif element == pivot: equal.append(element)
else: right.append(element)
return quick_sort(left)+equal+quick_sort(right)
# Create random array
def create_array(length=10, max=50):
arr = []
for _ in range(length):
arr.append(randint(0, max))
return arr
if __name__ == '__main__':
arr = create_array()
print('Before sorting: {}'.format(arr))
print('After sorting: {}'.format(quick_sort(arr)))
| true |
03670d974ef18610084e94c1e19573c55e060cdc | ravisjoshi/python_snippets | /DataStructure/StackAndQueue/MaximumElement.py | 1,417 | 4.3125 | 4 | """
You have an empty sequence, and you will be given N queries. Each query is one of these three types:
1 -Push the element x into the stack.
2 -Delete the element present at the top of the stack.
3 -Print the maximum element in the stack.
Input Format: The first line of input contains an integer N. The next lines each contain an above mentioned query. (It is guaranteed that each query is valid.)
Output Format: For each type 3 query, print the maximum element in the stack on a new line.
Input:
How many queries you want to enter:- 10
1 97
2
1 20
2
1 26
1 20
2
3
1 91
3
Output:
26
91
"""
class stack_template:
def __init__(self):
self.myStack = []
def insert_element(self, data):
self.myStack.append(data)
def delete_element(self):
self.myStack.pop(-1)
def find_max(self):
return max(self.myStack)
if __name__ == '__main__':
obj = stack_template()
num_of_queries = int(input('How many queries you want to enter:- '))
for _ in range(num_of_queries):
temp = input('Enter out of 3 options:- ').split()
if len(temp) == 2:
# query_to_call = int(temp[0])
# digit = int(temp[1])
obj.insert_element(int(temp[1]))
else:
query_to_call = int(temp[0])
if query_to_call == 2:
obj.delete_element()
else:
print(obj.find_max())
| true |
848696aadc4c2889406f5b2f1c61c47adb09f41d | ravisjoshi/python_snippets | /ProjectEuler/Basics-0/009-SpecialPythagoreanTriplet.py | 540 | 4.46875 | 4 | """
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
def pythagoreanTriplet(num):
for a in range(1, num//2):
for b in range(a+1, num//2):
c = num - (a+b)
if (a*a + b*b == c*c):
print('Values:- a={} b={} c={}'.format(a, b, c))
return a*b*c
num = 1000
print(pythagoreanTriplet(num))
| true |
24b03adda55bc74c4365e93ecf529f3cc1c4453d | ravisjoshi/python_snippets | /Permutation-Combination/PermutationAndCombination.py | 879 | 4.3125 | 4 | """
"My fruit salad is a combination of apples, grapes and bananas" We don't care what order the fruits are in, they could also be "bananas, grapes and apples" or "grapes, apples and bananas", its the same fruit salad.
"The combination to the safe is 472". Now we do care about the order. "724" won't work, nor will "247". It has to be exactly 4-7-2.
So, in Mathematics we use more precise language:
When the order doesn't matter, it is a Combination.
When the order does matter it is a Permutation.
"""
from itertools import permutations, combinations
text = 'ravi'
perm_list = ["".join(p) for p in permutations(text)]
print(perm_list)
# distinct Combination of 2 letter words
comb_list = ["".join(c) for c in combinations(text, 2)]
print(comb_list)
# distinct Combination of 3 letter words
comb_list = ["".join(c) for c in combinations(text, 3)]
print(comb_list)
| true |
c90e7d6f56a990f373775438722f91d821f1ff1f | ravisjoshi/python_snippets | /Basics-2/NumberOfDaysBetweenTwoDates.py | 815 | 4.21875 | 4 | """
Write a program to count the number of days between two dates.
The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples.
Input: date1 = "2019-06-29", date2 = "2019-06-30" / Output: 1
Input: date1 = "2020-01-15", date2 = "2019-12-31" / Output: 15
Constraints: The given dates are valid dates between the years 1971 and 2100.
"""
from datetime import date
class Solution:
def daysBetweenDates(self, date1, date2):
if date1 == date2:
return 0
y1, m1, d1 = map(int, date1.split('-'))
y2, m2, d2 = map(int, date2.split('-'))
d1 = date(y1, m1, d1)
d2 = date(y2, m2, d2)
delta = d2 - d1
return abs(delta.days)
s = Solution()
date1 = "2019-06-29"
date2 = "2019-06-30"
print(s.daysBetweenDates(date1, date2))
| true |
228e9868f9142aec935642cae53376452d296029 | monreyes/SelWebDriver | /PythonProj1/Sec3-UnderstandingVariablesAndDataTypes/319-StringMethods-Part2/string-methods2.py | 404 | 4.3125 | 4 | """
Examples to show available string methods in python
"""
# Replace Method
a = "1abc2abc3abc4abc"
print(a.replace('abc', 'ABC'))
#print(a.upper()) # another way to convert if all is need to upper case (or a.lower if all needed to be in lower case)
# Sub-Strings
# starting index is inclusive
# Ending index is exclusive
sub = a[0:6]
step = a[1:6:2]
print("****************")
print(sub)
print(step)
| true |
902b77933c6d369a13fa8963737cde0a22c0d01b | monreyes/SelWebDriver | /PythonProj1/Sec3-UnderstandingVariablesAndDataTypes/314-Numbers-ExponentiationAndModulo/numbers_operations.py | 427 | 4.28125 | 4 | # This is a one line comment
# Exponentiation
exponents = 10**2
print(exponents)
"""
this is a multi line comment
modulo - returns the remainder
"""
a=100
b=3
remainder = a % b
print("Getting the modulo of " + str(a)+ " % "+ str(b) + " is just like getting the remainder integer when " + str(a) +" is being divided by " + str(b))
print("The modulo of ("+str(a) +" % "+str(b) +") is " + str(remainder))
| true |
e0e58817c9c9c0f193702530713de5bdc9755ec9 | monreyes/SelWebDriver | /PythonProj1/Sec3-UnderstandingVariablesAndDataTypes/321-StringsFormating/strings_formatting.py | 314 | 4.25 | 4 | """
Examples to show how string formatting works in python
"""
city = "nyc"
dine = "alingdosya"
event = "show"
#dine = "alingdosya"
print("Welcome to "+city+" and enjoy the "+event+", dont forget to eat at "+dine )
print("Welcome to %s and enjoy the %s, dont forget to eat at %s" % (city,event,dine))
| false |
ddb4a47288b73951542d6c1aa3854b7c3846cf9c | DysphoricUnicorn/CodingChallenges | /extra_char_finder.py | 1,630 | 4.3125 | 4 | """
This is my solution to the interview question at https://www.careercup.com/question?id=5101712088498176
The exercise was to write a script that, when given two strings that are the same except that one string has an extra
character, prints out that character.
"""
import sys
def find_extra_char(longer_string, shorter_string):
"""
Returns the extra char that longer_string has but shorter_string hasn't got
:param str longer_string:
:param str shorter_string:
:return char:
"""
i = 0
for char in longer_string:
try:
if not char == shorter_string[i]:
# if the char is not the same as the one in the same position in the shorter string, it is the extra one
return char
except IndexError:
# if an IndexError occurs, we can assume that the extra char is at the end of the longer string
return char
i += 1
def main():
"""
Gets two strings from sys.argv and prints out the extra character
:return void:
"""
try:
string_one = sys.argv[1]
string_two = sys.argv[2]
except IndexError:
print("Could not find strings. Please call this script like this:")
print("python3 extra_char_finder <string1> <string2>")
sys.exit(1)
if len(string_one) > len(string_two):
# check which string is the longer one to iterate through it inside the find_extra_char function
char = find_extra_char(string_one, string_two)
else:
char = find_extra_char(string_two, string_one)
print(char)
if __name__ == '__main__':
main()
| true |
6a563dbae7b8cf7a46621ba9013275c2856ffc95 | pratikmallya/interview_questions | /sorting/insertion_sort.py | 1,011 | 4.34375 | 4 | """
Insertion Sort
Pick lowest element, push it to the front of the list
This will be an in-place sort. Why? Because that's a little
more complicated.
"""
import unittest
from random import sample
from copy import deepcopy
class TestAlg(unittest.TestCase):
def test_case_1(self):
v = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
insertion_sort(v)
self.assertEqual(v, list(range(1,11)))
maxlen = 10000
v1 = sample(range(maxlen), maxlen)
v2 = deepcopy(v1)
self.assertEqual(
v1.sort(), insertion_sort(v2))
def insertion_sort(v):
for i in range(1, len(v)):
ind = find_ind(v[:i], v[i])
insert_elem(v, i, ind)
def find_ind(v, elem):
for i,item in enumerate(v):
if elem < item:
return i
return i
def insert_elem(v, from_ind, to_ind):
elem = v[from_ind]
for i in reversed(range(to_ind+1, from_ind+1)):
v[i] = v[i-1]
v[to_ind] = elem
if __name__ == "__main__":
unittest.main()
| true |
4206e176b23841534c80170b24ca94ee87170c1a | navnathsatre/Python-pyCharm | /BasicOprations.py | 580 | 4.25 | 4 | num1=int(input("Enter the value for num1 "))
num2=int(input("Enter the value for num2 "))
#num1=568
#num2=64
add=num1+num2
multi=num1*num2
sub=num1-num2
div=num1/num2
pow=num1**num2
"""print("addition of num1 and num2 is:-",add)
print("multiplication of num1 and num2 is:-",multi)
print("substraction of num1 and num2 is:-",sub)
print("power of num1 and num2 is:-",pow)
print("division of num1 and num2 is:-%.5f"%(div))"""
print(f"addition of two no. is {add} multiplication of two no. is {multi} substraction of two no. is {sub} division is {div} power is{pow}")
| true |
147560dd844918b281b381aedec10aac292711e6 | navnathsatre/Python-pyCharm | /pyFunc_3.py | 301 | 4.1875 | 4 | # Factorial of number
# 5! = 5*4*3*2*1
#1! = 0
#0! = 0
def iterFactorial(num):
result = 1
for item in range(1, num+1):
result = result*item
return result
n = int(input("Enter the number: "))
out = iterFactorial(n)
print("Factorial of {} is {} ".format(n, out)) | true |
dc8d1e68476d077ab36ca4aece654e6ac5ef63bb | RyanLongRoad/Records | /Test scores.py | 745 | 4.15625 | 4 | #Ryan Cox
#29/01/15
#Store and display students test scores
#Blue print
class studentMarks:
def __init__(self):
self.testScore = "-"
self.studentName = "-"
#main program
def create_record():
new_studentMarks = studentMarks
def enter_enformation():
studentMarks.studentName = input("Enter the student's name: ")
studentMarks.testScore = int(input("Enter the test score: "))
scores = []
scores.append(studentMarks)
return scores
def disply(scores):
for each in scores:
print("The student {0} got the test score of {1}".format(studentMarks.studentName,studentMarks.testScore))
create_record()
scores = enter_enformation()
disply(scores)
| true |
3cdcc8c5f51e8b0813fad7ad93b09331af801b9a | tamkevindo97/Runestone-Academy-Exercises | /longest_word_dict.py | 456 | 4.28125 | 4 | import string
def longest_word(text):
text.translate(str.maketrans('', '', string.punctuation))
list_text = list(text.split())
dictionary = {}
for aChar in list_text:
dictionary.update({aChar: len(aChar)})
max_key = max(dictionary, key=dictionary.get)
print(dictionary)
return max_key
def main():
text = input("Enter a sentence to see which word is longest: ")
print(longest_word(text))
main() | true |
cf714d1796d56fe211f62161b158821164121c43 | Rajat986/Python-Learning | /nnum.py | 232 | 4.125 | 4 | a=[]
n=int(input("Enter number of elements:"))
for i in range(n):
b=int(input("Enter element:"))
a.append(b)
l=a[0]
#print(a[0])
for i in range(n):
if (l<a[i]):
l=a[i]
print("Largest element is:",l)
| false |
08f8761330af9c9dccb0ed64557e1b45516b2bc4 | PacktPublishing/Learn-Python-Programming-Second-Edition | /Chapter01/ch1/scopes3.py | 450 | 4.21875 | 4 | # Local, Enclosing and Global
def enclosing_func():
m = 13
def local():
# m doesn't belong to the scope defined by the local
# function so Python will keep looking into the next
# enclosing scope. This time m is found in the enclosing
# scope
print(m, 'printing from the local scope')
# calling the function local
local()
m = 5
print(m, 'printing from the global scope')
enclosing_func()
| true |
ac9ea2d72c9ff6c204e1da79909827b6dee8edce | shdx8/dtwrhs | /D01/lat1.py | 376 | 4.28125 | 4 | # Buat list untuk menampung nama-nama teman
my_friends = ["Anggun", "Dian", "Agung", "Adi", "Adam"]
# Tampilkan isi list my_friends dengan nomer indeks 3
print ("Isi my_friends indeks ke-3 adalah: {}".format(my_friends[3]))
print()
# Tampilkan semua daftar teman
print ("Semua teman: {} ada orang".format(len(my_friends)))
print()
for friend in my_friends:
print (friend) | false |
d19cb3e849ab5d6e7d43843a000d24992e0a3b22 | llewyn-jh/codingdojang | /calculate_trigonometric_function.py | 1,046 | 4.28125 | 4 | """Calculate cosine and sine funtions in person"""
import math
def calculate_trigonometric_function(radian_x: float) -> float:
"""This function refer to Taylor's theorm.
A remainder for cos or sin at radian_x follows Cauchy's remainder.
The function has 2 steps. Step1 get a degree of
Taylor polynomial function at radian_x. Step 2 calculates sin and cos at radian_x
and return two values
"""
# Step1: get a degree of Taylor polynomial function at radian_x
degree = 0
error = 5 * 1e-6
upper_limit = radian_x ** degree / math.factorial(degree)
while upper_limit >= error:
# Upper limit of Cauchy's remainder for sin or cos at radian_x
degree += 1
upper_limit = radian_x ** degree / math.factorial(degree)
# Step2: Calculate sin, cos at radian_x
sin = 0
cos = 0
for i in range(degree):
sin += (-1) ** i * radian_x ** ((2 * i) + 1) / math.factorial(2 * i + 1)
cos += (-1) ** i * radian_x ** (2 * i) / math.factorial(2 * i)
return sin + cos
| true |
e78bb6f14e5aa6a3fc8e765ac206b458bcaa2fb3 | sirobhushanamsreenath/DataStructures | /Stacks/stack.py | 1,026 | 4.21875 | 4 | # Implementation of stack data structure using linkedlist
class Node:
def __init__(self, data=None, next=None):
self.next = next
self.data = data
def has_next(self):
return self.next != None
class Stack:
def __init__(self, top=None):
self.top = top
def print_stack(self):
current = self.top
while current:
print(current.data)
current = current.next
def push(self, data):
current = self.top
if self.top == None:
new_node = Node(data, None)
self.top = new_node
else:
new_node = Node(data, current)
self.top = new_node
def pop(self):
current = self.top
if self.top == None:
print('The stack is empty')
else:
self.top = current.next
def peek(self):
print(self.top.data)
mystack = Stack()
mystack.push(2)
mystack.push(1)
mystack.push(3)
# mystack.pop()
# mystack.print_stack()
mystack.peek()
| true |
c33c1e6d9251779cf6f7f8484d8e431575e8d1fa | ronshuvy/IntroToCS-Course-Projects | /Ex2 - Math/shapes.py | 1,529 | 4.46875 | 4 | # FILE : shapes.py
# WRITER : Ron Shuvy , ronshuvy , 206330193
# EXERCISE : intro2cs1 2019
import math
def shape_area():
""" Calculates the area of a circle/rectangle/triangle (Input from user)
:return: the area of a shape
:rtype: float
"""
def circle_area(r):
""" Calculates the area of a circle
:param r: circle radius
:return: the area of the shape
:rtype: float
"""
return math.pi * (r**2)
def rectangle_area(side_a, side_b):
""" Calculates the area of a rectangle
:param side_a: rectangle first side
:param side_b: rectangle second side
:return: the area of the shape
:rtype: float
"""
return side_a * side_b
def triangle_area(side_a):
""" Calculates the area of an equilateral triangle
:param side_a: triangle side
:return: the area of the shape
:rtype: float
"""
return (side_a**2) * (math.sqrt(3)/4)
print('Choose shape (1=circle, 2=rectangle, 3=triangle):', end = " ")
shape_type = float(input())
if shape_type == 1: # Circle
radius = float(input())
return circle_area(radius)
elif shape_type == 2: # Rectangle
side1 = float(input())
side2 = float(input())
return rectangle_area(side1, side2)
elif shape_type == 3: # Triangle
side = float(input())
return triangle_area(side)
else:
return None
| true |
e3a613de2b32756b5a6bad7846b1db69cd134bab | SonnyTosco/HTML-Assignments | /Python/sonnytosco_pythonoop_bike.py | 1,603 | 4.3125 | 4 | class Bike(object):
def __init__(self, price,max_speed):
self.price=price
self.max_speed=max_speed
self.miles=0
print "Created a new bike"
def displayInfo(self):
print "Bike's price:"+ str(self.price)
print "Bike's max speed:"+str(self.max_speed)+'mph'
print "Bike's mileage:"+str(self.miles)+'miles'
def ride(self):
print 'Riding'
self.miles+=10
def reverse(self):
print 'Reversing'
if self.miles>=5:
self.miles-=5
bike1 = Bike(99.99, 12)
bike1.ride()
bike1.ride()
bike1.ride()
bike1.reverse()
bike1.displayInfo()
bike2 = Bike(139.99, 20)
bike2.ride()
bike2.ride()
bike2.reverse()
bike2.reverse()
bike2.displayInfo()
# Answer:
# class Bike(object):
# def __init__(self, price, max_speed):
# self.price = price
# self.max_speed = max_speed
# self.miles = 0
#
# def displayInfo(self):
# print 'Price is: $' + str(self.price)
# print 'Max speed: ' + str(self.max_speed) + 'mph'
# print 'Total miles: ' + str(self.miles) + ' miles'
#
# def drive(self):
# print 'Driving'
# self.miles += 10
#
# def reverse(self):
# print 'Reversing'
# # prevent negative miles
# if self.miles >= 5:
# self.miles -= 5
#
# # create instances and run methods
# bike1 = Bike(99.99, 12)
# bike1.drive()
# bike1.drive()
# bike1.drive()
# bike1.reverse()
# bike1.displayInfo()
#
# bike2 = Bike(139.99, 20)
# bike2.drive()
# bike2.drive()
# bike2.reverse()
# bike2.reverse()
# bik2.displayInfo()
| true |
13ff32648e515107376972672ac74737c6670379 | HanaAuana/PyWorld | /DNA.py | 2,807 | 4.21875 | 4 | #Michael Lim CS431 Fall 2013
import random
# A class to hold a binary string representing the DNA of an organism
class DNA():
#Takes an int representing the number of genes, and possibly an existing genotype to use
def __init__(self, numGenes, existingGenes):
self.numGenes = numGenes
#If a genotype is given, use this
if existingGenes is not None:
self.dna = existingGenes
#Else, create a random genotype
else:
self.dna = ""
#Randomly pick 1 or 0 for the required number of genes
for i in range(0, numGenes):
value = random.randint(0, 1)
if value == 0:
self.dna += "0"
else:
self.dna += "1"
#Given a number, return the corresponding bit
def getGene(self, num):
return self.dna[num]
#Return a string containing the genotype of this instance. Bits are grouped as they are expressed in an Organism
def getGeneotype(self):
#Get a string for each gene that an Organism will express
gene0to4 = self.getGene(0) + self.getGene(1) + self.getGene(2) + self.getGene(3) + self.getGene(4)
gene5to8 = self.getGene(5) + self.getGene(6) + self.getGene(7) + self.getGene(8)
gene9to12 = self.getGene(9) + self.getGene(10) + self.getGene(11) + self.getGene(12)
gene13to17 = self.getGene(13) + self.getGene(14) + self.getGene(15) + self.getGene(16) + self.getGene(17)
gene18to23 = self.getGene(17) + self.getGene(18) + self.getGene(19) + self.getGene(20) + self.getGene(21) + self.getGene(22)
gene24to30 = self.getGene(24) + self.getGene(25) + self.getGene(26) + self.getGene(27) + self.getGene(28) + self.getGene(29) + self.getGene(30)
gene31to33 = self.getGene(31) + self.getGene(32) + self.getGene(33)
gene34to36 = self.getGene(34) + self.getGene(35) + self.getGene(36)
gene37to39 = self.getGene(37) + self.getGene(38) + self.getGene(39)
#Prints out each chunk
genes = ""
genes += str(gene0to4)+" "
genes += str(gene5to8)+" "
genes += str(gene9to12)+" "
genes += str(gene13to17)+" "
genes += str(gene18to23)+" "
genes += str(gene24to30)+" "
genes += str(gene31to33)+" "
genes += str(gene34to36)+" "
genes += str(gene37to39)+" "
genes += " "
#Genes past 40 are also unused, group these together too
for i in range(40, self.numGenes):
genes += self.dna[i]
return genes
#Returns the genotype as a single contiguous string
def getGeneotypeString(self):
genes = ""
for i in range(0, len(self.dna)):
genes += self.dna[i]
return genes | true |
697f05adc3fd045a5d8b4757ba1ceae1a92de41c | DrewStanger/pset7-houses | /import.py | 1,595 | 4.375 | 4 | from sys import argv, exit
from cs50 import SQL
import csv
# gives access to the db.
db = SQL("sqlite:///students.db")
# Import CSV file as a command line arg
if len(argv) != 2:
# incorrect number print error and exit
print(f"Error there should be 1 argv, you have {argv}")
exit(1)
# assume CSV file exists and columns name, house and birth present
# open the CSV file
with open(argv[1], "r") as inputfile:
reader = list(csv.reader(inputfile))
char_list = []
# add each entry to the list name , house, birth
for row in reader:
char_list.append(row)
# for each entry in char_list row[0] is the two or three names, split splits these into individual strings. [1] is the house [2] is the birth year.
for row in char_list:
name = row[0].split(' ')
house = row[1]
birth = row[2]
# now to if to figure out if len = 2 first and last names only, if len = 3 first midddle last. The following then adds the names to the db
if len(name) == 2:
#No middle name
firstName = name[0]
middleName = None
lastName = name[1]
db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES(?,?,?,?,?)", firstName, middleName, lastName, house, birth)
elif len(name) == 3:
#Middle name
firstName = name[0]
middleName = name[1]
lastName = name[2]
db.execute("INSERT INTO students (first, middle, last, house, birth) VALUES(?,?,?,?,?)", firstName, middleName, lastName, house, birth)
| true |
b982d5403b5334baa6e3ec0af46dee88ac765ead | royanusree17/royanusree | /for-3.py | 240 | 4.15625 | 4 | numbers = [1,2,3,4,5,6,7,8,9]
odd_count=0
even_count=0
for a in numbers:
if a % 2:
odd_count+=1
else:
even_count+=1
print("total even numbers is:",even_count)
print("total odd numbers is:",odd_count) | false |
0606a46baee937e230d7ae503a69c4724957c3d0 | elaineli/ElaineHomework | /Justin/hw2.py | 834 | 4.125 | 4 | ages = { "Peter": 10, "Isabel": 11, "Anna": 9, "Thomas": 10, "Bob": 10, "Joseph": 11, "Maria": 12, "Gabriel": 10, }
# 1 find the number of students
numstudents = len(ages)
print(numstudents)
# 2 receives ages and returns average
def averageAge(ages):
sum = 0
for i in ages.values():
sum += i
length = len(ages)
average = sum/length
return average
print('average age is ' + str(averageAge(ages)))
#3 find oldest student
def oldest(ages):
max = 0
name = ''
for k, i in ages.items():
if i > max:
max = i
name = k
return name
print('The oldest student is ' + str(oldest(ages)))
#4 how old in time
def new_ages(ages, n):
for key, value in ages.items():
value += n
ages[key] = value
return ages
print(new_ages(ages, 10))
| true |
8e472f11b1d5e9c6d3cec5500c8fb2229f3a6641 | Kakadiyaraj/Leetcode-Solutions | /singalString.py | 539 | 4.21875 | 4 | #Write a program that reads names of two python files and strips the extension. The filenames are then concatenated to form a single string. The program then prints 'True' if the newly generated string is a palindrome, or prints 'False' otherwise.
name1 = input('Enter a first file name : ')
name2 = input('Enter a second file name : ')
name1 = name1.replace('.py','')
name2 = name2.replace('.py','')
name = name1+name2
print('Newly generated string : ',name)
if name==name[::-1]:
print('Output : True')
else:
print('Output : False')
| true |
55a870349405f243b9a7b6fad1a4a27c82d9017a | rohitgit7/Ethans_Python | /Class4_[13-10-2018]/dictionary.py | 2,117 | 4.40625 | 4 | #Dictionary is a collection which is unordered, changeable and indexed
data = { 'name' : 'Rohit',
'roll_no' : 20, #will be overriden by last key value
'city' : 'Pune',
'roll_no' : 34,
2 : 234}
#dict() is a constructor too
print data
print "type(data)", type(data)
data['name'] = 'India'
data['call'] = 12345
print data
my_dict = dict(apple="green",banana="yellow",cherry='red') #using dict constructor to make a dictionary or convert to dictionary
print 'my_dict',my_dict
del(my_dict['apple']) #Delete key from dictionary
print "Delete apple", my_dict
print"----------------------------------------------------------------------------------"
print "keys in data:", data.keys()
print "Values in data:", data.values()
print "items in data:", data.items() #returns list of tuples of each key value pair
print "has_key \'cherry\': ", data.has_key('city')
print "get value of key \'name\': ", data.get('name')
print "get value of key \'n\': ", data.get('n') #data['n'] returns error if key doesnot exists, but get() will return none if key doesn't exists
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
print "squares.pop(4):",squares.pop(4) #delete deletes the key/value pair silently where pop returns value while deleting
print "squares", squares
squares[4]=16
print "squares[4]=16",squares
print "squares.popitem()", squares.popitem() #popitem() does not require key like pop(). it pops single key/value pair from start
print squares
print "squares.popitem()", squares.popitem()
print squares
print "squares:",squares.clear() #clears the dictionary
sq = squares #creates reference/alias to squares. Change in sq will reflect in squares.
sq[6] = 36
print "squares",squares
squares.copy() #copy() will create a new copy unlike aliases sq=squares
print 23 in squares
print 6 in squares
print squares.has_key(6)
print len(sq)
sq[7] = ''
print squares
dict1 = {'Name':'Zara','Age':20}
dict2 = {'sex':'female'}
dict1.update(dict2) #update is like extend in lists unlike append() it extends the dictionary
print "dict1",dict1
print "-------------------------------------------------------------------------"
| true |
a8c836841bb5422473a60ffdee9b09f1be7e49ac | rohitgit7/Ethans_Python | /Class12_[01-12-2018]/regex.py | 567 | 4.15625 | 4 | import re
#match() checks for a match only at the beginning of the string
#while search() checks for a match anywhere in the string
var = "This is a regex with is repeated"
a = re.match(r'(.*) is (.*)',var)
s = re.search(r'(.*) is (.*)',var)
print a
print a.group()
print a.group(1)
print a.group(2)
print s.group()
print s.group(1)
line = "THIS IS CAPS STRING"
b = re.match(r'T.*is.*',line,re.I)
print b
print b.group()
phone = "123-456-789 # This is phone number"
num = re.sub(r'\D',"",phone)
print num
num1 = re.sub(r'#.*$',"",phone)
print num1
#re.findall() | false |
7c9ce41e8653586ddd1e030039f58924447fc038 | rohitgit7/Ethans_Python | /Class5_[14-10-2018]/Conditions.py | 596 | 4.15625 | 4 | #0 = False
#non-zero are True
name1 = raw_input("Enter name1:")
name2 = raw_input("Enter name2:")
if name1 != name2:
print "Names are not same"
elif name1=='Rohit':
print "Name is Rohit"
else:
print "Names are same"
stud = {1:{'Name':'Prakash','boy':True,'girl':False},
2:{'Name':'Pooja','boy':False,'girl':True}}
sname = 'Pooja'
if stud[1]['girl']:
print "Roll no. 1 is a girl"
elif stud[1]['boy']:
print "Roll no. 1 is boy"
elif stud[2]['boy']:
print "Roll no. 2 is boy"
elif stud[2]['girl']:
print "Roll no. 2 is girl"
else:
print "Unidentified!"
# logical operator - and, or, not | false |
afe039a8f713e6a13372d2de91ec8c0d972a3d6d | gwlilabmit/Ram_Y_complex | /msa/msas_with_bad_scores/daca/base_complement.py | 1,870 | 4.3125 | 4 | #sequence = raw_input("Enter the sequence you'd like the complement of: \n")
#seqtype = raw_input("Is this DNA or RNA? \n")
sequence = ''
seqtype = 'DNA'
def seqcomplement(sequence, seqtype):
complement = ''
for i in range(len(sequence)):
char = sequence[i]
if char == 'A' or char == 'a':
if 'R' in seqtype or 'r' in seqtype:
complement += 'U'
else:
complement += 'T'
elif char == 'T' or char == 't':
if 'R' in seqtype or 'r' in seqtype:
answer = raw_input("Just letting you know, this sequence has T's despite you saying it's RNA. Do you want me to treat it as DNA? [Answer yes/no]\n")
if 'y' in answer or 'Y' in answer:
seqtype = 'DNA'
for j in range(len(complement)):
if complement[j] == 'U':
complementlist = list(complement)
complementlist[j] = 'T'
complement = "".join(complementlist)
complement += 'A'
else:
complement += 'A'
elif char == 'U' or char == 'u':
if 'D' in seqtype or 'd' in seqtype:
answer = raw_input("Just letting you know, this sequence has U's despite you saying it's DNA. Do you want me to treat it as RNA? [Answer yes/no]\n")
if 'y' in answer or 'Y' in answer:
seqtype = 'RNA'
for j in range(len(complement)):
if complement[j]== 'T':
complementlist = list(complement)
complementlist[j] = 'U'
complement = "".join(complementlist)
complement += 'A'
elif char == 'C' or char == 'c':
complement += 'G'
elif char == 'G' or char == 'g':
complement += 'C'
elif char == '\n' or char == ' ':
continue
else:
print "There's some non-A/U/T/C/G base here. Check index", i, "for the problem. There may be more issues later on in the string but this is the first issue I'm detecting."
complement = ""
break
i+=1
return complement
seqcomplement(sequence, seqtype)
| true |
5eead0bd31ab85a27925a22a450abc5eeff8f689 | gayathrib17/pythonpractice | /IdentifyNumber.py | 1,356 | 4.40625 | 4 | # Program to input from user and validate
while True:
try: # try is used to catch any errors for the input validation into float
num = int(input("Please input a integer between -9999 and 9999: "))
except ValueError: # ValueError is raised when we are attempting to convert a non numeric string into float.
print("This is not a valid number, please try again.")
continue
else: # should be a number, but check for within range
if -9999 < num < 9999:
print("Congrats! You have given a valid number!")
break
else:
print("Enter an integer between -9999 and 9999")
continue
def valid(n):
if n >= 0:
print(n, "is a positive number.")
else:
print(n, "is a negative number.")
if n%2 == 0:
print(n," is also an even number")
else:
print(n, " is also an odd number.")
def prime(n):
if n > 1:
# check for factors
for i in range(2, n):
if (n % i) == 0:
print(n, "is not a prime number")
print(i, "times", n // i, "is", n)
break
else:
print("and",n, " is also a prime number!")
# if input number is less than or equal to 1, it is not prime
else:
print(n, "is not a prime number.")
valid(num)
prime(num) | true |
1110b8b86c71d30e8e220e005cc60ac2c3ce546a | oscarhuang1212/Leecode | /LeetCode#073_Set_Matrix_Zeroes.py | 2,350 | 4.15625 | 4 | # File name: LeetCode#73_Set_Matrix_Zeroes.py
# Author: Oscar Huang
# Description: Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
#
# Example 1:
# Input:
# [
# [1,1,1],
# [1,0,1],
# [1,1,1]
# ]
# Output:
# [
# [1,0,1],
# [0,0,0],
# [1,0,1]
# ]
# Example 2:
# Input:
# [
# [0,1,2,0],
# [3,4,5,2],
# [1,3,1,5]
# ]
# Output:
# [
# [0,0,0,0],
# [0,4,5,0],
# [0,3,1,0]
# ]
#
# Follow up:
# A straight forward solution using O(mn) space is probably a bad idea.
# A simple improvement uses O(m + n) space, but still not the best solution.
# Could you devise a constant space solution?
# KeyPoints: Array
from typing import List
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
#Do not return anything, modify matrix in-place instead.
firstColumnZero = False
firstRowZero = False
R = len(matrix)
C = len(matrix[0])
if matrix[0][0] == 0:
firstColumnZero = True
firstRowZero = True
for r in range(0,R):
for c in range(0,C):
if r==0 and c ==0:
continue
if(matrix[r][c]==0):
if r == 0:
firstRowZero = True
if c == 0 :
firstColumnZero = True
matrix[r][0] = 0
matrix[0][c] = 0
for r in range(1,R):
for c in range(1,C):
if matrix[r][0] == 0 or matrix [0][c] ==0:
matrix[r][c]=0
if firstColumnZero ==True:
for r in range(0,R):
matrix[r][0] = 0
if firstRowZero ==True:
for c in range(0,C):
matrix[0][c] = 0
print(matrix)
print(firstRowZero)
print(firstColumnZero)
return None
input = [
[1,1,1],
[1,0,1],
[1,1,1]
]
input2 = [
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
input3 = [[0,1]]
Solution.setZeroes(None, input3) | true |
2392192820c230c919b684c3d2d9ba92b8ca4d59 | Gt-gih/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/0-add_integer.py | 594 | 4.25 | 4 | #!/usr/bin/python3
"""
Module with function that add two integers
"""
def add_integer(a, b=98):
"""Function that add two numbers
Raises:
TypeError: a parameter must be integer type
TypeError: b parameter must be integer type
Args:
a (int): The first parameter.
b (int): The second parameter.
Returns:
int -- a+b
"""
if type(a) not in [int, float]:
raise TypeError('a must be an integer')
if type(b) not in [int, float]:
raise TypeError('b must be an integer')
else:
return(int(a) + int(b))
| true |
3b5f8c3e6f1bd65ba15d4af55840ef50afae0ffe | Gt-gih/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/2-uniq_add.py | 362 | 4.1875 | 4 | #!/usr/bin/python3
def uniq_add(my_list=[]):
# new list
new_list = []
for element in my_list:
# checking element not exist in list 🔄
if element not in new_list:
new_list.append(element)
result = 0
# adding each element in list into result 🔴
for item in new_list:
result += item
return result
| true |
5396b8418cf7c78edbd8f764607077eb23fbf556 | jaseela65/python_newPrgm | /create an empty list,set,tuple,dictionary.py | 1,200 | 4.21875 | 4 |
# Python program to make an empty list
a=[]
print("values of a:",a)
print(" \Type of a :",type(a))
print("Length of a :",len(a))
#output
values of a: []
Type of a : <class 'list'>
Length of a : 0
..........................................................
# Python program to make an empty tuple
b=()
print("values of b:",b)
print("Type of b :",type(b))
print("Length of b :",len(b))
#output
values of b: ()
Type of b : <class 'tuple'>
Length of b : 0
...........................................................
# Python program to make an empty dictionary
c={}
print("values of c:",c)
print("Type of c :",type(c))
print("Length of c :",len(c))
#output
values of c: {}
Type of c : <class 'dict'>
Length of c : 0
...........................................................
# Python program to make an empty set
d=set()
print("values of d:",d)
print("Type of d :",type(d))
print("Length of d :",len(d))
#output
values of d: set()
Type of d : <class 'set'>
Length of d : 0
.............................................................
| false |
e047b0eeda1e934eebcef822d70a9403f30f7eec | ngchrbn/DS-Roadmap | /DS Code/1. Programming/Python/Projects/banking_system.py | 1,217 | 4.28125 | 4 | """
Banking System using OOP:
==> Holds details about a user
==> Has a function to show user details
==> Child class : Bank
==> Stores details about the account balance
==> Stores details about the amount
==> Allows for deposits, withdrawals, and view balance
"""
class User:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
def show_details(self):
print("Personal Details\n")
print("Name ", self.name)
print("Age", self.age)
print("Gender", self.gender)
# Child class
class Bank(User):
def __init__(self, name, age, gender):
super().__init__(name, age, gender)
self.balance = 0
def deposit(self, amount):
self.balance += amount
print("Account balance has been updated: $", self.balance)
def withdrawal(self, amount):
if amount > self.balance:
print("Insufficient Funds | Balance Available: $", self.balance)
else:
self.balance -= amount
print("Account balance has been updated: $", self.balance)
def view_balance(self):
self.show_details()
print("Balance available: $", self.balance) | true |
99b2328f91fc4677b052733546c480604cbcf4c2 | RaadUH/RBARNETTCIS2348 | /homework_1.py | 752 | 4.125 | 4 | #Raad Barnett 1231583
current_date = input("Enter the current date in (mm/dd/yyyy)")
date_of_birth = input("Enter the date of birth in (mm/dd/yyyy)")
cur_month = int(current_date.split("/")[0])
cur_day = int(current_date.split("/")[1])
cur_year = int(current_date.split("/")[2])
birth_month = int(date_of_birth.split("/")[0])
birth_day = int(date_of_birth.split("/")[1])
birth_year = int(date_of_birth.split("/")[2])
print("Birthday calculator")
print("Current day")
print("Month: ",cur_month)
print("Day: ",cur_day)
print("Year: ",cur_year)
print("Birthday")
print("Month: ",birth_month)
print("Day: ",birth_day)
print("Year: ",birth_year)
print("You are {0} years old.".format(cur_year-birth_year))
# import datetime
# print(datetime.datetime.now())
| false |
cb217a8a547a07eb1c02e065e9a0db8416ffd117 | shaniajain/hello-world | /ShaniaJainLab3.py | 2,792 | 4.15625 | 4 | ###############################################################################
# CS 21A Python Programming: Lab #3
# Name: Shania Jain
# Description: Password Verification Program
# Filename: ShaniaJainLab3.py
# Date: 07/25/17
###############################################################################
def main():
str1 = input("Enter password: ")
str2 = input("Re-enter password: ")
while str1!=str2:
print("Passwords do not match. Try again.")
str1 = input("Enter password: ")
str2 = input("Re-enter password: ")
check_length(str1, str2)
check_uppercase(str1, str2)
check_digits(str1, str2)
check_lowercase(str1, str2)
def check_length(str1, str2):
#check if password is atleast 8 characters long
chars = len(str1)
MIN_LENGTH = 8
if chars >= MIN_LENGTH:
return
else:
print("That password didn't have the required properties.")
main()
return
def check_uppercase(str1, str2):
#check if password has atleast one uppercase letter
while str1 == str2:
for char in str1:
if char >= "A" and char <= "Z":
return
else:
print("That password didn't have the required properties.")
main()
return
def check_digits(str1, str2):
#check if password has atleast one digit
while str1 == str2:
for char in str1:
if char >= "0" and char <= "9":
return
else:
print("That password didn't have the required properties.")
main()
return
def check_lowercase(str1, str2):
#check if password has atleast one lowercase letter
while str1 == str2:
for char in str1:
if char >= "a" and char <= "z":
print("That pair of passwords will work.")
return
else:
print("That password didn't have the required properties.")
main()
return
main()
'''
Enter password: Abc12
Re-enter password: Abc12
That password didn't have the required properties.
Enter password: abcd12345
Re-enter password: abcd12345
That password didn't have the required properties.
Enter password: ABCDabcd
Re-enter password: ABCDabcd
That password didn't have the required properties.
Enter password: ABCD12345
Re-enter password: ABCD12345
That password didn't have the required properties.
Enter password: Hello1234
Re-enter password: Ello12345
Passwords do not match. Try again.
Enter password: 123ABCabc
Re-enter password: 456ABCabc
Passwords do not match. Try again.
Enter password: ABCabc123
Re-enter password: ABCabc123
That pair of passwords will work.
'''
| true |
0f504d31e78ec4dd3ed8bd52d3fe690a9475fbc0 | fg885436fg/python | /main/1/ifelse.py | 344 | 4.25 | 4 | height = float(input('please enter your height: '));
weight = float(input('please enter your weight: '));
bmi = weight / (height * height);
if bmi < 18.5:
print("过轻")
elif 18.5 <= bmi <= 25:
print("正常")
elif 25 <= bmi <= 28:
print("过重")
elif 28 <= bmi <= 32:
print("肥胖")
elif bmi > 32:
print("严重肥胖") | false |
15312026ea5140058f5d609559994b23a4bfaaaa | JackShang94/BasicStudy | /DeepDiveIntoPython/Day02/Strings.py | 1,578 | 4.34375 | 4 | # string formatting
## method 1
text = 'Hello'
text2 = 'World'
print('%s' % text)
print('...%s...%s' % (text,text2))
## method 2
text = 'Hello'
print(f'...{text}...')
## method 3
text = 'Hello'
print('...{:s}...'.format(text))
print('{}'.format(text))
print('{},{}'.format('one','two','three')) ## different parameter
print('{} {}'.format(1,2))
print('{},{}'.format('one','two','three'))
print('{1},{0}'.format('one','two')) ## rearrangement
print('{2} {3} {5} {1} {4} {6}'.format('See','how', 'the', 'words', 'are', 'mixed', 'up'))
print('{:d}'.format(23)) ## integers
print('{:f}'.format(3.142)) ## float
print('{:.2f}'.format(3.142)) ## float
print('{:10}'.format('Hi')) ## padding left
print('{:>10}'.format('Hi')) ## padding right
print('{:5}'.format('1234567890')) ## no paddings
print('{:_<10}'.format('Hi')) ## under line
print('{:^10}'.format('Hi')) ## specify center
print('{:*^10}'.format('Hi')) ## specify center
# Activity 1
## way 1
print('{:10}{:10}{:10}'.format('a','b','a to power of b'))
print('{:<10}{:<10}{:<10}'.format(1,2,1**2))
print('{:<10}{:<10}{:<10}'.format(2,3,2**3))
print('{:<10}{:<10}{:<10}'.format(3,4,3**4))
print('{:<10}{:<10}{:<10}'.format(4,5,4**5))
print('{:<10}{:<10}{:<10}'.format(5,6,5**6))
## way 2
print('{:10}{:10}{:10}'.format('a','b','a to power of b'))
for value in range(1,6):
print('{:<10}{:<10}{:<10}'.format(value,value+1,value**(value+1)))
first = 'Learning Strings'
print(first[3:]) # ing Strings
print(first[3:6]) # rni
print(first[3:9]) # rning
print(first[3:9:2]) # rig
print(first[3:9:-1]) # ''
| false |
ce0198d5caa2eb033fb1b4c40198232063d0de38 | asiftandel96/Python-Implementation | /LambdaFunctions.py | 2,580 | 4.40625 | 4 | """ Python Lambda Functions/Anonymous Functions.Anonymous function are those function which are without name."""
# Defining a Normal functions.
def addition_num(a, b):
c = a * b
print(c)
addition_num(2, 42)
# Using A Lambda
# Syntax lambda arguments:expression
# Note-(Lambda Function can take single expression one at a time) (x+y-This is a expression)
s = lambda x, y: x + y
print(s(2, 3))
# Now Using lambda function with Filter() method
# Filter method filter out the list and give the output
List_li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
g = list(filter(lambda x: (x % 2 == 0), List_li))
print(g)
# Now Using Lambda function with map() method
c_2 = list(map(lambda x1, x2: x1 * 2 + x2 * 2, [2, 4, 6, 8, 10], [4, 2, 5, 7, 8]))
# Using Lambda Functions with reduce() method
from functools import reduce
c_3 = reduce(lambda x3, x4: x3 + x4, [1, 2, 4, 6, 7] + [1, 6, 7, 8, 9])
print(c_3)
# This is very Important Code
full_name = lambda first, last: f'Full name: {first.title()} {last.title()}'
print(full_name('guido', 'van rossum'))
# Python Program to find Linear Equation using Lambda Functions
Linear_eq = lambda a, b: 3 * a + 4 * b
print(Linear_eq(3, 4))
# Python Program to find Quadratic Equations
Quadratic_eq = lambda a, b: (a + b) ** 2
print((Quadratic_eq(3, 4)))
Unknown_number = lambda x: x * x
print(Unknown_number(5))
# Write a Python program to sort a list of tuples using Lambda.
subject_marks = [('English', 88), ('Science', 90), ('Maths', 97), ('Social sciences', 82)]
print("Original list of tuples:")
print(subject_marks)
subject_marks.sort(key=lambda x: x[1])
print("\nSorting the List of Tuples:")
print(subject_marks)
# Python Program to sort List Of Dictionaries using lambda
models = [{'make': 'Nokia', 'model': 216, 'color': 'Black'}, {'make': 'Mi Max', 'model': '2', 'color': 'Gold'},
{'make': 'Samsung', 'model': 7, 'color': 'Blue'}]
print("Original list of dictionaries :")
print(models)
sorted_models = sorted(models, key=lambda x: x['color'])
print("\nSorting the List of dictionaries :")
print(sorted_models)
# Write a Python program to filter a list of integers using Lambda
List_Integers = [1, 2, 3, 4, 5, -1, -2, -3, -4, -5]
g_e = list(filter(lambda x: (x > 0), List_Integers))
print(g_e)
# Write a Python program to find if a given string starts with a given character using Lambda.
starts_with = lambda x: True if x.startswith('P') else False
print(starts_with('Python'))
starts_with = lambda x: True if x.startswith('P') else False
print(starts_with('Java'))
| true |
b2b8e0d4fdf58e5da673a45d4ce894de37e3aec0 | rp927/05-Python-Programming | /question_9.py | 221 | 4.34375 | 4 | '''Celsius to Fahrenheit'''
'''User input'''
celsius = int(input("Enter a temperature to convert to fahrenheit:"))
'''Output'''
print(F"{celsius} degrees celsius is equal to {(9/5)*celsius + 32:.2f} degrees fahrenheit") | false |
413f32f1367a8cbf5183add9771d598e630f9534 | amarinas/algo | /chapter_1_fundamentals/leapyear.py | 484 | 4.21875 | 4 | # write a function that determines whether a given year is a leap year
# if the year is divisible by four, its a leap year
# unless its divisible by 100
# if it is divisible by 400 than it is
def leapyear(year):
if year % 4 == 0:
print "it is a leap year"
elif year % 100 ==0:
print "not a leap year buddy!"
elif year % 400 == 0:
print "it is a leap year"
else:
print "not a leap year"
print(leapyear(1901))
print(leapyear(2000))
| true |
ef06ee1de6b838599b98c1bab5883c595086f514 | amarinas/algo | /Hack_rank_algo/writefunction.py | 304 | 4.1875 | 4 | #Determine if a year is a leap yesar
def is_leap(year):
leap = False
#condition for a leap year
if year % 4 == 0 and year % 400 == 0 or year % 100 != 0:
return True
#return leap if the above condition is false
return leap
year = int(raw_input())
print is_leap(year)
| true |
9554a30f82c858f0aacab04102ba43a7f7057f02 | amarinas/algo | /random_algo_exercise/strings_integers.py | 208 | 4.15625 | 4 | # Read a string,S , and print its integer value; if S cannot be converted to an integer, print Bad String
import sys
S = raw_input().strip()
try:
print(int(S))
except ValueError:
print("Bad String")
| true |
096abdbc6c7a049bbfbc7c8afc516bad0ec5d022 | amarinas/algo | /PlatformAlgo/reversing.py | 474 | 4.65625 | 5 | #Given an array X of multiple values (e.g. [-3,5,1,3,2,10]), write a program that reverses the values in the array. Once your program is done X should be in the reserved order. Do this without creating a temporary array. Also, do NOT use the reverse method but find a way to reverse the values in the array (HINT: swap the first value with the last; second with the second to last and so forth).
def reverse(arr):
return arr[::-1]
print(reverse([-3,5,1,3,2,10]))
| true |
f9bd0cca25a8e163eb84c490e44fc305f3e1dc85 | amarinas/algo | /PlatformAlgo/square_value.py | 477 | 4.21875 | 4 | #Given an array x (e.g. [1,5, 10, -2]), create an algorithm (sets of instructions) that squares each value in the array. When the program is done x should have values that have been squared (e.g. [1, 25, 100, 4]). You're not to use any of the pre-built function in Javascript. You could for example square the value by saying x[i] = x[i] * x[i];
def square(arr):
for i in range(len(arr)):
arr[i] = arr[i] * arr[i]
return arr
print(square([1,5, 10, -2]))
| true |
7f90da219ab5807749f17964bdd7b1ff78b3c1eb | amarinas/algo | /random_algo_exercise/arrays_day7.py | 302 | 4.125 | 4 | # Given an array, A, of N integers, print A's elements in reverse order as a single line of space-separated numbers.
from __future__ import print_function
import sys
n = int(raw_input().strip())
arr = map(int,raw_input().strip().split(' '))
arr.reverse()
for num in arr:
print(num + " ", end='')
| true |
113abd3f4d90aa0b95d135b2b7928b6400738fa1 | amarinas/algo | /PlatformAlgo/iterate_array.py | 394 | 4.3125 | 4 | #Given an array X say [1,3,5,7,9,13], write a program that would iterate through each member of the array and print each value on the screen. Being able to loop through each member of the array is extremely important. Do this over and over (under 2 minutes) before moving on to the next algorithm challenge.
def Iterate_a(arr):
for i in arr:
print i
Iterate_a([1,3,5,7,9,13])
| true |
a06208c839a3331629c2116f667e73a693dc62a9 | chyidl/chyidlTutorial | /root/os/DSAA/DataStructuresAndAlgorithms/python/sort_selection_array_implement.py | 1,878 | 4.34375 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# sort_selection_array_implement.py
# python
#
# 🎂"Here's to the crazy ones. The misfits. The rebels.
# The troublemakers. The round pegs in the square holes.
# The ones who see things differently. They're not found
# of rules. And they have no respect for the status quo.
# You can quote them, disagree with them, glority or vilify
# them. About the only thing you can't do is ignore them.
# Because they change things. They push the human race forward.
# And while some may see them as the creazy ones, we see genius.
# Because the poeple who are crazy enough to think thay can change
# the world, are the ones who do."
#
# Created by Chyi Yaqing on 02/18/19 16:16.
# Copyright © 2019. Chyi Yaqing.
# All rights reserved.
#
# Distributed under terms of the
# MIT
"""
Selection Sort:
The selection sort algorithm sorts an array by repeatedly finding the minimum
element(considering ascending order)from unsorted part and putting it at the
beginning. The algorithm maintains two subarrays in a given array.
1) The Subarray which is already sorted
2) Remaining subarray which is unsorted
In every iteration of selection sort, the minimum element (considering ascendin
order) from the unsorted subarray is picked and moved to the sorted subarray
"""
# Python program for implementation of Selection Sort
def selectionSort(arr):
for i in range(len(arr)):
# Find the minimum element in remaining unsorted array
min_idx = i
for j in range(i+1, len(arr)):
if arr[min_idx] > arr[j]:
min_idx = j
# Swap the found minimum element with the first element
arr[i], arr[min_idx] = arr[min_idx], arr[i]
# Driver code to test above
arr = [64, 25, 12, 22, 11]
print("Original array is : {}".format(arr))
selectionSort(arr)
print("Sorted array is : {}".format(arr))
| true |
3b2d4f6855512f17e98d393348cdf39f855ab739 | lstobie/CP1404_practicals | /prac_03/ASCII.py | 612 | 4.125 | 4 | def main():
LOWER_LIMIT = 33
UPPER_LIMIT = 127
char = input("Enter a character: ")
print("The ASCII code for {} is {}".format(char, ord(char)))
cord = int(input("Enter a number between {} and {}: ".format(LOWER_LIMIT, UPPER_LIMIT)))
if LOWER_LIMIT <= cord <= UPPER_LIMIT:
print("The character for {} is {}".format(cord, chr(cord)))
else:
print("invalid")
for i in range(LOWER_LIMIT, UPPER_LIMIT + 1):
print("{0:>3}{1:>10}".format(i, chr(i)))
# I only know data frames can edit column numbers unless we want an if/elif/elif... code with limits
main()
| true |
fa831333ccba3c9f683f4388160af0e640655d1b | bluisalima/Solyd-Python | /aula5.py | 548 | 4.28125 | 4 | ''' Exercício - Aula 5: Faça um programa que leia a quantidade de pessoas que serão convidadas para uma festa.
Após isso o programa irá perguntar o nome de todas as pessoas e colocar numa lista de convidados.
Imprima todos os nomes da lista.
'''
numero_convidados = input("Número de pessoas convidadas: ")
convidados = []
i = 0
while i < int(numero_convidados):
nome_convidado = input("Nome do convidado: ")
convidados.append(nome_convidado)
i += 1
print("Lista de convidados:\n")
for pessoas in convidados:
print(pessoas)
| false |
f607d1a6bb37486172a511d848657e146b3b104d | lzl813/Python_dataming | /python01/02/02.py | 412 | 4.25 | 4 | #创建列表
a = list("abc")
print(a)
#替换指定序列
a[1] = "5"
print(a)
#删除一个序列
del a[1]
print(a)
#追加
a.append("def")
print(a)
#链表的添加
a.extend(a)
print(a)
#链表的插入
a.insert(2,"kf")
print(a)
#删除指定序列的对象
a.pop(2)
print(a)
#链表的复制
s = a.copy()
print(s)
#链表的反转
s2 = a.reverse()
print(s2)
#链表排序
s3 = [2, 3, 4, 0]
s3.sort()
print(s3) | false |
967bb21482280ffe1eff1b09ee403dcaac27858d | alexpsimone/other-practice | /repls/anagram_finder.py | 2,072 | 4.1875 | 4 | # anagram finder
# write a function that takes two strings and returns whether or not they are anagrams
# abc cab -> true
# abc abc -> true
# abc abd -> False
# '' '' -> True
# abc1 1abc -> True
# abcd abc -> False
# numbers and letters, no spaces, any length strings
def anagram(x, y):
# if the strings are equal, return True
if x == y:
return True
# if one of the strings is empty, return False
if x == '' or y == '':
return False
# if len(x) != len(y), return False
if len(x) != len(y):
return False
list_x = sorted(x)
list_y = sorted(y)
# loop through each index in x
for idx in range(len(list_x)):
if list_x[idx] != list_y[idx]:
return False
# see if list_x[idx] = list_y[idx]
# if not equal, return False
# return True
return True
def anagram2(x, y):
# if the strings are equal, return True
if x == y:
return True
# if one of the strings is empty, return False
if x == '' or y == '':
return False
# if len(x) != len(y), return False
if len(x) != len(y):
return False
# initialize a dict for x
x_dict = {}
# initialize a dict for y
y_dict = {}
# loop through x
for char in x:
# if char in dict, increment value at char
if char in x_dict:
x_dict[char] += 1
else:
x_dict[char] = 1
# otherwise, initialize a value dict[char]: 1
# do the same things for y
for char in y:
if char in y_dict:
y_dict[char] += 1
else:
y_dict[char] = 1
# loop through each key in x dict
for x_key in x_dict:
# if key not in y_dict, return False
if x_key not in y_dict:
return False
# elif dict[key] != dict[key] return False
elif x_dict[x_key] != y_dict[x_key]:
return False
# else return True
return True
if __name__ == '__main__':
pass | true |
bb40fb86a454d0617480ae24c842a1cd91ca9c7c | erijones/phs | /python/intro/prime_finder.py | 1,815 | 4.40625 | 4 | #!/usr/bin/python3
# This program runs as ./prime_finder (with correct permissions), but
# incorrectly! The program's goal is to list the prime numbers below a certain
# number using the Sieve of Eratosthenes, discovered around 200 BC.
# Run the file, and mess around with the testing area below. Debug and
# troubleshoot with print() messages
# you can import this file into the shell with "import prime_finder" and then
# test individual functions
# end goal:
# ---------
# prime_list(30) returns [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
import math # so we can use the floor function! called with math.floor(2.33)
# check if 'num' is prime
def is_prime(num):
# to check, we divide num by all numbers less than it. If num is divisible
# by any number, we set flag to False
flag = True
# use is_integer to tell what sort of data type a number is (useful for
# divisibility)
print("ints? ", (4.0).is_integer(), (4.3).is_integer(), '\n')
# can you implement this same line using modulus (%) instead?
for elem in range(1,num):
if elem == 4:
print("elem is 4")
print(elem)
# [print(elem) for elem in range(num)]
# note this is the same as directly above!
return flag # let's say flag = True means prime, flag = False means composite
# return a list of prime numbers less than 'bound'
def prime_list(bound):
# return a list of all of the prime numbers up to
return [elem for elem in range(bound) if elem > 10]
# example test commands
# ------------
print("Is 15 prime?")
print(is_prime(15))
print("All primes under 30:")
print(prime_list(30))
# food for thought:
# -----------------
# how fast does this algorithm run?
# could you improve the speed? do you need to check whether n is divisible by
# every number from 1 to n?
| true |
4885d8d60b7b2245f2bc4c8d398a66e26a5620e9 | noehoro/Python-Data-Structures-and-Algorithms | /Recursion/recursiveMultiply.py | 349 | 4.15625 | 4 | def iterative_multiply(x, y):
results = 0
for i in range(y):
results += x
return results
def recursive_multiply(x, y):
# This cuts down on the total number of
# recursive calls:
if y == 0:
return 0
return x + recursive_multiply(x, y - 1)
x = 500
y = 2000
print(x * y)
print(recursive_multiply(x, y))
| true |
9ea9de95112cbcf5d0c6dc1e87833c67b9602bf1 | prince6635/expert-python-programming | /syntax_best_practices/coroutines.py | 2,417 | 4.1875 | 4 | """
Coroutines:
A coroutine is a function that can be suspended and resumed, and can have multiple entry points.
For example, each coroutine consumes or produces data, then pauses until other data are passed along.
PEP 342 that initiated the new behavior of generators also
provides a full example on how to create a coroutine scheduler.
The pattern is called Trampoline, and can be seen as a mediator between coroutines that produce and consume data.
It works with a queue where coroutines are wired together.
Threading:
Threading is an alternative to coroutines in Python.
It can be used to run an interaction between pieces of code.
But they need to take care of resource locking since they behave in a pre-emptive manner,
whereas coroutines don't.
"""
from __future__ import with_statement
from contextlib import closing
import socket
import multitask
# simple coroutine test
# The multitask module available at PyPI (install it with easy_install multitask)
# if it doesn't work, download .gz, unzip and then install
# $ tar -xzf multitask-0.2.0.tar.gz
# $ cd multitask-0.2.0
# $ python setup.py install
import time
def coroutine1():
for i in range(3):
print 'coroutine1'
yield i
def coroutine2():
for i in range(3):
print 'coroutine2'
yield i
def test_simple_coroutine():
multitask.add(coroutine1())
multitask.add(coroutine2())
multitask.run()
# complicated coroutine test for sockets and server
def client_handler(sock):
with closing(sock):
while True:
data = (yield multitask.recv(sock, 1024))
if not data:
break
yield multitask.send(sock, data)
def echo_server(hostname, port):
addrinfo = socket.getaddrinfo(hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM)
(family, socktype, proto, canonname, sockaddr) = addrinfo[0]
with closing(socket.socket(family, socktype, proto)) as sock:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(sockaddr)
sock.listen(5)
while True:
multitask.add(client_handler((yield multitask.accept(sock))[0]))
def test_complicated_coroutine():
hostname = 'localhost'
port = 1111
multitask.add(echo_server(hostname, port))
multitask.run()
if __name__ == '__main__':
test_simple_coroutine()
test_complicated_coroutine()
| true |
297be99001229c022c8cdeb10122df55491d401c | zackbrienza/fantasy-football | /sorting.py | 1,399 | 4.1875 | 4 | #Scott Dickson
#Practice writing sorting algorithms
import random
#Also as expected
def quicksort(arr):
n = len(arr)
if n == 1 or n == 0:
return arr
elif n == 2:
return arr if arr[1] > arr[0] else [arr[1],arr[0]]
else:
splitter = arr[random.randrange(n)]
right = []
left = []
for i in range(n):
if arr[i] > splitter:
right.append(arr[i])
else:
left.append(arr[i])
return quicksort(left)+quicksort(right)
#As expected
def mergesort(arr):
n = len(arr)
if n == 1 or n == 0:
return arr
elif n == 2:
return arr if arr[1] > arr[0] else [arr[1],arr[0]]
else:
splitter = n // 2
left = mergesort(arr[0:splitter])
right = mergesort(arr[splitter:])
return merge(left,right)
#Merge two sorted lists and return the result
def merge(arr1, arr2):
merged = []
while arr1 != [] and arr2 != []:
if(arr1[len(arr1) - 1] > arr2[len(arr2) - 1]):
merged = [arr1.pop()] + merged
else:
merged = [arr2.pop()] + merged
return arr1 + arr2 + merged
if __name__ == '__main__':
lst1 = [1,4,6,2,3,4,5,9,8,3,10]
lst2 = [4,5,5,6,10]
print(lst1)
print(lst2)
print(quicksort(lst1))
print(mergesort(lst1))
| false |
98aefb8c8ae08939ef877e268bfc10a54a0be896 | alancyao/fun-times | /Algorithms/reverse_contiguous_subset_to_sort.py | 794 | 4.21875 | 4 | #!/usr/bin/env python3
""" Problem description:
You have an array of n distinct integers. Determine whether it is possible to sort the array by reversing exactly one contiguous segment of the array. For example, 1 [4 3 2] 5 => 1 [2 3 4] 5.
"""
""" Some variables for testing """
possible = [1, 2, 6, 5, 4, 3, 7, 8]
impossible = [1, 2, 6, 3, 4, 5, 7, 8]
def can_sort_by_reversing_subsegment(arr):
s = sorted(arr)
oop = [x for x in enumerate(arr) if (x[1] != s[x[0]])]
return [x[1] for x in oop[::-1]] == s[oop[0][0]:oop[-1][0]+1]
def main():
print("Array: {}\n Possible: {}".format(possible,
can_sort_by_reversing_subsegment(possible)))
print("Array: {}\n Possible: {}".format(impossible,
can_sort_by_reversing_subsegment(impossible)))
if __name__ == '__main__':
main()
| true |
0e0bbc7c9d542fe1967d7b1fdd36cda4548bf5f7 | nicklambson/pcap | /class/subclass2.py | 460 | 4.28125 | 4 | class A:
def __init__(self):
self.a = 1
class B(A):
def __init__(self):
# super().__init__()
A.__init__(self)
# self.a = 2
self.b = 3
# use super() to access the methods of the parent class
# or A.__init__(self)
# use super().__init__() to initialize from the parent class
# If it's not initialized, b.a will not unless called explicitly from B's __init__()
a = A()
b = B()
print(a.a)
print(b.a)
print(b.b) | true |
3123e526b96d7aa2d5eaaa3e22bc676e127f9307 | nicklambson/pcap | /exceptions/which_exception.py | 419 | 4.125 | 4 | '''
try:
raise Exception
except:
print("c")
except BaseException:
print("a")
except Exception:
print("b")
'''
# error: default except: must be last
try:
raise Exception
except BaseException:
print("a")
except Exception:
print("b")
except:
print("c")
# a
try:
raise Exception
except BaseException:
print("a", end='')
else:
print("b", end='')
finally:
print("c")
# ac
| true |
e616966a28dbd8bbd905ecba525b13c87ce2980d | deelm7478/CTI110 | /P4T2_BugCollector_MathewDeel.py | 602 | 4.3125 | 4 | # Collects and displays the number of bugs collected.
# 10/15/18
# CTI-110 P4T2 - Bug Collector
# Mathew Deel
#
def main():
#Initialize the accumulator
total = 0
#Get the bugs collected for each day.
for day in range(1, 6):
#Prompt user for amount of bugs that day
print('Enter the bugs collected on day', day)
#User must input number of bugs
bugs = int(input())
#Gets the total for the week
total += bugs
#Display the total bugs.
print('You collected a total of', total, 'bugs.')
main()
| true |
f91daa21904b1c8272e2eaa69f2b416cd7942870 | deelm7478/CTI110 | /P4T1a_Deel.py | 852 | 4.21875 | 4 | # A program that draws both a square and a triangle
# 10/23/18
# CTI-110 P4T1a: Shapes
# Mathew Deel
#
def main():
#Import function
import turtle
#Specify shapes and playground
win = turtle.Screen()
s = turtle.Turtle()
t = turtle.Turtle()
#Specify pen characteristics for triangle
t.pensize(3)
t.pencolor("green")
t.shape("turtle")
#Specify pen characteristics for square
s.pensize(2)
s.pencolor("red")
s.shape("square")
#Draws triangle
for draw in range(3):
t.forward(50)
t.left(120)
#Moves pen to new spot
s.penup()
s.forward(70)
s.pendown()
#Draws square
for draw in range(4):
s.forward(50)
s.left(90)
# end commands
win.mainloop()
main()
| false |
9583849c3077e5aeefc86c503f69043286d0edf9 | amit70/Python-Interview-Examples | /isPower2.py | 481 | 4.28125 | 4 | #Given an integer, write a function to determine if it is a power of two.
def isPower(n):
# Base case
if (n <= 1):
return True
# Try all numbers from 2 to sqrt(n)
# as base
for x in range(2, (int)(math.sqrt(n)) + 1):
p = x
# Keep multiplying p with x while
# is smaller than or equal to x
while (p <= n):
p = p * x
if (p == n):
return True
return False
print isPower(8)
| true |
9155292ee252ccbf0682cca7df6a321f227d0d34 | kylebejel/Vigenere-Cipher | /vigenere.py | 663 | 4.125 | 4 | def encrypt(message, key):
alph = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
key_index = 0
new_message = ""
for ch in message:
new_ch = alph[(alph.index(ch) + (26 - alph.index(key[key_index])))%26]
new_message += new_ch
key_index = (key_index + 1)%len(key)
print("Original Message: " + message + "\nNew Message: " + new_message)
def __main__():
message = raw_input("Enter a message to encrypt: ").upper()
key = raw_input("Enter a key: ").upper()
encrypt(message, key)
if __name__ == '__main__':
__main__() | false |
134d690ef5727cce192900151ddb83c8d67b73b8 | jananee009/DataStructures_And_Algorithms | /Arrays_And_Strings/ReverseString.py | 1,183 | 4.6875 | 5 | # Implement a program to reverse a string.
# Follow up: Write a function to reverse an array of characters in place. "In place" means "without creating a new string in memory."
def reverseString(inputStr):
reversed = ""
for i in range(len(inputStr)-1,-1,-1):
reversed = reversed + inputStr[i]
return reversed
def reverseStringInPlace(inputStr):
# python strings are immutable. i.e. once we create a string, we cannot change it.
# To solve the problem, convert the string in to a list of characters and reverse the list in place.
# Then join all the characters in the list to get the reversed string
listOfChar = [] # create a list of characters from the inputStr.
listOfChar.extend(inputStr)
temp = ''
i=0
j=len(listOfChar)-1
while(i<j):
temp = listOfChar[i]
listOfChar[i] = listOfChar[j]
listOfChar[j] = temp
i = i+1
j = j-1
inputStr = ''.join(listOfChar)
return inputStr
def main():
user_input = input("Enter a string: ")
print "You entered: ",user_input
result1 = reverseString(user_input)
print "Reversed string: ",result1
result2 = reverseStringInPlace(user_input)
print "Reversed string: ",result2
if __name__ == "__main__":
main() | true |
d8c39538141f5d4065f9a6c89a0b438d66648a9e | jananee009/DataStructures_And_Algorithms | /Arrays_And_Strings/ReplaceAllSpaces.py | 749 | 4.4375 | 4 | # Write a method to replace all spaces in a string with '%20'. Assume that the string has sufficient space at the end of the string to hold the additional characters
# and that you are given the true length of the string.
# E.g. Input: "Mr John Smith ", 13
# Output: "Mr%20John%20Smith"
def replaceAllSpaces(input):
newString = ""
# Find each space in the input string. Replace it with '%20'.
for i in range(0,len(input)):
if(input[i] == " "):
newString = newString + "%20"
else:
newString = newString + input[i]
return newString
def main():
user_input = input("Enter a string: " )
print "You entered: ", user_input
result = replaceAllSpaces(user_input)
print "Result is: ",result
if __name__ == "__main__":
main()
| true |
f90911ff384b918a697fd987bf4e12b814bbc92c | jananee009/DataStructures_And_Algorithms | /Miscellaneous/Parentheticals.py | 1,984 | 4.125 | 4 | # Write a function that, given a sentence, , finds the position of an opening parenthesis and the corresponding closing parenthesis.
# Source: https://www.interviewcake.com/question/python/matching-parens?utm_source=weekly_email&__s=ibuidbvzaa2i67rfb2mc
# Approach: 1. Process the string character by character.
# We can solve the problem using a dictionary and a stack (list).
# 2. As you encounter a parentheses, check if it is opening or closing one:
# 3. If it is opening one, find its position in the string and store it as a key in the dictionary.
# Push the position of the last found open parentheses in to a stack.
# At any point in time, the position of the most recently found open parentheses can be obtained by popping the stack.
# 4. else if parentheses is a closing one:
# pop the stack. i.e. get the position of the open parentheses that was most recently found and for which the corresponding closing parentheses was not found.
# store the position of the closing parentheses as value for the key whose value is same as the popped value.
# this method uses a dictionary and a list to find the positions of opening and corresponding closing parentheses.
def findParentheses(inputString):
last_found_open_parentheses = [] # this will be used like a stack.
parentheses_dict = {}
for index, character in enumerate(inputString):
if character == "(":
parentheses_dict[index] = -1
last_found_open_parentheses.append(index)
elif character == ")":
if last_found_open_parentheses: # if last_found_open_parentheses is not empty
parentheses_dict[last_found_open_parentheses[-1]] = index
del last_found_open_parentheses[-1]
else:
print "String with invalid parentheses"
return
return parentheses_dict
def main():
sentence = "Sometimes (when I nest them (my parentheticals) too much (like this (and this))) they get confusing."
print findParentheses(sentence)
if __name__ == "__main__":
main()
| true |
89167fe59613bc1eba62d18d09deea19c0bad38f | jananee009/DataStructures_And_Algorithms | /Stacks_And_Queues/Stack.py | 1,046 | 4.25 | 4 | # Write a program to implement a stack (LIFO). Implement the operations : push, pop, peek.
class Stack:
def __init__(self):
self.stack = []
def isEmpty(self):
if(len(self.stack)==0):
return True
else:
return False
def push(self,element):
self.stack.append(element)
def pop(self):
if(len(self.stack)==0):
print "Empty!! Nothing to pop."
return
tmp = self.stack[len(self.stack)-1]
del self.stack[len(self.stack)-1]
return tmp
def peek(self):
if(len(self.stack)==0):
return "Empty stack."
return self.stack[len(self.stack)-1]
def getSize(self):
return len(self.stack)
def printStack(self):
print "printing elements:"
for i in range(len(self.stack)-1,-1,-1):
print self.stack[i]
return
def main():
myStack = Stack()
myStack.push(10)
myStack.push(20)
myStack.isEmpty()
myStack.getSize()
myStack.push(30)
myStack.peek()
myStack.pop()
myStack.peek()
myStack.pop()
myStack.pop()
myStack.pop()
myStack.isEmpty()
myStack.getSize()
if __name__ == "__main__":
main()
| true |
383821bb30931d9e849a4d0f14c9291eb5c799a8 | AndyFlower/PythonFullstackLearnNote | /projects/day10/02 函数的参数.py | 1,700 | 4.125 | 4 | # 形参角度
# 万能参数
def eat(a,b,c,d):
print('我请你吃:%s %s %s %s' %(a,b,c,d))
eat('西红柿','黄瓜','葡萄','黄桃')
# 急需一种形参,可以接受所有的实参
# 万能参数 *args 约定俗称 args
# * 函数定义时, *代表聚合 它将所有的位置参数聚合成一个元祖 赋值给args
def eat(*args):
print(args)
print('我请你吃:%s %s %s %s %s ' %args)
eat('西红柿','黄瓜','葡萄','黄桃','红提')
# 写一个函数 计算传入的所有的数字的和
def sumFunc(*args):
count = 0;
for i in args:
count = count +i
return count;
print(sumFunc(1,2,3,4,5))
# **kwargs
# 函数定义时,**将所有的关键字参数聚合到一个字典中 将这个字段赋值给kwargs
def func(**kwargs):
print(kwargs)
func(name='sa',age=18) #{'name': 'sa', 'age': 18}
# 形参角度的参数的顺序
def func(*args,a,b,sex='boy'):
print(a,b)
# func(1,2) #TypeError: func() missing 2 required keyword-only arguments: 'a' and 'b'
def func(a,b,*args,sex='boy'):
print(a,b)
print(args)
print(sex)
func(1,2,3,4,5,6,sex='girl')
## **kwargs
def func(a,b,*args,sex='boy',**kwargs):
print(a,b)
print(args)
print(sex)
print(kwargs)
func(1,2,3,4,5,6,sex='girl',name='s',age=18)
## 形参角度第四个参数仅限关键字参数 c 不能不传
def func(a,b,*args,sex= '男',c,**kwargs):
print(a,b)
print(sex)
print(args)
print(c)
print(kwargs)
func(1,2,3,4,5,6,7,sex='女',name='sa',age=18,c='666')
# 形参角度最终的顺序:位置参数,*args,默认参数,仅限关键字参数,**kwargs | false |
95c1d47ade4d105851b29eb1bbacf6231d188fbd | GuND0Wn151/Python_OOP | /13_MagicMethods_1.py | 1,670 | 4.4375 | 4 | #C0d3 n0=13
#made By GuND0Wn151
"""
there are some methods in python class
Magic methods in Python are the special methods which add "magic"
to your class. Magic methods are not
meant to be invoked directly by you, but the invocation happens
internally from the class on a certain action.
"""
"""
The below is example of overloading the arthematic methods like addition subtraction etc
whihc also returns a object of that class
"""
class Point:
x=0
y=0
def __init__(self,a,b):
self.x=a
self.y=b
def __add__(self,a):
return Point(self.x+a.x ,self.y+a.y)
def __sub__(self,a):
return Point(self.x-a.x ,self.y-a.y)
def __mul__(self,a):
return Point(self.x*a.x ,self.y*a.y)
def __floordiv__(self,a):
return Point(self.x/a.x ,self.y/a.y)
def displayDetails(self):
print("X:",self.x,', Y:',self.y)
a=Point(2,3)
b=Point(4,6)
# here + will invoke the overloaded __add__ method in the class and return a object of type Point
f=a+b
# here - will invoke the overloaded __sub__ method in the class and return a object of type Point
g=a-b
# here * will invoke the overloaded __mul__ method in the class and return a object of type Point
h=a*b
# here // will invoke the overloaded __floordiv__ method in the class and return a object of type Point
i=a//b
"""
the return type of the overloaded arthematic options are Point
so we acces them with the method displayDetails
"""
print(type(f))
f.displayDetails()
print(type(g))
g.displayDetails()
print(type(h))
h.displayDetails()
print(type(i))
i.displayDetails()
| true |
53f18b79d98cfc5fb94bc561d54248cb33c62165 | GuND0Wn151/Python_OOP | /10_Getter.py | 609 | 4.28125 | 4 | #C0d3 n0=10
#made By GuND0Wn151
'''
The getattr() method retu
the value of the named attribute of an object.
If not found, it returns the default value provided to the function.
'''
class person:
legs=2
hands=2
hair_color='black'
def __init__(self,a):
self.name=a
person1=person("kevin")
#usual syntax of accesing elements
print(person1.legs)
print(person1.hands)
print(person1.hair_color)
#using getter method
print(getattr(person1,"legs"))
print(getattr(person1,"hands","legs"))
#if used for a unknown attributes throws AttributeError
print(getattr(person1,"age")) | true |
28719c5fed80810c43c3376758b82f851f56a05b | DAVIDMIGWI/python | /lesson 3b.py | 399 | 4.15625 | 4 |
a = 40
b = 50
c = 500
if a > b:
print("A is greater than B")
if a > c:
print("A is also greater than C")
else:
print("A is not greater than C")
if c > b:
print("C is the largest")
else:
print("A is the largest")
else:
if b > c:
print("B is greater")
else:
print("its C")
| true |
b84c082c91b1a246fc6160ac1649c39b9a2c97eb | DAVIDMIGWI/python | /lesson 5d. lists in tuples.py | 394 | 4.46875 | 4 |
# applying conditional statements in decision making in list/tuples
supermarkets = ["naivas", "Carrefour", "turkeys", "nakumatt","quickmat"]
for supermarket in supermarkets:
print(supermarket)
if supermarket == "quickmat":
print("ill shop there today")
elif supermarket == "naivas":
print("i will shop over the weekend")
else:
print("No shopping")
| false |
369d0f3e749c5419d5e40d9e41f3db3a43c946b7 | jmmiddour/Old-CS-TK | /CS00_Intro_to_Python_1/src/05_lists.py | 1,707 | 4.625 | 5 | # For the exercise,
# look up the methods and functions that are available for use with Python lists.
# An array can only have one data type, list can have multiple data types.
# If you want to add to an array you have to create a new array twice the size of
# the one you have, taking up more space.
# You need to use numpy to use arrays or it will just be a list in python.
x = [1, 2, 3]
y = [8, 9, 10]
# For the following, DO NOT USE AN ASSIGNMENT (=).
# ## Change x so that it is [1, 2, 3, 4] ## #
x.append(4)
print(x)
# ## Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10] ## #
x.extend(y) # Best practice
# print(x + y) # Throws error with `pop` function below
# x = x + y # |
# print(x) # --> These 2 lines are another way to do the same
# ## Change x so that it is [1, 2, 3, 4, 9, 10] ## #
x.pop(4) # pop(index #) <-- Best practices if you know the index location
# x.pop(-3) # Counting backwards from the end of the index
# x.pop(x.index(8)) # gets the index if unknown, then "pops" it off
# x.remove(8) # computationally more expense but works if index unknown
print(x)
# ## Change x so that it is [1, 2, 3, 4, 9, 99, 10] ## #
x.insert(5, 99) # insert(<index place where to insert>, <value>)
print(x)
# ## Print the length of list x ## #
print(len(x))
# ## Print all the values in x multiplied by 1000 ## #
# Using a for loop will print each number individually
# for num in x:
# print(num * 1000)
# Same thing as above but in List Comprehension which will
# print it as a list - similar to .map in JavaScript
x = [num * 1000 for num in x]
print(x)
# Can also do it as a list of strings instead of integers:
# x = [str(num * 1000) for num in x]
# print (x)
| true |
2589aa703538ead00de18c0b828a84f27aeb16c1 | jmmiddour/Old-CS-TK | /CS00_Intro_to_Python_1/src/14_cal.py | 2,934 | 4.59375 | 5 | """
The Python standard library's 'calendar' module allows you to
render a calendar to your terminal.
https://docs.python.org/3.6/library/calendar.html
Write a program that accepts user input of the form
`14_cal.py [month] [year]`
and does the following:
- If the user doesn't specify any input, your program should
print the calendar for the current month. The 'datetime'
module may be helpful for this.
- If the user specifies one argument, assume they passed in a
month and render the calendar for that month of the current year.
- If the user specifies two arguments, assume they passed in
both the month and the year. Render the calendar for that
month and year.
- Otherwise, print a usage statement to the terminal indicating
the format that your program expects arguments to be given.
Then exit the program.
Note: the user should provide argument input (in the initial call to run the file) and not
prompted input. Also, the brackets around year are to denote that the argument is
optional, as this is a common convention in documentation.
This would mean that from the command line you would call `python3 14_cal.py 4 2015` to
print out a calendar for April in 2015, but if you omit either the year or both values,
it should use today’s date to get the month and year.
"""
# ## My Code ## #
import sys
import calendar as cal
from datetime import datetime as dt
# Create variable to hold today's date
today = dt.today()
# Get the user's input from the command line and check edge cases
# If user enters all required inputs in the command line
if len(sys.argv) == 3:
# Convert user input to ints and return the calender month and year
print(cal.TextCalendar().formatmonth(int(sys.argv[2]), int(sys.argv[1])))
sys.exit(0) # Exits the program
# If the user only enters one argument, such as month but not year or vise versa
elif len(sys.argv) == 2:
# Return current in place of missing value from user input
if int(sys.argv[1]) in range(12):
print(cal.TextCalendar().formatmonth(today.year, int(sys.argv[1])))
sys.exit(0) # Exits the program
elif int(sys.argv[1]) in range(1000, 2021):
print('Year', int(sys.argv[1]))
print(cal.TextCalendar().formatmonth(int(sys.argv[1]), today.month))
sys.exit(0) # Exits the program
# If the user does not enter and arguments in the command line
if len(sys.argv) == 1:
# Return current month and year
print(cal.TextCalendar().formatmonth(today.year, today.month))
sys.exit(0) # Exits the program
# If user enters an invalid format
else:
print('Usage: 14_cal.py [month number] [year]') # Return usage statement
sys.exit(1) # Exit the program
# # ## Ava's Code ## #
# import sys
# import calendar
# from datetime import datetime
#
#
#
#
# # ## Fatima's code: ## #
# # import sys
# # import calendar
# # from datetime import datetime
# #
# # date = datetime.now() | true |
d86a00d4050862b4e14da77ed994e90595b5e40a | Paahn/practice_python | /reverse_word_order.py | 265 | 4.34375 | 4 | # Write a program that asks the user
# for a long string containing multiple words.
# Print back to the user the same string, except with the words in backwards order.
a = input("Gimme a string containing multiple words:\n")
b = a.split(' ')
print(b[::-1])
| true |
7588d9c2400c665eb0be8ca319c3dc17f03ec568 | Paahn/practice_python | /guessing_game.py | 997 | 4.375 | 4 | # Generate a random number between 1 and 9 (including 1 and 9).
# Ask the user to guess the number, then tell them whether they guessed too low,
# too high, or exactly right.
# Keep the game going until the user types “exit”
# Keep track of how many guesses the user has taken, and when the game ends, print this out.
from random import randint
a = randint(1, 9)
ans = int(input("Guess a number between 1 and 9: "))
guesses = 0
while True:
try:
if ans == a and guesses == 0:
print("Wow! You got it right the first time!")
break
elif ans < a:
guesses += 1
ans = int(input("Too low. Guess again."))
elif ans > a:
guesses += 1
ans = int(input("Too high. Guess again."))
else:
guesses += 1
print("You guessed right! It only took you {} times.".format(guesses))
break
except ValueError:
print("Try again")
| true |
47717a3918ae9d4522508d3125763b31c3298a4d | elenaozdemir/Python_bootcamp | /Week 1/Day Two/Practicing with lists & functions.py | 747 | 4.53125 | 5 | # practicing with lists and functions
# EXAMPLE: Define a function that returns a list of even numbers
# between A and B (inclusive)
def find_events(A,B):
# make an empty list to return to something
evens = []
for nums in range (A,B+1): #inclusive
if (nums % 2 == 0):
evens.append(nums)
return evens
print(find_events(2,20))
# TODO: Define a function that returns a list of numbers between A and B (inclusive) that are multiples of 3
def list_num(A,B):
numlist = []
for numbers in range (A,B+1):
if (numbers % 2 == 0) and (numbers % 3 == 0): # or you can just do (numbers % 6 == 0), even multiples of 2 and 3
numlist.append(numbers)
return numlist
print(list_num(3,20))
| true |
185226e028f27439fa159136cfef3be1d36bad86 | darthols/mooc_Python-3 | /w1/turtle_fractal.py | 825 | 4.25 | 4 | #!/usr/bin/env python3
# coding: utf8
"""
Fractale
"""
import turtle
def left_triangle(length):
for i in range(3):
turtle.forward(length)
turtle.left(120)
def fractal_side(length, fractal):
if fractal == 0:
turtle.forward(length)
else:
length3 = length / 3.
fractal_side(length3, fractal-1)
turtle.right(60)
fractal_side(length3, fractal-1)
turtle.left(120)
fractal_side(length3, fractal-1)
turtle.right(60)
fractal_side(length3, fractal-1)
def fractal_triangle(length, fractal):
for i in range(3):
fractal_side(length,fractal)
turtle.left(120)
if __name__ == "__main__":
turtle.reset()
turtle.speed('fastest')
fractal_triangle(300, 3)
left_triangle(300)
turtle.exitonclick()
| false |
4c5a3b9f23c9910631860938ce17e86c87a31939 | SBenkhelfaSparta/eng89_python_basics | /string_casting_concatenation.py | 1,567 | 4.34375 | 4 | # using and managing strings
# strings casting
# string concatenation
# Casting methods
# Single and double quotes
single_quotes = 'These are single quotes and working perfectly fine!'
double_quotes = "These are double quotes also working fine"
# print(single_quotes)
# print(double_quotes)
# concatenation
# first_name = "James"
# last_name = "Bond"
# age = 22
# print(type(age))
# print(type(str(age)))
# create a variable called ge with int val and display age on the same line as james bond
# print(first_name + ' ' + last_name + ' ' + str(age))
# 01234567891011
# greetings = "Hello World"
#-1
# in python indexing start with 0
# print(greetings)
# to confrirm the length of the string as a method is len()
# print(len(greetings))
# print(greetings[0:5]) # slicing# the string from index 0 - 4 upto but not including 5
# print(greetings[-1]) # slicing string from the last index position
# print(greetings[6:])
# print(greetings[-5:])
# white_spaces = "Lots of white spaces "
# we have strip() tgat removes all the whire spaces
#print(str(len(white_spaces)) + 'including white spaces')
# some more built in methods that we can use with strings
example_text = " here's some text with lots of text"
print(example_text.count('text')) #count() method count the word in string
print(example_text.lower()) # brings everything to lower case
print(example_text.upper()) #brings everything to upper case
print(example_text.capitalize()) #capatilsises the first letter
print(example_text.replace('with', ',')) | true |
a8f4d513d0b552b70b9baa5767a2ddad07bb0629 | marnyansky/codewars-puzzles-python | /stepik-python-advanced-2021/chapter04_03_unit406261_step10_Pascals_triangle.py | 2,254 | 4.28125 | 4 | """
https://stepik.org/lesson/416753/step/10?thread=solutions&unit=406261
Треугольник Паскаля — бесконечная таблица биномиальных коэффициентов, имеющая треугольную форму.
В этом треугольнике на вершине и по бокам стоят единицы. Каждое число равно сумме двух расположенных над ним чисел.
0: 1
1: 1 1
2: 1 2 1
3: 1 3 3 1
4: 1 4 6 4 1
.....
На вход программе подается число n. Напишите программу, которая возвращает указанную строку
треугольника Паскаля в виде списка (нумерация строк начинается с нуля).
"""
from timeit import default_timer as timer
from exec_time import display_function_execution_time as elapsed
def pascals_triangle(key_num=4096):
if not key_num: # 0
return [1]
prev = [1, 1]
for i in range(key_num):
"""
build new temporary list
fill temporary list (thus getting a result)
"remember" list to store data for building a new list
"""
curr = [1] + [0] * i + [1]
for j in range(1, i + 1):
curr[j] = prev[j - 1] + prev[j]
prev = curr
return curr
def pascals_triangle_alt1(key_num=4096):
lst = [1]
for i in range(key_num):
for j in range(len(lst) - 1):
lst[j] = lst[j] + lst[j + 1]
lst.insert(0, 1)
return lst
def pascals_triangle_alt2(key_num=4096):
lst = [1]
for _ in range(key_num):
lst = [a + b for a, b in zip([*lst, 0], [0, *lst])]
return lst
# algorithms' efficiency measurements
if __name__ == '__main__':
time_s = timer()
print(pascals_triangle())
time_f = timer()
elapsed(time_s, time_f, function_name="pascals_triangle()")
time_s = timer()
print(pascals_triangle())
time_f = timer()
elapsed(time_s, time_f, function_name="pascals_triangle_alt1()")
time_s = timer()
print(pascals_triangle())
time_f = timer()
elapsed(time_s, time_f, function_name="pascals_triangle_alt2()")
| false |
95a2ee3b58d7fdf3e0bcc499b37b7bfa59a286b6 | Ms-Noxolo/Predict-Team-7 | /EskomFunctions/function3.py | 591 | 4.375 | 4 | def date_parser(dates):
""" This function returns a list of strings where each element in the returned list contains only the date
Example
-------
Input: ['2019-11-29 12:50:54',
'2019-11-29 12:46:53',
'2019-11-29 12:46:10']
Output: ['2019-11-29', '2019-11-29', '2019-11-29']
"""
c = [] # initialize an empty list
for i in dates:
i = i[:10] # the date from the datetime string is only made up of 9 characters
c.append(i) # Adds items to the list c
return c #return list c
| true |
813a5288fc26121aee0081f4b9ab131a2190e321 | aprabhu84/PythonBasics | /Methods and Functions/Level 1/03_Makes_Twenty.py | 473 | 4.15625 | 4 | #MAKES TWENTY:
# -- Given two integers,
# -- return True if the sum of the integers is 20
# -- or if one of the integers is 20.
# -- If not, return False
#makes_twenty(20,10) --> True
#makes_twenty(12,8) --> True
#makes_twenty(2,3) --> False
def makes_twenty(number1, number2):
int_num1 = int(number1)
int_num2 = int(number2)
if (int_num1 == 20) or (int_num2 == 20) or (int_num1+int_num2 == 20):
return True
else:
return False
| true |
f751e02345f05a8f287ff20671542153c6e88cac | aprabhu84/PythonBasics | /Methods and Functions/Level 2/02_Paper_Doll.py | 394 | 4.15625 | 4 | # PAPER DOLL: Given a string, return a string where for every character in the original there are three characters
# paper_doll('Hello') --> 'HHHeeellllllooo'
# paper_doll('Mississippi') --> 'MMMiiissssssiiippppppiii'
def paper_doll(someString):
resultString = ""
for pos in range(0,len(someString)):
resultString = resultString + someString[pos]*3
return resultString
| true |
4bb645c2831bb073979233c99e028cb59ff39c39 | oratusxd/Python-Curso_em_Video | /Mundo_1/Aula7/desafio8.py | 354 | 4.125 | 4 | '''
Escreva um programa que leia valor em metros e exiba convetido em centímetros
e em milímetros
'''
metro = float (input('Coloque o valor em metros: '))
km = metro/1000
hm = metro/100
dam = metro/10
dm = metro*10
cm = metro*100
mm = metro*1000
print(f'{metro} metros medirá:\n{km}km, {hm} hm , {dam} dam\n{dm} dm, {cm} cm e {mm} mm')
| false |
46be0a96d81cb8c48dc94ab9a2883c6ffdbaddd8 | Aleksandraboy/basics | /nesting.py | 2,894 | 4.5 | 4 | # 03/20/21
# 1. A List of Lists
# 2. A List of Dictionary
# 3. A List in a Dictionary
# 4. A Dictionary in a Dictionary
print('*** 1. A List of Lists***')
countries = ['usa', 'russia', 'spain', 'france']
cities = ['new york', 'moscow', 'barcelona', 'paris']
companies = ['level up', 'abc company', 'ola company']
customers = [countries, cities, companies]
print(customers)
print(customers[0]) # printing all countries. since countries has index '0'
print(customers[0][0]) # printing 'usa', since countries index [0] and index of 'usa' also [0]
print(customers[1][2]) # printing the 'Barcelona'
multi_dim_nums = [
[3, 9, 0],
[2, 7, 10],
[0, 1, 0]
] # multidimensional (многомерный)
print(multi_dim_nums[1][1]) # printing the number '7'
print("***Nested Loops: Looping through multidimensional list(array)***")
for column in customers: #
print(column)
for value in column:
print(value)
print('******')
# for customer in customers[0][1]:
# print(customer, end='\t')
print(customers[0][1].upper())
print('***** 2. List of dictionaries')
user_0 = {'name': 'jonh', 'age' : 25, 'city' : 'brooklyn'}
user_1 = {'name': 'jane', 'age' : 20, 'city' : 'paris'}
user_2 = {'name': 'mark', 'age' : 35, 'city' : 'tokyo'}
users = [user_1, user_0, user_2]
print(users[0])
print(users[0]['name'])
print(users[0]['age'])
print(users[0]['city'])
print(users[2]['name'])
print("******** Looping****")
for user in users:
print(user['name'], end='||')
print(user['age'], end='||' )
print(user['city'])
print('***** 3. A List in a Dictionary ***** ')
countries = ['usa', 'russia', 'spain', 'france']
cities = ['new york', 'moscow', 'barcelona', 'paris']
companies = ['level up', 'abc company', 'ola company']
customers = {
"countries" : ['usa', 'russia', 'spain', 'france'],
"cities" : ['new york', 'moscow', 'barcelona', 'paris'],
"companies" : ['level up', 'abc company', 'ola company']
}
print(customers['cities'])
print(customers['cities'][1]) # second element from cities
print('***** 4. A Dictionary in a Dictionary *****')
user_0 = {'name': 'jonh', 'age' : 25, 'city' : 'brooklyn'}
user_1 = {'name': 'jane', 'age' : 20, 'city' : 'paris'}
user_2 = {'name': 'mark', 'age' : 35, 'city' : 'tokyo'}
users = {
'user_0' : {'name': 'jonh', 'age' : 25, 'city' : 'brooklyn'},
'user_1' : {'name': 'jane', 'age' : 20, 'city' : 'paris'},
'user_2' : {'name': 'mark', 'age' : 35, 'city' : 'tokyo'}
}
print(users)
print(users['user_0'])
print(users['user_0']['name'])
print("***keys***")
for user in users.keys():
print(user)
print(users[user])
print("**items***")
for username, details in users.items():
print(username)
print(details['name'])
print("***items(key, value)***")
for username, details in users.items():
print(username)
for key, value in details.items():
print(key)
print(value)
| true |
0f0d4aca3a404655fe2e0e226e831b65d8d18307 | XDA-7/boids | /src/vector.py | 1,912 | 4.25 | 4 | """Vector module"""
from math import sqrt, sin, cos
class Vector:
"""2D Vector with operations useful to the program"""
def __init__(self, x: float, y: float):
self.x_val = x
self.y_val = y
def __add__(self, other: 'Vector'):
return Vector(self.x_val + other.x_val, self.y_val + other.y_val)
def __sub__(self, other: 'Vector'):
return Vector(self.x_val - other.x_val, self.y_val - other.y_val)
def __mul__(self, other: float):
return Vector(self.x_val * other, self.y_val * other)
def negative(self) -> 'Vector':
return Vector(-self.x_val, -self.y_val)
def magnitude(self) -> float:
return sqrt(self.x_val ** 2 + self.y_val ** 2)
def normalized(self) -> 'Vector':
if self.x_val == 0 and self.y_val == 0:
return Vector(0, 0)
magnitude = self.magnitude()
return Vector(self.x_val / magnitude, self.y_val / magnitude)
def rotate(self, rotation: float) -> 'Vector':
"""Rotate the vector counter-clockwise by the rotation specified in radians"""
x_val = self.x_val * cos(rotation) - self.y_val * sin(rotation)
y_val = self.x_val * sin(rotation) + self.y_val * cos(rotation)
return Vector(x_val, y_val)
def rotation(self) -> float:
"""Calculates the cosine of the angle of the vector from (0, 1),
a vector of (0, 0) will return 0"""
#Method: Simplification of the dot product where vector b = (0, 1) becomes
if self.x_val == 0 and self.y_val == 0:
return 0
return self.y_val / self.magnitude()
def rotation_normalized(self) -> float:
"""Calculates the cosine as above and then normalises it from (1, -1) to (0, 1)"""
cos_val = self.rotation()
return (-cos_val + 1) / 2
def str(self) -> str:
return '(' + str(self.x_val) + ', ' + str(self.y_val) + ')'
| false |
20127e1855c3307e7b25812eccb46818d7db4609 | JoseVteEsteve/Lists | /LI_03.py | 289 | 4.1875 | 4 | #given a list of numbers, find and print all the elements that are greater than the previous element.
list = [1,3,7,9,2,4,11,10,8,5,14,16]
n = len(list)
max = 0
for i in range(n):
if list[i] > list[i - 1]:
print(str(list[i]) + " is greater than " + str(list[i - 1]))
| true |
340ae067444d465b6f62d6e512544c76e494130a | sagardspeed2/PythonMiniprojects | /pattern/32123/pattern.py | 427 | 4.15625 | 4 | num = int(input("enter numbers of rows"))
# for i in range(1,num+1):
# for j in range (1,num-i+1):
# print(end=" ")
# for j in range (i,0,-1):
# print(j,end="")
# for j in range (2,i+1):
# print(j,end="")
# print()
for i in range(1, num+1):
for j in range(1, num-i+1):
print(end=" ")
for j in range(i,0,-1):
print(j, end="")
for j in range(2,i+1):
print(j, end="")
print() | false |
4b7f4c2120a385d0387838a7aaf034044be7a790 | DUDA18/ProgISD20202-1 | /Maria_Eduarda/aula 3/aula3.py | 826 | 4.25 | 4 |
import math #Importando Math
print("Python")
#Declarando variaveis
varString="maria"
p,l=9,4
escolha=True
variavel=list()
#printando type e variavel na tela
print(varString)
print(type(variavel))
print(type(varString))
print(type(p))
print(str(p) + "top" + str(escolha))
#Captando informações e usando a biblioteca math
x=input('entre com a matriz')
print(x)
k=25
print (math.sqrt(k))
#Operadores
res=5+5
print(res)
print(1+1)
print(1-1)
print(1*1)
print(1//1)
print(1**1)
print(1%1)
p+=1
p-=1
p*=1
p/=1
p%=1
#logico
print(p!=l)
print(p==l)
print(p<=l)
print(p>=l)
print(p>l)
print(p<l)
logic= int(input('tu se acha inteligente'))
log= int(input('tu se acha inteligente'))
if (not logic and not log):
print("debug breakpoint e f10")
elif (logic or log):
print("pega else if")
else:
print("pega else if")
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.