blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
b299c50e3fa26dbf0c1f7dab579813670ec6dea1 | moonlimb/tree_problems | /isBST.py | 383 | 4.1875 | 4 | from Node import Node
def is_BST(node):
"""returns True if a given node is a root node of a binary search tree"""
if node.is_leaf():
return True
else:
# Node class contains comparison methods
if (node.left and node.left >= node) or (node.right and node >= node.right):
return False
return isBST(node.left) and isBST(node.right)
| true |
8db19628f571ab9cb2e0babcb961974c8baaf99d | imsreyas7/DAA-lab | /Recursion/expo3.py | 263 | 4.21875 | 4 | def expo3(x,n):
if n=0:
return 1
else:
if n%2 ==0:
return expo3(x,n/2)*expo(x,n/2)
else:
return x*expo(x,n-1)
x=int(input("Enter a number whose power has to be found "))
n=int(input("Enter the power "))
print("The result is ",expo3(x,n)) | true |
ad02d70583ed30bea2710fbc61df4a00680dfdc0 | Aksharikc12/python-ws | /M_2/Q_2.py | 1,407 | 4.53125 | 5 | '''2. Write a program to accept a two-dimensional array containing integers as the parameter and determine the following from the elements of the array:
a. element with minimum value in the entire array
b. element with maximum value in the entire array
c. the elements with minimum and maximum values in each column
d. the elements with minimum and maximum values in each row
Example:
Input:
[[0 1 2 3]
[3 4 5 5]
[6 7 8 8]
[9 0 1 9]]
Output:
minimum value element in the array: 0
maximum value element in the array: 9
elements with minimum values column-wise: [0 0 1 3]
elements with maximum values column-wise: [9 7 8 9]
elements with minimum values row-wise: [0 3 6 0]
elements with maximum values row-wise: [3 5 8 9]
'''
lst = [[0,1, 2, 3], [3, 4, 5, 5], [6, 7, 8, 8], [9, 0, 1, 9]]
lst_1=[]
for num in lst:
lst_1.extend(num)
print(f"minimum value element in the array: {min(lst_1)}")
print(f"maximum value element in the array: {max(lst_1)}")
min_col=list(min(map(lambda x:x[i],lst)) for i in range(4))
print(f"elements with minimum values column-wise: {min_col}")
max_col=list(max(map(lambda x:x[i],lst)) for i in range(4))
print(f"elements with minimum values column-wise: {max_col}")
min_row=list(map(lambda x:min(x),lst))
print(f"elements with minimum values row-wise:{min_row}")
max_row=list(map(lambda x:max(x),lst))
print(f"elements with minimum values row-wise:{max_row}")
| true |
211f7d8c6027e43fa5933eb581ecee3a8daf0edb | Aksharikc12/python-ws | /M_1/Q_1.py | 413 | 4.25 | 4 | '''1. Write a program to accept a number and determine whether it is a prime number or not.'''
import math
num=int(input("enter the number"))
is_prime=True
if num<2:
is_prime=False
else:
for i in range(2,int(math.sqrt(num)) + 1):
if num % i == 0:
is_prime=False
break
if is_prime:
print(f"{num} is prime number")
else:
print(f"{num} is not a prime number")
| true |
50959738f8045b5b3d0beea7c9992cbbe820dc82 | murphy1/python_problems | /chapter6_string.py | 1,577 | 4.1875 | 4 | # file for Chapter 6 of slither into python
import re
# Question 1, user input will state how many decimal places 'e' should be formatted to.
"""
e = 2.7182818284590452353602874713527
format_num = input("Enter Format Number:")
form = "{:."+format_num+"f}"
print(form.format(e))
"""
# Question 2, User will input 2 numbers and a string. The string will be sliced depending on the numbers
# If the numbers are not in the range, the message will be displayed: Cannot slice using those indices
"""
string = input("Enter a string to slice:")
num1 = int(input("First num:"))
num2 = int(input("Second num:"))
if num1 > len(string) or num2 > len(string):
print("Cannot slice using those indices!")
else:
sliced = string[num1:num2]
print(sliced)
"""
# Question 3, Will grade your password depending on how strong it is. Levels are 1 -> 4 depending on if it has
# digits, lowercase letters, uppercase letters or special characters
password = input("Please enter your password:")
cap_check = re.findall('[A-Z]+', password)
lowcase_check = re.findall('[a-z]+', password)
digit_check = re.findall('[0-9]+', password)
special_char_check = re.findall('[$,@.#<>%*!]+', password)
strength = 0
if len(cap_check) > 0:
strength += 1
else:
pass
if len(lowcase_check) > 0:
strength += 1
else:
pass
if len(digit_check) > 0:
strength += 1
else:
pass
if len(special_char_check) > 0:
strength += 1
else:
pass
if strength >= 3:
print("Strength: %d, Valid Password" % (strength))
else:
print("Strength: %d, Invalid Password" % (strength))
| true |
da1190857891ba038938c4e7bba4cd26dbcc21ac | zabdulmanea/movie_trailer_website | /media.py | 555 | 4.125 | 4 | class Movie():
"""
This class provides the structure to store movie information
Attributes:
title (str): The movie title
trailer_youtube_url (str): A link to the movie trailer on youtube
poster_image_url (str): A link to the movie poster
"""
# constructor of Movie class, called when an instance of class is created
def __init__(self, movie_title, movie_poster, movie_trailer):
self.title = movie_title
self.trailer_youtube_url = movie_trailer
self.poster_image_url = movie_poster
| true |
b73b09b2466c362a584cada47b9ed0ba2c249d9e | Nitin-Diwakar/100-days-of-code | /day25/main.py | 1,431 | 4.53125 | 5 | # Write a Python GUI program
# using tkinter module
# to input Miles in Entry widget
# that is in text box and convert
# to Kilometers Km on button click.
import tkinter as tk
def main():
window= tk.Tk()
window.title("Miles to Kilometers Converter")
window.geometry("375x200")
# create a label with text Enter Miles
label1 = tk.Label(window, text="Enter Miles:")
# create a label with text Kilometers:
label2 = tk.Label(window, text="Kilometers:")
# place label1 in window at position x,y
label1.place(x=50,y=30)
# create an Entry widget (text box)
textbox1 = tk.Entry(window, width=12)
# place textbox1 in window at position x,y
textbox1.place(x=200,y=35)
# place label2 in window at position x,y
label2.place(x=50,y=100)
# create a label3 with empty text:
label3 = tk.Label(window, text=" ")
# place label3 in window at position x,y
label3.place(x=180,y=100)
def btn1_click():
kilometers = round(float(textbox1.get()) * 1.60934,5)
label3.configure(text = str(kilometers)+ ' Kilometers')
# create a button with text Button 1
btn1 = tk.Button(window, text="Click Me To Convert", command=btn1_click)
# place this button in window at position x,y
btn1.place(x=90,y=150)
window.mainloop()
main()
| true |
3d6cab692c8588bf46a2f4f4b96c441141472660 | Endie990/pythonweek-assigments | /Assignment_Guessing_game.py | 534 | 4.125 | 4 | #ass 2- guessing game
import random
guessnum=random.randint(1,9)
num= int(input('Guess a number between 1 and 9: '))
while guessnum!='num':
if num<guessnum:
print('Guess is too low,Try again')
num= int(input('Guess a number between 1 and 9: '))
elif num>guessnum:
print('Guess is too high,Try again')
num= int(input('Guess a number between 1 and 9: '))
else:
print('****Congratulations!!Well Guessed****!!!!!!!!!!')
break
| true |
5de52fcb51cf062e250533875d749f7fcd0c5a1e | AdityaJsr/Bl_week2 | /week 2/dictP/createDict.py | 587 | 4.125 | 4 | """
Title - Write a Python program to create a dictionary from a string.
Note: Track the count of the letters from the string.
Sample string : 'w3resource'
Expected output: {'3': 1, 's': 1, 'r': 2, 'u': 1, 'w': 1, 'c': 1, 'e': 2, 'o': 1}
Access individual element through indexes.
Author name - Aditya Kumar
Ceation time - 04 March 2021
Modified time - 04 March 2021
"""
from collections import defaultdict, Counter
str1 = 'thisIsaSampleString'
d = {}
for letter in str1:
d[letter] = d.get(letter, 0) + 1
print(d)
| true |
423df06c344e381a8d09156226b10ef17f37bebd | thatguysilver/pswaads | /listing.py | 966 | 4.21875 | 4 | '''
Trying to learn about the different list concatenation methods in py
and examine their efficiency.
'''
import time
def iterate_concat():
start = time.time()
new_list = []
for i in range(1000):
new_list += [i]
end = time.time()
return f'Regular iteration took {end - start} seconds.'
def append_concat():
start = time.time()
new_list = []
for i in range(1000):
new_list.append(i)
end = time.time()
return f'Append method took {end - start} seconds.'
def list_comp_concat():
start = time.time()
new_list = [i for i in range(1000)]
end = time.time()
return f'Using a list comprehension took {end - start} seconds.'
def make_list():
start = time.time()
new_list = list(range(1000))
end = time.time()
return f'Creating a list from a range took {end - start} seconds.'
print(iterate_concat())
print(append_concat())
print(list_comp_concat())
print(make_list())
| true |
304769d3a15878e844f87a8fa360e8a7ee5a5c97 | dan480/caesars-cipher | /main.py | 1,364 | 4.3125 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import argparse
from src.select_alphabet import select_alphabet
from src.decoding import decoding_func
from src.encoding import encoding_func
"""
The main file that runs the program logic.
The function of creating a command line parser is implemented here.
In the main () function, the received data is processed.
"""
def create_parser():
# The function of creating a command line parser.
parser = argparse.ArgumentParser(description="Process the string.")
parser.add_argument("action", type=str, help="Choosing a function")
parser.add_argument(
"string",
action="extend",
nargs="+",
type=str,
help="Get a string for processing",
)
return parser
def main():
# A function that contains the logic for processing input data.
parser = create_parser()
args = parser.parse_args()
letter = args.string[0]
param = vars(args)
action = param.get("action")
string = param.get("string")
string = " ".join(string)
alphabet = select_alphabet(letter[1])
if action in ["e", "encoding"]:
print(encoding_func(string, alphabet, -2))
elif action in ["d", "decoding"]:
print(decoding_func(string, alphabet, -2))
else:
print(f"{action} function does not exist")
if __name__ == "__main__":
main()
| true |
c9a18125f74caacb4b470d986bf7e09fe119b180 | Tchomasek/Codewars | /Codewars/6 kyu/Sort the odd.py | 663 | 4.3125 | 4 | def sort_array(source_array):
result = list(source_array)
even = {}
for index,num in enumerate(source_array):
if num % 2 == 0:
even[index] = num
result.remove(num)
result.sort()
for index,num in even.items():
result.insert(index, num)
return result
print(sort_array([0, 1, 2, 3, 4, 9, 8, 7, 6, 5]))
"""You have an array of numbers.
Your task is to sort ascending odd numbers but even numbers must be on their places.
Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it.
Example
sort_array([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4]"""
| true |
0adb0d78954c719dadafd33dde275e43387b70bc | Machin-Learning/Exercises | /Section-1/Data Types/set.py | 1,475 | 4.40625 | 4 | # #Set
# 1. Set in python is immuttable/non changeable and does not show duplicate
# 2. Set are collection of element seprated by comma inside {,}
# 3. Set can't be indexed or slice
# 4. Set can't add/concat or scale/multiply
# 5. we can use set to store multiple items in one variable
# 6. set are itrator
s = {1,2,3,4}
print(s)
#set are immuttable
# s[0]= 5 #TypeError: 'set' object does not support item assignment
# print(s)
#TypeError: 'set' object is not subscriptable
#Indexing :left to right [0][1][2][3][.][n]
# right to left [-1][-2][-3][-.][-n]
# print(s[0]) #TypeError: 'set' object is not subscriptable
# print(s[0:3])
s1 = {1,2,5,6}
# Operation on set
# print(s+s1) #TypeError: unsupported operand type(s) for +: 'set' and 'set'
# print(s*s1) #TypeError: unsupported operand type(s) for *: 'set' and 'set'
print(s.intersection(s1)) #--->{1, 2}
print(s.difference(s1)) #--->{3, 4}
print(s1.difference(s)) #--->{5, 6}
print(s.union(s1)) #--->{1, 2, 3, 4, 5, 6}
print(s.pop())
print(s)
print(s.pop())
print(s)
print(s.pop())
print(s)
print(s1)
print(s1.remove(5))
print(s1)
print()
print(s1.discard(2))
print(s1)
print()
print(s1.symmetric_difference(s))
s2 = {1,2,1,5,4,4,6,8,7,8}
print(s2) | true |
f6b584f4a4315fc01bba5463bca09b968f9f2d76 | Machin-Learning/Exercises | /Section-1/Data Types/variables.py | 1,191 | 4.125 | 4 | # Variables in python
# var = 5
# print(var)
# var = "Muzmmil pathan"
# print(var)
# Data Types
# 1. int()
# 2. str()
# 3. float()
# 4. list()
# 5. tuple()
# 6. set()
# 7. dict()
num = 4 #integers are a number "without point / non fractional / Decimal from 1-9 only"
print(type(num)) # type() is a inbuilt function use to check the type/class of the object
print()
s = "Python is Easy to learn" # s is string/charectors # In python no charechter data type. # Remember to right in single or dubble qouts #
print(type(s))
print()
f = 3.14 # f is float due to fraction /point after the number
print(type(f))
print()
l = [1,2,3,4,5,6] # l is list due to it's [] .value written inside the bracket is list
print(type(l))
print()
t = (1,2,3,4,5,6) #t is tuple due to it's () we can also write tuple by seprating value using comma as bellow
_t = 1,2,3,4,5,6
print(type(t))
print(type(_t))
print()
S = {1,2,3,4,5} # S is set due to value seprated by comma and written inside the curly bracket
print(type(S))
print()
d = {"username":"Muzmmil","password":9145686396} # d is Dictionary due to its written inside {} and have value pair
print(type(d))
#etc | true |
d9e48b09f2c3a902b3009279f89263b5eee7087e | yashbagla321/Mad | /computeDistancePointToSegment.py | 1,014 | 4.15625 | 4 | print 'Enter x and y coordinates of the point'
x0 = float(input())
y0 = float(input())
print 'Enter x and y coordinates of point1 then point2 of the line'
x1 = float(input())
y1 = float(input())
x2 = float(input())
y2 = float(input())
import math
def computeDistancePointToSegment(x1,y1, x2,y2, x3,y3): # x3,y3 is the point
px = x2-x1
py = y2-y1
something = px*px + py*py
u = ((x3 - x1) * px + (y3 - y1) * py) / float(something)
if u > 1:
u = 1
elif u < 0:
u = 0
x = x1 + u * px
y = y1 + u * py
dx = x - x3
dy = y - y3
# Note: If the actual distance does not matter,
# if you only want to compare what this function
# returns to other results of this function, you
# can just return the squared distance instead
# (i.e. remove the sqrt) to gain a little performance
dist = math.sqrt(dx*dx + dy*dy)
return dist
print(computeDistancePointToSegment(x1, y1, x2, y2, x0, y0)) | true |
e898d4e4b96bf10bdba01c473cfa8de608ff158d | mxu007/leetcode | /414_Third_Maximum_Number.py | 1,890 | 4.1875 | 4 | # Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).
# Example 1:
# Input: [3, 2, 1]
# Output: 1
# Explanation: The third maximum is 1.
# Example 2:
# Input: [1, 2]
# Output: 2
# Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
# Example 3:
# Input: [2, 2, 3, 1]
# Output: 1
# Explanation: Note that the third maximum here means the third maximum distinct number.
# Both numbers with value 2 are both considered as second maximum.
# https://leetcode.com/problems/third-maximum-number/description/
# 1) iterate the nums and compare with first, second and third, cannot sort as the problem specifies O(N) time
class Solution:
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
first, second, third = -sys.maxsize - 1, -sys.maxsize - 1, -sys.maxsize - 1
for num in nums:
if num > first:
first, second, third = num, first, second
elif second < num < first:
second, third = num, second
elif third < num < second:
third = num
return third if third != -sys.maxsize - 1 else first
# 2) use heapq, heapq.nlargest(n,B) takes O(mlog(n)) where m is number of elements in nums
# https://stackoverflow.com/questions/23038756/how-does-heapq-nlargest-work
# https://stackoverflow.com/questions/29109741/what-is-the-time-complexity-of-getting-first-n-largest-elements-in-min-heap?lq=1
import heapq
class Solution:
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
B = set(nums)
A = heapq.nlargest(3, B)
A.sort()
if len(A) != 3 :
return A[-1]
else:
return A[0]
| true |
00a7856bbfb3690bf77899cfa4ce5e1c59b43191 | saifeemustafaq/Magic-Maths-in-Python | /test.py | 892 | 4.25 | 4 | print ""
print " Please press enter after each step!"
print ""
print ' Think of a number below 10...'
a=raw_input( )
print ' Double the number you have thought.'
b=raw_input()
c= int(input(" Add something from 1-10 with the getting result and type it here (type only within 1-10):"))
print ""
print ' Half the answer, (that is divide it by 2.)'
d=raw_input()
print ' Take away the number you have thought from the answer\n that is, (subtract the number you have thought from the answer you have now.)'
e=raw_input()
if c==0 :
print "Please be honest"
if c==1 :
print "0.5"
if c==2 :
print "1"
if c==3 :
print "1.5"
if c==4 :
print "2"
if c==5 :
print "2.5"
if c==6 :
print "3"
if c==7 :
print "3.5"
if c==8 :
print "4"
if c==9 :
print "4.5"
if c==10 :
print "5"
| true |
85f11d93c2b76f8a0f8def3f861002cb73056ef9 | Hariharan-K/python | /remove_all_occurrences.py | 1,086 | 4.34375 | 4 | # Remove all occurrences of a number x from a list of N elements
# Example: Remove 3 from a list of size 5 containing elements 1 3 2 3 3
# Input: 3 5 1 3 2 3 3
# Output: 1 2
# Input: 4 7 1 4 4 2 4 7 9
########################
import sys
def remove_all_occurrences(mylist,n):
# loop to traverse each element in list
# and, remove elements
# which are equals to n
i=0 #loop counter
length = len(mylist) #list length
while(i<length):
if(mylist[i]==n):
mylist.remove (mylist[i])
# as an element is removed
# so decrease the length by 1
length = length -1
# run loop again to check element
# at same index, when item removed
# next item will shift to the left
continue
i = i+1
# print list after removing given element
print ("list after removing elements:")
print (mylist)
####################
# Driver code ######
x = list(map(int, input("Enter a multiple value: ").split()))
print("List of students: ", x)
val = x[0]
ar_size = x[1]
x = x[2:]
print ("val = ", val, "size = ", ar_size, x )
remove_all_occurrences(x, val)
| true |
b68c2c507980032894a5f75f3a3c619b28b559d1 | Hariharan-K/python | /max_sum_of_non_empty_array.py | 1,411 | 4.28125 | 4 | """
Given an array of integers, return the maximum sum for a non-empty subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible.
Note that the subarray needs to be non-empty after deleting one element.
Example 1:
Input: arr = [1,-2,0,3]
Output: 4
Explanation: Because we can choose [1, -2, 0, 3] and drop -2, thus the subarray [1, 0, 3] becomes the maximum value.
Example 2:
Input: arr = [1,-2,-2,3]
Output: 3
Explanation: We just choose [3] and it's the maximum sum.
Example 3:
Input: arr = [-1,-1,-1,-1]
Output: -1
Explanation: The final subarray needs to be non-empty. You can't choose [-1] and delete -1 from it, then get an empty subarray to make the sum equals to 0.
"""
import sys
def maximumSum(arr):
del_sum = non_del_sum = 0
res = -sys.maxsize
for i,a in enumerate(arr):
del_sum = max(del_sum + a,a)
print ("delsum ", del_sum)
if i > 0:
del_sum = max(del_sum,non_del_sum)
print ("delsum ", del_sum)
non_del_sum = max(non_del_sum + a,a)
res = max(res, del_sum)
return res
#print(maximumSum([1,-2,0,3]))
print(maximumSum([1,-2,-2,3]))
#print(maximumSum([-1,-1,-1,-1]))
| true |
88f55010db0303121f3c6ba25cba54efe923589f | Colfu/codewars | /6th_kyu/autocomplete_yay.py | 2,620 | 4.21875 | 4 | # It's time to create an autocomplete function! Yay!
# The autocomplete function will take in an input string and a dictionary array
# and return the values from the dictionary that start with the input string. **Cr.1
# If there are more than 5 matches, restrict your output to the first 5 results. **Cr.2
# If there are no matches, return an empty array. **Cr.3
#
# Example:
# autocomplete('ai', ['airplane','airport','apple','ball']) = ['airplane','airport']
#
# For this kata, the dictionary will always be a valid array of strings.
# Please return all results in the order given in the dictionary, **Cr.4
# even if they're not always alphabetical.
# The search should NOT be case sensitive, but the case of the word should be preserved when it's returned. **Cr.5
# For example, "Apple" and "airport" would both return for an input of 'a'.
# However, they should return as "Apple" and "airport" in their original cases. **Cr.6
#
# Important note:
# Any input that is NOT a letter should be treated as if it is not there. **Cr.7
# For example, an input of "$%^" should be treated as "" and an input of "ab*&1cd" should be treated as "abcd".
# -----------------------------------
# Plan:
# Assumption: they say 'dictionary' but mean 'list', as that's what they show in the example.
# 1. for word in dictionary, if word[0:len of input] = input, add to results list
# 2. case sensitive using .lower()
# 3. filter using >= a and <=z
def autocomplete(input_, dictionary):
"""Take in an input string and a dictionary array and return
the values from the dictionary that start with the input string.
Args:
input_ (string): letters used to start a word
dictionary (list): valid list of strings
Returns:
list: values from dictonary list that start with input_ string
"""
# Make lowercase, remove non-alpha characters, and store **Cr.7
filtered_input = ''
for char in input_.lower():
if char >= 'a' and char <= 'z':
filtered_input += char
# Store results
autocomplete_list = []
for word in dictionary:
# Compare characters in length of input to same length of each dictionary word, if the same, add to results list
if word[:(len(filtered_input))].lower() == filtered_input.lower(): #**Cr.5 & 6
autocomplete_list.append(word) # **Cr.1, **Cr.4
# If no matches, return empty list
if len(autocomplete_list) == 0: # **Cr.3
return []
else:
return autocomplete_list[:5] # **Cr.2
| true |
8c1e72d62ca4f9dcdc61a861d0dc8ed095d922ba | sankari-chelliah/Python | /int_binary.py | 414 | 4.34375 | 4 | #Program to convert integer to Binary number
num= int(input("Enter Number: "))
result=''
#Check the sign of the number
if num<0:
isneg=True
num = abs(num)
elif num==0:
result='0'
else:
isneg= False
# Does actual binary conversion
while num>0:
result=str(num%2)+result
num=num//2
#Display result with the sign of the input
if isneg==True:
print(f"-{result}")
else:
print(result)
| true |
ec094d809089a6cff9ded0f6cd4a10e98a698e60 | rstrozyk/codewars_projects1 | /#8 alternate_capitalization.py | 673 | 4.28125 | 4 | # Given a string, capitalize the letters that occupy even indexes and odd indexes separately, and return as shown below. Index 0 will be considered even.
# For example, capitalize("abcdef") = ['AbCdEf', 'aBcDeF']. See test cases for more examples.
# The input will be a lowercase string with no spaces.
# Good luck!
def capitalize(s):
outcome = ["",""]
i = 0
for char in s:
if i % 2 == 0:
outcome[0] += char.capitalize()
outcome[1] += char
i += 1
else:
outcome[0] += char
outcome[1] += char.capitalize()
i += 1
return outcome
print(capitalize("abracadabra")) # test | true |
1a84de296000421f725a38ef905ab5f590d085ac | SanghamitraDutta/dsp | /python/markov.py | 2,440 | 4.5625 | 5 | #!/usr/bin/env python
# Write a Markov text generator, [markov.py](python/markov.py). Your program should be called from the command line with two arguments: the name of a file containing *text to read*, and the *number of words to generate*. For example, if `chains.txt` contains the short story by Frigyes Karinthy, we could run:
# ```bash
# ./markov.py chains.txt 40
# ```
# A possible output would be:
# > show himself once more than the universe and what I often catch myself playing our well-connected game went on. Our friend was absolutely correct: nobody from the group needed this way. We never been as the Earth has the network of eternity.
# There are design choices to make; feel free to experiment and shape the program as you see fit. Jeff Atwood's [Markov and You](http://blog.codinghorror.com/markov-and-you/) is a fun place to get started learning about what you're trying to make.
import sys
import random
from collections import defaultdict
def readfile(in_file):
with open(in_file) as f:
text = f.read()
return text
def nxt_wrds_dict(text): # Makes dict with Keys: words from file & Values: list of words that follow the key word in the file
word_list = text.split()
d = defaultdict(list)
for i in range(0,len(word_list)-1): # for loop goes up to penultimate word in file as no words follow the last word
d[word_list[i]].append(word_list[i+1]) # for every word key append the value list with the word that follows the key in the file
return d
def markov_generator(nxt_word_dict, n):
StartWordsList = [word for word in nxt_word_dict.keys() if word[0].isupper()] #List all keys with Capital letter as they start a sentence
First_word = random.choice(StartWordsList) # find a random starting word
Output_List = [First_word]
i=1
while i< n:
NextWord = random.choice(nxt_word_dict[Output_List[-1]]) #for each output word(key) find next word randomly(from value list)
Output_List.append(NextWord)
i+=1
MarkovOutput = " ".join(Output_List)
return MarkovOutput
if __name__ == '__main__':
input_file = sys.argv[1] # 2nd argument entered on terminal
word_count = int(sys.argv[2]) # 3rd argument entered on terminal
input_text = readfile(input_file)
nextword_dict = nxt_wrds_dict(input_text)
markov_text = markov_generator(nextword_dict, word_count)
print(markov_text)
#print(nextword_dict)
| true |
14f4b6abd789bffaf54ab8587be22f13dd87e572 | j721/cs-module-project-recursive-sorting | /src/searching/searching.py | 1,128 | 4.4375 | 4 | # TO-DO: Implement a recursive implementation of binary search
def binary_search(arr, target, start, end):
# Your code here
middle = (start +end)//2
if len(arr) == 0:
return -1 #empty array
#if target is equal to the middle index in the array then return it
if arr[middle] == target:
return middle
#if target is less than middle than call recursion and focus on the left side
#disregard the middle index and those on the right side
elif arr[middle] > target:
return binary_search(arr, target, end, middle -1)
#if target is greater than the middle index than focus on the right side
#disregard the middle index and those on the left
else:
return binary_search(arr, target, start, middle + 1)
# STRETCH: implement an order-agnostic binary search
# This version of binary search should correctly find
# the target regardless of whether the input array is
# sorted in ascending order or in descending order
# You can implement this function either recursively
# or iteratively
# def agnostic_binary_search(arr, target):
# Your code here
| true |
570b85577fcc8343c1d9fa11d8e0bd95eb3a4e3f | kulsuri/playground | /daily_coding_problem/solutions/problem_9.py | 611 | 4.1875 | 4 | # Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative.
# For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10, since we pick 5 and 5.
def largest_sum(l):
inclusive = 0
exclusive = 0
for i in l:
temp = inclusive
inclusive = max(inclusive, exclusive + i)
exclusive = temp
answer = max(inclusive, exclusive)
return answer
print(largest_sum([2, 4, 6, 2, 5]))
print(largest_sum([5, 1, 1, 20, 2]))
print(largest_sum([5, 1, 1, 5])) | true |
4ecf79677118a95f24d80fe0ead4272e8f61eeec | kulsuri/playground | /udemy-11-essential-coding-interview-questions/1.1_arrays_most_freq_no.py | 911 | 4.21875 | 4 | # return the most frequent element in an array in O(n) runtime
def most_frequent(given_array):
# insert all elements and corresponding count in a hash table
Hash = dict()
for c,v in enumerate(given_array):
if given_array[c] in Hash.keys():
Hash[given_array[c]] += 1
else:
Hash[given_array[c]] = 1
# find the max frequency
max_count = 0
result = None
for i in Hash:
if max_count < Hash[i]:
result = i
max_count = Hash[i]
return result
# Examples
# most_frequent(list1) should return 1
list1 = [1, 3, 1, 3, 2, 1]
# most_frequent(list2) should return 3
list2 = [3, 3, 1, 3, 2, 1]
# most_frequent(list3) should return None
list3 = []
# most_frequent(list4) should return 0
list4 = [0]
# most_frequent(list5) should return -1
list5 = [0, -1, 10, 10, -1, 10, -1, -1, -1, 1]
print(most_frequent(list1)) | true |
07d0eb183fcc1f3fd342e785a743043658114649 | kylebush1986/CS3080_Python_Programming | /Homework/Homework_3/hw3_kyle_bush_ex_3.py | 1,708 | 4.4375 | 4 | '''
Homework 3, Exercise 3
Kyle Bush
9/21/2020
This program stores a store inventory in a dictionary.
The user can add items, delete items, and print the inventory.
'''
def printInventory(inventory):
print()
print('Item'.ljust(20), 'Quantity'.ljust(8))
for item, number in inventory.items():
print(item.ljust(20), str(number).ljust(8))
print()
def addItem(inventory, item):
inventory.setdefault(item, 0)
inventory[item] += 1
print('Item added: ' + item + ', Quantity in Inventory: ' + str(inventory[item]))
def deleteItem(inventory, item):
if item in inventory and inventory[item] >= 0:
inventory[item] -= 1
print('Item deleted: ' + item + ', Quantity in Inventory: ' + str(inventory[item]))
else:
print(item + ' is not in inventory.')
def main():
inventory = {
'Hand sanitizer': 10,
'Soap': 6,
'Kleenex': 11,
'Lotion': 16,
'Razors': 12
}
while True:
print('MENU')
print('1. Add Item')
print('2. Delete Item')
print('3. Print Inventory')
print('4. Exit')
menuSelection = input()
if menuSelection == '1':
print('Enter an item to add to the inventory.')
item = input()
addItem(inventory, item)
elif menuSelection == '2':
print('Enter an item to delete from the inventory.')
item = input()
deleteItem(inventory, item)
elif menuSelection == '3':
printInventory(inventory)
elif menuSelection == '4':
break
else:
print('Please enter a valid menu option.')
if __name__ == "__main__":
main()
| true |
1270188cab6e1d289056abee5013a4f729bfb40d | justinDeu/path-viz | /algo.py | 1,273 | 4.40625 | 4 | from board import Board
class Algo():
"""Defines an algorithm to find a path from a start to an end point.
The algorithm will be run against a 2D array where different values
signify some state in the path. The values are as follows:
0 - a free cell
1 - a blocked cell (cannot take)
2 - the start point
3 - the end point
4 - an explored point
All algorithms will expose 3 public functions: a constructor, the step function,
and a boolean solved function.
"""
def __init__(self, board: Board):
self._board = board
self._start = board.start()
self._end = board.end()
self._path = []
def step(self) -> (int, int):
"""Advances the algorithm through one iteration exploring one
more position on the board
Returns a tuple of the position explored
"""
pass
def running(self) -> bool:
"""
Returns a boolean value of whether the algorith has found a
True - path has been found/no possible path
False - path has not been found
"""
pass
def set_path(self):
self._board.set_path(self._path) | true |
5d3f9ba65e4c68e743ea21a0db8dbbb54c92bd6f | prahate/python-learn | /python_classes.py | 926 | 4.21875 | 4 | # self is defined as an instance of a class(similar to this in c++),and variables e.g. first, last and pay are called instance variables.
# instance variables are the ones that are unique for each instance e.g. first, last and pay. They are unique to each instance.
# __init__ is called as constructor(in languages like c++), this function is called as soon as we create object/instance of the class.
# we can pass default values to functions as __init__(self, pay=3000)
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
def full_name(self):
return '{} {}'.format(self.first, self.last)
# below e1 and e2 are called instances of class employee
e1 = Employee('Prath', 'rahate', 5000)
e2 = Employee('Prathamesh', 'rahate', 5000)
print(e1.full_name())
# other way to call function instaed of using object
# print(Employee.full_name(e1))
print(e2.full_name())
| true |
e9d4a5afa1859ec6b3ad87a3000bee910afef669 | prahate/python-learn | /python_sqlite.py | 698 | 4.5 | 4 | import sqlite3
# Creating a connection sqlite database, it will create .db file in file system
# other way to create is using memory, so database will be in memory (RAM)
# conn = sqlite3.connect(':memory:')
conn = sqlite3.connect('employees.db')
# To get cursor to the database
c = conn.cursor()
# Create table using cursor
#c.execute("""CREATE TABLE employees
# (
# first test,
# last text,
# pay integer
# )""")
#c.execute("""INSERT INTO employees VALUES ('sheldon', 'cooper', '50000')""")
c.execute("SELECT * FROM employees WHERE last='cooper'")
print(c.fetchone())
# Always use conn.commit after execute statement
conn.commit()
# always good to close a connection
conn.close()
| true |
ae1562f866cb8c54589f22867ba55c460fde26b3 | keshavsingh4522/Data-Structure-and-Algorithm | /prefix infix postfix/prefix_to_postfix.py | 689 | 4.21875 | 4 | '''
Algorith:
- Read the Prefix expression in reverse order (from right to left)
- If the symbol is an operand, then push it onto the Stack
- If the symbol is an operator, then pop two operands from the Stack
- Create a string by concatenating the two operands and the operator after them.
- string = operand1 + operand2 + operator
- And push the resultant string back to Stack
- Repeat the above steps until end of Prefix expression.
'''
prefix=input('Enter Prefix Operation: ')
operators='-+/*%^'
postfix=''
stack=[]
for i in prefix[::-1]:
if i in operators:
x1=stack.pop()
x2=stack.pop()
stack.append(x1+x2+i)
else:
stack.append(i)
print(*stack)
| true |
561ee4fb8b21c6eb2b2a3e0d9faab32145c58318 | jain7727/html | /2nd largest.py | 278 | 4.25 | 4 | num1=int(input("enter the first no"))
num2=int(input("enter the second no"))
num3=int(input("enter the third no"))
print(num1,num2,num3)
if(num1>num2>num3):
print("2nd largest no is ", num2)
elif(num2>num3>num1):
print("2nd largest no is ", num3)
else:
print(num1) | true |
18d1349155c4a17df235d6ef2a6adbaefd711cf8 | delroy2826/Programs_MasterBranch | /regular_expression_excercise.py | 2,675 | 4.59375 | 5 | #1 Write a Python program to check that a string contains only a certain set of characters (in this case a-z, A-Z and 0-9).
import re
def check(str1):
match = pattern.search(str1)
return not bool(match)
pattern = re.compile(r'[^\w+]')
str1 = "delro3y1229"
print(check(str1))
str1 = "delro#3y1229"
print(check(str1))
#Solution from web
import re
def is_allowed_specific_char(string):
charRe = re.compile(r'[^a-zA-Z0-9.]')
string = charRe.search(string)
return not bool(string)
print(is_allowed_specific_char("ABCDEFabcdef123450"))
print(is_allowed_specific_char("*&%@#!}{"))
#2 Write a Python program that matches a string that has an (a ) followed by (zero or more b's)
import re
str1 = "abbc"
pattern = re.compile(r'ab*')
match = pattern.finditer(str1)
for i in match:
print(i)
import re
def check(str1):
pattern=r'ab*'
if re.search(pattern,str1):
print("Found Match")
else:
print("Not Found Match")
check("ab")
check("cb")
check("abbbbb")
check("abbwww")
#3 Write a Python program that matches a string that has an (a) followed by (one or more b's)
import re
str1 = "abcs"
pattern = re.compile(r'ab+')
match = pattern.finditer(str1)
for i in match:
print(i)
import re
def check(str1):
pattern = r'ab+'
if re.search(pattern,str1):
print("Found Match")
else:
print("Not Found")
check("ab")
check("cb")
check("abbbbb")
check("a")
#4 Write a Python program that matches a string that has an a followed by zero or one 'b'
import re
def check(str1):
pattern = re.compile(r'ab?')
if re.search(pattern,str1):
print("Match")
else:
print("No Match")
l = ['ab','abc','abbc','aabbc','qwe']
for i in l:
check(i)
#5 Write a Python program that matches a string that has an a followed by three 'b'
import re
def check(str1):
pattern = re.compile(r'ab{3,}')
if re.search(pattern,str1):
print("Match")
else:
print("No Match")
l = ['ab','abbb','aabbbbbc','aabbbc','qwe']
for i in l:
check(i)
#6 Write a Python program that matches a string that has an a followed by two to three 'b'
import re
def check(str1):
pattern = re.compile(r'ab{2,3}?')
if re.search(pattern,str1):
print("Match")
else:
print("No Match")
l = ['ab','abbb','aabbbbbc','aabbbc','qwe']
for i in l:
check(i)
#7 Write a Python program to find sequences of lowercase letters joined with a underscore.
import re
def check(str1):
pattern = re.compile(r'^[a-z]+_[a-z]+$')
if re.search(pattern,str1):
print("Match")
else:
print("No Match")
l = ['aab_cbbbc','aab_Abbbc','Aaab_abbbc']
for i in l:
check(i)
| true |
d4352cfdd84a15f13d8c17ce5e69d6f20b0d3952 | delroy2826/Programs_MasterBranch | /pynativedatastruct5.py | 277 | 4.21875 | 4 | #Given a two list of equal size create a set such that it shows the element from both lists in the pair
firstList = [1, 2, 3, 4, 5]
secondList = [10, 20, 30, 40, 50]
new_list = []
for i in range(len(firstList)):
new_list.append((firstList[i],secondList[i]))
print(new_list) | true |
a47908baf91fad4982439dfd1c66059761aa92e4 | catliaw/hb_coding_challenges | /concatlists.py | 1,054 | 4.59375 | 5 | """Given two lists, concatenate the second list at the end of the first.
For example, given ``[1, 2]`` and ``[3, 4]``::
>>> concat_lists([1, 2], [3, 4])
[1, 2, 3, 4]
It should work if either list is empty::
>>> concat_lists([], [1, 2])
[1, 2]
>>> concat_lists([1, 2], [])
[1, 2]
>>> concat_lists([], [])
[]
"""
def concat_lists(list1, list2):
"""Combine lists."""
# can create new list that is first list, then loop through 2nd list
# and append on each item in 2nd list,
### actually can just loop through 2nd list and append to first list.
### do not need 3rd list.
# but can just combine using the + operator, which combines sequences
### this is probably doing the same thing as looping through 2nd list,
### append to 1st list under the hood.
for item in list2:
list1.append(item)
return list1
# return list1 + list2
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print "\n*** ALL TESTS PASSED. GO YOU!\n"
| true |
fb218791404f9ab8db796661c91e1ab0097af097 | yu-shin/yu-shin.github.io | /downloads/code/LeetCode/Array-Introduction/q977_MergeSort.py | 1,533 | 4.5 | 4 | # Python3 program to Sort square of the numbers of the array
# function to sort array after doing squares of elements
def sortSquares(arr, n):
# first dived array into part negative and positive
K = 0
for K in range(n):
if (arr[K] >= 0 ):
break
# Now do the same process that we learn
# in merge sort to merge to two sorted array
# here both two half are sorted and we traverse
# first half in reverse meaner because
# first half contain negative element
i = K - 1 # Initial index of first half
j = K # Initial index of second half
ind = 0 # Initial index of temp array
# store sorted array
temp = [0]*n
while (i >= 0 and j < n):
if (arr[i] * arr[i] < arr[j] * arr[j]):
temp[ind] = arr[i] * arr[i]
i -= 1
else:
temp[ind] = arr[j] * arr[j]
j += 1
ind += 1
''' Copy the remaining elements of first half '''
while (i >= 0):
temp[ind] = arr[i] * arr[i]
i -= 1
ind += 1
''' Copy the remaining elements of second half '''
while (j < n):
temp[ind] = arr[j] * arr[j]
j += 1
ind += 1
# copy 'temp' array into original array
for i in range(n):
arr[i] = temp[i]
# Driver code
arr = [-6, -3, -1, 2, 4, 5 ]
n = len(arr)
print("Before sort ")
for i in range(n):
print(arr[i], end =" " )
sortSquares(arr, n)
print("\nAfter Sort ")
for i in range(n):
print(arr[i], end =" " ) | true |
fb9f96fd4b3a3becd84531f4d07748c13bf6706d | kawing-ho/pl2py-ass1 | /test01.py | 268 | 4.53125 | 5 | #!/usr/bin/python3
# Use of "#" character in code to mimic comments
for x in range(0,5):
print("This line does't have any hash characters :)") #for now
print("but this one does! #whatcouldgowrong ? ") #what happens here ?
print("I love '#'s") and exit(ord('#'))
| true |
71b552431f56fea84e1062924a6c1782449fe976 | PrechyDev/Zuri | /budget.py | 1,882 | 4.1875 | 4 | class Budget:
'''
The Budget class creates budget instances for various categories.
A user can add funds, withdraw funds and calculate the balance in each category
A user can also transfer funds between categories.
'''
##total balance for all categories
total_balance = 0
@classmethod
def net_balance(cls):
print(f'The net balance of your budgets is {cls.total_balance}')
def __init__(self, category):
self.name = category
self.balance = 0
def deposit(self):
amount = int(input(f'How much do you want to deposit for {self.name}\n'))
self.balance += amount
Budget.total_balance += amount
print(f'Your current budget for {self.name} is {self.balance} ')
def withdraw(self):
amount = int(input(f'How much do you want to withdraw from your {self.name} account?\n'))
self.balance -= amount
Budget.total_balance -= amount
print(f'You just withdrew {amount}, you have {self.balance} left in your {self.name} account')
def transfer(self, other):
amount = int(input(f'How much do you want to transfer to your {other.name} account?\n'))
self.balance -= amount
other.balance += amount
print('Transfer successful!')
print(f'You have left in {self.balance} in your {self.name} account and {other.balance} in your {other.name} account')
def check_balance(self):
print(f'You have {self.balance} remaining in your {self.name} account')
## categories
#food = Budget('Food')
#transport = Budget('Transportation')
#clothing = Budget('Clothing')
#entertain = Budget('Entertainment')
#bills = Budget('Bills')
#rent = Budget('Rent')
#other = Budget('Others')
##tests
#food.deposit()
#food.withdraw()
#food.check_balance()
#bills.deposit()
#Budget.net_balance()
#food.transfer(rent)
| true |
d30896b9eb8a8bf8f73d05439906a5fd1a5c1973 | Weyinmik/pythonDjangoJourney | /dataTypeNumbers.py | 581 | 4.21875 | 4 | """
We have integers and floats
"""
a = 14
print(a)
b = 4
print(b)
print(a + b) # print addition of a and b, 18.
print(a - b) # print subtraction of a and b, 10.
print(a * b) # print multiplication of a and b, 56.
print(a / b) # print division of a and b in the complete decimal format, -3.5.
print(a // b) # print division of a and b but ignores everything after the decimal point, -3.
print(a % b) # Only print the remainder value as a result of the division, -2.
print(2+10*10+3) #Result:105
print(5 + 20 / 4 * 2 - 7) #Rsult:8.0 | true |
f7e5cd52ac7324617717081db83c6b849f5fab32 | katecpp/PythonExercises | /24_tic_tac_toe_1.py | 546 | 4.125 | 4 | #! python3
def readInteger():
value = ""
while value.isdigit() == False:
value = input("The size of the board: ")
if value.isdigit() == False:
print("This is not a number!")
return int(value)
def printHorizontal(size):
print(size * " ---")
def printVertical(size):
print((size + 1) * "| ")
def drawBoard(size):
for i in range(size):
printHorizontal(size)
printVertical(size)
printHorizontal(size)
if __name__=="__main__":
size = readInteger()
drawBoard(size)
| true |
c6ff43950f21b27f9c3dd61cf3d6840748ad2864 | katecpp/PythonExercises | /11_check_primality.py | 515 | 4.21875 | 4 | #! python3
import math
def readInteger():
value = ""
while value.isdigit() == False:
value = input("Check primality of number: ")
if value.isdigit() == False:
print("This is not a number!")
return int(value)
def isPrime(number):
upperBound = int(math.sqrt(number))
for d in range(2, upperBound+1):
if number % d == 0:
return False
return True
value = readInteger()
print(str(value) + (" is " if isPrime(value) else " is not ") + "prime")
| true |
d849a589929e610b588067d845bfcf182ca5b3b5 | Legoota/PythonAlgorithmTraining | /Sorts/mergesort.py | 572 | 4.125 | 4 | def mergesort(array):
if len(array) < 2:
return array
center = len(array)//2
left, right = array[:center], array[center:]
left = mergesort(left)
right = mergesort(right)
return mergelists(left, right)
def mergelists(left, right):
result = []
while len(left) > 0 and len(right) > 0:
if(left[0] <= right[0]):
result.append(left.pop(0))
else:
result.append(right.pop(0))
while left:
result.append(left.pop(0))
while right:
result.append(right.pop(0))
return result | true |
58451f498859eb61cd3e28d95915567432396483 | avigautam-329/Interview-Preparation | /OS/SemaphoreBasics.py | 842 | 4.15625 | 4 | from threading import Thread, Semaphore
import time
# creating semaphore instance to define the number of threads that can run at once.
obj = Semaphore(3)
def display(name):
# THis is where the thread acquire's the lock and the value of semaphore will decrease by 1.
obj.acquire()
for i in range(3):
print("Hello from {}".format(name))
time.sleep(1)
obj.release()
t1 = Thread(target = display, args = ("Thread 1",))
t2 = Thread(target = display, args = ("Thread 2",))
t3 = Thread(target = display, args = ("Thread 3",))
t4 = Thread(target = display, args = ("Thread 4",))
t5 = Thread(target = display, args = ("Thread 5",))
t6 = Thread(target = display, args = ("Thread 6",))
t1.start()
t2.start()
t3.start()
t4.start()
t5.start()
t6.start()
# join() is not needed as we are not making a main function
| true |
839181892842d62b803ab6040c89f29a2718514e | chuducthang77/Summer_code | /front-end/python/project301.py | 1,158 | 4.15625 | 4 | #Project 301: Banking App
#Class Based
# Withdraw and Deposit
# Write the transaction to a python file
class Bank:
def __init__(self, init=0):
self.balance = init
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
account = Bank()
while True:
action = input("What action do you want to take - deposit (d) or withdraw (w): ")
if action == 'd':
amount = input('Enter amount you want to deposit: ')
try:
amount = float(amount)
except:
print("Not a proper amount")
continue
account.deposit(amount)
with open('account.txt', 'a') as file:
file.write(f"Deposit: {amount}\n")
print(account.balance)
elif action == 'w':
amount = input('Enter amount you want to withdraw: ')
try:
amount = float(amount)
except:
print("Not a proper amount")
continue
account.withdraw(amount)
with open('account.txt', 'a') as file:
file.write(f"Withdraw: {amount}\n")
print(account.balance) | true |
798f3df4e5b30737ace8d3071d048a59745494e8 | bjchu5/pythonSort | /insertionsort.py | 1,848 | 4.5 | 4 | def insertionsort_method1(aList):
"""
This is a Insertion Sort algorithm
:param n: size of the list
:param temp: temporarily stores value in the list to swap later on
:param aList: An unsorted list
:return: A sorted ist
:precondition: An unsorted list
:Complexity: Best Case is O(N), Worst Case is O(N^2) because this algorithm is able to exit the while loop early if it nearly sorted, insertion sort starts sorting from the beginning towards
the end, so if one of the value in the list is bigger than the temporary value, it can exit early (assuming this is a true insertion sort algorithm). The worst case happens when the algorithm
is sorted in reverse, the entire list will compare and swap.
:Stability: Insertion sort is a stable sorting algorithm because the algorithm only swaps the compared value with the value before it and will not swap the position of similar value, making
it unable to break the relative order.
"""
n = len(aList)
for i in range(1, n):
temp = aList[i]
k = i - 1
while(k >= 0 and aList[k] > temp):
aList[k+1] = aList[k]
k-=1
aList[k+1] = temp
def insertionsort_method2(aList):
n = len(aList)
for i in range(1, n):
k = i-1
while k >= 0 and aList[k] > aList[k+1]:
aList[k] , aList[k+1] = aList[k+1] , aList[k]
k-=1
if __name__ == ("__main__"):
list1 = [12, 44, 6, 7, 19, 4, 10, 18]
list2 = [12, 44, 6, 7, 19, 4, 10, 18]
insertionsort_method1(list1)
insertionsort_method2(list2)
print("Method 1: ", list1)
print("Method 2: ", list2) | true |
ed571b223307d9ccf5f43fcc1d1aa0469c213bbf | Dongmo12/full-stack-projects | /Week 5 - OOP/Day 3/exercises.py | 666 | 4.34375 | 4 | '''
Exercise 1 : Built-In Functions
Python has many built-in functions, and if you do not know how to use it, you can read document online.
But Python has a built-in document function for every built-in functions.
Write a program to print some Python built-in functions documents, such as abs(), int(), raw_input().
And add documentation for your own function
'''
class Functions:
'''This is great'''
def raw_input(self):
'''This is for raw_input'''
def absolutes(self):
'''This for abs operations'''
def integers(self):
'''This is for integers'''
obj1 = Functions()
raw_in = obj1.raw_input()
print(Functions.__doc__)
| true |
fcb2f3f5194583a7162a38322303ab2945c8de79 | Dongmo12/full-stack-projects | /Week 4 Python and web programming/Day 2/exercises.py | 1,705 | 4.5 | 4 | '''
Exercise 1 : Favorite Numbers
Create a set called my_fav_numbers with your favorites numbers.
Add two new numbers to it.
Remove the last one.
Create a set called friend_fav_numbers with your friend’s favorites numbers.
Concatenate my_fav_numbers and friend_fav_numbers to our_fav_numbers.
# Solution
my_fav_numbers = {12,16,20}
print(my_fav_numbers)
my_fav_numbers.add(30)
print(my_fav_numbers)
my_fav_numbers.add(15)
print(my_fav_numbers)
my_fav_numbers.pop()
print(my_fav_numbers)
my_fav_numbers.pop()
print(my_fav_numbers)
friend_fav_numbers = {"jeff","jose","Armand"}
our_fav_numbers = my_fav_numbers.union(friend_fav_numbers)
print(our_fav_numbers)
'''
'''
Exercise 2: Tuple
Given a tuple with integers is it possible to add more integers to the tuple?
Answer: It would not be possible to add because a tuple is a collection which is ordered and unchangeable.
'''
'''
Use a for loop to print the numbers from 1 to 20, inclusive.
# Solution
for num in range(1,21):
print(num)
'''
'''
Exercise 4: Floats
Recap – What is a float? What is the difference between an integer and a float?
Can you think of another way of generating a sequence of floats?
Create a list containing the sequence 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5 without hard-coding the sequence.
#Solution
float represent real numbers and are written with a decimal point dividing the integer and fractional parts.
An integer (more commonly called an int) is a number without a decimal point. A float is a floating-point number, which means it is a number that has a decimal place. Floats are used when more precision is needed.
'''
list = list(range(1,6) )
for x in list:
print(x)
x = x+0.5
print(x) | true |
790e8b58ab3d9178d1468041d9f77b17c63fa8c1 | Dongmo12/full-stack-projects | /Week 4 Python and web programming/Day 1/exercises.py | 2,370 | 4.5 | 4 | '''
Exercise 4 : Your Computer Brand
Create a variable called computer_brand that contains the brand of your computer.
Insert and print the above variable in a sentence,like "I have a razer computer".
# Solution
computer_brand = "msi"
print('I have a {} computer'.format(computer_brand))
'''
'''
Exercise 5: Your Information
Create a variable called name, and give it your name as a value (text)
Create a variable called age, and give it your age as a value (number)
Create a variable called shoe_size, and give it your shoe size as a value
Create a variable called info. Its value should be an interesting sentence about yourself, including your name, age, and shoe size. Use the variables you created earlier.
Have your code print the info message.
Run your code
#Solution
name = "jeff"
age = 32
shoe_size = 40
info = "My name is {} and I am {} year old. My shoe size is {}. I can't change so just accept me as I am."
print(info.format(name,age,shoe_size))
'''
'''
Exercise 6: Odd Or Even
Write a script that asks the user for a number and determines whether this number is odd or even
#solution
val = int(input('Please, enter your name: '))
if val%2==0:
print('{} is even'.format(val))
else:
print('{} is odd'.format(val))
'''
'''
Exercise 7 : What’s Your Name ?
Write a script that asks the user for his name and determines
whether or not you have the same name, print out a funny message based on the outcome
#Solution
myName = 'Alexandra'.lower()
userName = input("Please, enter your name:").lower()
if userName==myName:
print('{} we have the same name.'.format(userName))
else:
print('{} sorry but we don t have the same name.'.format(userName))
'''
'''
Exercise 8 : Tall Enough To Ride A Roller Coaster
Write a script that will ask the user for their height in inches, print a message if they can ride a roller
coaster or not based on if they are taller than 145cm
Please note that the input is in inches and you’re calculating vs cm,
you’ll need to convert your data accordingly
# Solution
inches = int(input("Please enter your height in inches: "))
convert = int(inches*2.54)
val = 145
if convert>val:
print("You entered {} and you are {} cm so you can ride a roller coaster".format(inches, convert))
else:
print("You entered {} and you are {} cm so you can't ride a roller coaster".format(inches, convert))
''' | true |
edfcc0b98db78aa300f6cf4a804757129cf53321 | harasees-singh/Notes | /Searching/Binary_Search_Bisect.py | 947 | 4.125 | 4 | import bisect
# time complexities of bisect left and right are O(logn)
li = [8, 10, 45, 46, 47, 45, 42, 12]
index_where_x_should_be_inserted_is = bisect.bisect_right(li, 13) # 2 returned
index_where_x_should_be_inserted_is = bisect.bisect_left(li, 46) # 4 returned
print(index_where_x_should_be_inserted_is)
print(bisect.bisect_right([2,6,3,8,4,7,9,4,6,1], 5)) # it returns 5 or in other words 5 should be inserted between 4 and 7
# seems like it starts checking from the center
# note if list is not sorted then it will still work
sorted_list = [1, 2, 2, 3, 4, 5, 6]
print(bisect.bisect_right(sorted_list, 2), bisect.bisect_left(sorted_list, 2))
# note: you can get the count of 2 from the above info provided by the right and left bisect
# since right bisect returns 3 and left one returns 1 it means there are 3-1 = 2 number of 2s present already in the list
| true |
62b6bcd482dd774b75a816056a21247487f32b86 | maindolaamit/tutorials | /python/Beginer/higher_lower_guess_game.py | 1,519 | 4.3125 | 4 | """ A sample game to guess a number between 1 and 100 """
import random
rules = """
=========================================================================================================
= Hi, Below are the rules of the game !!!! =
= 1. At the Start of the game, Program will take a random number between 1 and 100. =
= 2. Then program will ask player to guess the number. You have to input the number you have guessed. =
= 3. Program will then show you the results, if your guess is higher or lower. =
=========================================================================================================
"""
message = {'success': 'Congratulations !!!, You have guess it right',
'high': 'You have guessed a higher value.',
'low': 'Oops !! You have guess a lower value'}
end_credits = """ Thanks for Playing !!! """
# Display the rules
print rules
play = input("Press 1 to Play the game\n")
# Continue playing till user gives the input
while play == 1:
num = random.randint(1, 100)
guess = input("\tEnter the number you have guessed : \t")
msg = "\tProgram's Number : {} ,".format(num)
if guess < num:
print msg + message['low']
elif guess > num:
print msg + message['high']
else:
print msg + message['success']
# Check with User if he wants to play again
play = input("\n\tPress 1 to Play again.\t")
print(end_credits)
| true |
ecf870ac240d1faf8202039bcc235bdb14bb8440 | vsandadi/dna_sequence_design | /generating_dna_sequences.py | 2,007 | 4.28125 | 4 | '''
Function to generate DNA sequences for each bit string.
'''
#initial_sequence = 'ATTCCGAGA'
#mutation_list = [(2, 'T', 'C'), (4, 'C', 'A')]
#bitstring = ['101', '100']
def generating_sequences(initial_sequence, mutation_list, bitstring):
'''
Inputs: initial_sequence as a string of DNA bases
mutation_list as list of tuples of mutation site (int), intial base (str), and mutation (str)
bitstring as list of multiple strings of bits
Returns: the list of final sequences
'''
#Element is one bistring in the list bitstring
final_sequence_list = []
for element in bitstring:
#Raise AssertionError for invalid length of bitstring
assert len(mutation_list) >= len(element), 'Number of mutations has to be greater than or equal to length of bitstring.'
#Turning string inputs into lists for mutability
sequence_list = list(str(initial_sequence))
#Sorting mutation_list by numerical order of mutation placement to match up to correct bitstring value
mutation_list = sorted(mutation_list, key=lambda x: x[0])
#Zipping will pair each element of an index together
#First bitstring will pair with first tuple
#Mutation will iterate through each tuple in zip
#Bit will iterate through each bitstring value
for mutation,bit in zip(mutation_list, element):
#Unwrapping elements in each tuple
#Underscore indicates that variable (the original base) will not be needed
mutation_position, _ , final_base = mutation
if bit == '1':
sequence_list[mutation_position] = final_base
#Combines mutated DNA bases from list into a string
new_sequence = "".join(sequence_list)
final_sequence_list.append(new_sequence)
return final_sequence_list
| true |
18b3a779a6f144bf679eb47b8438b997e87f04ba | summitkumarsharma/pythontutorials | /tut28.py | 752 | 4.1875 | 4 | # file handling - write operation
# f = open("test-write.txt", "w")
# content = "To write to an existing file, you must add a parameter to the open()function" \
# "\n1.a - Append - will append to the end of the file \n2.w - Write - will overwrite any existing content"
# no_of_chars = f.write(content)
# print("File content is written ")
# print("Number of Characters written - ", no_of_chars)
# f.close()
#
#
# f = open("test-write.txt", "a")
# content = "\n3.r - open the file in read mode - default mode \n" \
# "4.w - open the file in write mode\n5.x - create file if not exits"
# f.write(content)
# print("content is appended")
# f.close()
f = open("test-write.txt", "r+")
print(f.read())
f.write("\nEnd of file")
f.close()
| true |
f07bddfa311a3cf735afe4d7e7f139a0bbe94c6c | KiikiTinna/Python_programming_exercises | /41to45.py | 1,684 | 4.15625 | 4 | #Question 41: Create a function that takes a word from user and translates it using a dictionary of three words,
#returning a message when the word is not in the dict,
# considering user may enter different letter cases
d = dict(weather = "clima", earth = "terra", rain = "chuva")
#Question 42: Print out the text of this file www.pythonhow.com/data/universe.txt.
#Count how many a the text file has
#Question 43:Create a script that let the user type in a search term and opens and search on the browser for that term on Google
#Question 44: Plot the data in the file provided through the URL http://www.pythonhow.com/data/sampledata.txt
#Question 45: Create a script that gets user's age and returns year of birth
#Answers
#Q41:
#def vocabulary(word):
# try:
# return d[word]
# except KeyError:
# return "That word does not exist."
#word = input("Enter word: ").lower()
#print(vocabulary(word))
#Q42:
#import requests
#response = requests.get("http://www.pythonhow.com/data/universe.txt")
#text = response.text
#print(text)
#count_a = text.count("a")
#print(count_a)
#Q43:
#import webbrowser
#query = input("Enter your Google query: ")
#url = "https://www.google.com/?gws_rd=cr,ssl&ei=NCZFWIOJN8yMsgHCyLV4&fg=1#q=%s" % str(query)
#webbrowser.open_new(url)
#Q44:
#import pandas
#import pylab as plt
#data = pandas.read_csv("http://www.pythonhow.com/data/sampledata.txt")
#data.plot(x='x', y='y', kind='scatter')
#plt.show()
#Q45:
#from datetime import datetime
#age = int(input("What's your age? "))
#year_birth = datetime.now().year - age
#print("You were born back in %s" % year_birth)
| true |
c65bc508a10563fa6a391cdfdd1997db19569b7a | bsamaha/hackerrank_coding_challenges | /Sock Merchant.py | 761 | 4.125 | 4 | # %%
from collections import defaultdict
# Complete the sockMerchant function below.
def sockMerchant(n, ar):
"""[Find how many pairs can be made from a list of integers]
Args:
n ([int]): [nymber of socks]
ar ([list of integers]): [inventory of socks]
Returns:
[type]: [description]
"""
sock_dict = defaultdict(int)
# For each sock (val) in the sock inventory add one to the value count creating a dictionary
for val in ar:
sock_dict[val] += 1
print(sock_dict)
# initialize counter
cnt = 0
# Divide item count by 2 discarding remainders to get number of pairs possible
for pair in sock_dict.values():
cnt += pair // 2
# Return the answer
return cnt
| true |
e064d9a951cc77879be234b921f3712a4782652e | jz1611/python-codewars | /squareDigits.py | 377 | 4.1875 | 4 | # Welcome. In this kata, you are asked to square every digit of a number.
# For example, if we run 9119 through the function, 811181 will come out,
# because 92 is 81 and 12 is 1.
# Note: The function accepts an integer and returns an integer
def square_digits(num):
new = []
for num in list(str(num)):
new.append(str(int(num) * int(num)))
return int(''.join(new)) | true |
d75bbaf6a902034ade93a755ce5762091a2f2532 | driscolllu17/csf_prog_labs | /hw2.py | 2,408 | 4.375 | 4 | # Name: Joseph Barnes
# Evergreen Login: barjos05
# Computer Science Foundations
# Homework 2
# You may do your work by editing this file, or by typing code at the
# command line and copying it into the appropriate part of this file when
# you are done. When you are done, running this file should compute and
# print the answers to all the problems.
#Name: Joseph Barnes
# Evergreen Login: barjos05
# Computer Science Foundations
###
### Problem 1
###
# DO NOT CHANGE THE FOLLOWING LINE
print "Problem 1 solution follows:"
import hw2_test
n = hw2_test.n
sum = 0
i = 0
while i <= n :
sum = sum + i
print sum
i = i + 1
##I added 1 to n in order for the program to print all the numbers
##up to 100.
### Problem 2
# DO NOT CHANGE THE FOLLOWING LINE
print "Problem 2 solution follows:"
n=10
for i in range(n+1):
if i > 0:
print 1.0/i
###
### Problem 3
###
# DO NOT CHANGE THE FOLLOWING LINE
print "Problem 3 solution follows:"
n = 10
triangular = 0
for i in range(n):
triangular = n * (n+1) / 2
print "Triangular number", n, "via loop:", triangular
print "Triangular number", n, "via formula:", n * (n+1) / 2
###
### Problem 4
###
# DO NOT CHANGE THE FOLLOWING LINE
print "Problem 4 solution follows:"
n = 10
product = 1
for i in range(n):
product = product * (i + 1)
print "factorial=",product
###
### Problem 5
###
# DO NOT CHANGE THE FOLLOWING LINE
print "Problem 5 solution follows:"
n = 10
numlines = n
for i in range(n):
print 'factorial of', n, '='
n = n-1
product = 1
for i in range(n+1):
product = product * (i + 1)
print product
###
### Problem 6
###
# DO NOT CHANGE THE FOLLOWING LINE
print "Problem 6 solution follows:"
n = 10
recip = 0
for i in range(n):
if i > 0:
recip = (1.0/i) + recip
print recip
###
### Collaboration
###
# For this assignment I did not use any collaborators. However I did use the text
# a good deal in order to complete this assignment.
###
### Reflection
###
# This assignment has taken me some time because I thought I had submitted an updated copy to my git hub repository.
# I have made the corrections a second time. Initially I was having trouble with figuring out how to get parts two and six to output decimal reciprocals.
# I thought that this was a good assignment and that it contained everything that was necessary to complete the assignment.
| true |
498852c54abdaf2be80bfe67dc88c0490f5a8ae1 | chrisalexman/google-it-automation-with-python | /Crash Course in Python/Week_2/main.py | 2,822 | 4.1875 | 4 | # Data Types
x = 2.5
print(type(x))
print("\n")
# Expressions
length = 10
width = 5
area = length * width
print(area)
print("\n")
# Expressions, Numbers, and Type Conversions
print(7 + 8.5) # implicit conversion
print("a" + "b" + "c")
print("\n")
base = 6
height = 3
area = (base * height) / 2
print("Area: " + str(area)) # explicit conversion
print("\n")
total = 2048 + 4357 + 97658 + 125 + 8
files = 5
average = total / files
print("The average size is:" + str(average))
print("\n")
bill = 47.28
tip = bill * 0.15
total = bill + tip
share = total / 2
print("Each person needs to pay: " + str(share))
print("\n")
# Defining Functions
def greeting(name, dept):
print("Welcome, " + name)
print("You are part of " + dept)
greeting("Chris", "Parks Dept")
result = greeting("Andrew", "IT Dept")
print(result)
print("\n")
def get_seconds(hours, minutes, seconds):
return 3600 * hours + 60 * minutes + seconds
amount_a = get_seconds(2, 30, 0)
amount_b = get_seconds(0, 45, 15)
result = amount_a + amount_b
print(result)
print("\n")
def area_triangle(base, height):
return (base * height) / 2
area_a = area_triangle(5, 4)
area_b = area_triangle(7, 3)
the_sum = area_a + area_b
print("Sum is: " + str(the_sum))
print("\n")
def convert_seconds(sec):
hours = sec // 3600
minutes = (sec - hours * 3600) // 60
remaining_seconds = sec - hours * 3600 - minutes * 60
return hours, minutes, remaining_seconds
hours, minutes, seconds = convert_seconds(5000)
print(hours, minutes, seconds)
print("\n")
# Code Style
# 1. Self-Documenting: easy to read, understand
# 2. Refactoring: clear intent
# 3. Comment
def circle_area(radius):
pi = 3.14
area = pi * (radius ** 2)
print(area)
circle_area(5)
print("\n")
# Conditionals
# operations
print(10 > 1)
print("cat" == "dog")
print(1 != 2)
# print(1 < "1") # error here
# keywords: and or not
print(1 == "1")
print("cat" > "Cat")
print("Yellow" > "Cyan" and "Brown" > "Magenta") # alphabetical for strings, (T and F)
print(25 > 50 or 1 != 2)
print(not 42 == "Answer")
print("\n")
# branching
def hint_username(username):
if len(username) < 3:
print("Invalid username. Must be at least 3 characters long.")
elif len(username) > 15:
print("Invalid username. Must be at most 15 characters long.")
else:
print("Valid username.")
hint_username("Al")
hint_username("Edward")
hint_username("abcdefghijlmnopq")
print("\n")
def is_even(num):
if num % 2 == 0:
return True
return False
result = is_even(3)
print(result)
result = is_even(4)
print(result)
print("\n")
# Module
print("big" > "small")
def thesum(x, y):
return x + y
print(thesum(thesum(1, 2), thesum(3, 4)))
print((10 >= 5*2) and (10 <= 5*2))
| true |
cf2ed5f62e36f00f2f5dead043ceec03a21a5ab3 | AlexFeeley/RummyAIBot | /tests/test_card.py | 2,223 | 4.21875 | 4 | import unittest
from src.card import *
# Tests the card class using standard unit tests
# from src.card import Card
class TestCard(unittest.TestCase):
# Tests constructor returns valid suit and number of card created
def test_constructor(self):
card = Card("Hearts", 3)
self.assertEqual(card.get_suit(), 'Hearts', "Card constructor did not create a card of the correct suit")
self.assertEqual(card.get_number(), 3, "Card constructor did not create a card of the correct number")
# Tests constructor throws correct errors for invalid card construction
def test_constructor_bounds(self):
with self.assertRaises(ValueError):
Card("Hello World", 2)
with self.assertRaises(ValueError):
Card("Hearts", 0)
with self.assertRaises(ValueError):
Card("Hearts", 20)
# Find correct syntax for comparing namedtuples
# def test_get_card(self):
# card = Card("Hearts", 3)
# self.assertIsInstance(card.get_card(), Card())
# Tests correct suit is returned
def test_getSuit(self):
card = Card("Hearts", 3)
self.assertEqual(card.get_suit(), "Hearts", "Get suit returned the wrong suit")
self.assertNotEqual(card.get_suit(), "Spades", "Get suit returned the wrong suit")
# Tests corect number is returned
def test_getNumber(self):
card = Card("Hearts", 3)
self.assertEqual(card.get_number(), 3, "Get number returned the wrong number")
self.assertNotEqual(card.get_number(), 10, "Get number returned the wrong number")
# Tests == for two equal cards
def test_equals_true(self):
card1 = Card("Hearts", 3)
card2 = Card("Hearts", 3)
self.assertTrue(card1 == card2, "Equals operator did not return true for equal cards")
# Tests == for two unequal cards
def test_equals_false(self):
card1 = Card("Hearts", 3)
card2 = Card("Spades", 3)
card3 = Card("Hearts", 4)
self.assertFalse(card1 == card2, "Equals operator did not return false for cards with different numbers")
self.assertFalse(card1 == card3, "Equals operator did not return false for cards with different suits") | true |
de7296225ab80c6c325bd91d83eae0610115b263 | kvraiden/Simple-Python-Projects | /T3.py | 266 | 4.21875 | 4 | print('This a program to find area of a triangle')
#The formulae is 1/2 h*b
h = float(input("Enter the height of the triangle: "))
b = float(input("Enter the base of the triangle: "))
area = 1/2*h*b
print("The area of given triangle is %0.2f" % (area)+" unit.") | true |
b50f2c051b7ae0506cbc6f8a414d943ab3a20c51 | tristandaly/CS50 | /PSET6/mario/more/mario.py | 727 | 4.1875 | 4 | from cs50 import get_int
def main():
# Begin loop - continues until a number from 1-8 is entered
while True:
Height = get_int("Height: ")
if Height >= 1 and Height <= 8:
break
# Based on height, spaces are added to the equivalent of height - 1, subtracting with each row from the top
# Same rule applies to hash symbols, only one is added with each line
# Double-space is added at the end of each pyramid-half (after hash is printed) before right side is printed with same formula
for i in range(Height):
print(" "*(Height-i-1), end="")
print("#"*(i+1), end="")
print(" ", end="")
print("#"*(i+1))
if __name__ == "__main__":
main()
| true |
c8646e494885027bdf3819d0773b1ebb698db0a1 | fatih-iver/Daily-Coding-Interview-Solutions | /Question #7 - Facebook.py | 951 | 4.21875 | 4 | """
This problem was asked by Facebook.
Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded.
For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'.
You can assume that the messages are decodable. For example, '001' is not allowed.
"""
def decode(cipher):
length = len(cipher)
if length == 0:
return 1
elif length == 1:
return decode(cipher[1:])
else:
f2d = int(cipher[:2])
if f2d < 27:
return decode(cipher[1:]) + decode(cipher[2:])
return decode(cipher[1:])
def decode2(cipher, N, index = 0):
if N - index == 0:
return 1
elif N - index == 1:
return decode2(cipher, N, index + 1)
else:
f2d = int(cipher[:2])
if f2d < 27:
return decode2(cipher, N, index + 1) + decode2(cipher, N, index+2)
return decode2(cipher, N, index + 1)
print(decode("111"))
print(decode2("111", 3))
| true |
3e3f17c7877bf2001a9de9d48ca4b9652648bc1f | natepill/problem-solving | /PracticePython/Fibonacci.py | 490 | 4.25 | 4 | # Write a program that asks the user how many Fibonnaci numbers to generate and then generates them.
# Take this opportunity to think about how you can use functions.
# Make sure to ask the user to enter the number of numbers in the sequence to generate.
# (Hint: The Fibonnaci seqence is a sequence of numbers where the next number in the sequence is the sum of the previous two numbers
# in the sequence. The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …)
def Fibonnaci(number):
| true |
5e37fb9cff13522653e0e9006951e0db5839e259 | aarontinn13/Winter-Quarter-History | /Homework2/problem6.py | 938 | 4.3125 | 4 | def palindrome_tester(phrase):
#takes raw phrase and removes all spaces
phrase_without_spaces = phrase.replace(' ', '')
#takes phrase and removes all special characters AND numbers
phrase_alpha_numeric = ''.join(i for i in phrase_without_spaces if i.isalpha())
#takes phrase and transforms all upper case to lower case
phrase_all_lower_case = phrase_alpha_numeric.lower()
#incase my string was only numbers and special characters, I have a check.
if phrase_all_lower_case == '':
print'This is not a palindrome.'
#Final check to see if forward step is the same as reverse step.
else:
if phrase_all_lower_case == phrase_all_lower_case[::-1]:
print'This is a palindrome.\n'
else:
print'This is not a palindrome.\n'
#no loop since any 'break command' could be an input
string = raw_input('What is your word or phrase? ')
palindrome_tester(str(string))
| true |
bf26a7742b55fa080d22c1fadffccbf21ae9ce34 | aarontinn13/Winter-Quarter-History | /Homework3/problem7.py | 1,088 | 4.28125 | 4 | def centered_average_with_iteration(nums):
#sort list first
nums = sorted(nums)
if len(nums) > 2:
#remove last element
nums.remove(nums[-1])
#remove first element
nums.remove(nums[0])
#create total
total = 0.0
#iterate through and add all remaining in the list
for i in nums:
total += i
#take the total and divide by the length of list
average = ((total) / (len(nums)))
return float(average)
else:
return 'please enter at least three numbers in the list'
print(centered_average_with_iteration([1,2,3,4,5]))
def centered_average(nums):
#sort list first
nums = sorted(nums)
if len(nums) > 2:
#removing last element
nums.remove(nums[-1])
#removing first element
nums.remove(nums[0])
#taking sum of numbers and dividing by elements
average = sum(nums) / len(nums)
return float(average)
else:
return 'please enter at least three numbers in the list'
print(centered_average([3,4,5]))
| true |
4d80546ca7dfd20737f12f2dfddf3f9a0b5db00b | nip009/2048 | /twentyfortyeight.py | 2,776 | 4.125 | 4 | # Link to the problem: https://open.kattis.com/problems/2048
def printArr(grid):
for i in range(len(grid)):
row = ""
for j in range(len(grid[i])):
if(j != 3):
row += str(grid[i][j]) + " "
else:
row += str(grid[i][j])
print(row)
def transpose(l1):
'''
Takes a 2d list (a list of lists) and returns the transpose of that 2d list.
'''
l2 = []
for i in range(len(l1[0])):
row = []
for item in l1:
row.append(item[i])
l2.append(row)
return l2
def sortNonZeroValuesToTheRightAndMerge(grid):
'''
Sort non-zero values to the right side, and zeros to the left. Merge once afterwards.
As an example, the row [2, 0, 2, 0] will be sorted to [0, 0, 2, 2] and then merged to be [0, 0, 0, 4].
'''
for i in range(len(grid)):
for j, _ in reversed(list(enumerate(grid[i]))):
# Move numbers not equal to zero over to the right side.
grid[i].sort(key=lambda x: x != 0)
if(grid[i][j] == 0):
continue
if(j > 0 and grid[i][j-1] == grid[i][j]):
grid[i][j-1] *= 2
grid[i][j] = 0
return grid
def sortNonZeroValuesToTheLeftAndMerge(grid):
'''
Sort non-zero values to the left, and zeros to the right. Merge once afterwards.
As an example, the row [0, 2, 2, 0] will be sorted to [2, 2, 0, 0] and then merged to be [4, 0, 0, 0].
'''
for i in range(len(grid)):
for j in range(len(grid[i])):
grid[i].sort(key=lambda x: x != 0, reverse=True)
if(grid[i][j] == 0):
continue
if(j > 0 and grid[i][j-1] == grid[i][j]): # 2 2 0 0 -> 4 0 0 0
grid[i][j-1] *= 2
grid[i][j] = 0
return grid
def goLeft(grid):
grid = sortNonZeroValuesToTheLeftAndMerge(grid)
return grid
def goRight(grid):
grid = sortNonZeroValuesToTheRightAndMerge(grid)
return grid
def goUp(grid):
grid = transpose(grid)
grid = sortNonZeroValuesToTheLeftAndMerge(grid)
grid = transpose(grid)
return grid
def goDown(grid):
grid = transpose(grid)
grid = sortNonZeroValuesToTheRightAndMerge(grid)
grid = transpose(grid)
return grid
def runGame(move):
global grid
if move == 0: # left
return goLeft(grid)
elif move == 1: # up
return goUp(grid)
elif move == 2: # right
return goRight(grid)
elif(move == 3): # down
return goDown(grid)
grid = [[0 for i in range(4)] for j in range(4)]
for i in range(4):
inp = input().split(" ")
for j in range(4):
grid[i][j] = int(inp[j])
move = int(input())
grid = runGame(move)
printArr(grid)
| true |
e3ce4ff4dff53081b377cee46412ea42365651fa | digvijaybhakuni/python-playground | /pyListDictionaries/ch1-list.py | 2,221 | 4.1875 | 4 |
numbers = [5, 6, 7, 8]
print "Adding the numbers at indices 0 and 2..."
print numbers[0] + numbers[2]
print "Adding the numbers at indices 1 and 3..."
print numbers[1] + numbers[3]
"""
Replace in Place
"""
zoo_animals = ["pangolin", "cassowary", "sloth", "tiger"]
# Last night our zoo's sloth brutally attacked
#the poor tiger and ate it whole.
# The ferocious sloth has been replaced by a friendly hyena.
zoo_animals[2] = "hyena"
# What shall fill the void left by our dear departed tiger?
zoo_animals[3] = "sloth"
"""
Lenght and append
"""
suitcase = []
suitcase.append("sunglasses")
# Your code here!
suitcase.append("watch")
suitcase.append("shoes")
suitcase.append("pants")
list_length = len(suitcase) # Set this to the length of suitcase
print "There are %d items in the suitcase." % (list_length)
print suitcase
"""
List Slicing
"""
suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"]
first = suitcase[0:2] # The first and second items (index zero and one)
middle = suitcase[2:4] # Third and fourth items (index two and three)
last = suitcase[4:6] # The last two items (index four and five)
print first
print middle
print last
"""
Slicings Lists and String
"""
animals = "catdogfrog"
cat = animals[:3] # The first three characters of animals
dog = animals[3:6] # The fourth through sixth characters
frog = animals[6:] # From the seventh character to the end
"""
Maintaining Orders
"""
animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]
duck_index = animals.index("duck") # Use index() to find "duck"
animals.insert(duck_index, "cobra")
print animals # Observe what prints after the insert operation
"""
For One and all
"""
my_list = [1,9,3,8,5,7]
for number in my_list:
print number, " = ", number * 2
"""
More with 'For'
"""
start_list = [5, 3, 1, 2, 4]
square_list = []
for x in start_list:
square_list.append(x ** 2)
square_list.sort()
start_list.sort()
print start_list
print square_list
"""
How to remove
"""
backpack = ['xylophone', 'dagger', 'tent', 'bread loaf']
backpack.remove("dagger")
| true |
52c0773a6f69824b10bfe91e91d21acb1154012b | pmcollins757/check_sudoku | /check_sudoku.py | 2,091 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Author: Patrick Collins
"""
# Sudoku puzzle solution checker that takes as input
# a square list of lists representing an n x n
# sudoku puzzle solution and returns the boolean
# True if the input is a valid
# sudoku square solution and returns the boolean False
# otherwise.
# A valid sudoku square solution satisfies these
# two properties:
# 1. Each column of the square contains
# each of the whole numbers from 1 to n exactly once.
# 2. Each row of the square contains each
# of the whole numbers from 1 to n exactly once.
# Assuming the the input is square and contains at
# least one row and one column.
correct = [[1,2,3],
[2,3,1],
[3,1,2]]
incorrect = [[1,2,3,4],
[2,3,1,3],
[3,1,2,3],
[4,4,4,4]]
incorrect2 = [[1,2,3,4],
[2,3,1,4],
[4,1,2,3],
[3,4,1,2]]
incorrect3 = [[1,2,3,4,5],
[2,3,1,5,6],
[4,5,2,1,3],
[3,4,5,2,1],
[5,6,4,3,2]]
incorrect4 = [['a','b','c'],
['b','c','a'],
['c','a','b']]
incorrect5 = [ [1, 1.5],
[1.5, 1]]
incorrect6 = [[0,1,2],
[2,0,1],
[1,2,0]]
def check_sudoku(puzzle):
sqr_size = len(puzzle)
column_puzzle = zip(*puzzle)
for row in puzzle:
for x in row:
if not isinstance(x, int) or x > sqr_size or x < 1:
return False
if sum(row) != sum(set(row)):
return False
for column in column_puzzle:
if sum(column) != sum(set(column)):
return False
return True
print check_sudoku(correct), "True"
#>>> True
print check_sudoku(incorrect), "False"
#>>> False
print check_sudoku(incorrect2), "False2"
#>>> False
print check_sudoku(incorrect3), "False3"
#>>> False
print check_sudoku(incorrect4), "False4"
#>>> False
print check_sudoku(incorrect5), "False5"
#>>> False
print check_sudoku(incorrect6), "False6"
#>>> False
| true |
60950955c5fcd3bc7a7410b78c3be383feb7e9ed | marcotello/PythonPractices | /Recursion/palindrome.py | 1,696 | 4.4375 | 4 | def reverse_string(input):
"""
Return reversed input string
Examples:
reverse_string("abc") returns "cba"
Args:
input(str): string to be reversed
Returns:
a string that is the reverse of input
"""
# TODO: Write your recursive string reverser solution here
if len(input) == 0:
return ""
else:
first_char = input[0]
the_rest = slice(1, None)
sub_string = input[the_rest]
reversed_substring = reverse_string(sub_string)
return reversed_substring + first_char
def is_palindrome(input):
"""
Return True if input is palindrome, False otherwise.
Args:
input(str): input to be checked if it is palindrome
"""
# TODO: Write your recursive palindrome checker here
reversed_str = reverse_string(input)
if reversed_str == input:
return True
else:
return False
'''
# Solution
def is_palindrome(input):
"""
Return True if input is palindrome, False otherwise.
Args:
input(str): input to be checked if it is palindrome
"""
if len(input) <= 1:
return True
else:
first_char = input[0]
last_char = input[-1]
# sub_input is input with first and last char removed
sub_input = input[1:-1]
return (first_char == last_char) and is_palindrome(sub_input)
'''
# Test Cases
print ("Pass" if (is_palindrome("")) else "Fail")
print ("Pass" if (is_palindrome("a")) else "Fail")
print ("Pass" if (is_palindrome("madam")) else "Fail")
print ("Pass" if (is_palindrome("abba")) else "Fail")
print ("Pass" if not (is_palindrome("Udacity")) else "Fail") | true |
a26b16019c44c2ff2ea44916bcc3fa66a62a826e | marcotello/PythonPractices | /P0/Task1.py | 2,427 | 4.3125 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 1:
How many different telephone numbers are there in the records?
Print a message:
"There are <count> different telephone numbers in the records."
"""
def get_unique_numbers(numbers, numbers_set):
"""
This function returns a set of unique numbers
INPUT:
numbers: a list of numbers with the following format on each element ["number1", "number 2" ... more elements].
numbers_set: the set where the unique numbers are stored.
RETURN: a set with unique numbers.
"""
# iterating the list to get the numbers - O(n)
# this has a complexity of O(n), because it is iterating over the whole list.
for number in numbers:
# getting the fist element of each record and storing it on the Set - O(1)
numbers_set.add(number[0])
# getting the second element of each record and storing it on the Set - O(1)
numbers_set.add(number[1])
# returning the set of unique numbers - O(1)
return numbers_set
def main():
# I have chosen set as my data collection because for this problem the order doesn't matter. Set holds unique hashable object like strings.
# Creating the set - O(1)
numbers_set = set()
# calling get_unique_numbers function - O(n)
numbers_set = get_unique_numbers(calls, numbers_set)
# calling get_unique_numbers function - O(n)
numbers_set = get_unique_numbers(texts, numbers_set)
# printing the len of the set - O(3)
print("There are {} different telephone numbers in the records.".format(len(numbers_set)))
if __name__ == "__main__":
main()
"""
# UNIT TESTING
# get_unique_numbers test
test_list1 = [["(022)39006198", "98440 65896"], ["90087 42537", "(080)35121497"],
["(044)30727085", "90087 42537"], ["90087 42537", "(022)39006198"]]
assert(len(get_unique_numbers(test_list1, set())) == 5)
test_list2 = [["(022)39006198", "98440 65896"], ["(022)39006198", "98440 65896"],
["98440 65896", "(022)39006198"], ["98440 65896", "(022)39006198"]]
assert(len(get_unique_numbers(test_list2, set())) == 2)
print("test for get_unique_numbers passed")
""" | true |
2252d7e3ea30fe49636bbeeb50f6c3b3c7fdf80d | marcotello/PythonPractices | /DataStrucutures/Linked_lists/flattening_linked_list.py | 1,622 | 4.125 | 4 | # Use this class as the nodes in your linked list
class Node:
def __init__(self, value):
self.value = value
self.next = None
def __repr__(self):
return str(self.value)
class LinkedList:
def __init__(self, head):
self.head = head
def append(self, value):
if self.head is None:
self.head = Node(value)
return
node = self.head
while node.next is not None:
node = node.next
node.next = Node(value)
def to_list(linked_list, lst):
node = linked_list.head
while node:
lst.append(node.value)
node = node.next
return lst
def merge(list1, list2):
# TODO: Implement this function so that it merges the two linked lists in a single, sorted linked list.
temp_list = []
# merged_list = None
temp_list = to_list(list1, temp_list)
temp_list = to_list(list2, temp_list)
temp_list.sort()
llist = LinkedList(Node(temp_list[0]))
index = 1
while index < len(temp_list):
llist.append(temp_list[index])
return llist
class NestedLinkedList(LinkedList):
def flatten(self):
# TODO: Implement this method to flatten the linked list in ascending sorted order.
# First Test scenario
linked_list = LinkedList(Node(1))
linked_list.append(3)
linked_list.append(5)
nested_linked_list = NestedLinkedList(Node(linked_list))
second_linked_list = LinkedList(Node(2))
second_linked_list.append(4)
nested_linked_list.append(Node(second_linked_list))
merge(linked_list, second_linked_list) | true |
1543e31bbe36f352dd18b284bd9fc688332e9486 | LucasBeeman/Whats-for-dinner | /dinner.py | 1,446 | 4.40625 | 4 | import random
ethnicity = [0, 1, 2, 3]
type_choice = -1
user_choice = input("Which ethnnic resturaunt would you like to eat at? Italian(1), Indian(2), Chinese(3), Middle Eastern(4), Don't know(5)")
#if the user pick I dont know, the code will pick one for them through randomness
if user_choice.strip() == "5":
type_choice = random.choice(ethnicity)
#change "ethnicity" to a string stating what the ethnicity is, this is for the print later on. add a list of at least 3 rasturants of that ethnicity
if type_choice == 0 or user_choice.strip() == "1":
ethnicity = "italian"
place = ["Bruno Bros", "Belleria", "Bella Napoli"]
elif type_choice == 1 or user_choice.strip() == "2":
ethnicity = "Indian"
place = ["Cafe India", "Bombay Curry and Grill", "Kabab and Curry"]
elif type_choice == 2 or user_choice.strip() == "3":
ethnicity = "Chinese"
place = ["Main Moon", "Hunan Express", "Imperial Graden"]
elif type_choice == 3 or user_choice.strip() == "4":
ethnicity = "Middle Eastern"
place = ["Zenobia", "Ghossain's", "sauceino"]
#error handeling
else:
print("ERROR")
#if the user said that they don't know, state what ethnicity the resturant is
if type_choice is not -1:
print("your ethnicity is", ethnicity)
#prints the random reasturaunt from the list of 3 resturants, then prints it out
place_choice = random.choice(place)
print("your going to", str(place_choice) + "!") | true |
9f60c2a26e4ea5bf41c310598568ea0b532c167b | Rajeshinu/bitrm11 | /4.Stringcount.py | 231 | 4.25 | 4 | """Write a program that asks the user for a string
and returns an estimate of how many words are in the string"""
string=input("Please enter the string to count the number of words in the string\n")
c=string.count(" ")
print(c+1)
| true |
42bd0e1748a8964afe699112c9d63bc45cd421f3 | Rajeshinu/bitrm11 | /8.Numbersformat.py | 347 | 4.125 | 4 | """Write a program that asks the user for a large integer and inserts commas into it according
to the standard American convention for commas in large numbers. For instance,
if the user enters 1000000, the output should be 1,000,000"""
intnum=int(input(print("Please enter the large integer number : ")))
fnum=format((intnum),',d')
print(fnum)
| true |
50531ecdd319b058d9c2fe98b17a76a1392f85bf | Aqib04/tathastu_week_of_code | /Day4/p1.py | 306 | 4.21875 | 4 | size = int(input("Enter the size of tuple: "))
print("Enter the elements in tuple one by one")
arr = []
for i in range(size):
arr.append(input())
arr = tuple(arr)
element = input("Enter the element whose occurrences you want to know: ")
print("Tuple contains the element", arr.count(element), "times")
| true |
058d1ae6fa21662f7bac3d3e05ef0aedfdbe14b2 | gneelimavarma/practicepython | /C-1.19.py | 340 | 4.4375 | 4 | ##C-1.19 Demonstrate how to use Python’s list comprehension syntax to produce
##the list [ a , b , c , ..., z ], but without having to type all 26 such
##characters literally.
##ascii_value = ord('a')
##print(ascii_value)
i=0
start = 97 ##ascii of 'a'
result = []
while(i<26):
result.append(chr(start+i))
i+=1
print(result)
| true |
0396e783aca5febe373e32fc544dead5a5817760 | marbor92/checkio_python | /index_power.py | 367 | 4.125 | 4 | # Function finds the N-th power of the element in the array with the index N.
# If N is outside of the array, then return -1.
def index_power(my_list, power) -> int:
pos = 0
index = []
for i in my_list:
index.append(pos)
pos += 1
if power not in index:
ans = -1
else:
ans = my_list[power] ** power
return ans
| true |
2c455ec9c2bbd31d79aa5a3b69c4b9b17c25b7a7 | whalenrp/IBM_Challenge | /SimpleLearner.py | 1,584 | 4.125 | 4 | import sys
import math
import csv
from AbstractLearner import AbstractLearner
class SimpleLearner(AbstractLearner):
"""
Derived class implementation of AbstractLearner. This class implements the learn()
and classify() functions using a simple approach to classify all as true or false
"""
def __init__(self, trainingInputFile, testInputFile, isMachineReadable, outputFile):
AbstractLearner.__init__(self, trainingInputFile, testInputFile,
isMachineReadable, outputFile)
#global variable for classification of data, default false
self.classification = False
def learn(self):
"""
Creates a classification model based on data held in the AbstractLearner's
trainingData list-of-lists
"""
numRows = len(self.trainingData)
numTrue = 0
numFalse = 0
#get number of true and false elements in the data
for i in range(numRows):
if self.trainingData[i][-1]:
numTrue += 1
else:
numFalse += 1
#if there are more trues, set classification to true, otherwise it will be false
if numTrue >= numFalse:
self.classification = True
def classify(self):
"""
Based on the classification model generated by learn(), this function will read from
the testData list-of-lists in AbstractLearner and output the prediction for each
variable
"""
#create a csv writer for output
myWriter = csv.writer(open(self.outputFile, "wb"))
#if classification is true
if self.classification:
numRows = len(self.testData)
#write index of all rows, since all are true
for i in range(numRows):
myWriter.writerow([i])
sys.exit(0)
| true |
d272fde739325284f99d1f148d1603d739d24721 | ganesh28gorli/Fibonacci-series | /fibonacci series.py | 678 | 4.4375 | 4 | #!/usr/bin/env python
# coding: utf-8
# # fibonacci series
# In[15]:
# n is the number of terms to be printed in fibonacci series
# In[16]:
n = int(input("enter number of terms: "))
# In[17]:
# assigning first two terms of the sequence
# In[18]:
a=0
b=1
# In[19]:
#checking if the number of terms of sequence(n), given by the user is valid or not.if number is valid the fibinacci sequence.
# In[20]:
if n<=0:
print("enter number greater than zero")
print(a)
elif n == 1:
print(a)
else:
print(a)
print(b)
for i in range(2,n):
c=a+b
a=b
b=c
print(c)
# In[ ]:
# In[ ]:
| true |
aef6477c03006ff40a937946213ea05c1ec11106 | ta11ey/algoPractice | /algorithms/linkedList_insertionSort.py | 1,088 | 4.3125 | 4 | # Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head.
# The steps of the insertion sort algorithm:
# Insertion sort iterates, consuming one input element each repetition and growing a sorted output list.
# At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there.
# It repeats until no input elements remain.
from algoPractice.dataStructures.ListNode import ListNode
def dummyInsert(head: ListNode, item: ListNode):
dummy = ListNode()
current = dummy
current.next = head
while current.next and current.next.val < item.val:
current = current.next
item = ListNode(item.val, current.next)
current.next = item
return dummy.next
def exec(head):
# sorted part
sortedHead = ListNode(head.val, None)
# Current
current = head
# Unsorted
while current.next is not None:
sortedHead = dummyInsert(sortedHead, current.next)
current = current.next
return sortedHead
| true |
084cb1de7fece4e3f74452233bd61c03af0812b8 | amitp-ai/Resources | /leet_code.py | 1,353 | 4.65625 | 5 | #test
"""
Syntax for decorators with parameters
def decorator(p):
def inner_func():
#do something
return inner_func
@decorator(params)
def func_name():
''' Function implementation'''
The above code is equivalent to
def func_name():
''' Function implementation'''
func_name = (decorator(params))(func_name) #same as decorator(params)(func_name)
As the execution starts from left to right decorator(params) is called which returns a function object fun_obj.
Using the fun_obj the call fun_obj(fun_name) is made. Inside the inner function, required operations are performed and
the actual function reference is returned which will be assigned to func_name. Now, func_name() can be used to call the function
with decorator applied on it.
"""
# Decorators with parameters in Python
def big_func(dumy):
print(dumy)
return func1
def func1(x):
print('xxxxx')
print(x)
big_func('zzzz')(2)
@big_func('zzz')
def func1(x):
print(x)
print('1'*50)
def decorator(*args, **kwargs):
print("Inside decorator")
def inner(func):
print("Inside inner function")
print("I like", kwargs['like'])
return func
return inner
@decorator(like = "geeksforgeeks")
def func():
print("Inside actual function")
func()
print('2'*50)
decorator(like = "geeksforgeeks")(func)()
| true |
fb55395ee175bdce797e17f48c6c04d7f2c574a2 | dukeofdisaster/HackerRank | /TimeConversion.py | 2,484 | 4.21875 | 4 | ###############################################################################
# TIME CONVERSION
# Given a time in 12-hour am/pm format, convert it to military (24-hr) time.
#
# INPUT FORMAT
# A single string containing a time in 12-hour clock format (hh:mm:ssAM or
# hh:mm:ssPM) wehre 01 <= hh <= 12 and 00 <= mm, ss <= 59
#
# OUTPUT FORMAT
# Convert and print given time in 24hr format where 00 <= hh <= 23
###############################################################################
# Note: We have several options for figuring out how to tackle this problem. At
# first look it might seem like we can use the 're' library, to find a matching
# sequence in the time string, i.e. "AM" or "PM"...which is nice, but also more
# complicated than we need the problem to be.
#
# We've seen that HackerRank likes to use the split() function, what if we used
# it ourselves to split our time string into 3 separate strings, based on the
# fact that the format of the string is somewhat split itself by the colon ':'?
#
# This method works. We can declare multiple variables in the same line by
# using commas, so a,b,c = time.split(':') works just fine because splitting
# the time string by the two colons creates 3 separate substrings.The first two
# of these substrings will be easy to work with because they are numbers, so
# type casting them with int() will be easy.but the last string still contains
# AM or PM. How can we separate the numbers from the letters?
# The next useful method will be slicing. we can slice a string x using the
# format: myString[int:int], which will create a substring from the left value
# to the right value based on what you give the string. [:2] will return the
# first two values of the string, while [2:] will return the values between the
# second character all the way to the end of the string... i.e. all but the 1st
# two. so we can create two sub values from the c string by slicing and storing
# these values as aORp (am or pm) and seconds.
import sys
time = raw_input().strip()
a,b,c = time.split(':')
aORp = c[2:]
seconds= c[:2]
if aORp[0] == 'A':
if a == '12':
print('00'+':'+b+':'+seconds)
else:
print(a+':'+b+':'+seconds)
# For PM, we use two type casts: first we typecast a to an int so we can
# do the conversion to 24 time, which consists of adding 12 to the time
elif aORp[0] == 'P':
if a == '12':
print (a+':'+b+':'+seconds)
else:
print(str((int(a)+12))+':'+b+':'+seconds)
| true |
f7c35cd71de55bd957da4338110c3343918c641d | Dr-A-Kale/Python-intro | /str_format.py | 669 | 4.125 | 4 | #https://python.swaroopch.com/basics.html
age = 20
name = 'Swaroop'
print('{0} was {1} years old when he wrote this book'.format(name, age))
print('Why is {0} playing with that python?'.format(name))
print(f'{name} was {age} years old when he wrote this book')
print(f'Why is {name} playing with that python?')
print("What's your name?")
print('What\'s your name?')
# This line is being left as a space for jokes.
print("Bond said \"hi my name is james\"") # The use of backslash as an escape sequence
# Below is an example of a two-line string using \n
print("This is the first line\nThis is the second line")
print("This is the first line\tThis is the second line")
| true |
03b4609e13f7b1f3bafbdc8c9ffc83e04ca49b04 | KartikeyParashar/FunctionalPrograms | /LeapYear.py | 322 | 4.21875 | 4 | year = int(input("Enter the year you want to check that Leap Year or not: "))
if year%4==0:
if year%100==0:
if year%400==0:
print("Yes it is a Leap Year")
else:
print("Not a Leap Year")
else:
print("Yes it is a Leap Year")
else:
print("No its not a Leap Year") | true |
169d013c1c226c53da4c2e5d0fa6444d7f8bb087 | natalya-patrikeeva/interview_prep | /binary-search.py | 1,672 | 4.3125 | 4 | """You're going to write a binary search function.
You should use an iterative approach - meaning
using loops.
Your function should take two inputs:
a Python list to search through, and the value
you're searching for.
Assume the list only has distinct elements,
meaning there are no repeated values, and
elements are in a strictly increasing order.
Return the index of value, or -1 if the value
doesn't exist in the list."""
def binary_search(input_array, value):
count = 0
while len(input_array) > 1:
array = input_array
length = len(input_array)
# Even number of elements
if length % 2 == 0:
half_index = length / 2
if value > input_array[half_index - 1]:
input_array = input_array[half_index:]
count += half_index
elif value < input_array[half_index - 1]:
input_array = input_array[:half_index]
else:
count += half_index - 1
return count
# Odd number of elements
else:
half_index = (length - 1 ) / 2
if value > input_array[half_index]:
input_array = input_array[half_index + 1:]
count += half_index + 1
elif value < input_array[half_index]:
input_array = input_array[:half_index]
else:
count += half_index
return count
if value == input_array[0]:
return count
else:
return -1
test_list = [1,3,9,11,15,19,29]
test_val1 = 25
test_val2 = 15
print binary_search(test_list, test_val1)
print binary_search(test_list, test_val2)
| true |
eed9c8739eb2daa6ecbc47e10693e3d9b1970d82 | sarthakjain95/UPESx162 | /SEM I/CSE/PYTHON CLASS/CLASSx8.py | 1,757 | 4.71875 | 5 | # -*- coding: utf-8 -*-
#! /usr/bin/env python3
# Classes and Objects
# Suppose there is a class 'Vehicles'
# A few of the other objects can be represented as objects/children of this super class
# For instance, Car, Scooter, Truck are all vehicles and can be denoted as a derivative
# of the class 'Vehicle'
# Furthermore, these derived objects can have some other properties that are unique to
# them and are not available in the super class.
# Superclass - Baseclass
# 'Subclasses' derive properties from the super class
class MeClass:
print("\nIn Class")
x=32
foo= MeClass()
print(foo)
print(foo.x)
class FirstClass:
print("Inside Class")
def __init__(self, prop):
print("Inside Init function")
self.x= prop
foo= FirstClass(45)
print(foo)
print(foo.x,'\n')
class Person:
# Assignment of values to the properties of the objects created is done
# inside the init function.
def __init__(self, name, age, city):
self.name= name
self.age= age
self.city= city
def introduceInSpanish(self):
print("Hola! Me llamo "+self.name)
# Treating Ramesh as an object.
ramesh= Person("Ramesh", 32, "Noida")
print( "Name:", ramesh.name )
print( "Age: ", ramesh.age )
print( "City:", ramesh.city )
ramesh.introduceInSpanish()
# To reassign/modify any propert of an object
# Object.Property= NewValue
ramesh.age= 55
print( "\nNew Age: ", ramesh.age )
# Let's delete his name from records.
del ramesh.name
# Gives out error. No attribute 'name'
# print( ramesh.name )
print( ramesh.__dict__ )
print("\nYou know what? I don't really like ramesh.")
print("Let's delete him.")
del ramesh
print("Deleted.")
try:
print("Trying to access ramesh ...")
print( ramesh.__dict__ )
except:
print("There was an error. There's no ramesh.")
| true |
f0cf8343b7cb9293b5ecea2532953d0ca0b55d49 | devaljansari/consultadd | /1.py | 1,496 | 4.59375 | 5 | """Write a Python program to print the following string in a specific
format (see the output).
Sample String :
"Twinkle, twinkle, little star,
How I wonder what you are!
Up above the world so high,
Like a diamond in the sky.
Twinkle, twinkle, little star,
How I wonder what you are"""
print ("Trial 1 is :")
print()
print("Twinkle, twinkle, little star, \n\tHow I wonder what you are! \n\t\tUp above the world so high, \n\t\tLike a diamond in the sky. \nTwinkle, twinkle, little star, \n\tHow I wonder what you are!")
print()
print()
print ("Trial 2 is :")
print()
print("Twinkle, twinkle, little star, \n")
print(" How I wonder what you are! \n")
print(" Up above the world so high, \n")
print(" Like a diamond in the sky. \n")
print("Twinkle, twinkle, little star, \n")
print(" How I wonder what you are!")
print();print()
print ("Trial 3 is :")
print()
print("Twinkle, twinkle, little star, \
\n\tHow I wonder what you are! \
\n\t\tUp above the world so high,\
\n\t\tLike a diamond in the sky.\
\nTwinkle, twinkle, little star,\
\n\tHow I wonder what you are!")
print()
print()
print ("Trial 4 is :")
print()
print("Twinkle, twinkle, little star, \n")
print("\tHow I wonder what you are! \n")
print("\t\tUp above the world so high, \n")
print("\t\tLike a diamond in the sky. \n")
print("Twinkle, twinkle, little star, \n")
print("\tHow I wonder what you are!") | true |
2b18385f2dc36a87477c3e7df27ff8bd2a988c33 | heet-gorakhiya/Scaler-solutions | /Trees/Trees-1-AS_inorder_traversal.py | 1,783 | 4.125 | 4 | # Inorder Traversal
# Problem Description
# Given a binary tree, return the inorder traversal of its nodes values.
# NOTE: Using recursion is not allowed.
# Problem Constraints
# 1 <= number of nodes <= 10^5
# Input Format
# First and only argument is root node of the binary tree, A.
# Output Format
# Return an integer array denoting the inorder traversal of the given binary tree.
# Example Input
# Input 1:
# 1
# \
# 2
# /
# 3
# Input 2:
# 1
# / \
# 6 2
# /
# 3
# Example Output
# Output 1:
# [1, 3, 2]
# Output 2:
# [6, 1, 3, 2]
# Example Explanation
# Explanation 1:
# The Inorder Traversal of the given tree is [1, 3, 2].
# Explanation 2:
# The Inorder Traversal of the given tree is [6, 1, 3, 2].
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param A : root node of tree
# @return a list of integers
def inorderTraversal(self, A):
from queue import LifoQueue
# Recursive solution
# if not A:
# return
# self.inorderTraversal(A.left)
# # ans_arr.append(A.val)
# print(A.val)
# self.inorderTraversal(A.right)
# Iterative Solution using stack
curr_node = A
ans_arr = []
stack = LifoQueue()
while True:
if curr_node:
stack.put(curr_node)
curr_node = curr_node.left
else:
if not stack.empty():
temp = stack.get()
ans_arr.append(temp.val)
curr_node = temp.right
else:
return ans_arr | true |
459ee1c60423011457183df6e5a897df77b7b62d | ani07/Coding_Problems | /project_euler1.py | 491 | 4.28125 | 4 | """
This solution is based on Project Euler Problem Number 1.
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
class MultiplesThreeFive():
def multiples(self):
sum = 0
for i in range(1000):
if i % 3 == 0 or i % 5 == 0:
sum += i
return sum
ans = MultiplesThreeFive()
print(ans.multiples())
| true |
5d401b278b9e481bc02bfd5c57cedcbf945b9104 | DeepakMe/Excellence-Technologies- | /QONE.py | 309 | 4.15625 | 4 | # Question1
# Q1.Write a function which returns sum of the list of numbers?
# Ans:
list1 = [1,2,3,4]
def Sumlist(list,size):
if (size==0):
return 0
else:
return list[size-1]+Sumlist(list,size-1)
total = Sumlist(list1,len(list1))
print("Sum of given elements in List: ",total) | true |
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 |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.