blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
35a0fdd29e629a3e4bd1e795d6a7de6805243aaa
DayGitH/Python-Challenges
/DailyProgrammer/20120219A.py
491
4.4375
4
''' The program should take three arguments. The first will be a day, the second will be month, and the third will be year. Then, your program should compute the day of the week that date will fall on. ''' import datetime day_list = {0: 'Monday', 1: 'Tuesday', 2: 'Wednesday', 3: 'Thursday', 4: 'Friday', 5: 'Saturday', 6: 'Sunday'} year = int(input('Year >> ')) month = int(input('Month >> ')) day = int(input('Day >> ')) print(day_list[datetime.date(year, month, day).weekday()])
true
ea8e85c489477c5736dbbaa83c565228543da9e4
seesiva/ML
/lpthw/newnumerals.py
1,169
4.65625
5
""" Your Informatics teacher at school likes coming up with new ways to help you understand the material. When you started studying numeral systems, he introduced his own numeral system, which he's convinced will help clarify things. His numeral system has base 26, and its digits are represented by English capital letters - A for 0, B for 1, and so on. The teacher assigned you the following numeral system exercise: given a one-digit number, you should find all unordered pairs of one-digit numbers whose values add up to the number. Example For number = 'G', the output should be newNumeralSystem(number) = ["A + G", "B + F", "C + E", "D + D"]. Translating this into the decimal numeral system we get: number = 6, so it is ["0 + 6", "1 + 5", "2 + 4", "3 + 3"]. """ def newNumeralSystem(number): letter=number.upper() alphabet = list('abcdefghijklmnopqrstuvwxyz'.upper()) numeral=alphabet.index(letter) newNumeral=[] for i in range(0,(numeral/2)+1): print i print i+numeral newNumeral.append(alphabet[i]+" + "+alphabet[numeral-i]) return newNumeral if __name__=="__main__": print newNumeralSystem("g")
true
5514cb1b4588c60ba18477693747381d99b2073f
seesiva/ML
/lpthw/ex20.py
777
4.28125
4
""" Given a string, , of length that is indexed from to , print its even-indexed and odd-indexed characters as space-separated strings on a single line (see the Sample below for more detail). Note: is considered to be an even index. """ import sys if __name__=="__main__": string_list=[] T=int(raw_input()) for i in range (0,T): inputstring=raw_input() string_list.append(inputstring) for i in range (0,T): even="" odd="" #print i #print string_list[i] for j, char in enumerate(string_list[i]): print j if j % 2 == 0: #print char even=even+char else: #print char odd=odd+char print even, odd
true
9958b0569eea52042d347d1e977137d3fff8ffc8
seesiva/ML
/lpthw/euclids.py
357
4.125
4
""" Compute the greatest common divisor of two non-negative integers p and q as follows: If q is 0, the answer is p. If not, divide p by q and take the remainder r. The answer is the greatest common divisor of q and r. """ def gcd(p,q): if q==0: return p else: r=p % q return r if __name__=="__main__": print gcd(13,2)
true
953469d38c6689be6f48986e855b6b3c6881aa56
seesiva/ML
/lpthw/ex9.py
698
4.21875
4
""" Higher Order Functions HoF:Function as a return value """ def add_two_nums(x,y): return x+y def add_three_nums(x,y,z): return x+y+z def get_appropriate_function(num_len): if num_len==3: return add_three_nums else: return add_two_nums if __name__=="__main__": args = [1,2,3] num_len=len(args) res_function=get_appropriate_function(num_len) print(res_function) # when length is 3 print (res_function(*args)) # Addition according to 3 params args = [1,2] num_len=len(args) res_function=get_appropriate_function(num_len) print(res_function) # when length is 2 print (res_function(*args)) # Addition according 2 parameters
true
ca138f087a7cdadb84ea054df8fff44596fc265d
AdishiSood/The-Joy-of-Computing-using-Python
/Week 4/Factorial.py
285
4.28125
4
""" Given an integer number n, you have to print the factorial of this number. Input Format: A number n. Output Format: Print the factorial of n. Example: Input: 4 Output: 24 """ k = int(input()) fac = 1 for i in range(1,k+1): if(k==0): break fac=fac*i print(fac)
true
76651f9226b584f4a7a0dfe0f1ceeb338ba0e2ae
AdishiSood/The-Joy-of-Computing-using-Python
/Week 12/Sentence.py
807
4.21875
4
""" Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalised. Input Format: The first line of the input contains a number n which represents the number of line. From second line there are statements which has to be converted. Each statement comes in a new line. Output Format: Print statements with each word in capital letters. Example: Input: 2 Hello world Practice makes perfect Output: HELLO WORLD PRACTICE MAKES PERFECT """ n=int(input()) for i in range(n): print(input().upper(),end="") if i!=n-1: print() or lines = [] n = int(input()) for i in range(n): s = input() if s: lines.append(s.upper()) else: break; for sentence in lines: print(sentence)
true
82401ab5f1d228c0312819a08859994363fdce4f
AdishiSood/The-Joy-of-Computing-using-Python
/Week 9/First and Last.py
470
4.21875
4
""" Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string. If the string length is less than 2, return instead of the empty string. Input Format: The first line of the input contains the String S. Output Format: The first line of the output contains the modified string. Sample Input: Programming Sample Output: Prng """ s=input() output="" if(len(s)<2): print("",end="") else: print(s[0:2]+s[-2:-1]+s[-1],end="")
true
e588bbb9899fa27aa4ee92fc9825a38ee626259e
kildarejoe1/CourseWork_Lotery_App
/app.py
1,859
4.15625
4
#Udemy Course Work - Lottery App #Import the random class import random def menu(): """Controlling method that 1. Ask players for numbers 2. Calculate the lottery numbers 3. Print out the winnings """ players_numbers = get_players_numbers() lottery_numbers = create_lottery_numbers() if len(players_numbers.intersection(lottery_numbers)) == 1: print("Congratulations, you have won 10 Euro!!!") elif len(players_numbers.intersection(lottery_numbers)) == 2: print("Congratulations, you have won 20 Euro!!!") elif len(players_numbers.intersection(lottery_numbers)) == 3: print("Congratulations, you have won 30 Euro!!!") elif len(players_numbers.intersection(lottery_numbers)) == 4: print("Congratulations, you have won 40 Euro!!!") elif len(players_numbers.intersection(lottery_numbers)) == 5: print("Congratulations, you have won 50 Euro!!!") elif len(players_numbers.intersection(lottery_numbers)) == 6: print("Congratulations, you have won it all!!!") else: print("Sorry, you have won nothing!!!") #Get the Lottery numbers def get_players_numbers(): numbers = str( raw_input("Enter the numbers separated by commas: ")) #Now split the string into a list using the string split method numbers_in_list=numbers.split(",") #Now get a set of numbers instead of list of string by using set comprehension, same as list just returns a set. numbers_in_set={int(x) for x in numbers_in_list} #Now return a set from the invoking call return numbers_in_set #Lottery calaculates 6 random nubers def create_lottery_numbers(): lottery_num=set() for x in range(6): lottery_num.add(random.randint(1,100)) #Prints a random number between 1 and 100 return lottery_num if __name__ == "__main__": menu()
true
88e0893f2afce21f3eae1cf65e1cef3a833f09b2
outcoldman/codeinterview003
/2013/cracking/01-02.py
426
4.15625
4
# coding=utf8 # Write code to reverse a C-Style String. (C-String means that "abcd" is represented as five characters, including the null character.) def reverse_string(str): buffer = list(str) length = len(buffer) for i in xrange(length / 2): t = buffer[i] buffer[i] = str[length - i - 1] buffer[length - i - 1] = t return "".join(buffer) print "Result %s" % reverse_string("abcde")
true
c73a54771e27fb298a73d595b5d925514f68e6cc
prashantchanne12/Leetcode
/find the first k missing positive numbers.py
1,383
4.125
4
''' Given an unsorted array containing numbers and a number ‘k’, find the first ‘k’ missing positive numbers in the array. Example 1: Input: [3, -1, 4, 5, 5], k=3 Output: [1, 2, 6] Explanation: The smallest missing positive numbers are 1, 2 and 6. Example 2: Input: [2, 3, 4], k=3 Output: [1, 5, 6] Explanation: The smallest missing positive numbers are 1, 5 and 6. Example 3: Input: [-2, -3, 4], k=2 Output: [1, 2] Explanation: The smallest missing positive numbers are 1 and 2. ''' def find_first_k_missing_positive(nums, k): n = len(nums) i = 0 while i < n: j = nums[i] - 1 if nums[i] > 0 and nums[i] <= n and nums[i] != nums[j]: # swap nums[i], nums[j] = nums[j], nums[i] else: i += 1 missing_numbers = [] extra_numbers = set() for i in range(n): if len(missing_numbers) < k: if nums[i] != i + 1: missing_numbers.append(i+1) extra_numbers.add(nums[i]) # add the remaining numbers i = 1 while len(missing_numbers) < k: candidate_number = i + n # ignore if the extra_array contains the candidate number if candidate_number not in extra_numbers: missing_numbers.append(candidate_number) i += 1 print(missing_numbers) find_first_k_missing_positive([2, 3, 4], 3)
true
5718a2011b7dcd969516e4c3f2b24b2cebfa713b
prashantchanne12/Leetcode
/reverse linked list.py
1,355
4.3125
4
''' Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both? ''' # Solution 1 class Solution(object): def reverseList(self, head): prev = None current = head while current is not None: next = current.next current.next = prev prev = current current = next head = prev return head # Solution 2 class Node: def __init__(self, val, next=None): self.val = val self.next = next def print_list(head): while head is not None: print(head.val, end='->') head = head.next def reverse_linked_list(current): previous = None current = head next = None while current is not None: next = current.next # temporary store the next node current.next = previous # reverse the current node # before we move to the next node, point previous node to the current node previous = current current = next # move on the next node return previous head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) head.next.next.next.next = Node(5) reversed = reverse_linked_list(head) print_list(reversed)
true
d57e3c988f5311a9198d2d8bcd415c58ebb837d6
prashantchanne12/Leetcode
/daily tempratures.py
923
4.1875
4
''' Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead. Example 1: Input: temperatures = [73,74,75,71,69,72,76,73] Output: [1,1,4,2,1,1,0,0] Example 2: Input: temperatures = [30,40,50,60] Output: [1,1,1,0] Example 3: Input: temperatures = [30,60,90] Output: [1,1,0] ''' class Solution(object): def dailyTemperatures(self, T): """ :type T: List[int] :rtype: List[int] """ res = [0] * len(T) stack = [] for i, t in enumerate(T): while stack and t > stack[-1][1]: index, temprature = stack.pop() res[index] = i - index stack.append((i, t)) return res
true
20801f067b8f3b6248285c98c759bf60ef833c5f
prashantchanne12/Leetcode
/backspace string compare - stack.py
1,839
4.1875
4
''' Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character. Note that after backspacing an empty text, the text will continue empty. Example 1: Input: S = "ab#c", T = "ad#c" Output: true Explanation: Both S and T become "ac". Example 2: Input: S = "ab##", T = "c#d#" Output: true Explanation: Both S and T become "". Example 3: Input: S = "a##c", T = "#a#c" Output: true Explanation: Both S and T become "c". ''' # Solution - 1 class Solution(object): def backspaceCompare(self, S, T): """ :type S: str :type T: str :rtype: bool """ def build(str): arr = [] for i in str: if i != '#': arr.append(i) else: if arr: arr.pop() return ''.join(arr) return build(S) == build(T) # Solution - 2 def build(string): arr = [] for chr in string: if chr == '#' and len(arr) != 0: arr.pop() elif chr != '#': arr.append(chr) return arr def typed_out_strings(s, t): s_arr = build(s) t_arr = build(t) return ''.join(s_arr) == ''.join(t_arr) print(typed_out_strings('##z', '#z')) class Solution: def backspaceCompare(self, s: str, t: str) -> bool: string_1 = '' string_2 = '' for char in s: if char == '#': if len(string_1) > 0: string_1 = string_1[:-1] else: string_1 += char for char in t: if char == '#': if len(string_2) > 0: string_2 = string_2[:-1] else: string_2 += char return string_1 == string_2
true
4cc773965da12e433077f96090bdeea04579534a
prashantchanne12/Leetcode
/pascal triangle II.py
688
4.1875
4
''' Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: Example 1: Input: rowIndex = 3 Output: [1,3,3,1] Example 2: Input: rowIndex = 0 Output: [1] ''' class Solution(object): def getRow(self, rowIndex): """ :type rowIndex: int :rtype: List[int] """ res = [[1]] for i in range(rowIndex): temp = [0] + res[-1] + [0] row = [] for j in range(len(res[-1])+1): row.append(temp[j] + temp[j+1]) res.append(row) return res[-1]
true
5efbfb64f054e7cbcd77aa0f55599835c48b4d0d
prashantchanne12/Leetcode
/bitonic array maximum.py
998
4.34375
4
''' Find the maximum value in a given Bitonic array. An array is considered bitonic if it is monotonically increasing and then monotonically decreasing. Monotonically increasing or decreasing means that for any index i in the array arr[i] != arr[i+1]. Example 1: Input: [1, 3, 8, 12, 4, 2] Output: 12 Explanation: The maximum number in the input bitonic array is '12'. Example 2: Input: [3, 8, 3, 1] Output: 8 Example 3: Input: [1, 3, 8, 12] Output: 12 Example 4: Input: [10, 9, 8] Output: 10 ''' def find_max_in_bitonic_array(arr): low = 0 high = len(arr) - 1 while low < high: mid = (low+high) // 2 if arr[mid] > arr[mid+1]: high = mid else: low = mid + 1 # at the end of the while loop, 'start == end' return arr[low] print(find_max_in_bitonic_array([1, 3, 8, 12, 4, 2])) print(find_max_in_bitonic_array([3, 8, 3, 1])) print(find_max_in_bitonic_array([1, 3, 8, 12])) print(find_max_in_bitonic_array([10, 9, 8]))
true
c8ce6f1d1f34106357210c7361c2471bea783240
prashantchanne12/Leetcode
/smallest missing positive number.py
712
4.21875
4
''' Given an unsorted array containing numbers, find the smallest missing positive number in it. Example 1: Input: [-3, 1, 5, 4, 2] Output: 3 Explanation: The smallest missing positive number is '3' Example 2: Input: [3, -2, 0, 1, 2] Output: 4 Example 3: Input: [3, 2, 5, 1] Output: 4 ''' def find_missing_positive(nums): i = 0 n = len(nums) while i < n: j = nums[i] - 1 if nums[i] > 0 and nums[i] <= n and nums[i] != nums[j]: # swap nums[i], nums[j] = nums[j], nums[i] else: i += 1 for i in range(0, n): if nums[i] != i + 1: return i + 1 return n + 1 print(find_missing_positive([3, -2, 0, 1, 2]))
true
1811fedf3317e61f5fa1f70b1669b47cae04716d
prashantchanne12/Leetcode
/validate binary search tree.py
1,294
4.125
4
import math ''' Given the root of a binary tree, determine if it is a valid binary search tree (BST). A valid BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. Example 1: Input: root = [2,1,3] Output: true Example 2: Input: root = [5,1,4,null,null,3,6] Output: false Explanation: The root node's value is 5 but its right child's value is 4. ''' # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def isValidBST(self, root: TreeNode) -> bool: if root is None: return True return self.dfs(root, -math.inf, math.inf) def dfs(self, root, min_val, max_val): if root.val <= min_val or root.val >= max_val: return False if root.left: if not self.dfs(root.left, min_val, root.val): return False if root.right: if not self.dfs(root.right, root.val, max_val): return False return True
true
0423ec8f68bdbea0933002ff792eaaf73b0026e5
prashantchanne12/Leetcode
/merge intervals.py
1,718
4.375
4
''' Given a list of intervals, merge all the overlapping intervals to produce a list that has only mutually exclusive intervals. Example 1: Intervals: [[1,4], [2,5], [7,9]] Output: [[1,5], [7,9]] Explanation: Since the first two intervals [1,4] and [2,5] overlap, we merged them into one [1,5]. Example 2: Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. Example 3: Input: intervals = [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considered overlapping. ''' def sort_array(intervals): arr = [] # sort outer elements intervals.sort() # sort inner elements for nums in intervals: nums.sort() arr.append(nums) return arr class Solution(object): def merge(self, intervals): """ :type intervals: List[List[int]] :rtype: List[List[int]] """ if len(intervals) <= 1: return intervals # sort 2D array of intervals arr = sort_array(intervals) merged_array = [] start = arr[0][0] end = arr[0][1] for i in range(1,len(intervals)): interval = intervals[i] if interval[0] <= end: end = max(end, interval[1]) else: merged_array.append([start, end]) # update the start and end start = interval[0] end = interval[1] # add the last interval merged_array.append([start, end]) return merged_array
true
30c022b03d26825d5edcce633de3b490123772eb
prashantchanne12/Leetcode
/valid pallindrome.py
698
4.21875
4
''' Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Note: For the purpose of this problem, we define empty string as valid palindrome. Example 1: Input: "A man, a plan, a canal: Panama" Output: true Example 2: Input: "race a car" Output: false ''' import re class Solution(object): def isPalindrome(self, s): s = s.lower() arr = re.findall(r'[^\W_]', s) s = ''.join(arr) left = 0 right = len(s) - 1 while left < right: if s[left] == s[right]: left += 1 right -= 1 else: return False return True
true
04774b08d79956c826dd25ece5d12f3aea56922b
sgpl/project_euler
/1_solution.py
586
4.28125
4
#!/usr/bin/python 2.7 # 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. counter = 0 terminating_condition = 1000 sum_of_multiples = 0 while counter < terminating_condition: if counter % 3 == 0 and counter % 5 == 0: sum_of_multiples += counter elif counter % 3 == 0: sum_of_multiples += counter elif counter % 5 == 0: sum_of_multiples += counter else: sum_of_multiples += 0 counter += 1 print sum_of_multiples
true
60140c55c6e6b002931c8fe16280ce14bed7186c
iamsabhoho/PythonProgramming
/Q1-3/MasteringFunctions/PrintingMenu.py
713
4.21875
4
#Write a function for printing menus in the terminal. #The input is a list of options, and the output is the option selected by the user. print('The options are: ') #list = input() #menu = ['Meat','Chicken','Fish'] menu = [] print(menu) print() def options(menu): menu = input('Please enter the options: ') for i in range(len(menu)): option = i + 1 print(str(option) + menu[i]) user = input('What is your preference? Press X to exit: ') if user == 'x': exit() elif user == '1': print(menu[0]) return user elif user == '2': print(menu[1]) return user else: print(menu[2]) return user return user options()
true
c7c547252f8deb024b850f43dea0e73c3e8d849f
iamsabhoho/PythonProgramming
/Q1-3/WUP#7/Driving.py
1,121
4.375
4
#You are driving a little too fast, and a police officer stops you. Write an script that computes the result as “no ticket”, “small ticket”, and “big ticket”. If speed is 60 or less, the result is “no ticket”. If speed is between 61 and 80 inclusive, the result is “small ticket”. If speed is 81 or more, the result is “big ticket”. Unless it is your birthday -- on that day, your speed can be 5 higher in all cases. The input of the script in your speed and a boolean variable that indicates if it is your birthday. import sys print('The arguments passed were(birthday?/speed?): ') print(sys.argv) birthday = str(sys.argv[1]) speed = float(sys.argv[2]) #see if it is the driver's birthday if birthday == str('yes'): if 0 <= float(speed) <= 65: print('No ticket.') elif 66 <= float(speed) <= 85: print('Small ticket.') elif 86 <= float(speed): print('Big ticket.') else: if 0 <= float(speed) <= 60: print('No ticket.') elif 61 <= float(speed) <= 80: print('Small ticket.') elif 81 <= float(speed): print('Big ticket.')
true
dbece212a7cbf94c2bc33dc0b26dee6c0933cb81
ATLS1300/pc04-generative-section11-sydney-green
/PC04_GenArt.py
2,373
4.1875
4
""" Created on Thu Sep 15 11:39:56 2020 PC04 start code @author: Sydney Green This code creates two circle patterns from two seperate turtles. This is different than my pseudocode as I struggled bringing that to life but I was able to make something I liked so much more. Turtle 1 is a larger circle with larger cirlces making it up and alternating colors. Turtle 2 is a smaller circle made up of smaller cirlces containing different alternating colors as turtle 1. The random aspect of this code is that each time that it is run the circles are located in different places as the time before. The array of colors represented in each of the patterns makes me feel warm and happy as both circles contain bright and vibrant color palettes. """ #Randomized Circle Dots #Borrowed code helped me randomize the locations of the circle dots #Borrowed code is from "Quick guide to random library" canvas assignment page import turtle import math, random turtle.colormode(255) panel = turtle.Screen().bgcolor('black') T1large = turtle.Turtle() #Turtle 1 has its name because it will create the larger circle pattern made of cirlcles T2small = turtle.Turtle() #Turtle 2 has its name because it will create the smaller circle pattern made of circles T2small.shapesize(3) T1large.width(2) T2small.width(2) T1large.speed(11) T2small.speed(11) T1large.goto(random.randint(0,250),random.randint(0,250)) #Turtle 1's goto is random. It's random because I want its location to change each time the code is ran. #This first for loop creates many large circles that come together forming one large complete circle. for i in range(10): for colours in [(217,4,41), (220,96,46), (254,215,102), (104,163,87), (4,139,168)]: T1large.color(colours) T1large.down() T1large.circle(50) T1large.left(10) T1large.up() T2small.goto(random.randint(100,350),random.randint(100,350)) #Turtle 2's goto is random. It's random because I want its locaction to change each time the code is ran. #This second for loop creates many small circles that come together forming one smaller complete circle. for i in range(10): for colours in [(138,234,146), (167,153,183), (48,102,190), (255,251,252), (251,186,114)]: T2small.color(colours) T2small.down() T2small.circle(20) T2small.left(10) T2small.up() turtle.done()
true
5e4da675ae102831a30af49576b89c665f7ed89c
nelvinpoulose999/Pythonfiles
/practice_prgms/factorial.py
222
4.21875
4
num=int(input('enter the number')) factorial=1 if num<0: print('no should be positive') elif num==0: print('the number is 1') else: for i in range (1,num+1): factorial=factorial*i print(factorial)
true
85263ed8c3d2b28a3502e947024e1c9aaafaec39
ShreyasJothish/ML-Precourse
/precourse.py
1,771
4.25
4
# Machine Learning/Data Science Precourse Work # ### # LAMBDA SCHOOL # ### # MIT LICENSE # ### # Free example function definition # This function passes one of the 11 tests contained inside of test.py. Write the rest, defined in README.md, here, and execute python test.py to test. Passing this precourse work will greatly increase your odds of acceptance into the program. def f(x): return x**2 def f_2(x): return x**3 def f_3(x): return (f_2(x)+5*x) # Derivative functions # d_f returns the derivative of f def d_f(x): return 2*x # d_f_2 returns the derivative of f_2 def d_f_2(x): return 3*(x**2) # d_f_3 returns the derivative of f_3 def d_f_3(x): return (d_f_2(x)+5) # Sum of two vectors x and y def vector_sum(x, y): v = [] for i in range(len(x)): v.append(x[i] + y[i]) return v # Difference of two vectors x and y def vector_less(x, y): v = [] for i in range(len(x)): v.append(x[i] - y[i]) return v # Magnitude of a vector def vector_magnitude(v): sum = 0 for i in v: sum = sum + i**2 return int(sum ** (1/2)) import numpy as np def vec5(): return np.array([1,1,1,1,1]) def vec3(): return np.array([0,0,0]) def vec2_1(): return np.array([1,0]) def vec2_2(): return np.array([0,1]) # Matrix multiplication function that multiplies a 2 element vector by a 2x2 matrix def matrix_multiply(vec,matrix): result = [0,0] for i in range(2): for j in range(2): result[i] = result[i]+matrix[i][j]*vec[i] return result def matrix_multiply_simplified(vec,matrix): result = [0,0] result[0] = (matrix[0][0]*vec[0]+matrix[0][1]*vec[1]) result[1] = (matrix[1][0]*vec[0]+matrix[1][1]*vec[1]) return result
true
29775912584cbf014fe4a2820dd8a5694c9dc7d1
jossrc/LearningPython
/D012_Scope/project.py
803
4.15625
4
import random random_number = random.randint(1, 100) # GUESS THE NUMBER attempts = { "easy": 10, "hard": 5 } print("Welcome to the Number Guessing Game!") print("I'm thinking of a number between 1 and 100") difficulty = input("Choose a difficulty. Type 'easy' or 'hard': ") attempts_remaining = attempts[difficulty] while attempts_remaining > 0: print(f"You have {attempts_remaining} attempts remaining to guess the number.") number = int(input("Make a guess: ")) if number < random_number: print("Too low.") elif number > random_number: print("Too high.") else: print(f"You got it! The answer was {random_number}") break attempts_remaining -= 1 if attempts_remaining == 0: print("You've run out of guesses, you lose")
true
35eb7b4f8ce9723f9452d06ffd91c6c0db2dd9fe
kiyokosaito/Collatz
/collatz.py
480
4.34375
4
# The number we will perform the Collatz opperation on. n = int(input ("Enter a positive integer : ")) # Keep looping until we reach 1. # Note : this assumes the Collatz congecture is true. while n != 1: # Print the current value of n. print (n) #chech if n is even. if n % 2 == 0: #If n is even, divede it by two. n = n / 2 else : #If n is odd, multiply by three and add 1. n = (3 * n ) + 1 #Finally, print the 1. print (n)
true
bb40d33e9bf091ae3be7652cc60fa12d80c27b71
Selvaganapathi06/Python
/day3/Day3.py
700
4.25
4
#!/usr/bin/env python # coding: utf-8 # In[1]: #sample list and print bicycles = ["trek", "redline","hero"] print(bicycles) # In[2]: #accessing first element in the list print(bicycles[0]) # In[4]: #Apply title() print(bicycles[0].title()) # In[5]: #replace element values bicycles[0] = "Honda" print(bicycles) # In[6]: #append bicycles.append("ranger") print(bicycles) # In[7]: #insert bicycles.insert(1,"shine") print(bicycles) # In[8]: #delete from a list bicycles.pop() print(bicycles) # In[9]: #delete specific element from a list bicycles.pop(1) print(bicycles) # In[11]: #sorting cars = ["audi","bmw","benz","toyota"] cars.sort() print(cars) # In[ ]:
true
edb0162e3d1c5b0582c9305da3fe9aff1d9a317b
surajbarailee/PythonExercise
/python_topics/generators.py
2,369
4.53125
5
""" Retur:. A function that returns a value is called once. The return statement returns a value and exits the function altogether. Yield: A function that yields values, is called repeatedly. The yield statement pauses the execution of a function and returns a value. When called again, the function continues execution from the previous yield. A function that yields values is known as a generator. # https://www.codingem.com/wp-content/uploads/2021/11/1_iBgdO1ukASeyaLtSv3Jpnw.png A generator function returns a generator object, also known as an iterator. The iterator generates one value at a time. It does not store any values. This makes a generator memory-efficient. Using the next() function demonstrates how generators work. In reality, you don’t need to call the next() function. Instead, you can use a for loop with the same syntax you would use on a list. The for loop actually calls the next() function under the hood. """ def infinite_values(start): current = start while True: yield current current += 1 """ When Use Yield in Python Ask yourself, “Do I need multiple items at the same time?”. If the answer is “No”, use a generator. The difference between return and yield in Python is that return is used with regular functions and yield with generators. The return statement returns a value from the function to its caller. After this, the function scope is exited and everything inside the function is gone. The yield statement in Python turns a function into a generator. A generator is a memory-efficient function that is called repeatedly to retrieve values one at a time. The yield statement pauses the generator from executing and returns a single value. When the generator is called again, it continues execution from where it paused. This process continues until there are no values left. A generator does not store any values in memory. Instead, it knows the current value and how to get the next one. This makes a generator memory-efficient to create. The syntactical benefit of generators is that looping through a generator looks identical to looping through a list. Using generators is good when you loop through a group of elements and do not need to store them anywhere. """ # https://docs.python.org/3/howto/functional.html#generator-expressions-and-list-comprehensions
true
711895f2590aa58911073abb4914d25ae9320548
AyeChanKoGH/Small-code-
/DrawPyV1.py
1,686
4.46875
4
""" get screen and drawing shape with python turtle #To draw line, press "l" key and click first end point and second end point #To draw circle, press "c" key and click the center point and click the quarent point #To draw Rectangle, press "r" key and click 1st end point and second end point #To clean the screen, press "delete" key. """ from turtle import* import turtle import time import math x=0 y=0 clicked=False #To get the position of on screen click def on_click(x,y): global clicked global po po=[x,y] clicked=Turtle #To wait user point def wait(): global clicked turtle.update() clicked=False while not clicked: turtle.update() time.sleep(.1) clicked=False turtle.update() #drawing turtle line def line(): turtle.onscreenclick(on_click) wait() pu() goto(po[0],po[1]) Fpo=po pd() turtle.onscreenclick(on_click) wait() goto(po[0],po[1]) #drawing circle def dCircle(): turtle.onscreenclick(on_click) wait() pu() goto(po[0],po[1]) Fpo=po pd() turtle.onscreenclick(on_click) wait() Spo=po radi=math.sqrt(((Spo[0]-Fpo[0])**2)+((Spo[1]-Fpo[1])**2) ) pu() goto(Fpo[0],Fpo[1]-radi) pd() circle(radi) #drawing rectangular shape def rectangle(): turtle.onscreenclick(on_click) wait() pu() goto(po[0],po[1]) Fpo=po pd() turtle.onscreenclick(on_click) wait() Spo=po goto(Spo[0],Fpo[1]) goto(Spo[0],Spo[1]) goto(Fpo[0],Spo[1]) goto(Fpo[0],Fpo[1]) #To clean the screen def Sclear(): clear() listen() onkey(dCircle,"c") onkey(rectangle,"r") onkey(line,"l") onkey(Sclear,"Delete") mainloop()
true
fa085d5bace6c4496c002a929a41548604227ebb
kimit956/MyRepo
/Simple Math.py
402
4.125
4
num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) sum1 = num1 + num2 diff1 = num1 - num2 prod1 = num1 * num2 try: divide1 = num1 / num2 except ZeroDivisionError: num2 = int(input("Cannot divide by 0. Please enter a different number: ")) divide1 = num1 / num2 print("Sum:", sum1, "\tDifference:", diff1, "\tProduct:", prod1, "\tQuotient:", divide1)
true
c20743ca806704d3cbdb98cb3bed95e4ebf7af61
DeeCoob/hello_python
/_manual/format.py
1,163
4.125
4
# форматирование строки в стиле C s – форматная строка, x 1 …x n – значения # s % x # s % (x 1 , x 2 , …, x n ) # return Python has 002 quote types. print("%(language)s has %(number)03d quote types." % {'language': "Python", "number": 2}) # '#' The value conversion will use the “alternate form” (where defined below). # '0' The conversion will be zero padded for numeric values. # '-' The converted value is left adjusted (overrides the '0' conversion if both are given). # ' ' (a space) A blank should be left before a positive number (or empty string) produced by a signed conversion. # '+' A sign character ('+' or '-') will precede the conversion (overrides a “space” flag). # s.format(args) форматирование строки в стиле C# print("The sum of 1 + 2 + {0} is {1}".format(1+2, 6)) print("Harold's a clever {0!s}".format("boy")) # Calls str() on the argument first print("Bring out the holy {name!r}".format(name="1+3")) # Calls repr() on the argument first print("More {!a}".format("bloods")) # Calls ascii() on the argument first
true
558c51cde6f1a6992bc7202b5b2cfbbd93e514f6
DeeCoob/hello_python
/_tceh_lection/05_constructors.py
688
4.28125
4
# Constructor is called when new instance is create class TestClass: def __init__(self): print('Constructor is called') print('Self is the object itself', self) print() t = TestClass() t1 = TestClass() # Constructor can have parameters class Table: def __init__(self, numbers_of_legs): print('New table has {} legs'.format(numbers_of_legs)) t = Table(4) t1 = Table(3) print() # But we need to save them into the fields! class Chair: wood = 'Same tree' def __init__(self, color): self.color = color c = Chair('green') print(c, c.color, c.wood) c1 = Chair('Red') print('variable c did not change!', c.color) print()
true
a34c861f7c41768a76883e7e6f59c7149f106f36
vikramriyer/FCS
/rotate_image.py
419
4.125
4
#!/usr/bin/python init_list = [[1,2,3],[4,5,6],[7,8,9]] def rotate_matrix(matrix): '''Algo: First: take transpose of the matrix Second: interchange row 0 and row 2 ''' matrix = zip(*matrix) return swap_rows(matrix) def swap_rows(matrix): print matrix row0, row2 = matrix[0], matrix[2] matrix[0] = row2 matrix[2] = row0 return matrix final_matrix = rotate_matrix(init_list) print final_matrix
true
ddbc01b74befc3cb94f28d9f0c23ea1392e7eadb
Rkhwong/RHK_CODEWARS
/Fundamentals - Python/Arrays/Convert an array of strings to array of numbers.py
618
4.1875
4
# https://www.codewars.com/kata/5783d8f3202c0e486c001d23 """Oh no! Some really funny web dev gave you a sequence of numbers from his API response as an sequence of strings! You need to cast the whole array to the correct type. Create the function that takes as a parameter a sequence of numbers represented as strings and outputs a sequence of numbers. ie:["1", "2", "3"] to [1, 2, 3] Note that you can receive floats as well.""" def to_float_array(arr): new_list = [] for x in (arr): (new_list.append(float(x))) return new_list print( to_float_array(["1.1", "2.2", "3.3"]) ) #RW 02/06/2021
true
8c8861259b03ed4f89574f56a3fff922b05619fa
drazovicfilip/Firecode
/Problems/firecode4_fibonacci.py
1,182
4.1875
4
""" The Fibonacci Sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... The next number is found by adding up the two numbers before it. Write a recursive method fib(n) that returns the nth Fibonacci number. n is 0 indexed, which means that in the sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ..., n == 0 should return 0 and n == 3 should return 2. Assume n is less than 15. Even though this problem asks you to use recursion, more efficient ways to solve it include using an Array, or better still using 3 volatile variables to keep a track of all required values. Check out this blog post to examine better solutions for this problem. Examples: fib(0) ==> 0 fib(1) ==> 1 fib(3) ==> 2 """ def fib(n): # Edge cases if n == 0: return 0 elif n == 1 or n == 2: return 1 elif n == 3: return 2 previous1 = 1 previous2 = 1 current = previous1 + previous2 # Traverse through the fibonacci sequence, updating it for the needed amount of times for i in range(3, n): previous1 = previous2 previous2 = current current = previous1 + previous2 return current
true
ac5fb09501c10e94d3f0c3149967aa2dc28d46ab
pranjal2203/Python_Programs
/recursive fibonacci.py
518
4.5
4
#program to print fibonacci series using recursion #recursive function for generating fibonacci series def FibRecursion(n): if n <= 1: return n else: return(FibRecursion(n-1) + FibRecursion(n-2)) #input from the users no = int(input("Enter the terms: ")) #checking if the input is correct or not if no <= 0: print("Please enter a positive integer") else: print("Fibonacci sequence:") for i in range(no): print(FibRecursion(i),end=" ")
true
2049e82aa7a5a24f4f9bdf39393b2aba2b1faa6a
kipland-m/PythonPathway
/FactorialRecursion.py
764
4.21875
4
# This program is a part of my program series that I will be using to nail Python as a whole. # Assuming given parameter is greater than or equal to 1 | Or just 0. def Factorial(n): if (n >= 1): return n * Factorial(n-1) else: return 1 # Function Fibonacci will take "n" as parameter, in which said parameter returns value in corresponding # position within Fibonacci sequence, so if n=4 it would return 4th number in Fibonacci sequence. def Fibonacci(n): #If this condition is met it can be referred to as the recursive case if (n >= 3): return Fibonacci(n-1) + Fibonacci(n-2) #If this condition is met it can be referred to as the base case else: return 1 print(Factorial(3)) print(Fibonacci(4))
true
e32e692b073d079bb59aa2ed83460f8f3ff8802d
mukeshmithrakumar/PythonUtils
/PythonMasterclass/Exercise2.py
1,362
4.5625
5
""" Create a program that takes an IP address entered at the keyboard and prints out the number of segments it contains, and the length of each segment. An IP address consists of 4 numbers, separated from each other with a full stop. But your program should just count however many are entered Examples of the input you may get are: 127.0.0.1 .192.168.0.1 10.0.123456.255 172.16 255 So your program should work even with invalid IP Addresses. We're just interested in the number of segments and how long each one is. Once you have a working program, here are some more suggestions for invalid input to test: .123.45.678.91 123.4567.8.9. 123.156.289.10123456 10.10t.10.10 12.9.34.6.12.90 '' - that is, press enter without typing anything This challenge is intended to practise for loops and if/else statements, so although you could use other techniques (such as splitting the string up), that's not the approach we're looking for here. """ IP_address =(input("Please enter an IP Address: \n")) segment_length = 0 segment = 1 for char in IP_address: if (char !='.'): segment_length += 1 else: print("The {} segment length is {}".format(segment,segment_length)) segment_length = 0 segment += 1 if char != '.': print("The {} segment length is {}".format(segment, segment_length))
true
0512db35031316c393b4571c8dca11b0a411b22a
kramin343/test_2
/first.py
428
4.28125
4
largest = None smallest = None while True: num1 = input("Enter a number: ") try: num = float(num1) except: print('Invalid input') continue if num == "done" : break if largest == none: largest = num smallest = num if largest < num: largest = num if smallest > num: smallest = num print("Maximum is",largest) print("Minimum is",smallest)
true
3e7950446a092a65ef871c98e64e9820a6e637a5
victormaiam/python_studies
/exercise1_4.py
399
4.3125
4
'''' Write a function that returns the sum of multiples of 3 and 5 between 0 and limit (parameter). For example, if limit is 20, it should return the sum of 3, 5, 6, 9, 10, 12, 15, 18, 20. ''' def calcula_soma(limite): soma = 0 for i in range(0, limite + 1): if i%3 == 0 or i%5 == 0: soma = soma + i return(soma) limite = 20 soma = calcula_soma(limite) print(soma)
true
28d5915b71c0f0ce0266c6169d724582b0d3963c
ranju117/cegtask
/7.py
286
4.21875
4
#tuple tuple1 = ('python', 'ruby','c','java') list1 = ['python','ruby','c','java'] print tuple1 print list1 # Let's include windows in the list and it works! list1[1] = "windows" list1[2]="Python" print list1 # Windows does not work here! tuple1[1] = "windows" print tuple1
true
2293c26f5ae1fdf5417ce4033829cc36c80cff00
furkanaygur/Codewars-Examples
/RemoveTheParantheses.py
754
4.4375
4
''' Remove the parentheses In this kata you are given a string for example: "example(unwanted thing)example" Your task is to remove everything inside the parentheses as well as the parentheses themselves. The example above would return: "exampleexample" Notes Other than parentheses only letters and spaces can occur in the string. Don't worry about other brackets like "[]" and "{}" as these will never appear. There can be multiple parentheses. The parentheses can be nested. ''' def remove_parentheses(s): result = '' a = 0 for i in s: if i == '(': a += 1 elif i == ')': a -=1 elif a == 0: result += i return result print(remove_parentheses('sBtJXYI()DpVxQWId MWVozwWva kri obRgP AXjTKQUjXj xoEA xmkTQ LvrfGyNzCTqHHTWFPuLvrRWba fnWbFNVQBANn ZqwHzLTxkSuAPQiccORuQHNLxlaiYJSTESsOMoMooVbvDxZiEbilrgJeUfACIeEw AzPXkOrDk vjAAaqiPyMIOl UvLWq UMigMOi YRwiiOFcNRVyZbAPajY e YHldtivKMbFGwr pfKGlBRBjq wiHlobnqR GNMxf eW veFKMNzopYXf sG)VAyjLrHjxwNR ZPlkAp NRyKEKCM'))
true
d7eb20ba3f3a7b3b858265fb5dc87aea3939d909
furkanaygur/Codewars-Examples
/MatrixAddition.py
1,056
4.15625
4
''' Write a function that accepts two square matrices (N x N two dimensional arrays), and return the sum of the two. Both matrices being passed into the function will be of size N x N (square), containing only integers. How to sum two matrices: Take each cell [n][m] from the first matrix, and add it with the same [n][m] cell from the second matrix. This will be cell [n][m] of the solution matrix. Visualization: |1 2 3| |2 2 1| |1+2 2+2 3+1| |3 4 4| |3 2 1| + |3 2 3| = |3+3 2+2 1+3| = |6 4 4| |1 1 1| |1 1 3| |1+1 1+1 1+3| |2 2 4| Example matrixAddition( [ [1, 2, 3], [3, 2, 1], [1, 1, 1] ], // + [ [2, 2, 1], [3, 2, 3], [1, 1, 3] ] ) // returns: [ [3, 4, 4], [6, 4, 4], [2, 2, 4] ] ''' def matrix_addition(a,b): result = [] for i in range(len(a)): temp = [] for j in range(len(a)): temp.append(a[i][j] + b[i][j]) result.append(temp) return result print(matrix_addition([[1, 2], [1, 2]], [[2, 3], [2, 3]]))
true
a8477323029366675ff8de5169e40fbc701ffe0a
furkanaygur/Codewars-Examples
/SplitStrings.py
844
4.28125
4
''' Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore ('_'). Examples: solution('abc') # should return ['ab', 'c_'] solution('abcdef') # should return ['ab', 'cd', 'ef'] ''' def solution(s): result = '' result_array = [] flag = False for i in range(len(s)): if result == '': result += f'{s[i]}' flag = True elif flag == True: result += f'{s[i]}' result_array.append(result) result = '' flag = False if i == len(s)-1 and flag == True: result_array.append(f'{s[i]}_') return result_array print(solution(''))
true
ad213ac20a71fb84dfa39d4ad5375110c6f6281b
furkanaygur/Codewars-Examples
/Snail.py
2,004
4.3125
4
''' Snail Sort Given an n x n array, return the array elements arranged from outermost elements to the middle element, traveling clockwise. array = [[1,2,3], [4,5,6], [7,8,9]] snail(array) #=> [1,2,3,6,9,8,7,4,5] For better understanding, please follow the numbers of the next array consecutively: array = [[1,2,3], [8,9,4], [7,6,5]] snail(array) #=> [1,2,3,4,5,6,7,8,9] This image will illustrate things more clearly: Note 1: The idea is not sort the elements from the lowest value to the highest; the idea is to traverse the 2-d array in a clockwise snailshell pattern. Note 2: The 0x0 (empty matrix) is represented as en empty array inside an array [[]]. ''' def snail(snail_map): result = [] def leftToRight(array): a = snail_map[0] snail_map.remove(snail_map[0]) return a def upToBottom(array): a = [] for i in range(len(array)): a += array[i][len(array)], snail_map[i]= snail_map[i][:-1] return a def rightToLeft(array): a = [] for i in reversed(array[len(array)-1]): a += i, snail_map.remove(snail_map[len(array)-1]) return a def bottomToUp(array): a = [] x = len(array)-1 for i in range(len(array)): a += array[x][0], snail_map[x]= snail_map[x][1:] x -= 1 return a lenght = [len(i) for i in snail_map] while True: if len(result) != sum(lenght): result += leftToRight(snail_map) else: break if len(result) != sum(lenght): result += upToBottom(snail_map) else: break if len(result) != sum(lenght): result += rightToLeft(snail_map) else: break if len(result) != sum(lenght): result += bottomToUp(snail_map) else: break return result print(snail([[1,2,3,1], [4,5,6,4], [7,8,9,7],[7,8,9,7]]))
true
0d644ab18e56d13805766663cc0fb4bf7fd20840
reeha-parkar/python
/dunder_magic_methods.py
1,006
4.15625
4
import inspect '''x = [1, 2, 3] y = [4, 5] print(type(x)) # Output: <class 'list'> # Whatever we make it print, it follows a certain pattern # Which means that there is some class related method that works uunder the hood to give a certain output ''' # Let's make our own data type: class Person: def __init__(self, name): self.name = name def __repr__(self): # a dunder/magic method that allows us to define object's string representation return f'Person({self.name})' def __mul__(self, x): if type(x) is not int: raise Exception('Invalid argument, must be type int') self.name = self.name * x def __call__(self, y): print('called this function', y) def __len__(self): return(len(self.name)) p = Person('tim') p * 4 p(4) # When you call this function, __call__ will work print(p) # this initially, prints the memory address location # The dunder methods are a part of 'data model' of python print(len(p))
true
bdee03756772c0848b3a27bf3c309e3523205975
reeha-parkar/python
/classmethod_and_staticmethod.py
1,109
4.1875
4
# class methods and static method: # class method is a method in the class whcih takes te class name as a parameter, requires class instances # static method is a method which can be directly called without creating an instance of the class class Dog: dogs = [] def __init__(self, name): self.name = name self.dogs.append(self) @classmethod def num_dogs(cls): # cls means the name of the class return len(cls.dogs) @staticmethod def bark(n): for _ in range(n): print('Bark!') ''' # Calling a classmethod: tim = Dog('tim') jim = Dog('jim') print(Dog.dogs) # will get the Dog objects print(tim.dogs) # will get the same 2 dog objects print(Dog.num_dogs()) # will get 2 ''' # Calling a static method Dog.bark(5) # Only using the class name to get the method, without creating an instance # Static method is used when you don't need self or an object of the class # does not require a minimum parameter # Class method takes the actual class and can access whatever is in the class # requires a minimum one oarameter and that is 'cls'
true
0232446325b58ecb878807316e3007eff77940fe
lalitp20/Python-Projects
/Self Study/Basic Scripts/IF_STATEMENT.py
213
4.34375
4
# Example for Python If Statement number = int(input(" Please Enter any integer Value: ")) if number >= 1: print(" You Have Entered Positive Integer ") else: print(" You Have Entered Negative Integer ")
true
b203678db14a642b6da0446d34aa0223a7010718
lalitp20/Python-Projects
/Self Study/Basic Scripts/For_ELSE Statement.py
263
4.25
4
number = int(input(" Please Enter any integer below 100: ")) for i in range(0, 100): if number == i: print(" User entered Value is within the Range (Below 100)") break else: print(" User entered Value is Outside the Range (Above 100)")
true
7b70d150000739cb2e83695b2908f09c6e1e13bf
hfyeomans/python-100days-class
/day_13_debugging/debugging fizzbuzz.py
1,094
4.15625
4
# # Orginal code to debug # for number in range(1, 101): # if number % 3 == 0 or number % 5 == 0: # print("FizzBuzz") # if number % 3 == 0: # print("Fizz") # if number % 5 == 0: # print("Buzz") # else: # print([number]) for number in range(1, 101): if number % 3 == 0 and number % 5 == 0: # <-- problem resolved print("FizzBuzz") elif number % 3 == 0: print("Fizz") elif number % 5 == 0: # <-- problem resolved print("Buzz") else: print([number]) # In this debug exercise we put it into a debugger. We see it count 1, 2, but from the first if statement it prints Fizz. but then it continues to evalulate all the if statements below. so it also prints Fizz. Then the last if is false, so it hits the else and prints the number. These ifs have to be indented. The first if statement is or so every time its either or it prints fizz, buzz, but also goes through the other statements and prings fizz and buzz and catches else. # The resolution was the or statement to and and also the third if statement to elif
true
5bf7b52e8961a49b3667ae1731295ae1719a0900
aishtel/Prep
/solutions_to_recursive_problems/geometric_progression.py
655
4.34375
4
# Geometric progression using recursion # starting term = a = 1 # factor = r = a2/a1 # Find the nth term - 8th term # 1, 3, 9, 27, ... def geo_sequence(a, r, n): if r == 0 or r == 1: raise Exception("Sequence is not geometric") if n < 1: raise Exception("n should be >= 1") if a == 0: return 0 if n == 1: return a else: return r * geo_sequence(a, r, n-1) print "The geometric sequence is", geo_sequence(6, 2, 9) print "The geometric sequence is", geo_sequence(1, 3, 8) print "The geometric sequence is", geo_sequence(10, 3, 4) # print "The geometric sequence is",geo_sequence(2, 4, -1)
true
f5dab06d3a74c77757d299124fbe8bcabbfa3c07
aishtel/Prep
/solutions_to_recursive_problems/factorial_recursive.py
465
4.5
4
# Return the factorial of a given number using recursive method. # Example: # n = 6 # fact = 6*5*4*3*2*1 = 720 def factorial(n): if n < 0: raise Exception("n should be >= 0") elif n == 0: return 1 elif n == 1: return 1 else: return n * factorial(n - 1) print "The factorial is", factorial(4) print "The factorial is", factorial(0) print "The factorial is", factorial(1) # print "The factorial is", factorial(-4)
true
d5d66badeefb003f0d8356f94586ed89d869fc5e
Andrew-Callan/linux_academy_python
/age
248
4.15625
4
#!/usr/bin/env python3.7 name = input("What is your name? ") birthdate = input("What is your birthday? ") age = int(input("How old are you? ")) print(f"{name} was born on {birthdate}") print(f"Half your age is {age/2}") print(f"Fuck you {name}")
true
e5de3dc1d18e6f517f24b58851dd96d88b007999
Wyuchen/python_hardway
/29.py
484
4.28125
4
#!/usr/bin/python #coding=utf-8 #笨办法学 Python-第二十九题 #条件判断语句if people=20 cats=30 dogs=15 if people < cats: print 'too many cats!too little people' if people > cats: print 'too many people,too little cats' if people < dogs: print 'the world is drooled on' if people > dogs: print 'the world is dry' dogs+=5 if people >dogs: print 'people > dogs' if people <dogs: print 'people <dogs' if people == dogs: print 'people are dogs'
true
3e7b21d4fc0b9776ec7990f6aff7e5ae7abe7d1c
dianeGH/working-on-python
/menu/main.py
1,100
4.53125
5
#Write a program that allows user to enter their favourite starter, main course, dessert and drink. Concatenate these and output a message which says – “Your favourite meal is .........with a glass of....” def function_1(): user_name = input("Hi there, what's your name? \n") #print ("Nice to meet you " + user_name + ". Let's find out some more about you.\n") starter = input("I'd like to take you out for dinner. \nLet's go to your favourite restaurant! \nWhat is your favourite starter?\n") main_meal = input("That's awesome, I love " + starter + " too!\nWhat is your favourite main meal?\n") dessert = input("Cool, well " + main_meal+ " isn't my favourite, but I still like it!, What would your favourite dessert be? \n") drink = input("Now a drink, I like a good Merlot, but I'm pretty easy going. What is your favourite drink?\n") print("Well, I think we're going to have a great time! You'll have " + starter + " to start, followed by " + main_meal + " and " + dessert + " to finish, with a glass or two of " + drink + ". Shall we say Friday night? \n Great I'll book the table!!" )
true
09b28c6215e30d68fe17becca9b4495559ccb9de
dianeGH/working-on-python
/depreciation/main.py
349
4.28125
4
#A motorbike costs £2000 and loses 10% of its value every year. Using a loop, print the value of the bike every following year until it falls below £1000. print("Today, Jim bought a motorbike for £2000.00") year = 1 cost = 2000 while cost >1000: print("At the end of year ",year,", Jim's bike is worth £", cost) year+=1 cost=cost*.9
true
5361bceaf8f580c2855c45a3396525a7a326bffa
shubhneetkumar/python-lab
/anagram,py.py
203
4.15625
4
#anagram string s1 = input("Enter first string:") s2 = input("Enter second string:") if(sorted(s1) == sorted(s2)): print("string are anagram") else: print("strings are not anagram")
true
c69eda975eaa6a5d7da163d458845a1e4a9e3366
iloveyii/tut-python
/loop.py
259
4.15625
4
# For loop fruits = ['banana', 'orange', 'banana', 'orange', 'grapes', 'banana'] print('For loop:') for fruit in fruits: print(fruit) # While loop count = len(fruits) print('While loop') while count > 0: print(count, fruits[count-1]) count -= 1
true
580c275bc2bd3394aae13f831d36e0b588bc2024
MariomcgeeArt/CS2.1-sorting_algorithms-
/iterative_sorting2.py
2,069
4.34375
4
#funtion returns weather items are sorted or not boolean #creating the function and passing in items def is_sorted(items): # setting variable copy to equal items copy = items[:] #calling sort method on copy copy.sort() # if copy is equal to items it returns true return copy == items def bubble_sort(items): #set is sorted to true is_sorted = True # set a counter to 0 counter = 0 # while items_is_sorted we want to then change is sorted to false while(is_sorted): #set is sorted to false is_sorted = False # this is the for loop to loop trhough the items for i in range(len(items) - counter - 1): #if the item we are looking at is larger thane the item to its right we want to swap them if items[i] > items[i+1]: # swap the items positioins items[i], items[i+1] = items[i+1], items[i] # is sorted now becomes troue is_sorted = True # incremantation of the counter to move though the array counter += 1 def selection_sort(items): #finding the minimum item and swaping it with the first unsorted item and repeating until all items are in soreted order #for loop to loop throught the items items_length = range(0, len(items)-1) for i in items_length: #set min value to i min_value = i #nested for loop to set j value for j in range(i+1, len(items)): if items[j] < items[min_value]: min_value = j items[min_value], items[i] = items[i], items[min_value] return items def insertion_sort(items): item_length = range(1, len(items)) for i in item_length: #element to be compared unsorted_value = items[i] #comparing the current element with the sorted portion and swapping while items[i-1] > unsorted_value and i > 0: items[i], items[i-1] = items[i-1], items[i] i -= 1 #returning items return items
true
b40a434cf49126560b59272992e223eed3b78d22
ppfenninger/ToolBox-WordFrequency
/frequency.py
1,918
4.21875
4
""" Analyzes the word frequencies in a book downloaded from Project Gutenberg """ import string from pickle import load, dump def getWordList(fileName): """ Takes raw data from project Gutenberg and cuts out the introduction and bottom part It also tranfers the entire text to lowercase and removes punctuation and whitespace Returns a list >>> s = 'A***H ***1234@&().ABCab c***' >>> f = open('text.txt', 'w') >>> dump(s, f) >>> f.close() >>> get_word_list('text.txt') ['abcab', 'c'] """ inputFile = open(fileName, 'r') text = load(inputFile) l = text.split('***') #marker for stop and end of text in gutenberg try: #returns none in case there is something strange with the project gutenberg text mainText = l[2] #main text is the third block of text except: return None mainText = mainText.lower() #changes everything to lowercase mainText = mainText.replace("\r\n", "") mainText = mainText.translate(string.maketrans("",""), string.punctuation) #removes punctuation mainText = mainText.translate(string.maketrans("",""), string.digits) #removes numbers mainList = mainText.split() return mainList def getTopNWords(wordList, n): """ Takes a list of words as input and returns a list of the n most frequently occurring words ordered from most to least frequently occurring. word_list: a list of words (assumed to all be in lower case with no punctuation n: the number of words to return returns: a list of n most frequently occurring words ordered from most frequently to least frequently occurring """ d = {} for word in wordList: d[word] = d.get(word, 0) d[word] += 1 l = [] for i in d: l.append((d[i], i)) l.sort(reverse = True) mostCommon = l[0:(n-1)] words = [x[1] for x in mostCommon] return words if __name__ == "__main__": # import doctest # doctest.testmod() l1 = getWordList('odyssey.txt') l2 = getTopNWords(l1, 100) print l2
true
c127da0e7bf2078aa65dfcbec441b1c6dd6e7328
Habibur-Rahman0927/1_months_Python_Crouse
/Python All Day Work/05-05-2021 Days Work/Task_2_error_exception.py
2,582
4.34375
4
# Python Error and Exception Handling """ try: your code except: message """ # try: # with open('test.txt', mode='r') as open_file: # openFlie = open_file.read() # print(data) # except: # print("File is not found") # print('Hello, its working') """ try: your code except ExceptionName: your message """ # try: # with open('test.txt', mode='r') as my_new_file: # data_file = my_new_files.read() # print(data_file) # except NameError: # print('Name not found') # print('Hello, Its working.') """ try: your code except ExceptionName1: message except ExceptionName2: message """ # try: # with open('test.txt', mode='r') as my_file: # data = my_file.read() # print(data) # except NameError: # print('Name not found') # except FileNotFoundError: # print('Oops!!, File not found.') # print('Hello, Its working.') """ try: your code except (ExceptionName1, ExceptionName2...) message """ # try: # with open('test.txt', mode='r') as my_new_file: # data = my_new_file.read() # print(data) # except (NameError, FileNotFoundError): # print('Errors Found! Please check') # print('Hello, Its working.') """ try: your code except ExceptionName as msg: msg """ # try: # with open('test.txt', mode='r') as my_new_file: # print('Yes') # data = my_new_file.read() # print(data) # except FileNotFoundError as msg: # print(msg) # print('Please ensure that required file is exist') # print('Hello, Its working.') """ try: your code except ExceptionName: message else: message """ # try: # with open('test.txt', mode='r') as my_new_file: # data = my_new_file.read() # print(data) # except FileNotFoundError: # print("File not found.") # else: # print('No errors found :') # print('Hello, Its working.') """ try: your code except ExceptionName: message else: message finally: your code """ # try: # with open('test.txt', mode='r') as my_new_file: # data = my_new_file.read() # print(data) # except FileNotFoundError: # print(" File not found.") # else: # print('No errors found :') # finally: # print('Finally') # print('Hello, Its working.') """ try: raise NameError('Hello, It is user defined error msg.') except NameError as msg: message """ try: raise NameError('Hello, It is user defined error msg.') except NameError as msg: print(msg)
true
c5c77da3e67eacdc6c02fa2f052ae89c508cd743
FalseG0d/PythonGUIDev
/Sample.py
236
4.125
4
from tkinter import * root=Tk() #To create a Window label=Label(root,text="Hello World") #To create text on label and connect it to root label.pack() #to put it on root root.mainloop() #To avoid closing until close button is clicked
true
18c9cc619d5e44504665132e9fad5315a8b44799
pjkellysf/Python-Examples
/backwards.py
960
4.78125
5
#!/usr/local/bin/python3 # Patrick Kelly # September 29, 2015 # Write a program that prints out its own command line arguments, but in reverse order. # Note: The arguments passed in through the CLI (Command Line Interface) are stored in sys.argv. # Assumption: The first item argument in sys.argv is the filename and should NOT be included in the output. # Import the sys module import sys # Subtract one from the length of sys.argv to access the last index and store the result in the variable argumentIndex. argumentIndex = len(sys.argv) - 1 # Iterate through sys.argv starting with the last argument at index argumentIndex. for argument in sys.argv: # Exclude the filename which is the first argument in sys.argv at index 0. if argumentIndex > 0: # Print out the indexed argument from sys.argv print (sys.argv[argumentIndex]) # Decrement argumentIndex to access the previous argument in the next loop argumentIndex -= 1
true
d8f1f90bcf7d84a8a52a5055ab3f4850de1d4a77
lykketrolle/Noroff_NIS2016
/TAP 4/TAP04-sets[4].py
2,083
4.75
5
#!/usr/bin/python """ Name: Kjell Chr. Larsen Date: 24.05.2017 Make two different set with fruits, copy the one set in to the other and compare the two sets for equality and difference. """ print("This program will have two sets of fruits. One will then be copied,\n" "into the other, then a comparison of the two sets for difference and equality \n" "is done to show the operators used and the result produced.\n") print("A set is an unordered collection with no duplicate elements. Curly braces or the \n" "set() function can be used to create sets. Note: to create an empty set, we use the \n" "set() and not {} - curly braces, where the latter creates an empty dictionary.\n") print("Here is a demonstration. A set with duplicate elements: ") print(""" "basket = {'Banana', 'Apple', 'Banana', 'Apple', 'Pear', 'Orange'}" Here we see there are duplicate elements, lets see how the printout will be. """) test_basket = {'Banana', 'Apple', 'Banana', 'Apple', 'Pear', 'Orange'} print(test_basket) print("\nAs we can see, the printout only prints out one of the duplicate elements.\n") # Here is the sets related to the assignment. Both sets have different and equal values set1 = {'Grapes', 'Apples', 'Oranges', 'Pear', 'Peaches'} set2 = {'Blueberry', 'Apricot', 'Avocado', 'Apples', 'Bilberry'} print("SET1:", set1, "\nSET2:", set2) print("") """ Now I will copy the content from set2 into set1. I do this by using the | operator. """ # Here I copy set2 into set1 and then print out the result cp_set = set1 | set2 print("Here is the result of copying set2 into set1 using ' | ':\n", cp_set) print("") # Now I will use the ' - ' operator to check the difference between set1 and set2 diff_set = set1 - set2 print("The difference between set1 and set2: ", diff_set) print("Now to test difference between the sets. First I test to see if every\n" "element is in set1 and set2 by using the ' set.difference() 'operator.\n") print(set1.difference(set2)) print("This is the difference in the two sets.")
true
810a9ba68bf4e22c888a6b530265e7be8fbc457d
Amantini1997/FromUbuntu
/Sem 2/MLE/Week 2 - Decision Tree & Boosting/regression.py
1,658
4.375
4
# regression.py # parsons/2017-2-05 # # A simple example using regression. # # This illustrates both using the linear regression implmentation that is # built into scikit-learn and the function to create a regression problem. # # Code is based on: # # http://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.html # http://scikit-learn.org/stable/auto_examples/linear_model/plot_ransac.html import math import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model from sklearn.datasets import make_regression from sklearn.model_selection import train_test_split # # Generate a regression problem: # # The main parameters of make-regression are the number of samples, the number # of features (how many dimensions the problem has), and the amount of noise. X, y = make_regression(n_samples=100, n_features=1, noise = 2) # Split the data into training and test set X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=0) # # Solve the problem using the built-in regresson model # regr = linear_model.LinearRegression() # A regression model object regr.fit(X_train, y_train) # Train the regression model # # Evaluate the model # # Data on how good the model is: print("Mean squared error: %.2f" % np.mean((regr.predict(X_test) - y_test) ** 2)) # Explained variance score: 1 is perfect prediction print('Variance score: %.2f' % regr.score(X_test, y_test)) # Plotting training data, test data, and results. plt.scatter(X_train, y_train, color="black") plt.scatter(X_test, y_test, color="red") plt.scatter(X_test, regr.predict(X_test), color="blue") plt.show()
true
4ed2d4ef6171647b08629409ec77b488d059bc6f
greatwallgoogle/Learnings
/other/learn_python_the_hard_way/ex9.py
975
4.21875
4
# 打印,打印,打印 days = "Mon Tue Wed Thu Fri Sat Sun" # 第一中方法:将一个字符串扩展成多行 months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJuly\nAug" print("Here are the days :",days) # 等价于 print("Here are the days : %s" % days) print("Here are the months : ", months) #等价于 print("Here are the months : %s" % months) # 第二种方法:使用三引号输出任意行的字符串 print(""" There's something going on here. With the three double-quotes. We'll be able to type as much as we like. Even 4 lines if we want, or 5, or6. """) # for example tabby_cat = "\tI'm tabbed in." print("tabby_cat:",tabby_cat) persian_cat = "I'm split\non a line." print("persian_cat:",persian_cat) backslash_cat = "I'm \\ a \\ cat." print("backslash_cat:",backslash_cat) fat_cat = ''' I'll do a list: \t* Cat food \t* Fishied \t* Catnit\n\t* Grass ''' print(fat_cat) # # while True: # for i in ["/","-","|","\\","|"]: # print("%s\r" % i)
true
a73adc9082e54df28f0db2a9b93496e2f1bcd5ff
thekayode/area_of_shapes
/area_of_triangle _assignment.py
993
4.40625
4
''' This programme is too calculate the area of a triangle. ''' base = float(input('Enter the base of the triangle\n')) height = float(input('Enter the height of the the triangle\n')) area = 1/2 * (base * height) print('area', '=', area) ''' This programme is too calculate the area of a square. ''' length = float(input('Enter the length of the square\n')) area = length**2 print('area', '=', area) ''' This programme is too calculate the area of a cylinder. ''' radius = float(input('Enter the radius of cylinder: ')) pi = 3.142 height = float(input('Enter the heigth of cylinder: ')) area = (2 * pi * radius**2) + (2 * pi * radius * height) print('Enter the area', (round(area,2))) ''' This programme is too calculate the area of a trapezoid. ''' a = float(input('Enter base 1 of trapezoid: ')) b = float(input('Enter base 2 of trapezoid: ')) height = float(input('Enter the height of trapezoid: ')) area = 1/2 * (a + b) * height print('area', '=', area)
true
b1869818de65a93e61f1fc9cf4320396c09ca8bc
oct0f1sh/cs-diagnostic-duncan-macdonald
/functions.py
760
4.21875
4
# Solution for problem 8 def fibonacci_iterative(num = 10): previous = 1 precedingPrevious = 0 for number in range(0,num): fibonacci = (previous + precedingPrevious) print(fibonacci) precedingPrevious = previous previous = fibonacci # Solution for problem 9 # I don't know how to call stuff from the terminal and my python # installation is really screwed up so I'm using PyCharm to run these # and i'm just going to set an input arg = int(input("Enter a number: ")) fibonacci_iterative(arg) print() # Solution for problem 10 def factorial_recursive(num): solution = num while num != 0: solution = solution * (num - 1) print(solution) num = num - 1 factorial_recursive(6)
true
18db5e61c29a777be3bd163202dce195042b6878
dianamorenosa/Python_Fall2019
/ATcontent.py
487
4.125
4
#!/usr/bin/python #1.- Asign the sequence to a variable #2.- Count how many A's are in the sequence #3.- Count how many T's are in the sequence #4.- Sum the number of A's and the number of T's #5.- Print the sum of A's and T's seq1= ("ACTGATCGATTACGTATAGTATTTGCTATCATACATATATATCGATGCGTTCAT") #Asign the sequence to the variable seq1 ATcount= seq1.count ("A") + seq1.count("T") #Use count method for A and T, the + symbol will sum the number of A's and the number of T's print(ATcount)
true
a3037b8de00a8552d355fb5e45a15c6dc0743b77
rsingla92/advent_of_code_2017
/day_3/part_1.py
2,422
4.15625
4
''' You come across an experimental new kind of memory stored on an infinite two-dimensional grid. Each square on the grid is allocated in a spiral pattern starting at a location marked 1 and then counting up while spiraling outward. For example, the first few squares are allocated like this: 17 16 15 14 13 18 5 4 3 12 19 6 1 2 11 20 7 8 9 10 21 22 23---> ... While this is very space-efficient (no squares are skipped), requested data must be carried back to square 1 (the location of the only access port for this memory system) by programs that can only move up, down, left, or right. They always take the shortest path: the Manhattan Distance between the location of the data and square 1. For example: Data from square 1 is carried 0 steps, since it's at the access port. Data from square 12 is carried 3 steps, such as: down, left, left. Data from square 23 is carried only 2 steps: up twice. Data from square 1024 must be carried 31 steps. How many steps are required to carry the data from the square identified in your puzzle input all the way to the access port? ''' from math import sqrt, floor, fabs def calculate_spiral_coords(n): # Determine the radius of the spiral 'n' is in. # If the spiral length is u, then the last element is at u^2. # The next spiral is u^2 + 1 right, continuing u up, then u+1 # leftwards, u+1 downwards, and u+2 right. # Calculate u u = floor(sqrt(n)) if u % 2 == 0: u -= 1 radius = (u - 1) // 2 n -= u ** 2 if n == 0: return radius, radius n -= 1 if n < u: return radius+1, radius-n n -= u if n < u + 1: return radius + 1 - n, radius - u n -= u+1 if n < u + 1: return radius - u, radius - u + n n -= u + 1 if n < u + 2: return radius - u + n, radius + 1 def calculate_steps(n): x, y = calculate_spiral_coords(n) print 'x: ' + str(x) + ' y: ' + str(y) return fabs(x)+fabs(y) if __name__ == '__main__': test_1 = 1 print 'Test 1 result is ' + str(calculate_steps(test_1)) test_2 = 12 print 'Test 2 result is ' + str(calculate_steps(test_2)) test_3 = 23 print 'Test 3 result is ' + str(calculate_steps(test_3)) test_4 = 1024 print 'Test 4 result is ' + str(calculate_steps(test_4)) my_input = 347991 print 'My result is ' + str(calculate_steps(my_input))
true
23241e4ba4dadda493f44610e334ff1dfa533d82
Algorant/HackerRank
/Python/string_validators/string_validators.py
586
4.125
4
# You are given a string . Your task is to find out if the string contains: # alphanumeric characters, alphabetical characters, digits, lowercase # and uppercase characters. if __name__ == '__main__': s = input() # any() checks for anything true, will iterate through all tests # Check for alphanumerics print(any(c.isalnum() for c in s)) # Check for alphabet characters print(any(c.isalpha() for c in s)) # Check for digits print(any(c.isdigit() for c in s)) # Check for lowercase print(any(c.islower() for c in s)) # Check for uppercase print(any(c.isupper() for c in s))
true
aa361a509b9cb245ecbf9448f4df5279cfc078c6
Algorant/HackerRank
/Python/reduce/reduce.py
557
4.25
4
''' Given list of n pairs of rational numbers, use reduce to return the product of each pair of numbers as numerator/denominator fraction by every fraction in list n. ''' # some of this code is supplied to user from fractions import Fraction from functools import reduce def product(fracs): t = reduce(lambda x, y: x * y, fracs) return t.numerator, t.denominator if __name__ == '__main__': fracs = [] for _ in range(int(input())): fracs.append(Fraction(*map(int, input().split()))) result = product(fracs) print(*result)
true
f6b7564f728de2663ab87128b71fd4280236772a
Algorant/HackerRank
/Python/set_add/set_add.py
204
4.25
4
''' Given an integer and a list of items as input, use set.add function to count the number of unique items in the set. ''' n = int(input()) s = set() for i in range(n): s.add(input()) print(len(s))
true
91df05bb5905d70cc260c414ec0f4ba2bcaf3d88
Algorant/HackerRank
/30_days_of_code/d25_running_time_and_complexity/running_time.py
1,020
4.1875
4
''' Given list of integers of length T, separated by /n, check if that number is prime and return "Prime" or "Not Prime" for that integer. ''' # This was first attempt. Naive approach that works but fails 2 test cases # due to timeout! (Too slow) # def ptest(T): # # Make sure greater than 1 # if T > 1: # # Check if its even or has any other factors # for i in range(2, T): # if (T % i) == 0: # print("Not Prime") # break # can end if it finds any # else: # print("Prime") # no factors other than 1 and self # # else: # print("Not Prime") # any other case not prime # # # ptest(31) # ptest(12) # ptest(33) # Attempt 2 def prime(num): if num == 1: return False else: return all((num % r) for r in range(2, round(num ** 0.5) + 1)) T = int(input()) for i in range(1, T+1): num = int(input()) if prime(num)==True: print("Not prime") else: print("Prime")
true
996bb5aa753930626a1a6a45d930437dd015c850
Algorant/HackerRank
/Python/findall_finditer/find.py
482
4.21875
4
''' Given a string S, consisting of alphanumeric characters, spaces, and symbols, find all the substrings of S that contain 2 or more vowels. The substrings should lie between 2 consonants and should contain vowels only. ''' import re vowels = 'aeiou' consonants = 'bcdfghjklmnpqrstvwxyz' regex = '(?<=[' + consonants + '])([' + vowels + ']{2,})[' + consonants + ']' match = re.findall(regex, input(), re.IGNORECASE) if match: print(*match, sep='\n') else: print('-1')
true
97128f21e73b655557a2dee31dc5610b40b6011a
coding-with-fun/Python-Lectures
/Lec 7/Types of UDF.py
2,476
4.875
5
# Function Arguments: # 1) Required arguments # 2) Keyword arguments # 3) Default arguments # 4) Variable-length arguments # 5) Dictionary arguments # 1) Required arguments: # Required arguments are the arguments passed to a function in correct positional order. # Here, the number of arguments in the function call should match exactly with the function definition. def fn1(a): print (a) fn1("Hello World") #Output:Hello World # 2) Keyword arguments: # Keyword arguments are related to the function calls. # When you use keyword arguments in a function call, # the caller identifies the arguments by the parameter name. def fn2(str): print str fn2(str="Good Evening") #Output:Good Evening # 3) Default arguments: # A default argument is an argument that assumes a default value # if a value is not provided in the function call for that argument,it prints default value if it is not passed def fn3(name,marks=35): print "Name=",name print "Marks=",marks fn3(marks=50,name="XYZ") #Output: # Name=XYZ # Marks=50 fn3(name="ABC") #Output: # Name=ABC # Marks=35 # 4) Variable-length arguments # You may need to process a function for more arguments than you specified while defining the function. # These arguments are called variable-length arguments and are not given in the function definition, # An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments. # This tuple remains empty if no additional arguments are specified during the function call. def fn4(arg1,*tuplevar): print "arg1=",arg1 for var in tuplevar: print "tuple=",var fn4(50) #Output:50 fn4(60,70,"Hello") #Output: # 60 # 70 # Hello # 5) Dictionary arguments # #A keyword argument is where you provide a name to the variable as you pass it into the function. # #One can think of the kwargs as being a dictionary that maps each keyword to the value that we pass alongside it. # #That is why when we iterate over the kwargs there doesn’t seem to be any order in which they were printed out. def fn5(**kwargs): if kwargs is not None: for key,value in kwargs.items(): print("%s = %s" %(key, value)) fn5(fn='Abc',ln='Def') #Output: # fn=Abc # ln=Def
true
0bdd0d5acbe261113fe3ff023be27216a3aad75b
rfpoulos/python-exercises
/1.31.18/blastoff.py
287
4.125
4
import time numbers = int(raw_input("How many numbers should we count down?: ")) text = raw_input("What should we say when we finish out countdown?: ") for i in range(0, numbers + 1): if numbers - i == 0: print text else: print numbers - i time.sleep(1)
true
a2acc5778a677f03e5474f25b9750224c509b316
rfpoulos/python-exercises
/1.30.18/name.py
509
4.5
4
first_name = raw_input('What is your first name? ') last_name = raw_input('%s! What is your last name? ' % first_name) full_name = '%s %s' % (first_name, last_name) print full_name #Below is a qualitative analysis if first_name == 'Rachel': print "That's a great name!" elif first_name == 'Rachael': print "That's the devil's spelling. . ." else: print "That's a fine name, but not the BEST name." print (full_name.upper() + "! Your full name is " + str(len(full_name)) + " character's long")
true
f47fd9998823803e0b731023430aa0d226b12ca0
ssahussai/Python-control-flow
/exercises/exercise-5.py
824
4.34375
4
# exercise-05 Fibonacci sequence for first 50 terms # Write the code that: # 1. Calculates and prints the first 50 terms of the fibonacci sequence. # 2. Print each term and number as follows: # term: 0 / number: 0 # term: 1 / number: 1 # term: 2 / number: 1 # term: 3 / number: 2 # term: 4 / number: 3 # term: 5 / number: 5 # etc. # Hint: The next number is found by adding the two numbers before it terms = int(input("Enter term:")) n1 = 0 n2 = 1 count = 0 if terms <= 0: print("Enter a positive number!") elif terms == 1: print(f"Fibonacci sequence: {n1}") elif terms < 51: print("Fibonacci sequences:") while count < terms: print(n1) nth = n1 + n2 n1 = n2 = nth count += 1 else: print("This function goes only upto 50 terms!")
true
d4a4dd99e068910c239d94119bac23744e7e0e8b
AIHackerTest/xinweixu1_Py101-004
/Chap0/project/ex36_number_guess.py
1,899
4.34375
4
#ex 36 # The task of this exercise is to design a number guessing game. import random goal = random.randint(1, 20) n = 10 print ("Please enter an integer from 0 to 20." ) print ("And you have 10 chances to guess the correct number.") guess = int(input ('> ')) while n != 0: if guess == goal: print ("Yes, you win!") exit(0) elif guess < goal: n = n - 1 print ("Your guess is smaller than the correct number.") print (f"You can still try {n} times.") guess = int(input ('> ')) else: n = n - 1 print ("Your guess is larger than the correct number.") print (f"You can still try {n} times.") guess = int(input ('> ')) #Notes on if-statements & loops: # Rules for if-statements: # 1) every if-statement must have an else # 2) if this else should never run because it doesn't make sense, # then you must use a die function in the else that prints out # an error message and dies # 3) never nest if-statements more than two deep # 4) treat if-statements like paragraphs, where if-elif-else grouping # is like a set of sentences. Put blank lines before and after # 5) Your boolean tests should be SIMPLE! # If they are complex, move their calculations to variables earlier in # your function and use a good name for the variable. # Rules for Loops: # 1) use a while loop ONLY to loop forever, and that means probably never... # this only applies to python, other languages might be different # 2) use for-loop for all other kinds of looping, esp. if there is a # fixed or limited number of things to loop over # Tips for debugging: # 1) The best way to debug is to use print to print out the values of # variables at points in the program to see where they go wrong # 2) Do NOT write massive files of code before you try to run them, # code a little, run a little, fix a little.
true
fa69a550806f7cfcbf2fd6d02cbdf443a9e48622
lepperson2000/CSP
/1.3/1.3.7/LEpperson137.py
1,231
4.3125
4
import matplotlib.pyplot as plt import random def days(): '''function explanation: the print will be of the 'MTWRFSS' in front of 'day' and the print will include the 5-7 days of September ''' for day in 'MTWRFSS': print(day + 'day') for day in range(5,8): print('It is the ' + str(day) + 'th of September') plt.ion() # sets "interactive on": figures redrawn when updated def picks(): a = [] # make an empty list a += [random.choice([1,3,10])] plt.hist(a) plt.show() def roll_hundred_pair(): b = [] b += [random.choice([2,4,6])] plt.hist(b) plt.show() def dice(n): number = range(2-12) number += [random.choice(range(2,12))] return dice(n) def hangman_display(guessed, secret): letter = range(1,26) letter += [hangman_display(range(1,26))] return hangman_display(guessed, secret) def matches(ticket, winners): ticket = list[11,12,13,14,15] winners = list[3,8,12,13,17] for ticket in winners: print(matches) def report(guess, secret): color = range(1,4) color += [report(range(1,4))] return report(guess, secret)
true
8860a1eb440ef0f1249875bc5a97a5157bf0c258
ShamanicWisdom/Basic-Python-3
/Simple_If_Else_Calculator.py
2,753
4.4375
4
# IF-ELSE simple two-argument calculator. def addition(): try: first_value = float(input("Input the first value: ")) second_value = float(input("Input the second value: ")) result = first_value + second_value # %g will ignore trailing zeroes. print("\nResult of %.5g + %.5g is: %.5g\n" % (first_value, second_value, result)) except ValueError: print("Please insert proper numbers!") def subtraction(): try: first_value = float(input("Input the first value: ")) second_value = float(input("Input the second value: ")) result = first_value - second_value # %g will ignore trailing zeroes. print("\nResult of %.5g - %.5g is: %.5g\n" % (first_value, second_value, result)) except ValueError: print("Please insert proper numbers!") def multiplication(): try: first_value = float(input("Input the first value: ")) second_value = float(input("Input the second value: ")) result = first_value * second_value # %g will ignore trailing zeroes. print("\nResult of %.5g * %.5g is: %.5g\n" % (first_value, second_value, result)) except ValueError: print("Please insert proper numbers!") def division(): try: first_value = float(input("Input the first value: ")) second_value = float(input("Input the second value: ")) if second_value == 0: print("Cannot divide by zero!") else: result = first_value / second_value # %g will ignore trailing zeroes. print("\nResult of %.5g / %.5g is: %.5g\n" % (first_value, second_value, result)) except ValueError: print("\nPlease insert proper numbers!\n") print("==Calculator==") user_choice = -1 while user_choice != 0: print("1. Addition.") print("2. Subtraction.") print("3. Multiplication.") print("4. Division.") print("0. Exit.") try: user_choice = int(input("Please input a number: ")) if user_choice not in [0, 1, 2, 3, 4]: print("\nPlease input a proper choice!\n") else: if user_choice == 0: print("\nExiting the program...\n") else: if user_choice == 1: addition() else: if user_choice == 2: subtraction() else: if user_choice == 3: multiplication() else: if user_choice == 4: division() except ValueError: print("\nProgram will accept only integer numbers as an user choice!\n")
true
c6cbfb6a8c91fedba94151405a0e6e064a9cf7dd
pradeep-sukhwani/reverse_multiples
/multiples_in_reserve_order.py
581
4.25
4
# Design an efficient program that prints out, in reverse order, every multiple # of 7 that is between 1 and 300. Extend the program to other multiples and number # ranges. Write the program in any programming language of your choice. def number(): multiple_number = int(raw_input("Enter the Multiple Number: ")) start_range = int(raw_input("Enter the Start Range Number: ")) end_range = int(raw_input("Enter the End Range Number: ")) for i in range(start_range, end_range+1) [::-1]: if i % multiple_number == 0: print i, number()
true
b2825f7313f3834263cc59e8dd49cf3e11d2a86a
AdityaLad/python
/python-projects/src/root/frameworks/ClassCar.py
550
4.125
4
''' Created on Sep 11, 2014 @author: lada the only purpose of init method is to initialize instance variables ''' ''' def __init__(self, name="Honda", *args, **kwargs): self.name = name ''' class Car: #constructor def __init__(self, name="Honda"): self.name = name def drive(self): print "Drive car", self.name #destructor def __del__(self): print "Car object destroyed.." c1 = Car("Toyota") c2 = Car("Nissan") c3 = Car() c1.drive() c2.drive() c3.drive()
true
6cbfc9e2bd18f1181041287a56317200b1b789a8
DaehanHong/Principles-of-Computing-Part-2-
/Principles of Computing (Part 2)/Week7/Practice ActivityRecursionSolution5.py
925
4.46875
4
""" Example of a recursive function that inserts the character 'x' between all adjacent pairs of characters in a string """ def insert_x(my_string): """ Takes a string my_string and add the character 'x' between all pairs of adjacent characters in my_string Returns a string """ if len(my_string) <= 1: return my_string else: first_character = my_string[0] rest_inserted = insert_x(my_string[1 :]) return first_character + 'x' + rest_inserted def test_insert_x(): """ Some test cases for insert_x """ print "Computed:", "\"" + insert_x("") + "\"", "Expected: \"\"" print "Computed:", "\"" + insert_x("c") + "\"", "Expected: \"c\"" print "Computed:", "\"" + insert_x("pig") + "\"", "Expected: \"pxixg\"" print "Computed:", "\"" + insert_x("catdog") + "\"", "Expected: \"cxaxtxdxoxg\"" test_insert_x()
true
87f5557c82320e63816047943679b70effe5aecf
DaehanHong/Principles-of-Computing-Part-2-
/Principles of Computing (Part 2)/Week6/Inheritance2.py
437
4.25
4
""" Simple example of using inheritance. """ class Base: """ Simple base class. """ def __init__(self, num): self._number = num def __str__(self): """ Return human readable string. """ return str(self._number) class Sub(Base): """ Simple sub class. """ def __init__(self, num): pass obj = Sub(42) print obj
true
9f045af90875eea13a4954d2a22a8089fd07724a
Thuhaa/PythonClass
/28-July/if_else_b.py
713
4.21875
4
marks = int(input("Enter the marks: ")) # Enter the marks # Between 0 and 30 == F # Between 31 and 40 == D # Between 41 and 50 == C # Between 51 and 60 == B # Above 61 == A # True and True == True # True and False == False # False and False == False # True or True == True # True or False == True # False and False == False # Use elif If there is more than 2 condition if marks <= 30: print("The student has scored an F") elif marks > 30 and marks <=40: print("The student has scored a D") elif marks >40 and marks<=50: print("The student score a C") elif marks > 50 and marks <= 60: print("The student scored a B") else: print("The student scored and A")
true
6795c4e6e07de121d7dce93da430830b71f0cb3e
akoschnitzki/Module-4
/branching-Lab 4.py
884
4.375
4
# A time traveler has suddenly appeared in your classroom! # Create a variable representing the traveler's # year of origin (e.g., year = 2000) # and greet our strange visitor with a different message # if he is from the distant past (before 1900), # the present era (1900-2020) or from the far future (beyond 2020). year = int(input("Greetings! What is your year of origin?")) # Add the missing quotation mark and an extra equal sign. ''' if year < 1900: ''' if year <= 1900: # Add the missing colon. print("Woah, that's the past!") # Add the missing quotation marks. '''elif year >= 1900 and year < 2020 : ''' elif year >= 1900 and year <= 2020: # Must add the word and to make the statement run. print("That's totally the present!") '''else: ''' elif year >= 2020: # Add the statement to print the years that are in the future. print("Far out, that's the future!!")
true
55ab453d18e2b12b64378fd70fc3843ec169eb29
Deepak10995/node_react_ds_and_algo
/assignments/week03/day1-2.py
901
4.4375
4
''' Assignments 1)Write a Python program to sort (ascending and descending) a dictionary by value. [use sorted()] 2)Write a Python program to combine two dictionary adding values for common keys. d1 = {'a': 100, 'b': 200, 'c':300} d2 = {'a': 300, 'b': 200, 'd':400} Sample output: Counter({'a': 400, 'b': 400, 'd': 400, 'c': 300}) ''' #ques 1 d1 = {'a': 100, 'b': 200, 'c':300} d2 = {'a': 300, 'b': 200, 'd':400} def sorted_dict_increasing(d1): sorted_d1 = sorted(d1.items(),key= lambda x: x[1]) print(sorted_d1) sorted_d1 = sorted(d1.items(),key= lambda x: x[1],reverse=True) print(sorted_d1) return sorted_d1 sorted_dict_increasing(d1) # Ques 2 from collections import Counter d1 = {'a': 100, 'b': 200, 'c':300} d2 = {'a': 300, 'b': 200, 'd':400} def dict_combine(d1,d2): d_combine = Counter(d1) + Counter(d2) print(d_combine) return d_combine dict_combine(d1,d2)
true
24f3091c067759e7cde9222bfb761a777da668df
Deepak10995/node_react_ds_and_algo
/coding-challenges/week06/day-1.py
2,263
4.28125
4
''' CC: 1)Implement Queue Using a linked list ''' #solution class Node: def __init__(self, data): self.data = data self.next = None class Queue: def __init__(self): self.head = None self.last = None def enqueue(self, data): if self.last is None: self.head = Node(data) self.last = self.head else: self.last.next = Node(data) self.last = self.last.next def dequeue(self): if self.head is None: return None else: to_return = self.head.data self.head = self.head.next return to_return a_queue = Queue() while True: print('enqueue <value>') print('dequeue') print('quit') do = input('What would you like to do? ').split() operation = do[0].strip().lower() if operation == 'enqueue': a_queue.enqueue(int(do[1])) elif operation == 'dequeue': dequeued = a_queue.dequeue() if dequeued is None: print('Queue is empty.') else: print('Dequeued element: ', int(dequeued)) elif operation == 'quit': break ''' 2)Implement Stack using a linked list ''' #solution class Node: def __init__(self, data): self.data = data self.next = None class Stack: def __init__(self): self.head = None def push(self, data): if self.head is None: self.head = Node(data) else: new_node = Node(data) new_node.next = self.head self.head = new_node def pop(self): if self.head is None: return None else: popped = self.head.data self.head = self.head.next return popped a_stack = Stack() while True: print('push <value>') print('pop') print('quit') do = input('What would you like to do? ').split() operation = do[0].strip().lower() if operation == 'push': a_stack.push(int(do[1])) elif operation == 'pop': popped = a_stack.pop() if popped is None: print('Stack is empty.') else: print('Popped value: ', int(popped)) elif operation == 'quit': break
true
a729758b2b951b8c38983b7dd5336c8f36f933da
DajkaCsaba/PythonBasic
/4.py
293
4.53125
5
#4. Write a Python program which accepts the radius of a circle from the user and compute the area. Go to the editor #Sample Output : #r = 1.1 #Area = 3.8013271108436504 from math import pi r = float(input("Input the radius of the circle: ")) print("r = "+str(r)) print("Area = "+str(pi*r**2))
true
3de713f7ca2f61358268815be48dbe7a217db2ee
wojtbauer/Python_challenges
/Problem_2.py
865
4.125
4
#Question 2 # Write a program which can compute the factorial of a given numbers. # The results should be printed in a comma-separated sequence on a single line. # Suppose the following input is supplied to the program: # 8 # Then, the output should be: # 40320 # Factorial = int(input("Wpisz liczbę: ")) # wynik = 1 # # #if/elif solution! - option 1 # if Factorial < 0: # print("Wstaw wartość nieujemną!") # elif Factorial == 0: # print("0! = 1") # else: # for i in range(1, Factorial+1): # wynik = wynik*i # print(Factorial, wynik) #while solution! - option 2 # while Factorial > 0: # wynik = wynik * Factorial # Factorial = Factorial - 1 # print(wynik) #Function solution - option 3 def Fact(x): if x == 0: return 1 elif x > 0: return x * Fact(x-1) x = int(input("Wpisz liczbę: ")) print(Fact(x))
true
c5b87a3edc367f76c12b0fa2734ee8deafa4b965
jcbain/fun_side_projects
/unique_digits/unique_digits.py
1,948
4.1875
4
from collections import Counter def separate_digits(val): """ separate the digits of a number in a list of its digits Parameters ----- val : int number to separate out Returns ----- list a list of ints of the digits that make up val """ return [int(x) for x in str(val)] def any_intersection(x,y): """ check to see if there are any intersecting values between two lists Parameters ----- x : list first list of values y : list second list of values Returns ----- bool True if there is an intersection, False otherwise """ inter = set(x).intersection(set(y)) return bool(inter) def run_exponential(exp,upper_bound = 10000): """ finds the values between 0 and an upper bound that contains all unique digits and shares no digits with its value raised to some exponent Parameters ----- exp : int exponent to raise the values to upper_bound : int the upper limit of where the list should stop at Returns lists first list is a list the base values that meet the criteria second list is a list of the base values that work raised to the exponent """ candidates_result = [] candidates_base = [] for i in range(0,upper_bound): num = i ** exp compound = str(i) + str(exp) separate_compound = separate_digits(compound) separate_num = separate_digits(num) base_digit_counts = list(Counter(separate_digits(i)).values()) intersection_check = not any_intersection(separate_num,separate_compound) base_check = not any(i > 1 for i in base_digit_counts) if intersection_check & base_check: candidates_result.append(num) candidates_base.append(i) return candidates_base,candidates_result if __name__ == '__main__': print(run_exponential(6, 1000000000))
true
802480d75cc45bb911de93e28e8e830b743b4db6
Mattx2k1/Notes-for-basics
/Basics.py
2,087
4.6875
5
# Hello World print("Hello World") print() # Drawing a shape # Programming is just giving the computer a set of instructions print(" /!") print(" / !") print(" / !") print("/___!") print() # console is where we have a little window into what our program is doing # Pyton is looking at these instructions line by line in order # The order in which we write the instructions is very important. It matters a lot # Variables and Data Types # In python we'll be dealing with a lot of data, values and information # That data can be difficult to manage # A variable is a container where we can store certain data values, and when we use variables it's a lot easier to work with and manage the information in our programs. # Let's start with this story print("There once was a man named George, ") print("he was 70 years old. ") print("He really liked the name George, ") print("but didn't like being 70.") print() # Let's say we wanted to change the name in the story from George to John, or change the age, we'd have to do it line by line. Except we have Variables which make it easier for us: #variable_name character_name = "John" character_age = "35" #Now we can just add in the variables in the story print("There once was a man named " + character_name + ", ") print("he was " + character_age + " years old. ") print("He really liked the name George, ") print("but didn't like being " + character_age + ".") # Now all you would have to do is change the variables to update many lines in the story. # We can update the variable simply writing it out again character_name = "Tom" print("There once was a man named " + character_name + ", ") print("he was " + character_age + " years old. ") print("He really liked the name George, ") print("but didn't like being " + character_age + ".") # We are storing these names as strings # Strings are plain text # Can store numbers, don't use quotations character_age = 35 # can store whole numbers character age = 35.5 # can store decimal numbers # Boolean returns true or false values. Example: is_male = False
true
cdd823dbe94b600742ba2158e50f516446aba57e
Mattx2k1/Notes-for-basics
/Try Except.py
1,072
4.53125
5
# Try Except # Catching errors # Anticipate errors and handle them when they occur. That way errors don't bring our program to a crashing halt number = int(input("Enter a number: ")) print(number) # if you enter a non number, it will cause the program to crash. So you need to be able to handle the exceptions # Try except block is what is used for this try: number = int(input("Enter a number: ")) print(number) except: print("Invalid input") # Specify the type of error you want to catch with this format for except: try: value = 10 / 0 number = int(input("Enter a number: ")) print(number) except ZeroDivisionError: print("Divided by zero") except ValueError: print("Invalid input") # store error as a variable: try: value = 10 / 0 number = int(input("Enter a number: ")) print(number) except ZeroDivisionError as err: print("err") except ValueError: print("Invalid input") # A best practice is to set up for catching specific errors. "Except:" by itself is too broad and may break your program on it's own
true
0896dad37cd3b5d93a60fb30672ccd902fcdc337
Mattx2k1/Notes-for-basics
/Guessing Game.py
564
4.25
4
# guessing game # start with the variables secret_word = "giraffe" guess = "" guess_count = 0 guess_limit = 3 out_of_guesses = False # use a while loop to continually guess the word until they get it correct # added in the "and not" condition, and new variables to create a limit on guesses while guess != secret_word and not (out_of_guesses): if guess_count < guess_limit: guess = input("Enter guess: ") guess_count += 1 else: out_of_guesses = True if out_of_guesses: print("Out of guesses, YOU LOSE!") else: print("You win!")
true
5284bda9251b8da6fe08e0c44d2721e87738e3ad
samsonwang/ToyPython
/PlayGround/26TicTacToe/draw_pattern.py
1,813
4.34375
4
#! /usr/bin/python3.6 ''' Tic Tac Toe Draw https://www.practicepython.org/exercise/2015/11/26/27-tic-tac-toe-draw.html - For this exercise, assume that player 1 (the first player to move) will always be X and player 2 (the second player) will always be O. - Notice how in the example I gave coordinates for where I want to move starting from (1, 1) instead of (0, 0). To people who don’t program, starting to count at 0 is a strange concept, so it is better for the user experience if the row counts and column counts start at 1. This is not required, but whichever way you choose to implement this, it should be explained to the player. - Ask the user to enter coordinates in the form “row,col” - a number, then a comma, then a number. Then you can use your Python skills to figure out which row and column they want their piece to be in. - Don’t worry about checking whether someone won the game, but if a player tries to put a piece in a game position where there already is another piece, do not allow the piece to go there. ''' import logging # get cordinate and return a tuple def get_player_input(str_player): log = logging.getLogger("root") str_cordinates = input("%s, which col and row? " % str_player) log.debug("%s, input: %s" % (str_player, str_cordinates) ) list_cord = str_cordinates.strip().split(',') return tuple(list_cord) def tic_tac_toe_game(): log = logging.getLogger("root") print("Welcome to tic tac toe") tup_p1 = get_player_input("Player 1") log.debug("Player 1: %s" % (tup_p1, )) def main(): logger = logging.getLogger("root") FORMAT = "%(filename)s:%(lineno)s %(funcName)s() %(message)s" logging.basicConfig(format=FORMAT) logger.setLevel(logging.DEBUG) tic_tac_toe_game() if __name__ == '__main__': main()
true
5521559091299b2af7b6c72fa20cea4dcffe9a03
arun-p12/project-euler
/p0001_p0050/p0025.py
1,056
4.125
4
''' In a Fibonacci series 1, 1, 2, 3, 5, 8, ... the first 2-digit number (13) is the 7th term. Likewise the first 3-digit number (144) is the 12th term. What is the index of the first term in the Fibonacci sequence to contain 1000 digits? ''' def n_digit_fibonacci(number): digits = 1 fibonacci = [1, 1] while(digits < number): fibonacci.append(fibonacci[-1] + fibonacci[-2]) # next term = sum of last two terms digits = len(str(fibonacci[-1])) # how many digits in the new term? if(digits >= number): # is it the required length print("fibonacci = ", len(fibonacci)) return(0) import time # get a sense of the time taken t = time.time() # get time just before the main routine ########## the main routine ############# number = 1000 n_digit_fibonacci(number) ########## end of main routine ########### t = time.time() - t # and now, after the routine print("time = {:7.5f} s\t{:7.5f} ms\t{:7.3f} µs".format(t, t * 1000, t*1_000_000))
true