blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
837a1620e23665aa6492269ae6da3ee8ec530b16
YoungsAppWorkshop/codewars
/r1/day12_counting_duplicates.py
1,531
4.28125
4
#!/usr/bin/env python3 """ Counting Duplicates - 6 kyu Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits. Example "abcde" -> 0 # no characters repeats more than once "aabbcde" -> 2 # 'a' and 'b' "aabBcde" -> 2 # 'a' occurs twice and 'b' twice (bandB) "indivisibility" -> 1 # 'i' occurs six times "Indivisibilities" -> 2 # 'i' occurs seven times and 's' occurs twice "aA11" -> 2 # 'a' and '1' "ABBA" -> 2 # 'A' and 'B' each occur twice https://www.codewars.com/kata/counting-duplicates """ # My Solution def duplicate_count(text): dict, sum = {}, 0 for letter in text: key = letter.lower() if dict.get(key): dict[key] += 1 else: dict[key] = 1 for key in dict: if dict[key] > 1: sum += 1 return sum # Best Practice # def duplicate_count(s): # return len([c for c in set(s.lower()) if s.lower().count(c)>1]) if __name__ == '__main__': print(duplicate_count("abcde")) print(duplicate_count("aabbcde")) print(duplicate_count("aabBcde")) print(duplicate_count("indivisibility")) print(duplicate_count("Indivisibilities")) print(duplicate_count("aA11")) print(duplicate_count("ABBA"))
true
bff80bbce617c38683818404de6303502ad9dfc5
YoungsAppWorkshop/codewars
/r1/day19_detect_pangram.py
870
4.15625
4
#!/usr/bin/env python3 """ Detect Pangram A pangram is a sentence that contains every single letter of the alphabet at least once. For example, the sentence "The quick brown fox jumps over the lazy dog" is a pangram, because it uses the letters A-Z at least once (case is irrelevant). Given a string, detect whether or not it is a pangram. Return True if it is, False if not. Ignore numbers and punctuation. https://www.codewars.com/kata/detect-pangram """ import re # My Solution def is_pangram(s): return True if len(set("".join(re.findall("[a-zA-Z]+", s)).lower())) == 26 else False # noqa # Best Practice # import string # def is_pangram(s): # return set(string.lowercase) <= set(s.lower()) if __name__ == '__main__': pangram = "The quick, brown fox jumps over the lazy dog!" print(is_pangram(pangram))
true
1f0aeec8258dfc8157c34ac91b8f27b20f28df0f
YoungsAppWorkshop/codewars
/r1/day28_pyramid_slide_down.py
2,081
4.53125
5
#!/usr/bin/env python3 """ Pyramid Slide Down Pyramids are amazing! Both in architectural and mathematical sense. If you have a computer, you can mess with pyramids even if you are not in Egypt at the time. For example, let's consider the following problem. Imagine that you have a plane pyramid built of numbers, like this one here: /3/ \7\ 4 2 \4\ 6 8 5 \9\ 3 Here comes the task... Let's say that the 'slide down' is a sum of consecutive numbers from the top to the bottom of the pyramid. As you can see, the longest 'slide down' is 3 + 7 + 4 + 9 = 23 Your task is to write a function longestSlideDown (in ruby: longest_slide_down) that takes a pyramid representation as argument and returns its' longest 'slide down'. For example, longestSlideDown([[3], [7, 4], [2, 4, 6], [8, 5, 9, 3]]) # => 23 By the way... My tests include some extraordinarily high pyramides so as you can guess, brute-force method is a bad idea unless you have a few centuries to waste. You must come up with something more clever than that. http://www.codewars.com/kata/pyramid-slide-down """ # My Solution def longest_slide_down(pyramid): if len(pyramid) <= 1: return pyramid[0][0] else: lst0 = pyramid[-2] lst1 = pyramid[-1] for i in range(len(lst0)): lst0[i] += lst1[i] if lst1[i] > lst1[i + 1] else lst1[i + 1] lst2 = pyramid[:-2] lst2.append(lst0) return longest_slide_down(lst2) # Best Practice # def longest_slide_down(p): # res = p.pop() # while p: # tmp = p.pop() # res = [tmp[i] + max(res[i],res[i+1]) for i in range(len(tmp))] # return res.pop() # longest_slide_down = lambda l:reduce(lambda x,y:[max([x[i],x[i+1]])+y[i] for i in range(len(y))],l[::-1])[0] # noqa if __name__ == '__main__': lst = [[3], [7, 4], [2, 4, 6], [8, 5, 9, 3]] # lst = [[3], [7, 4], [2, 4, 6]] # lst = [[3], [7, 4]] print(longest_slide_down(lst))
true
ea62b2be949b188490713b11c43b9f0eeada73f7
Limitlessmatrix/automation_scripts
/list_comprehensions.py
2,236
4.375
4
#deriving one list to another using comprehension to shorten filtering or mapping a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] squares = [x**2 for x in a] print(squares) #try writing as a function:::: #def squares(numbers_squared): # squaring = [x**2 for x in a] # return print(squaring) #visually nosiy example::::::::::: squares = map(lambda x: x ** 2, a) #easier to read then next example::::::::::::: even_squares = [x**2 for x in a if x % 2 == 0] print(even_squares) #example using map and filter::::::::::::::::::::::::::::: alt = map(lambda x: x**2, filter(lambda x: x % 2 == 0, a)) assert even_squares == list(alt) #Dicitionaires and Sets have their own equivalents of list comprehensions. #Making it easier for deriative data structure creation. chile_ranks = {'ghost': 1, 'habanero': 2, 'cayenne':3} rank_dict = {rank: name for name, rank in chile_ranks.items()} chile_len_set = {len(name) for name in rank_dict.values()} print(rank_dict) print(chile_len_set) #things to remember::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: #list comprehensions are clearer than map and filter built in functions #list comprehnsions allow you to skip items from input list, a behavior map doesn't without help from filter #dictionaries and sets also support comprehsion expressions. #avoid more that two expressions in list comprehension matrix = [[1, 2, 3], [4, 5, 6 ], [7, 8, 9]] flat = [x for row in matrix for x in row] print(flat) #other practice:::::::::::::::::::::::::::::::::: squared = [[x**2 for x in row] for row in matrix] print(squared) my_lists = [ [[1, 2, 3], [4, 5, 6]], #... ] flat = [x for sublist1 in my_lists for sublist2 in sublist1 for x in sublist2] # another version little clearer flat = [] for sublist1 in my_lists: for sublist2 in sublist1: flat.extend(sublist2) #List comprehensions also supports multiple if conitions a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] b = [x for x in a if x > 4 if x %2 == 0] c = [x for x in a if x > 4 and x %2 == 0] #conditions can be specifcied at each level of looping after the for expression. matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] filtered = [[x for x in row if x % 3 == 0] for row in matrix if sum(row) >= 10] print(filtered)
true
ba314c4b2e58b67d17c3af0745ed865fb84461bf
ngirmachew/my_codes_on_sololearn
/Create_Pandas_DataFrame_from_List_of_Lists_2020_05_11.py
824
4.21875
4
import pandas as pd # Given: """ ['Lagos', '1,845', '1,343', '469', '33'] ['Kano', '602', '528', '48', '26'] ['FCT', '356', '297', '53', '6'] ['Borno', '185', '157', '12', '16'] """ # Create a list of lists and/or a Pandas DataFrame: # 1. List of Lists: -> Just zip them all and turn each into a list within a list comprehension: list_of_lists = [list(lst) for lst in zip(['Lagos', '1,845', '1,343', '469', '33'], ['Kano', '602', '528', '48', '26'], ['FCT', '356', '297', '53', '6'], ['Borno', '185', '157', '12', '16'])] print("*" * 30) print(f"Here is the list of lists:\n\t{list_of_lists}") # 2. Use that list of lists to create a dataframe with the cities as columns: df = pd.DataFrame.from_records(list_of_lists[1:], columns = list_of_lists[0]) print("*" * 30) print(f"Here is the dataFrame:\n{df}") print("*" * 30)
false
e64cedf7e615f119c03b35944d462a182e4eda4d
ngirmachew/my_codes_on_sololearn
/GPA_calculator_2020_05_12.py
700
4.28125
4
grade_scale = {'A': 4.0, 'A-':3.7, 'B+':3.3, 'B':3.0, 'B-':2.7, 'C+':2.3, 'C':2.0, 'C-':1.7, 'D':1.3, 'D-':0.7,'F':0} print(f'This program computes your GPA \nPlease enter your completed courses \nTerminate your entry by entering 0 credits') allcredit = [] allgrades = [] while True: credit = int(input('Credits?:' )) if credit == 0: break grade = input('Grade?: ') prod_grade_credit = grade_scale[grade.upper()] * credit allgrades.append(prod_grade_credit) allcredit.append(credit) #credit = int(input('Credits?: ') if sum(allcredit) == 0: print("Unable to calculate GPA for 0 credit" else: print(f'Your GPA is: {(sum(allgrades) / sum(allcredit)):.2f}')
true
beec15fef21dd80eb11ebb2710b60f8f826562ca
vinamrathakv/pythonCodesMS
/TurtleTwoCircle.py
2,064
4.4375
4
# display if circles overlap or not using turtle import turtle import math # get user input for both the circls' co-ordinates and radii x1, y1, r1 = eval(input("Enter the x co-ordinate, y co-ordinate and radius of circle 1 : ")) x2, y2, r2 = eval(input("Enter the x co-ordinate, y co-ordinate and radius of circle 2 : ")) turtle.penup() turtle.goto(x1,y1) turtle.right(90) #point south turtle.forward(r1) #move down equal to radius turtle.right(270) #turn east turtle.pendown() turtle.pensize(4) turtle.color("teal") #draw circle with specified coordinates as center turtle.circle(r1) turtle.penup() turtle.goto(x2,y2) turtle.right(90) turtle.forward(r2) turtle.right(270) turtle.pendown() turtle.color("purple") turtle.circle(r2) turtle.penup() turtle.goto(0,-200) turtle.pendown() turtle.color("red") distance = math.sqrt((x1-x2) ** 2 + (y1-y2) ** 2) print("Distance between centers : ",distance) #calculate distance between the centers of the two circles if(distance <= math.fabs(r1-r2)): #check if centers are closer than or equal to difference in radii if(r1 > r2): # if r1 is greater than r2, second circle is insede first circle turtle.write("The second circle is inside first circle") if(r2 > r1): # if r2 is greater than r1, first circle is inside second circle turtle.write("The first circle is inside second circle") elif(distance <= math.fabs(r1+r2)): #check if distance between centers is less than or equal to sum of radii turtle.write("The circles overlap") elif(distance > math.fabs(r1+r2)): # check if distance between centers is greater than sum of radii turtle.write("The circles do not overlap") turtle.penup() turtle.goto(0,0) turtle.exitonclick()
true
2ec5653b1eec72cf5393a979cee5992d3ecb796e
vinamrathakv/pythonCodesMS
/AreaOfTriangle2_14.py
802
4.34375
4
# Calculate area of a triangle given 3 vertices x1, y1 = eval(input("Enter first point of the triangle : ")) x2, y2 = eval(input("Enter second point of the triangle : ")) x3, y3 = eval(input("Enter third point of the triangle : ")) side_1 = ((x1-x2)**2 + (y1-y2)**2)**0.5 side_2 = ((x2-x3)**2 + (y2-y3)**2)**0.5 side_3 = ((x3-x1)**2 + (y3-y1)**2)**0.5 if(((side_1 + side_2) <= side_3) or ((side_2 + side_3) <= side_1) or ((side_3 + side_1) <= side_2)): print("The entered points do not make a triangle.") else: s = (side_1 + side_2 + side_3)/2 area = (s*(s-side_1)*(s-side_2)*(s-side_3))**0.5 print("The lengths of the 3 sides of the triangle are : ",round(side_1,2),", ",round(side_2,2),", ",round(side_3,2), " and it's area is : ",round(area,2))
true
94ae0cc5d1e9490f5f1a6f8ca09b087c023e5ec5
vinamrathakv/pythonCodesMS
/LongestCommonPrefix8_13.py
419
4.125
4
# find longest common prefix between two stringStart def prefix(s1, s2): p = '' for c in s1: p += c if s2.startswith(p): continue else: return p[0:len(p)-1] def main(): s1 = input("String 1 : ") s2 = input("string 2 : ") pre = prefix(s1,s2) print("Longest prefix is : ",pre) main()
true
209439c405be2e7ca51d764037183b8916e2fcae
vinamrathakv/pythonCodesMS
/PalindromicPrime6_24.py
1,670
4.15625
4
#check if entered integer is palindromic prime #check if input is prime def isPrime(number): divisor = 2 while divisor <= number / 2: if number % divisor == 0: # If true, number is not prime return False # number is not a prime divisor += 1 return True # number is prime #check if input is a palindrome def isPalindrome(number): n = number count = len(str(number)) rev_number = 0 while(n > 0): digit = n % 10 rev_number += digit * (10 ** (count-1)) n = n // 10 count -= 1 if (rev_number == number): #print(rev_number, number) return True else: #print(rev_number,number) return False count = 0 number = 2 i = 0 while count <100: if isPrime(number): if isPalindrome(number): print(format(number, "5d"), end = " ") i += 1 if i == 10: print() i = 0 number += 1 count += 1 else: number += 1 else: number += 1 '''print(isPalindrome(232)) print(isPrime(13111379)) user_input = eval(input("Enter any integer to be checked : ")) if(isPrime(user_input) == True): #print("Integer is Prime.") if(isPalindrome(user_input) == True): print("Integer is Palindromic Prime") else: print("Integer is Prime but not a Palindrome") else : print("Integer is neither Prime nor a Palindrome.")'''
true
625b8778c2ab8b0de731d6fdf6acb49e97a34570
DomenOslaj/step-counter
/main.py
392
4.34375
4
# Create a function that will calculate the number of steps that you # make for a certain distance. def calculate_steps(distance, step_length): steps = int(distance/step_length) print("Number of steps: {0}".format(steps)) distance_m = int(input("Enter a distance in meters: ")) step_length_m = int(input("Enter a length of you step: ")) calculate_steps(distance_m, step_length_m)
true
9833a362eaee6c6e998d7be088f6baabae1cf4ea
gutiantian123Abc/algorithm-py
/DFS/Matrix_Water_Injection.py
1,972
4.125
4
""" 1410. Matrix Water Injection Given a two-dimensional matrix, the value of each grid represents the height of the terrain. The flow of water will only flow up, down, right and left, and it must flow from the high ground to the low ground. As the matrix is surrounded by water, it is now filled with water from (R,C) and asked if water can flow out of the matrix. Example Given mat = [ [10,18,13], [9,8,7], [1,2,3] ] R = 1, C = 1, return "YES"。 Explanation: (1,1) →(1,2)→Outflow. Given mat = [ [10,18,13], [9,7,8], [1,11,3] ] R = 1, C = 1, return "NO"。 Explanation: Since (1,1) cannot flow to any other grid, it cannot flow out. Notice The input matrix size is n x n, n <= 200. Ensure that each height is a positive integer. """ class Solution: """ @param matrix: the height matrix @param R: the row of (R,C) @param C: the columns of (R,C) @return: Whether the water can flow outside """ def waterInjection(self, matrix, R, C): # Write your code here m = len(matrix) n = len(matrix[0]) v = [[False for j in range(0, n)] for i in range(0, m)] res = self.dfs(matrix, R, C, v) if res: return "YES" return "NO" def dfs(self, matrix, R, C, v): dx = [0, 0, 1, -1] dy = [1, -1, 0, 0] res = False for i in range(4): nx = R + dx[i] ny = C + dy[i] if self.outside(matrix, nx, ny): return True if not v[nx][ny] and matrix[R][C] > matrix[nx][ny]: v[nx][ny] = True res = res or self.dfs(matrix, nx, ny, v) return res def outside(self, matrix, R, C): m = len(matrix) n = len(matrix[0]) return R < 0 or R >= m or C < 0 or C >= n
true
64d39c5d6ffac35f897299a02a128eaf862941bf
bopopescu/SQL-Pthon
/tests/span1.py
1,515
4.1875
4
# the from is the name of th efile with the class definition and import the name of the class from span import Student # we make a instance of the class while also passing arguments to use the init method and assigning values student1 = Student("Jim", "Business", 2.1, False) student2 = Student student2.name = "Pam" print(student2.name) print(student1.gpa) print(student1.checkGpa()) print(student2.gpa) prices = [10, 20, 30] total = 0; for items in prices: total += items print(total) # co-ordinates using nested loops for x in range(4): for y in range(3): # this is a formatted string print(f'({x},{y})') numbers = [5, 2, 5, 2, 2] for i in numbers: print('x' * i) numberz = [2, 2, 2, 2, 5] # proper way of doing the above example for x_count in numberz: # makes a string which we append output = '' # for the number started in x_count the range loop will go that number of times each time adding a x for count in range(x_count): output += 'x' print(output) ints = list(range(51)) biggest = ints[0] for i in ints: if i > biggest: biggest = i print(biggest) # 2D lists matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] # to access the single number print(matrix[0][0]) for i in matrix: for j in i: print(j) # list methods # appedn adds to the end of the list numbers.append(20) print(numbers) # inser you can choose location of insertion the first number us the index second is the number numbers.insert(0, 30)
true
084d121d73b26927b894868359ace19cab4e2493
fkfouri/Algorithms
/Recursividade/003 - Fibonacci_recursivo.py
672
4.375
4
''' Algoritimo iterativo de Calculo Fibonacci Otimo em termos de complexidade espaco de memoria, portanto Ɵ(1). Em termos de complexidade de tempo eh Ω(2^(n/2)), ou seja, cresce na ordem exponencial de n. Esse foi um piso calculado, mas ja demonstra a alta complexidade de tempo de um Fibonacci recursivo. Melhor usar o Fibonacci Iterativo. ''' def fib(n): if( n == 0 or n == 1): return 1 return fib(n-1) + fib(n-2) #Base print('Base =>', fib(0), fib(1)) print('Fibonacci de 3 =>', fib(3)) print('Fibonacci de 6 =>', fib(6)) print('Fibonacci de 10 =>', fib(10)) print('Fibonacci de 30 =>', fib(30)) print('Fibonacci de 50 =>', 'Nao processa')
false
978dd023fbfe18346c98a3e25b1ade8b80b2134d
Gaydarenko/PY-111
/Tasks/d0_stairway.py
1,397
4.34375
4
from typing import Union, Sequence def stairway_path(stairway: Sequence[Union[float, int]]) -> Union[float, int]: """ Calculate min cost of getting to the top of stairway if agent can go on next or through one step. :param stairway: list of ints, where each int is a cost of appropriate step :return: minimal cost of getting to the top """ # print(stairway) # length = 0 # i = 0 # while i < len(stairway): # if len(stairway) - i == 1: # length += stairway[i] # break # if stairway[i] < stairway[i+1]: # length += stairway[i] # i += 1 # else: # length += stairway[i+1] # i += 2 # return length # step_2 = [stairway[0],] # step_1 = [stairway[0] + stairway[1], stairway[1]] # for i in range(2, len(stairway)): # step_2, step_1 = step_1, list(map(lambda x: x + stairway[i], step_1 + step_2)) # return min(step_1) if len(stairway) == 0: return 0 return stairway[-1] + min(stairway_path(stairway[:-1]), stairway_path(stairway[:-2])) if __name__ == '__main__': print(stairway_path([1, 3, 1, 5, 2, 7, 7, 8, 9, 4, 6, 3])) # print(stairway_path([4, 4, 3, 2, 3, 4, 5, 9, 1, 2, 4, 2])) # print(stairway_path([5, 11, 43, 2, 23, 43, 22, 12, 6, 8])) # print(stairway_path([4, 12, 32, 22, 1, 7, 0, 12, 4, 2, 2]))
true
ac152f5fecf95bcd67ecd2cc00319297dcc4b38b
Anupriya7/File_handling_Python
/longestWord.py
252
4.1875
4
def longest_word(file): with open(file,"r") as f: words=f.read().split() max_len=len(max(words,key=len)) print(max_len) for i in words: if(len(i)==max_len): return i print(longest_word("text.txt"))
false
91070b64174970d708ec237ab85415979062f749
Parth-Bhavsar-98/Python-for-Everybody-Coursera-
/Course-1 Programming for Everybody (Getting Started with Python)/Week 6/Assignment_1.py
922
4.34375
4
#Write a program to prompt the user for hours and rate per hour using input to compute gross pay. #Pay should be the normal rate for hours up to 40 and time-and-a-half for the hourly rate for all hours worked above 40 hours. #Put the logic to do the computation of pay in a function called computepay() and use the function to do the computation. #The function should return a value. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). #You should use input to read a string and float() to convert the string to a number. #Do not name your variable sum or use the sum() function. def computepay(h,r): if h>40: ohr=h-40 orate=1.5*r opay=ohr*orate pay=40*r tpay=opay+pay else: tpay=h*r return tpay h = float(input("Enter Hours:")) r = float(input("Enter Rate:")) p = computepay(h, r) print("Pay",p)
true
1191edc1718f6c98b55cdcfd5eaedb1f43093436
Parth-Bhavsar-98/Python-for-Everybody-Coursera-
/Course-1 Programming for Everybody (Getting Started with Python)/Week 4/Assignment_1.py
216
4.21875
4
#Write a program that uses input to prompt a user for their name and then welcomes them. # Enter your name as Input and welcome youself to teh world of Python name = input("Enter your name") print("Hello", name)
true
476c57ebcbdf2aff47981f6e8781b95fdaa0338b
jaydeepdevda/NLP-NounToPlural
/nounToPlural.py
1,252
4.59375
5
# -*- coding: utf-8 -*- """ Created on Sat Aug 26 23:04:04 2017 This script is simple conversion a word from Noun to Plural @author: Jaydeep noun to plural 10 Examples: 1. tree -> trees 2. lake -> lakes 3. window -> windows 4. story -> stories 5. butterfly -> butterflies 6. glass -> glasses 7. wish -> wishes 8. pitch -> pitches 9. bus -> buses 10. box -> boxes """ #function nounToPlural which take a word as argument and return Plural of that word def nounToPlural(noun): if (noun.endswith("y")): #remove "y" with "ies" return noun[0:-1]+"ies"; elif (noun.endswith("ss") or noun.endswith("sh") or noun.endswith("ch")): #append "es" return noun+"es"; elif (noun.endswith("s") or noun.endswith("x")): #append "es" return noun+"es"; else : #for general cases append "s" return noun+"s"; # end of function nounToPlural print "Please Enter Noun you want to convert to Plural:" #input word from console inputNoun = raw_input(); #Convert to lower case inputNoun = inputNoun.lower(); #input word print "Noun : "+inputNoun; #Output Plural of input Word print "Plural: "+nounToPlural(inputNoun);
false
5176079e300428d0d28cf798872669fff93e6ef0
kyalan/CUHK-PyTutorial-2019
/Week1/Classwork Answer/Ex1.4_ans.py
399
4.125
4
# Using Loops to calculate the average of the numeric list [9, 41, 12, 3, 74, 15] # Before 0 0 # 1 9 9 # 2 50 41 # 3 62 12 # 4 65 3 # 5 139 74 # 6 154 15 # After 6 154 25.666 count = 0 sum = 0 print('Before', count, sum) for value in [9, 41, 12, 3, 74, 15] : count = count + 1 sum = sum + value print(count, sum, value) print('After', count, sum, sum / count)
false
17b7c28f436b38226f36b6db92b6aa82b54d502c
AndreeaNenciuCrasi/Programming-Basics-Exercises
/Fourth SI week/How_many_bees.py
1,010
4.15625
4
# How many bees are in the beehive? # bees can be facing UP, DOWN, LEFT, or RIGHT # bees can share parts of other bees # Examples # Ex1 # bee.bee # .e..e.. # .b..eeb # Answer: 5 # Ex2 ``` bee.bee e.e.e.e eeb.eeb ``` *Answer: 8* # Notes # The hive may be empty or null/None/nil/... # Python: the hive is passed as a list of lists (not a list of strings) hive = ["bee.bee", ".e..e..", ".b..eeb"] hive2 = ["bee.bee", "e.e.e.e", "eeb.eeb"] def how_many_bees(hive): bee_row_string = '' bee_column_string = '' for i in hive: bee_row_string += i nr_of_bee = bee_row_string.count('bee') + bee_row_string.count('eeb') list_0 = list(hive[0]) list_1 = list(hive[1]) list_2 = list(hive[2]) for j in range(7): bee_column_string += list_0[j] + list_1[j] + list_2[j] nr_of_bee += bee_column_string.count('bee') + \ bee_column_string.count('eeb') return nr_of_bee print(how_many_bees(hive)) print(how_many_bees(hive2))
false
1302bdc4e059ab4eb2c35593b888e4a01e6e234a
AndreeaNenciuCrasi/Programming-Basics-Exercises
/Second SI week/dimensional_ex7.py
624
4.1875
4
# Create a list a which contains three tuples. The first tuple should contain a single element, the second two elements # and the third three elements. # Print the second element of the second element of a. # Create a list b which contains four lists, each of which contains four elements. # Print the last two elements of the first element of b. a = [(1), (1, 2), (1, 2, 3)] print(a[1][1]) b1 = [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], ] print(b1[0][-2:]) b = [ list(range(10)), list(range(10, 20)), list(range(20, 30)), list(range(30, 40)), ] print(b[0][1:-1])
true
8954f3be1e7af3a3814cb3f53a96a3c32f1d37f7
AndreeaNenciuCrasi/Programming-Basics-Exercises
/Second SI week/function_ex4.py
1,524
4.375
4
import math # Write a function called calculator. It should take the following parameters: two numbers, an arithmetic operation # (which can be addition, subtraction, multiplication or division and is addition by default), and an output format # (which can be integer or floating point, and is floating point by default). Division should be floating-point division. # The function should perform the requested operation on the two input numbers, and return a result in the requested # format (if the format is integer, the result should be rounded and not just truncated). Raise exceptions as appropriate # if any of the parameters passed to the function are invalid. # Call the function with the following sets of parameters, and check that the answer is what you expect: # 2, 3.0 # 2, 3.0, output format is integer # 2, 3.0, operation is division # 2, 3.0, operation is division, output format is integer ADD, SUB, MUL, DIV = range(4) def calculator(a, b, operation=ADD, output_format=float): if operation == ADD: result = a + b elif operation == SUB: result = a - b elif operation == MUL: result = a * b elif operation == DIV: result = a / b else: raise ValueError('False operation') if output_format == float: result = float(result) elif output_format == int: result = math.round(result) else: raise ValueError('Type must be float or int') return result print(calculator(2, 3.0)) print(calculator(2, 3.0, DIV))
true
437a701e73109a252bb6a36ea1a5f8f0163ca208
AleksandrovichDm/git-homework
/les01/les01_normal.py
1,613
4.25
4
# Задача: используя цикл запрашивайте у пользователя число пока оно не станет больше 0, но меньше 10. # После того, как пользователь введет корректное число, возведите его в степерь 2 и выведите на экран. # Например, пользователь вводит число 123, вы сообщаете ему, что число не верное, # и сообщаете об диапазоне допустимых. И просите ввести заного. # Допустим пользователь ввел 2, оно подходит, возводим в степень 2, и выводим 4 number = int( input('Enter number: ') ) while number <= 0 or number >= 10 : print('Number is not correct!') print('Enter number from 1 to 9') number = int( input('Enter number: ')) print(number ** 2) # Задача-2: Исходные значения двух переменных запросить у пользователя. # Поменять значения переменных местами. Вывести новые значения на экран. # Решите задачу, используя только две переменные. # Подсказки: # * постарайтесь сделать решение через действия над числами; a = int( input('Enter number 1: ') ) b = int( input('Enter number 2: ') ) a = a + b b = a - b a = a - b print('number 1: ', a) print('number 2: ', b)
false
73d57d9579fd819f1f485b02e935e8e4208bc1e3
VVVictini/Calculator
/main.py
2,406
4.125
4
import time import sys def main(): def add(x,y): return x+y def subtract(x,y): return x-y def multiply(x,y): return x*y def divide(x,y): return x/y def delay_print(s): for c in s: sys.stdout.write(c) sys.stdout.flush() time.sleep(0.05) delay_print("Hello.") time.sleep(0.5) delay_print(" My name is Colton the Calculator.\n") time.sleep(0.5) delay_print("1.Add\n") time.sleep(0.5) delay_print("2.Subtract\n") time.sleep(0.5) delay_print("3.Multiply\n") time.sleep(0.5) delay_print("4.Divide\n") time.sleep(0.5) i = 0 while i < 100: try: choice = int(input("Enter a number(1,2,3,4): ")) if choice >= 1 and choice <= 4: break else: print("Did you enter a number 1-4? No. So why did you type that! Please enter a number(1,2,3,4) >:(") except ValueError: print("Did you enter a number 1-4? No. So why did you type that! Please enter a number(1,2,3,4) >:(") except NameError: print("Did you enter a number 1-4? No. So why did you type that! Please enter a number(1,2,3,4) >:(") i += 1 i = 0 while i < 100: try: num1 = float(input("Enter First Number: ")) break except ValueError: print("Did you even enter a number? No! So please enter a number this time! >:(") except NameError: print("Did you even enter a number? No! So please enter a number this time! >:(") i += 1 i = 0 while i < 100: try: num2 = float(input("Enter Second Number: ")) break except ValueError: print("Did you even enter a number? No! So please enter a number this time! >:(") except NameError: print("Did you even enter a number? No! So please enter a number this time! >:(") i += 1 if choice==1: print(num1,"+",num2,"=",add(num1,num2)) elif choice==2: print(num1,"-",num2,"=",subtract(num1,num2)) elif choice==3: print(num1,"*",num2,"=",multiply(num1,num2)) elif choice==4: print(num1,"/",num2,"=",divide(num1,num2)) while True: main() if input("Are there anymore calculations you would like for me to do? (y/n): ") != "y": break
true
373ce5acf460a1402cf49f3450e569d4ffce4721
chen240/stu
/exercise_3.5/student_project/student_info.py
2,833
4.125
4
# 3. 改写之前学生信息管理程序,添加如下四个功能 # 5) 按成绩从高至低打印学生信息 # 6) 按成绩从低至高打印学生信息 # 7) 按年龄从大到小打印学生信息 # 8) 按年龄从小到大打印学生信息 # (要求原来输入的列表顺序保持不变) # 1) 添加学生信息 def input_student(): #此函数获取学生信息,并返回学生信息的字典的列表 L = [] # d = {} # 此处所有学生将共用一个字典,会出错 while True: name = input("请输入学生姓名: ") if not name: break age = int(input("请输入学生年龄: ")) score = int(input("请输入学生成绩: ")) d = {} # 重新创建一个新的字典 d['name'] = name d['age'] = age d['score'] = score L.append(d) return L # 2) 查看所有学生信息 def output_student(L): # 以表格形式再打印学生信息 print('+------------+------+-------+') print('| name | age | score |') print('+------------+------+-------+') for d in L: # d绑定的是字典 t = (d['name'].center(12), str(d['age']).center(6), str(d['score']).center(7)) line = "|%s|%s|%s|" % t # t是元组 print(line) print('+------------+------+-------+') # 此函数用来存改学生的信息 def modify_student_info(lst): name = input("请输入要修改学生的姓名: ") for d in lst: if d['name'] == name: score = int(input("请输入新的成绩: ")) d['score'] = score print("修改", name, '的成绩为', score) return else: print("没有找到名为:", name, '的学生信息') # 定义一个删除学生信息的函数 def delete_student_info(lst): name = input("请输入要删除学生的姓名: ") for i in range(len(lst)): # 从0开始把所有索引取出一遍 if lst[i]['name'] == name: del lst[i] print("已成功删除: ", name) return True else: print("没有找到名为:", name, "的学生") # 5) 按成绩从高至低打印学生信息 def print_by_score_desc(lst): L=sorted(lst,key=lambda d: d['score'], reverse=True) output_student(L) # 6) 按成绩从低至高打印学生信息 def print_by_score_asc(lst): L=sorted(lst, key=lambda d: d['score']) output_student(L) # 7) 按年龄从大到小打印学生信息 def print_by_age_desc(lst): L=sorted(lst, key=lambda d: d['age'], reverse=True) output_student(L) # 8) 按年龄从小到大打印学生信息 def print_by_age_asc(lst): L=sorted(lst, key=lambda d: d['age']) output_student(L)
false
c3fe2bc56054f3e553e7bd59756adbecb5d81079
jmalonzo/project-euler-solutions
/py/4.py
577
4.21875
4
#!/usr/bin/env python import sys def palindrome(s_num): length = len(s_num) for x in range(length / 2): if s_num[x] is not s_num[length - x - 1]: return False return s_num if __name__ == '__main__': start = 999 end = 99 lp = 0 for i in range(start, end, -1): for j in range(start, end, -1): num = i * j p = int(palindrome(str(num))) if p and p > lp: lp = p print >> sys.stdout, "The largest palindrome made from the product of two 3-digit numbers is: %s" % lp
false
1726b8c5772153e4cfc7fa62fae6921c4d1ac9cd
megangodwin/cp1404practicals
/prac5/string_occurances.py
236
4.25
4
""" CP1404/CP5632 Practical Counts the occurrences of words in a string """ string_to_evaluate = input("Text :") string_dict = {} string_dict = string_to_evaluate.split() for item in string_dict: item in print(string_list)
true
2d4230d06a2b5ec17f0c3efea8a79c3129fcaa3d
FilipLe/DailyInterviewPro-Unsolved
/Convert to Hexadecimal (SOLVED)/dec_to_hex.py
1,411
4.25
4
import math #Examples step by step converting to Hex #Example 1: 1365 to hex #1365 ÷ 16 = 85 R 5 --> 5 # 85 ÷ 16 = 5 R 5 --> 5 # 5 --> 5 #--> Hex value: 555 #Example 2: 1237 #1237 ÷ 16 = 77 R 5 --> 5 # 77 ÷ 16 = 4 R 13 --> 13 = D --> D # 4 --> 4 #-->Hex Value: 4D5 def to_hex(n): hexVal = '' remainder = 0 while n > 0: #When n=123, 123÷16=7R11 --> currentQuotient=7 currentQuotient = math.floor(n/16) #current stores the product of currentQuotient and 16 (to later be subtracted to find remainder) current = currentQuotient*16 #remainder = n - product of currentQuotient and 16 --> find remainder of n when divided by 16 remainder = n - current #in Hexadecimal: #0-9 in decimal = 0-9 in hex #10-15 in dec = A-F in hex if remainder < 10: hexVal += str(remainder) else: if remainder == 10: hexVal += 'A' elif remainder == 11: hexVal += 'B' elif remainder == 12: hexVal += 'C' elif remainder == 13: hexVal += 'D' elif remainder == 14: hexVal += 'E' else: hexVal += 'F' n = currentQuotient #Reverse hexVal return hexVal[::-1] print(to_hex(123)) # 7B #123÷16=7R11-->11=B #7÷16=0R7 #7B
true
8c5bf3e6d5d7cd8ce823d8d2d2204a49c98f120d
FilipLe/DailyInterviewPro-Unsolved
/Palindrome Integers (SOLVED)/checkPalindrome.py
939
4.125
4
import math def is_palindrome(n): # Fill this in. #Convert num into string stringVal = str(n) #Store the digits in a list arr = [] #Loop through the digits and append them into the list arr[] for digits in stringVal: arr.append(digits) #Number of the digits sizeVal = len(arr) #initialize counter counter = 0 #since we're working with palindromes supposingly, we only #need to loop through the first half and check if they #correspond to the last half #E.g. if it's a number consisting of 7 digits: # check if digit[0]=digit[6], digit[1]=digit[5],... and so on while counter < math.floor(sizeVal/2): if arr[counter] != arr[sizeVal-1-counter]: return False else: return True print(is_palindrome(1234321)) # True print(is_palindrome(1234322)) # False print(is_palindrome(1221)) # True
true
37e896be8e1aaaa16be19ba3b122bb8c0dacc84f
FilipLe/DailyInterviewPro-Unsolved
/Intersection of Lists (SOLVED)/listIntersection.py
477
4.34375
4
def intersection(list1, list2, list3): # Fill this in. #Array to store intersections arr = [] #Iterate through all the elements in list1 for i in list1: #Logic Gate AND #-->Both conditions have to be met in order to execute #-->Add element ONLY if it's in both list2 and list3 if i in list2 and i in list3: arr.append(i) return arr print(intersection([1, 2, 3, 4], [2, 4, 6, 8], [3, 4, 5])) # [4]
true
bba97d7fe44664aa78c96693003aa168d589a5e9
deesnow/PrincipleOfComputing
/HW1_q9/py.py
416
4.28125
4
def appendsums(lst): """ Repeatedly append the sum of the current last three elements of lst to lst. """ for i in range(25): new_value = lst[len(lst)-1] + lst[len(lst)-2] + lst[len(lst)-3] lst.append(new_value) print lst return lst sum_three = [0, 1, 2] appendsums(sum_three) print sum_three[20] print "DONE"
true
1f0d67b96fb3d80015d44aac2fe07263382df42b
jupa005/Guessing_games.py
/Program guesses your number.py
684
4.125
4
from random import * print('HELLO! WELCOME TO GUESSING GAME!') print('Imagine one number 1-100 and i will try to guess it') print('If your number is lower than my guess, press 1') print('If your number is higher than my guess, press 2') print('If I hit your number, press 3') mini=1 maks=100 av=50 guess=0 c=randint(mini,maks) a=int(input('Is your number '+str(c)+'?')) guess+=1 while a!=3: guess+=1 if a==1: maks=c-1 c=randint(mini,maks) elif a==2: mini=c+1 c=randint(mini,maks) a=int(input('Is your number '+str(c)+'?')) print('I needed '+str(guess)+" tries to guess your number! ")
true
99874d7fe26a1d3fe66e812fc4b4a47ac88d1675
Suyash906/Design-2
/232_Implement_Queue_using_Stacks.py
1,944
4.15625
4
# Time Complexity : # push: O(n) # pop: O(1) # top: O(1) # empty: O(1) # # Space Complexity : O(n) [n is the number of elements inserted into Stack] # # Did this code successfully run on Leetcode : Yes # # Any problem you faced while coding this : No # # Problem Approach # 1. Two stack(main_stack and aux_stack) are used to implement the queue operations # 2. When a new element needs to enqueued, the existing elements are popped from the main_stack and pushed in to the aux_stack. The new element is pushed on to the main stack. At the end, all the elememts in the aux_stack are popped out and pushed on to the main_stack. class MyQueue: def __init__(self): """ Initialize your data structure here. """ self.main_stack = [] self.aux_stack = [] def push(self, x: int) -> None: """ Push element x to the back of queue. """ if len(self.main_stack) == 0: self.main_stack.append(x) else: while self.main_stack: self.aux_stack.append(self.main_stack.pop()) self.main_stack.append(x) while self.aux_stack: self.main_stack.append(self.aux_stack.pop()) def pop(self) -> int: """ Removes the element from in front of queue and returns that element. """ if self.main_stack: return self.main_stack.pop() def peek(self) -> int: """ Get the front element. """ if self.main_stack: return self.main_stack[-1] def empty(self) -> bool: """ Returns whether the queue is empty. """ return False if len(self.main_stack) > 0 else True # Your MyQueue object will be instantiated and called as such: # obj = MyQueue() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.peek() # param_4 = obj.empty()
true
d61e5149effa07c69f1160d8e3634e5a2c18833b
felipecpassos/Rat-Escape-AI-Pathfinding
/priority_queue.py
1,001
4.125
4
# Modified implementation of PriorityQueue using tuple as value class PriorityQueue(object): def __init__(self): self.queue = [] def __str__(self): return ' '.join([str(i) for i in self.queue]) # for checking if the queue is empty def isEmpty(self): return len(self.queue) == 0 # for inserting an element in the queue def insert(self, data): self.queue.append(data) # for popping an element based on Priority def delete(self): try: min = 0 for i in range(len(self.queue)): # acessing the second element ([1]) in the tuple: the weight of the node if self.queue[i][1] < self.queue[min][1]: min = i item = self.queue[min] del self.queue[min] return item except IndexError: print('ERRAO') exit() def clear(self): while not self.isEmpty(): self.delete()
true
e80e5097cf98b0be5a2ca0ecacad47947a48b9f0
aishahanif666/Python_practice
/Rock, paper, scissor(game).py
1,601
4.21875
4
#Rock, paper, Scissor game import random comp = 0 user = 0 comp_list=["Rock","Paper","Scissors"] while True: user_choice=input('Enter "R" for Rock, "P" for Paper and "S" for Scissor: ') comp_choice = random.choice(comp_list) print("Computer's Choice:",comp_choice) if user_choice=="R" and comp_choice=="Paper": print("\nComputer got 1 point\n") comp+=1 print(f"Computer Score: {comp}\nYour score: {user}\n") elif user_choice=="R" and comp_choice=="Scissors": print("\nYou got 1 point\n") user+=1 print(f"Computer Score: {comp}\nYour Score: {user}\n") elif user_choice=="P" and comp_choice=="Rock": print("\nYou got a point\n") user+=1 print(f"Computer Score: {comp}\nYour Score: {user}\n") elif user_choice=="P" and comp_choice=="Scissors": print("\nComputer got another point\n") comp+=1 print(f"Computer Score: {comp}\nYour Score: {user}\n") elif user_choice=="S" and comp_choice=="Rock": print("\nComputer gain a point\n") comp+=1 print(f"Computer Score: {comp}\nYour Score: {user}\n") elif user_choice=="S" and comp_choice=="Paper": print("\nYou got a point\n") user+=1 print(f"Computer Score: {comp}\nYour Score: {user}\n") else: print("\nYou both choose the same\n") if user==3: print("You Won!!\n") break elif comp==3: print("Computer Won!!You've tried well...\n") break print("\nGAME OVER")
true
61a9a7c6c08c348944c2b6083850467c8928fb3f
lopezz/py-scripts
/random-passwd/generate_pass.py
1,306
4.1875
4
""" Generate a random password based of the lenght specified optional arguments can be passed to specify the use of different sets of characters. """ import random import string def generate_pass(lenght=8, lower=True, upper=True, digits=True, special=True): """Returns a random password based of the lenght specified Optional arguments: lentght -- the lenght of the password, defaults to 8. lower -- Use lowercase characters. upper -- Use upper characters. digits -- Use numbers. special -- Use special characters (such as '?*+{}...') """ lowercase = string.ascii_lowercase if lower else '' uppercase = string.ascii_uppercase if upper else '' digit_chars = string.digits if digits else '' special_chars = string.punctuation if special else '' alphabet = lowercase + uppercase + digit_chars + special_chars if alphabet != '': try: return ''.join(random.SystemRandom().sample(alphabet, lenght)) # SystemRandom() uses os.urandom(), this is not available in all systems # If a randomness source is not found, NotImplementedError will be raised. except NotImplementedError: return ''.join(random.sample(alphabet, lenght)) else: raise Exception('There must be at least one true value')
true
b6c9f122f81180bb9a62791e53646b6108c30244
geangohn/nlp_projects
/dish_tagging/src/data_cleansing.py
2,015
4.34375
4
import pandas as pd import numpy as np def clean(df): """Cleans the dataset""" # Drop dishes that does not have product name df = df[~df['product_name'].isna()] print('taking into account only dishes with product names: {}'.format(df.shape[0])) # Drop dishes without ingredients information df = df[~df['ingredients_text'].isna()] print('taking into account only dishes with ingredients info: {}'.format(df.shape[0])) # Drop dishes that do not have category df = df[~df['main_category'].isna()] print('taking into account only dishes with category: {}'.format(df.shape[0])) # Drop dishes that have category name NOT in English df = df[df.main_category.str.contains('en:')] print('taking into account only dishes with category in English: {}'.format(df.shape[0])) # Drop categories with small value_counts big_categories = df.main_category.value_counts()[df.main_category.value_counts() > 300].index.tolist() df = df[df['main_category'].isin(big_categories)] print('taking into account only categories with value_count > 300: {}'.format(df.shape[0])) # Let's drop some confusing categories (that can contain another categories). For example, # "Breakfast" can contain "meals" drop_categories = ['en:breakfasts', 'en:baby-foods'] df = df[~df['main_category'].isin(drop_categories)] print('taking into account only non-confusing categories: {}'.format(df.shape[0])) # Drop dishes with product name lengths < 3 (there are some strange items like 'O') df = df[df['product_name'].apply(lambda x: len(x) >= 3)] print( 'taking into account only dishes with correct product_name (product name length >= 3): {}'.format(df.shape[0])) # Drop dishes with ingredient info lengths < 5 df = df[df['ingredients_text'].apply(lambda x: len(x) >= 5)] print('taking into account only dishes with correct ingredients_text (ingredients text length >= 5): {}'.format( df.shape[0])) return df
true
ef3ad85a0a2ed4f92dfd4c0191552a58c9e1dc62
seiha1/git_practice
/list/guests.py
939
4.34375
4
#Guest List guests = ['dara','sreymom','chhayou','many'] for person in guests: print(person.title()+" is invited to dinner.") print("Number of guests:",len(guests)) print("----------") #Changing Guest List print(guests[0].title()+ " can't make the dinner.") guests[0]='Seiha' for person in guests: print(person.title()+" is invited to dinner.") print("Number of guests:",len(guests)) print("----------") #More Guests print("We just found a bigger dinner table for more guests") guests.insert(0,'seavhuong') guests.insert(3,'sreypich') guests.append('samay') for person in guests: print(person.title()+" is invited to dinner.") print("Number of guests:",len(guests)) print("----------") #Shrinking Guest List print("We can invite only two people for dinner.") guests.pop() guests.pop() guests.pop() guests.pop() guests.pop() for person in guests: print(person.title()+" is invited to dinner.") del guests[0] del guests[0] print(guests)
false
1cc66a9deff9e35be0a13c6e87ba38d3fc2d12f7
Azfarbakht/Python-Games
/9. Eat Food Game/Eat Food Game.py
2,568
4.15625
4
#We have learnt so much about so far. We have seen what variables are and how we can store data in them. We have seen how we can reduce the lines in our code by writing loops and automating different parts of our project. Exlored conditionals. We have even learnt how to make a game. #Importing Libraries import turtle import random from random import randint #Screen Commands window = turtle.Screen() turtle.tracer(0) #Making Variables boundary = turtle.Turtle() player = turtle.Turtle() charm = turtle.Turtle() score = turtle.Turtle() spawnc = False points = 0 style = ('Courier', 30, 'italic') #Making the Boundary boundary.speed('fastest') boundary.hudeturtle() boundary.goto(0,0) for i in range(4): boundary.fd(250) boundary.rt(90) boundary.hideturtle() #Spawning the Player player.shape('turtle') player.up() player.goto(125,-125) player.showturtle() #Defining Functions def forward(): player.fd(10) def backward(): player.fd(-10) def left(): player.lt(10) def right(): player.rt(10) def spawn(spawnc, charmx, charmy, charm): if spawnc == False: charm.showturtle() charm.up() charm.goto(charmx, charmy) charm.color('red') charm.shape('circle') spawnc = True def clash(player, charmx1, charmy1, charm): if player.distance(charmx1,charmy1) < 15: return False def scorehandling(points): score.clear() score.up() score.hideturtle() score.goto(0,20) point = str(points) score.write("Score : "+ point, style) #Game Loop while True: #We're constantly updating our game window so the screen refreshes and all new changes are visible. window.update() #Adding Movements to our turtle window.onkey(forward, "Up") window.onkey(backward, "Down") window.onkey(left, "Left") window.onkey(right, "Right") window.listen() #Making Sure the turtle stays within boundaries if(int(player.xcor())<= 0): y = int(player.ycor()) player.goto(1,y) if(int(player.xcor())>= 250): y = int(player.ycor()) player.goto(249,y) if(int(player.ycor())>= 0): x = int(player.xcor()) player.goto(x,-1) if(int(player.ycor())<= -250): x = int(player.xcor()) player.goto(x,-249) #Randomizing the position of the Red Dot charmx = randint(10,240) charmy = -1 * randint(10,240) #Saving the Position of the Red Dot if spawnc == False: charmx1 = charmx charmy1 = charmy #Spawning the Circle and Detecting CLashes spawn(spawnc, charmx, charmy, charm) spawnc = clash(player, charmx1, charmy1, charm) if(spawnc==False): points+=1 scorehandling(points)
true
a7f7a27d99de535050d1a3d59e9b4c0df27f2678
nishantsingh01/Python
/Ques4.py
253
4.1875
4
print("Enter a No. greater than or equal to 10:") num = int(input()) if num >= 10: _set = set() while num != 0: _set.add(num%10) num = int(num/10) print("Set: ", _set) else: print("Sorry! Number is less than 10")
true
95f45218766ef02750cead71ef1e8164c10e5a4c
Avani18/Algorithms
/Sorting/MergeSort.py
1,572
4.40625
4
#Merge Sort- Split array into half and recursively split both the halves till 1 element is left and then they are merged in order #Function for Merge Sort def mergeSort(arr): #If length of array is greater than 1 if (len(arr) > 1): #Index of mid element mid = len(arr) // 2 #Left half of array left = arr[:mid] #Right half of array right = arr[mid:] #Recursive call to left half mergeSort(left) #Recursive call to right half mergeSort(right) #3 variables for merging i = 0 j = 0 k = 0 #For accessing resultant array's index #i to iterate the left half #j to iterate the right half while (i < len(left) and j < len(right)): #If element in left half is less than element in right half if (left[i] < right[j]): #Add element to resultant array arr[k] = left[i] #Increment i i += 1 #Element in right half is less than element in left half else: #Add element to resultant array arr[k] = right[j] #Increment j j += 1 #Increment k as 1 element is added k += 1 #If elements are remaining in left half while (i < len(left)): #Add to array arr[k] = left[i] #Increment indices i += 1 k += 1 #If elements are remaining in right half while (j < len(right)): #Add to array arr[k] = right[j] #Increment indices j += 1 k += 1 print ("Enter an array of integers") arr = list(map(int, input().split())) mergeSort(arr) print ("The sorted array is: ", arr) #Divide and Conquer Algorithm #Time Complexity: O(nlog n) #Auxiliary Space: O(n)
true
1c003c1f5f7e3b4aa4d013bdf084c469fb258621
JacksonMorton/Advanced_Python_at_NYU
/Session_1/homework_1_4.py
2,388
4.53125
5
#!/usr/bin/env python """ Advanced Python @ NYU w/ David Blaikie homework_1_4.py (Extra Credit) Write the classic "number guessing" program in which you think of a number and the computer program attempts to guess it. See suggested output for behavioral details. """ from sys import argv from sys import exit print 'Think of a number between 0 and 100, and I will try to guess it.'\ ' Hit [Enter] to start.' raw_input() guess_number = 50; guess_history = [50]; last_guess = 50 while True: guess = raw_input('Is it {}? (yes/no/quit) '.format(guess_number)) last_guess_dummy = guess_number if guess == 'yes': print 'I knew it!\n' exit(1) elif guess == 'quit': print "Leaving the number guessing game...\n" exit(1) elif guess == 'no': higher_lower = raw_input('Is it higher or lower than {}? '.format(guess_number)) if higher_lower == 'lower': if guess_number == min(guess_history): guess_number = guess_number / 2 else: diffs = [] for num in guess_history: if guess_number - num > 0: diffs.append(guess_number - num) else: pass # highest_lower = highest number that has been guessed that is lower than guess_number highest_lower = guess_number - min(diffs) guess_number = guess_number - ((guess_number - highest_lower) / 2) elif higher_lower == 'higher': if guess_number == max(guess_history): guess_number = guess_number + ((100 - guess_number) / 2) else: diffs = [] for num in guess_history: if num - guess_number > 0: diffs.append(num - guess_number) else: pass # lowest_higher = lowest number that has been guessed that is higher than guess_number lowest_higher = min(diffs) + guess_number guess_number = guess_number + ((lowest_higher - guess_number) / 2) else: print 'Invalid response. Enter either \'higher\' or \'lower\'.' print '\n' guess_history.append(guess_number) last_guess = last_guess_dummy else: print 'Invalid response. Enter either \'yes\', \'no\', or \'quit\'.'
true
d00984ccc4161ea9d4e4af07905a5980d419bf3a
Er-Divya/PythonBegins
/ReadingaFile.py
563
4.28125
4
# This code will demonstrate how to read files in python emp_file = open("employee_file_read.txt", "r") # Check if the file is readable or not print(emp_file.readable()) # Read first line. Once this command run cursor be on second line and we can read that by writing same command. line = emp_file.readline() print(line) print(emp_file.readline()) # Read all lines: this method returns all lines in list print(emp_file.readlines()) # Read whole file, this does not work if used after readline method and vice versa. print(emp_file.read()) emp_file.close()
true
63f2b572930b83c406247bcd1520a53d451b7a99
Er-Divya/PythonBegins
/UnPacking.py
376
4.4375
4
# UnPacking items = [1, 2, 3, 4, 5, 6, 7] print(items) # Below code will unpack first element of list in a and rest will be ignored. a, _ = [3, 4] print(a) # First two elements of the list will be unpacked and stored in x and y. Rest all will be stored in z x, y, *z = [10, 11, 12, 13, 14, 15, 16, 17, 18] print("Printing value of x, y and z: ") print(z) print(y) print(z)
true
802cfb9696a785d97501de97edfabbcb14f2fdd8
bhumip214/Data-Structures
/heap/max_heap.py
2,932
4.21875
4
class Heap: def __init__(self): self.storage = [] # adds the input value into the heap; this method should ensure that the inserted value is in the correct spot in the heap def insert(self, value): self.storage.append(value) self._bubble_up(len(self.storage) - 1) # removes and returns the 'topmost' value from the heap; this method needs to ensure that the heap property is maintained after the topmost element has been removed. def delete(self): self.storage[0], self.storage[len(self.storage) - 1] = self.storage[len(self.storage) - 1], self.storage[0] topmost_value = self.storage.pop() self._sift_down(0) return topmost_value # returns the maximum value in the heap in constant time. def get_max(self): return self.storage[0] # returns the number of elements stored in the heap. def get_size(self): return len(self.storage) # moves the element at the specified index "up" the heap by swapping it with its parent if the parent's value is less than the value at the specified index # the index parameter is the index of the node wherever it is in the array def _bubble_up(self, index): # loop until either the element reaches the top of the array # or we'll break thhe loop when we realize the element's priority # is not larger than its parent's value while index > 0: # the value at 'index' fetches the index of its parent parent = (index - 1) // 2 # check if the element at 'index' has priority than the elemts at the parent index if self.storage[index] > self.storage[parent]: # then we need to swap the elements self.storage[index], self.storage[parent] = self.storage[parent], self.storage[index] # we also need to update the index index = parent else: # otherwise, our element has reached a spot in the heap where its parent # element had higher priority; stop climbing break # grabs the indices of this element's children and determines which child has a larger value. If the larger child's value is larger than the parent's value, the child element is swapped with the parent. def _sift_down(self, index): largest = index l = (2 * index) + 1 r = (2 * index) + 2 # Check if left child exists and its value is greater than root value if l < self.get_size() and self.storage[l] > self.storage[largest]: largest = l # Check if right child exists and its value is greater than root value if r < self.get_size() and self.storage[r] > self.storage[largest]: largest = r # Check if index of largest value is not same as the index of root value if largest != index: # swap self.storage[index], self.storage[largest] = self.storage[largest], self.storage[index] # keep recursing until both largest and index matches self._sift_down(largest)
true
c53fcea372864928e8396f5261d2e7d868cfb460
Rings-Of-Neptune/Python-Project-Repository
/IT-140 3.12 Lab.py
894
4.15625
4
input_month = input() input_day = int(input()) valid_dates = {"January":31, "February":28, "March":31, "April":30, "May":31, "June":30, "July":31, "August":31, "September":30, "October":31, "November":30, "December":31} if (input_month in valid_dates) and (0 < input_day <= valid_dates[input_month]): if ((input_month == "March") and (input_day >= 20)) or (input_month in ["April", "May"]) or ((input_month == "June") and (input_day <= 20)): print("Spring") elif ((input_month == "June") and (input_day > 20)) or (input_month in ["July", "August"]) or ((input_month == "September") and (input_day <= 20)): print("Summer") elif ((input_month == "September") and (input_day > 20)) or (input_month in ["October", "November"]) or ((input_month == "December") and (input_day <= 20)): print("Autumn") else: print("Winter") else: print("Invalid")
true
a0f30735d3361fae0f4a70c2f57df6727e3c9dee
csemanish12/DSA
/Algorithms/bubble sort/merge sort/Merge Sort.py
1,926
4.21875
4
def merge(arr, left_index, middle_index, right_index): """ sorts the array in descending order change left_half[i] <= right_half[j] to left_half[i] >= right_half[j] for sorting in descending order """ n1 = middle_index - left_index + 1 n2 = right_index - middle_index # create temp arrays left_half = [0] * n1 right_half = [0] * n2 # copy data to temp arrays left and right for i in range(0, n1): left_half[i] = arr[left_index + i] for j in range(0, n2): right_half[j] = arr[middle_index + 1 + j] # merge the temp arrays back into arr[left..right] i = 0 # initial index of first subarray j = 0 # initial index of second subarray k = left_index # initial index of merged subarray while i < n1 and j < n2: if left_half[i] <= right_half[j]: arr[k] = left_half[i] i += 1 else: arr[k] = right_half[j] j += 1 k += 1 # copy the remaining elements of left, if there are any while i < n1: arr[k] = left_half[i] i += 1 k += 1 # copy the remaining elements of right, if there are any while j < n2: arr[k] = right_half[j] j += 1 k += 1 def merge_sort(arr, left_index, right_index): """ :param arr: array of numbers :param left_index:left index :param right_index:right index """ if left_index < right_index: # same as (l + r)//2, but avoids overflow for large l and h middle_index = (left_index + (right_index - 1)) // 2 # sort first and second halves merge_sort(arr, left_index, middle_index) merge_sort(arr, middle_index + 1, right_index) merge(arr, left_index, middle_index, right_index) numbers = [12, 11, 4, 1, 9, 0, 16] print('before sorting:', numbers) merge_sort(numbers, 0, len(numbers) - 1) print('after sorting:', numbers)
false
70ded82c64ecbaf715229a60c11a2de5daa8ed0b
DannyMeister177/CEBD-1160-PyCharm
/pandas-notebook/pandas-homework-advanced.py
2,691
4.40625
4
import pandas as pd # 2. Load the insurance.csv in a DataFrame using pandas. Explore the dataset using functions like to_string(), columns, # index, dtypes, shape, info() and describe(). Use this DataFrame for the following exercises. df = pd.read_csv('winter2020-code/4-python-advanced-notebook/data/insurance.csv', header=0) print(df.to_string()) print() print(df.columns) print() print(df.index) print() print(df.dtypes) print() print(df.shape) print() print(df.info()) print() print(df.describe()) print() # 3. Print only the column age print(df.age) print() # 4. Print only the columns age,children and charges print(df[['age', 'children', 'charges']]) print() # 5. Print only the first 5 lines and only the columns age,children and charges print(df[['age', 'children', 'charges']].iloc[:5]) print() # 6. What is the average, minimum and maximum charges ? print(df['charges'].mean()) print() print(df['charges'].min()) print() print(df['charges'].max()) print() # 7. What is the age and sex of the person that paid 10797.3362. Was he/she a smoker? person = df[df["charges"] == 10797.3362].index[0] print(f'The age of the person is {df.at[person, "age"]} and the sex is {df.at[person, "sex"]}.\n') print(f'Is this person a smoker: {df.at[person, "smoker"]}\n\n') # 8. What is the age of the person who paid the maximum charge? person2 = df[df['charges'] == df['charges'].max()].index[0] print(f'The age of the oldest person is {df.at[person2, "age"]}.\n\n') # 9. How many insured people do we have for each region? print('How many insured people do we have for each region?\n') for name, group in df.groupby('region'): print(f'Group: {name}') print(f'Size: {len(group)} insured') print('------------------------\n') # 10. How many insured people are children? print(f'Total number of insured children: {df["children"].sum()}\n') # 11. What do you expect to be the correlation between charges and age, bmi and children? print(f'I expect the correlation between charges and age to be positive as health risks increase with age so \n' f'insurers will raise premiums to older people and depending on the plan, using the insurance will involve\n' f'deductibles or other out of pocket expenses which may be included in this dataset.\n' f'I expect the correlation between bmi and children to be positive as bmi and age are positively correlated\n' f'and age and children should also be positively correlated.\n') # 12. Using the method corr(), check if your assumptions were correct. print(f'Correlation between charges and age: {df["charges"].corr(df["age"])}') print(f'Correlation between bmi and children: {df["bmi"].corr(df["children"])}\n')
true
4dfb659cfb4fada710bbe1f21f910247fb0a1b0e
egolodnikov/qa_projects
/exceptions/exceptions.py
1,365
4.375
4
""" # Syntax error example: print(15/5)) """ """ # ZeroDivisionError example: print(15 / 0) """ """ # Example custom ValueError: name = input("Enter your name: ") age = int(input("Enter your age: ")) print("Your name is: " + name) if age < 18: raise ValueError("Error: you need to be over 18") else: print("Your age is: " + str(age)) """ """ # Example custom Exception: number = 4 if number < 5: raise Exception("Error: value need to be greater than 5") """ """ # Example custom AssertionError x = 1 y = 0 assert y != 0, "Invalid Operation" print(x / y) """ """ # Example custom AssertionError: def print_age(age): assert age > 0, "The value for age has to be greater than zero" print("Your age is: " + str(age)) print_age(-1) """ """ # Example try except ZeroDivisionError try: num1 = 4 num2 = 0 result = num1 / num2 print(result) except ZeroDivisionError as e: print(e) """ """ # Example try except else TypeError: try: num1 = '4' num2 = 2 result = num1 / num2 print("End of try block") except TypeError as e: print("TypeError: Value has to be an integer") else: print("No exception raised") """ """ # Example try except finally FileNotFoundError try: f = open("example1.txt") except FileNotFoundError: print("FileNotFoundError: The file is not found") finally: f.close() """
true
9c11afa8ca1f9cffa53b812396d6dcddb1ed03fa
M4cs/python-ds
/algorithms/sorting/bubble_sort.py
343
4.25
4
''' Bubble Sort worst time complexity occurs when array is reverse sorted - O(n^2) Best time scenario is when array is already sorted - O(n) ''' def bubbleSort(array): n = len(array) for i in range(n): for j in range(0, n-i-1): if array[j] > array[j+1]: array[j], array[j+1] = array[j+1], array[j]
true
d1270d8e71fa26d016c3097167efb2a1c626ea16
C1ickz/NNfS
/p03-Dot-Product.py
837
4.125
4
""" 1D Array = Vector 2D Array = Matrix - Array of vectors 3D Array = Tensor A tensor is an object that can be represented as an array, not just an array. """ import numpy as np inputs = [4, 5, 6, 7] weights = [[0.1, 0.3, -0.5, 0.402], [0.584, 0.102, -0.808, 0.404], [0.27, 0.53, -0.511, 0.22]] # Matrix of vectors biases = [5, 2, .5] output = np.dot(weights, inputs) + biases # First element that is passed is how return value is indexed print(output) ''' layer_outputs = [] # outputs of current layer for neuron_weights, neuron_bias in zip(weights, biases): neuron_output = 0 for n_input, weight in zip(inputs, neuron_weights): neuron_output += n_input*weight neuron_output += neuron_bias layer_outputs.append(neuron_output) return(layer_outputs) print(layer_outputs) '''
true
97d65f9db793caf625f081442d7b5365230dfd6f
Gangadharbhuvan/31-Day-Leetcode-May-Challenge
/Day-16_Odd_Even_Linked_List.py
1,384
4.125
4
''' Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity. Example 1: Input: 1->2->3->4->5->NULL Output: 1->3->5->2->4->NULL Example 2: Input: 2->1->3->5->6->4->7->NULL Output: 2->3->6->7->1->5->4->NULL Note: The relative order inside both the even and odd groups should remain as it was in the input. The first node is considered odd, the second node even and so on ... ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def oddEvenList(self, head: ListNode) -> ListNode: no_of_nodes = 0 last = None temp = head while(temp!=None): no_of_nodes += 1 last = temp temp = temp.next temp = head while(no_of_nodes > 1): if temp!= None and temp.next!=None: last.next = temp.next last = last.next temp.next = temp.next.next temp = temp.next last.next = None no_of_nodes -= 2 return head
true
94429272ebae1933b44b59643dc92008b43576be
Gangadharbhuvan/31-Day-Leetcode-May-Challenge
/Day-14_Implement_a_trie.py
1,768
4.40625
4
''' Implement a trie with insert, search, and startsWith methods. Example: Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // returns true trie.search("app"); // returns false trie.startsWith("app"); // returns true trie.insert("app"); trie.search("app"); // returns true Note: You may assume that all inputs are consist of lowercase letters a-z. All inputs are guaranteed to be non-empty strings. ''' class Trie: def __init__(self): """ Initialize your data structure here. """ self.head={} def insert(self, word: str) -> None: """ Inserts a word into the trie. """ curr=self.head for i in word: if i not in curr: curr[i]={} curr=curr[i] curr['*']=True def search(self, word: str) -> bool: """ Returns if the word is in the trie. """ curr=self.head for i in word: if i not in curr: return False else: curr=curr[i] if '*' in curr: return True else: return False def startsWith(self, prefix: str) -> bool: """ Returns if there is any word in the trie that starts with the given prefix. """ curr=self.head for i in prefix: if i not in curr: return False else: curr=curr[i] return True # Your Trie object will be instantiated and called as such: # obj = Trie() # obj.insert(word) # param_2 = obj.search(word) # param_3 = obj.startsWith(prefix)
true
768d2015cfe8e08e4a1836f8c084428df27c0463
18-2-SKKU-OSS/2018-2-OSS-E5
/sorts/1.Bubble_sort.py
1,404
4.21875
4
""" 파이썬으로 bubble sort를 구현한 코드입니다. 함수 bubble_sort: 버블 소트라고 불리며 두 인접한 원소를 검사하며 정렬하는 방법입니다. 코드가 단순하기 때문에 자주 사용 됩니다. """ from __future__ import print_function def bubble_sort(collection): """ Examples: >>> bubble_sort([0, 5, 4, 2, 2]) [0, 2, 2, 4, 5] >>> bubble_sort([]) [] >>> bubble_sort([-2, -5, -45]) [-45, -5, -2] >>> bubble_sort([-23,0,6,-4,34]) [-23,-4,0,6,34] """ length = len(collection) for i in range(length-1): swapped = False for j in range(length-1-i): if collection[j] > collection[j+1]: swapped = True #인접한 원소를 비교후 배열에서 왼쪽의 원소가 더작을 경우 True 만들어준다 collection[j], collection[j+1] = collection[j+1], collection[j] if not swapped: break # 원소들이 이미 정렬되어있다면 종료한다. return collection if __name__ == '__main__': try: raw_input # Python 2 except NameError: raw_input = input # Python 3 user_input = raw_input('Enter numbers separated by a comma:').strip() #콤마로 원소들을 구분한다. unsorted = [int(item) for item in user_input.split(',')] print(*bubble_sort(unsorted), sep=',')
false
d7d62cbaf2e5de9069c544030619bf7120fa1073
18-2-SKKU-OSS/2018-2-OSS-E5
/Maths/find_hcf.py
651
4.3125
4
# Program to find the HCF of two Numbers def find_hcf(num_1, num_2): if num_1 == 0: #exception case return num_2 if num_2 == 0: #exception case return num_1 # Base Case if num_1 == num_2: #if two numbers are equal return num_1 if num_1 > num_2: #if num1 is larger than num2, recursively function call return find_hcf(num_1 - num_2, num_2) return find_hcf(num_1, num_2 - num_1) def main(): num_1 = int(input("input number 1: ")) num_2 = int(input("input number 2: ")) print('HCF of %s and %s is %s:' % (num_1, num_2, find_hcf(num_1, num_2))) if __name__ == '__main__': main()
true
c787c1170025b7371e6cbb7c2f8246f9c297aebc
s3wasser/List-Organization
/mergeSory.py
1,188
4.3125
4
''' Author: Sabrina Wasserman Date: December 1, 2015 Title: mergeSort Purpose: to run merge sort on these algorithms ''' num_array = list() elements = raw_input("Please enter the number of elements in your array:") print 'Enter each element of your array, followed by "enter"' for i in range(int(elements)): n = raw_input('item ' + str(i+1) + ': ') num_array.append(int(n)) print 'Your list: ', num_array def mergeSort(list): if len(list)<=1: return list #Dividing up the List middleOfList = len(list)/2 listFirstHalf = list[: middleOfList] listSecondHalf = list[middleOfList :] #Running merge sort recursively to shorten the list leftSideArray = mergeSort(listFirstHalf) rightSideArray = mergeSort(listSecondHalf) #Merging the values return merge(leftSideArray, rightSideArray) def merge(leftSide, rightSide): if len(leftSide) == 0: return rightSide elif len(rightSide) == 0: return leftSide if leftSide[0] <= rightSide[0]: return [leftSide[0]] + merge(leftSide[1:], rightSide) else: return [rightSide[0]] + merge(leftSide, rightSide[1:]) print 'Your sorted list (using Merge Sort): ', mergeSort(num_array)
true
ecc24982c3a3e97fd79d2b006f5cea39de434ce0
darothub/Pythonprog
/caesar.py
1,013
4.1875
4
from sys import argv def caesar(): key = argv[1] plaintext = input("plaintext: ") length = len(plaintext) for x in range(length): letter = plaintext[x] convert = ord(letter) word = '' if (convert >= 65 and convert < 90): convert = convert + int(key) if(convert > 90): convert = convert - 90 convert = convert + 64 word += chr(convert) else: word +=chr(convert) elif (convert >= 97 and convert < 122): convert = convert + int(key) if(convert > 122): convert = convert - 122 convert = convert + 96 word += chr(convert) else: word +=chr(convert) else: word += chr(convert) print(word, end='') caesar()
true
084e970f2b49e77293304980a5e4f077417d0022
iishchenko/PythonCoursesExercises
/130.py
847
4.34375
4
#The Collatz conjecture describes a sequence: starting with a positive number, if the number if even, halve it. If the number is odd, triple it and and add 1. Repeat. This sequence will always eventually reach 1, and should then stop. For example, if we started with 17: #17 → 52 → 26 → 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 #The Collatz conjecture can be implemented recursively. Select the code below that could fill in the blank on line 6 so that this code will print every number in a Collatz sequence until it reaches 1, and then stop printing numbers after that. def collatz(current_number): print(current_number) if current_number % 2 == 0: return collatz(current_number // 2) else: if current_number != 1: return collatz(current_number * 3 + 1) print(collatz(17))
true
bf02ea2fbda8767acd68af9a52b3114f07a76fac
iishchenko/PythonCoursesExercises
/47.py
1,743
4.375
4
#Imagine you're writing the software for an inventory system for #a store. Part of the software needs to check to see if inputted #product codes are valid. # #A product code is valid if all of the following conditions are #true: # # - The length of the product code is a multiple of 4. It could # be 4, 8, 12, 16, 20, etc. characters long. # - Every character in the product code is either an uppercase # character or a numeral. No lowercase letters or punctuation # marks are permitted. # - The character sequence "A1" appears somewhere in the # product code. # #Write a function called valid_product_code. valid_product_code #should have one parameter, a string. It should return True if #the string is a valid product code, and False if it is not. #Add your code here! def check_lenght_mul4(codestr): if (len(codestr)) % 4 == 0: return True else: return False def check_case_num(codestr): for character in codestr: if not (character.isnumeric() or character.isupper()): return False return True def check_A1(codestr): found = "A1" in codestr return found def valid_product_code(codestr): return check_lenght_mul4(codestr) and check_A1(codestr) and check_case_num(codestr) #Below are some lines of code that will test your function. #You can change the value of the variable(s) to test your #function with different inputs. # #If your function works correctly, this will originally #print: True, True, False, False, False print(valid_product_code("A12B44BP")) print(valid_product_code("BFDSAUSA98932RWEFOEWA9FEAA1DSFSF")) print(valid_product_code("A1BBD5")) print(valid_product_code("BDD5664S")) print(valid_product_code("66aBSaA1fdsv"))
true
dcedf6dc534cffaceecd0620cb7d4bc66ae51505
arjunkorandla/automationlearning
/arjun2/ali.py
830
4.21875
4
directions = ["ali", "west", "nrth", "south", "nw", "sw", "ew", "ne","arjun","35.65"] choose_directions = "" while choose_directions not in directions: choose_directions = input("please choose proper directions:") if choose_directions not in directions: # TODO: write code... choose_directions not in directions : print("youu have reached max limit") break elif choose_directions == "ali": print("you are belle pizza owner") break elif choose_directions == "arjun": print("you are a student") break elif choose_directions == "35.65" : print("it is mega special") break else: print("you have choosen the proper dir:") myjoinlist = ",".join(directions) print(myjoinlist) list(myjoinlist) print(myjoinlist) print(dict(directions))
false
e8bf31247e2f545878208826e9bf3b98808100aa
nikhithagoli/basic
/cspp1-practice/m6/p3/digit_product.py
804
4.15625
4
''' Given a number int_input, find the product of all the digits example: input: 123 output: 6 ''' def main(): ''' Read any number from the input, store it in variable int_input. ''' int_input = int(input()) if int_input == 0: print("0") elif int_input < 0: int_input = -int_input digit_product = 1 while int_input != 0: digit = int_input % 10 digit_product = digit_product * digit int_input = int_input // 10 print("-" + str(digit_product)) else: digit_product = 1 while int_input != 0: digit = int_input % 10 digit_product = digit_product * digit int_input = int_input // 10 print(digit_product) if __name__ == "__main__": main()
true
514cc4d82b1d4b74a879d69e02d1d7d0a37213b0
Arsala999/AIPractice
/dictionaries.py
1,041
4.125
4
''' a=int(input("Enter number 1:")) b=int(input("Enter number 2:")) def add(n1,n2): #Receiving info / data called parameters my_sum=n1+n2 print(my_sum) def sub(n1,n2): my_sum=n1-n2 print(my_sum) def mul(n1,n2): my_sum=n1*n2 print(my_sum) def div(n1,n2): my_sum=n1/n2 print(my_sum) c=str(input("Enter operation:")) if c == '+': add(a,b) elif c == '-': sub(a,b) elif c== '*': mul(a,b) else: div(a,b) def my_pet(owner,pet): print(owner, "is an owner of " , pet) my_pet(pet = "cat", owner = "Sarah" ) #takes nothing returns sth def sum(): a=2 b=3 return(a+b) result= sum() print(result) #takes sth returns sth a=int(input("enter num 1:")) b=int(input("Enter num 2:")) def sum(val1,val2): result = val1+val2 return result output_of_function = sum(a,b) print(output_of_function) ''' #Even odd a=int(input('Enter any number:')) def evenodd(a): if a % 2==0: return('Even') else: return('odd') b=evenodd(a) print(b)
false
e99a9a3144136fee9878c309c87e701f942d5af4
gyam28/CodeChallengePython
/song.py
1,538
4.3125
4
""" 6. SONG CHALLENGE: A playlist is considered a repeating playlist if any of the songs contain a reference to a previous song in the playlist. Otherwise, the playlist will end with the last song which points to None. Implement a function is_repeating_playlist that returns true if a playlist is repeating or false if it is not. For example, the following code prints "True" as both songs point to each other. first = Song("Hello") second = Song("Eye of the tiger") third = Song("Third Eye") first.next_song(second); second.next_song(third); third.next_song(first) print(first.is_repeating_playlist()) should return True """ class Song: def __init__(self, name): self.name = name self.next = None def next_song(self, song): self.next = song def is_repeating_playlist(self): """ :returns: (bool) True if the playlist is repeating, False if not. """ # YOUR CODE GOES HERE played_song = [self.name] nextSong = self.next while True: if nextSong != None: if nextSong.name in played_song: return True else: played_song.append(nextSong.name) nextSong = nextSong.next else: return False first = Song("Hello") second = Song("Eye of the tiger") third = Song("Third Eye") first.next_song(second); second.next_song(third); third.next_song(first) print(first.is_repeating_playlist()) # This should return True
true
5acb4977f0ec3bc33f39573ea81f97cae5d60824
aaron-sc/CSCI-100
/exact__change.py
1,327
4.21875
4
# Dicts to hold val of each type of change change = {"dollar" : 100, "quarter" : 25, "dime" : 10, "nickel" : 5, "penny" : 1} # User's change amount_of_change = {"dollar" : 0, "quarter" : 0, "dime" : 0, "nickel" : 0, "penny" : 0} # Total change amount_to_convert = int(input()) # No change if(amount_to_convert <= 0): print("No change") # Split the change for change_type in change.keys(): # Update the user's change amount_of_change[change_type] = amount_to_convert // change[change_type] # Update the change left over amount_to_convert %= change[change_type] else: # For each type of change for change_type in amount_of_change.keys(): # As long as there's change if(amount_of_change[change_type] != 0): # Singular coin if(amount_of_change[change_type] == 1): # Print the change print(str(amount_of_change[change_type]) + " " + change_type.title()) else: # Check if a penny if(change_type == "penny"): # Print it print(str(amount_of_change[change_type]) + " " + "Pennies") else: # If not a penny # Print it print(str(amount_of_change[change_type]) + " " + change_type.title() + "s")
true
fe459005c1a67e6af53a2d7cc3ef89e97dbbffea
aaron-sc/CSCI-100
/interstatehighwaynumbers.py
546
4.25
4
direction = {1 : "north/south", 0 : "east/west"} highway_number = int(input()) toPrint = "I-" + str(highway_number) + " is " valid = True if(highway_number > 999 or highway_number <= 0): valid = False if(highway_number <= 99): toPrint += "primary, going " else: primary = str(int(str(highway_number)[1:])) toPrint += "auxiliary, serving I-"+primary+", going " toPrint += direction[(highway_number % 2)] + "." if(valid): print(toPrint) else: print(str(highway_number) + " is not a valid interstate highway number.")
false
27052e06543ab67b3e487a7a909f818a4151f6d2
Linus-Marco/Curso-em-Video---Python
/ex008.py
676
4.40625
4
''' Exercício Python 008: Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros. ''' m = float(input('\nInforme a medida em metros: ')) # c = m*100 # mm = m*1000 # print('A medida {} metros, é equivalente a {} centímetros e {} milímetros.'.format(m,c,mm)) print('\nA tabela de conversão da medida inserida é:') print('{} m = {} km'.format(m, (m / 1000))) print('{} m = {} hm'.format(m, (m / 100))) print('{} m = {} dam'.format(m, (m / 10))) print('{} m = {} m'.format(m, m)) print('{} m = {} dm'.format(m, (m * 10))) print('{} m = {} cm'.format(m, (m * 100))) print('{} m = {} mm'.format(m, (m * 1000)))
false
08b4f7646009b26c4ee02db573206892d6051c58
ksks05908/basicPython
/first/1.py
1,069
4.25
4
# Поработайте с переменными, создайте несколько, # выведите на экран, запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран. my_string = 'this is a string' my_int_number = 111 my_float_number = 1.11 my_bool_value = True print(f'Строка: {my_string},целое число: {my_int_number},вещественное число: {my_float_number},логическое значение: {my_bool_value}') user_string = input('Введите строку: ') user_int_number = input('Введите целое число: ') user_float_number = input('Введите вещественное число: ') user_bool_value = input('Введите логическое значение: ') print(f'Строка: {user_string},целое число: {user_int_number},вещественное число: {user_float_number},логическое значение: {user_bool_value}')
false
292882535f5e10142e1a43bad2a346054c03a2e1
Zhu-Justin/ZGEN
/rna.py
2,001
4.1875
4
# Functions for RNA data def isRNANucleotide(letter): """Determines if letter is an RNA nucleotide""" if letter == 'A' or letter == 'C' or letter == 'G' or letter == 'U': return True return False def RNAparser(text): """Parses text to create valid RNA sequence""" upper_text = text.upper() RNAsequence = "" # Splits text into an array of no whitespace text no_space_text_array = upper_text.split() # Parse through all the text in the text within the array, adding nucleotide letters to RNA sequence for no_space_sequence in no_space_text_array: for letter in no_space_sequence: if isRNANucleotide(letter): RNAsequence += letter # If there exists invalid RNA nucleotide, then the text file must not be a RNA sequence if not isRNANucleotide(letter): return "" # Otherwise return a RNA sequence with no blank spaces return RNAsequence def uracil_count(RNAsequence): """Counts the number of Uracils""" uracil = 0 for nucleotide in RNAsequence: if nucleotide == 'U': uracil += 1 return uracil def complement_RNA(RNAsequence): """Returns complement of RNA""" complement = "" for nucleotide in RNAsequence: if nucleotide == "A": complement += "U" if nucleotide == "C": complement += "G" if nucleotide == "G": complement += "C" if nucleotide == "U": complement += "A" return complement def reverse_complement_RNA(RNAsequence): """Returns reverse complement of RNA""" complement = "" for nucleotide in RNAsequence: if nucleotide == "A": complement = "U" + complement if nucleotide == "C": complement = "G" + complement if nucleotide == "G": complement = "C" + complement if nucleotide == "U": complement = "A" + complement return complement
true
1bd659bd6857ed0d8cef37a69f476f1594fb3caf
calvinshalim/BINUSIAN-2023
/Functions/function2.py
552
4.125
4
# Palindrome checking str_tocheck = input("Enter your string: ") def ispalindrome(input_str): return (input_str == input_str[::-1]) print (ispalindrome(str_tocheck)) # Task 1: Create a function to return a reversed string (e.g Input: asda; Output: adsa) # Task 2: Create a function to print the total of even numbers given an input of a list # (e.g Input [0,3,4,5,6,7,9] Output 10) #%% task 1 def reverse(word): return word[::-1] #%% task 2 def genap(nums): z = 0 for x in nums: if x %2 == 0: z += x return z
true
eccf965d071a71a15462e519e173a5d37b752296
burkharz9279/cti110
/M2HW1_DistanceTraveled_Burkhardt.py
447
4.125
4
#CTI-110 #M2HW1 - Distance Traveled #Zachary Burkhardt #9/10/17 print("Distance = Speed * Time") print("A car travels at 70 mph for 6, 10, and 15 hours") speed = 70 time = 6 distance = speed * time print("6 hour distance is", distance) speed = 70 time = 10 distance_after6 = speed * time print("10 hour distance is", distance_after6) speed = 70 time = 15 distance_after10 = speed * time print("15 hour distance is", distance_after10)
false
4916508313a366f3968652007157e42344fb7d0d
fakecoinbase/KalenAsberry12slashFintech-bootcamp
/Calendar-module.py
629
4.1875
4
# import calendar info import calendar # weekheader first 3 charactors print(calendar.weekheader(3)) print() # first weekday print(calendar.firstweekday()) print() # calendar month print(calendar.month(2020, 5,)) # matrix of calendar print(calendar.monthcalendar(2020, 5)) # calendar for the entire year print(calendar.calendar(2020 )) # what day of the week day_of_the_week = calendar.weekday(2020, 5, 17) print(day_of_the_week) print() # is 2020 a leap year is_leap = calendar.isleap(2020) print(is_leap) print() # how many leap days by year how_many_leap_days =calendar.leapdays(2000,2005) print(how_many_leap_days)
false
beae4c6c0adbe39d88098921978517b619bba1b8
JustinAnthonyB/Python
/wk3/f6.py
471
4.25
4
""" Ask the user to enter a password that is 8 characters or long Using an if statement, output whether text meets requirement Input from user? 1: no, default = text outputs(s): message of whether text meets requirement data structures / sanitation: no. not really """ default = input("Enter a password. 8 char or more") if len(default) > 7: print("Password meets requirement") else: print("Password does NOT meet requirement")
true
ef90ca1a04d285a87bace03a4ab4e09aa66e1ac6
JustinAnthonyB/Python
/Feb2020/words.py
484
4.75
5
# Python3 code to demonstrate # to extract words from string # using regex( findall() ) import re x = re.findall(r'\w',) # # initializing string # test_string = "Geeksforgeeks, is best @# Computer Science Portal.!!!" # # printing original string # print ("The original string is : " + test_string) # # using regex( findall() ) # # to extract words from string # res = re.findall(r'\w+', test_string) # # printing result # print ("The list of words is : " + str(res))
true
b4f485fef096563349f4142d3638530f1001420d
prasadghagare/learning
/ex1/module2.py
1,780
4.28125
4
#lets make a list #they are really arrays #https://docs.python.org/2/faq/design.html#how-are-lists-implemented num = [23,41,73,37,81,12] #check its type on your system #access O(1) print "index 2 = ", num[2] #slice it print "slicing operation again gives a list : ", num[3:6] #print following line for me using string formatting and list access #"Addition of second number 41 and last number 81 is 122 " #skip an index print "num only even indexed : ", num[::2] #grow your list num.append(64) #append a list itself num.append([1,2,3,"not just numbers"]) #pop the last element, it returns the removed item O(1) print( num.pop()) #pop with index : print(num.pop(0)) #make a stack datastructure for me #remove the known element num.remove(73) #in test print 81 in num #To check complexity of these DS in Python : https://wiki.python.org/moin/TimeComplexity? ages = [23,41,73,37,81,12] print "sum ages earlier: ", sum(ages) #for has meaning in Python for iterables #list is an iterable ages_5 = [] #Look at indentation : Python forces this for age in ages: ages_5.append(age + 5) print ages_5 #add alternate numbers of above list i = 0 sum1 = 0 sum2 = 0 for age in ages_5: if i % 2 == 0: sum1 = sum1 + age else: sum2 = sum2 + age i+=1 sum1 = 0 sum2 = 0 for i , age in enumerate(ages_5): if i % 2 == 0: sum1 = sum1 + age else: sum2 = sum2 + age print sum1 #can you make it shorter?? print sum(ages_5[::2]) #explain range and xrange #list comprehensions #creating lists from existing lists instead of using for print [i + 6 for i in ages if i < 30 ] #explain zip #print squares of first 10 natural numbers using list comprehensions #https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
true
e8a5c68aab1b4c939050f824934dbdf7aa7a3c5c
stacygo/2021-01_UCD-SCinDAE-EXS
/05_Working-with-Dates-and-Times-in-Python/05_ex_1-10.py
376
4.375
4
# Exercise 1-10: Representing dates in different ways # Import date from datetime import date # Create a date object andrew = date(1992, 8, 26) # Print the date in the format 'YYYY-MM' print(andrew.strftime("%Y-%m")) # Print the date in the format 'MONTH (YYYY)' print(andrew.strftime("%B (%Y)")) # Print the date in the format 'YYYY-DDD' print(andrew.strftime("%Y-%j"))
true
f3bb55326b5038f9df244ef148441ed559fc0389
stacygo/2021-01_UCD-SCinDAE-EXS
/02_Python-Data-Science-Toolbox-2/02_ex-1-03.py
415
4.4375
4
# Exercise 1-03: Iterating over iterables (1) # Create a list of strings: flash flash = ['jay garrick', 'barry allen', 'wally west', 'bart allen'] # Print each list item in flash using a for loop for person in flash: print(person) # Create an iterator for flash: superhero superhero = iter(flash) # Print each item from the iterator print(next(superhero)) print(next(superhero)) print(next(superhero)) print(next(superhero))
true
e3a33cf0557cf37d396e903a1e8652dbbb9d04f0
calanquee/Grokking-Algorithms-Code
/mergesort.py
731
4.15625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # 归并 def merge(left, right): result = [] i = 0 j = 0 while((i<len(left))and(j<len(right))): if(left[i]<=right[j]): result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 result += left[i:] result += right[j:] return result # 分治 def mergesort(list): if(len(list)<2): return list else: mid = int(len(list)/2) left = mergesort(list[:mid]) right = mergesort(list[mid:]) result = merge(left, right) return result if __name__ == '__main__': list = [2,3,1,4,5,6,2,4] newlist = mergesort(list) print(newlist)
false
0dfa257c543a31b4f4dcd04f5e4667155b4b4041
Shruti-D/Python
/Basics/Ex1.py
247
4.34375
4
#Python Program to check if a Number Is Positive Or Negative. num = int(input("Enter a Number:")) if num>0: print("Number is Positive.") elif num==0: print("Number is neither Negative nor Positive.") else: print("Number is Negative.")
true
b07b972e358ae371d2ba425d429b3ff7978804f8
Parmida-Mohebali/Into-Python
/ex2/prog2.py
870
4.15625
4
evenlist=[] def prog2(a, b): """(int, int)-> list Return list of even numbers between a and b. No matter which one is bigger. Ex) input: 10, 5 output:[6, 8] Ex) input:32, 43 output:[34, 36, 38, 40, 42] """ if a<b: if a%2==0: for i in range(a+2, b, 2): evenlist.append(i) return evenlist else: for i in range(a+1, b, 2): evenlist.append(i) return evenlist else: if b%2==0: for i in range(b+2, a, 2): evenlist.append(i) return evenlist else: for i in range(b+1, a, 2): evenlist.append(i) return evenlist print(prog1(int(input("Enter your first number:" )), int(input("Enter your second number:"))))
true
42bee2c91884e2cb6331d8a1911bb47abbcdf13a
MrFufux/Automate-the-Boring-Stuff-with-Python-Programming
/SECTION 2/If, Else and Elif Statements.py
2,793
4.25
4
#If Statement name = 'Alice' if name == 'Alice': #Block donde If evalua a True por lo que la línea de abajo aparece. print ('Hi Alice') print ('Done') name = 'Bob' #Para empezar un nuevo block se debe copiar el : if name == 'Andres': #Block donde If evalúa a False por lo que la línea de abajo no aparece. print('Hi Andres') print ('Done') # else Statement password = 'swordfish' if password == 'swordfish': #Evalua a True por lo que aparece en pantalla print ('Access Granted.') else: print ('Wrong password.') password = 'maluta' if password == 'swordfish': # Lo evalua como False por lo que se salta esta línea y siue con el block de else print ('Access Granted.') else: print ('Wrong Password.') #Elif Statement name = 'Bob' age = 3000 if name == 'Alice': #Evalua a False por lo que lo salta print ('Hi Alice') elif age < 12: #Evalua a False por lo que lo salta print ('You are not Alice, kiddo.') elif age > 2000: #Evalua a True, por lo que aparece print ('Unlike you, Alice is not an undead, inmortal vampire') elif age > 100: #Evalua a False, por lo que lo salta print ('You are not Alice, grannie') name = 'Bob' age = 3000 if name == 'Bob': #Evalua a True, por lo que aparece print('Hello Bob') elif age < 12: #Evalua a False por lo que lo salta print ('You are not Alice, kiddo.') elif age > 2000: #Evalua a False por lo que lo salta print ('Unlike you, Alice is not an undead, inmortal vampire') elif age > 100: #Evalua a False por lo que lo salta print ('You are not Alice, grannie') #Last thing of Flow control Statements print('ENTER A NAME.') name = input () #Shortcut (Atajo) if name: print('Thank You for entering your name.') else: print('You did not enter a name.') #haciendolo más explícito... print('ENTER A NAME.') name = input () if name != '': #Utilizamos el no es igual (!=) print('Thank You for entering your name.') else: print('You did not enter a name.') #EJERCICIOS print('Enter the Password.') password = input () if password == 'swordfish': print ('Access Granted.') else: print ('Wrong password.') print ('What is your age?') age = input() if int(age) == 17: print ('Nice') elif int(age) < 16: print ('Younger than my bitch') elif int(age) > 18: print ('Older than my second bitch')
false
b37dfb5b484ae5e63b5a2f6a965f27237337c9fb
YMalinov/py-misc-code
/recursive/multifactorial.py
724
4.375
4
#!/bin/python def multitorial(number, level): if (level == 0): return number result = 1 for num in range(2, number + 1): result *= multitorial(num, level - 1) return result number = int(raw_input('Enter a number: ')) levels = int(raw_input('Enter levels: ')) print multitorial(number, levels) # we all know the factorial of a number is the product of all numbers from 1 to the number [1 * 2 *...* number = number!] # the superfactorial of a number is the product of all factorials from 1 to the number [1! * 2! *...* number! = number!!] # if we call the factorial of a number level 1, and the superfactorial - level 2, this program can calculate the factorial # to whatever level you give it
true
e26bb12116baa61126ee4286c6ade70ced87503b
fazl/python
/hellotkinter/keyboard-event.py
911
4.21875
4
# Loosely following tuturial at # http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm # For Python2 need uppercase T i.e. Tkinter # try: import tkinter as Tk ## python3: tkinter except ImportError: import Tkinter as Tk ## python2: tkinter # To invoke this listener needs two pre-requisites: # 1) connect function to event using bind() # 2) keyboard events will pass to widget that has focus # def onKeyPress(event): print( "pressed", repr(event.char) ) # basic window with title and standard controls win = Tk.Tk() # won't accept args width=200, height=200 # click event handler def onClick(event): print( "Clicked at", event.x, event.y ) # Can we do this directly on a window ? # frame = Tk.Frame( win, width=200, height=200 ) frame.bind("<Button-1>", onClick) frame.bind("<Key>", onKeyPress) frame.pack() frame.focus_set() # Doh, why not setFocus() ?! win.mainloop()
true
acfe84bacaa9841f8e1eb754bbf1d775f5ba0a45
caoxunmo/exercise
/python_base/python_tra_json/tra_json.py
1,216
4.21875
4
# -*- encoding:utf-8 -*- import json dict = {} dict["1"] = {"name": "xiaohua"} dict["2"] = {"sex": "boy"} dict["3"] = {"age": "twenty"} #print(dict) #使用json格式存储数据: def store_data(): with open('with.text', 'r+') as f: json.dump(dict, f) #从json文件中读取数据(open默认r权限): def read_data(): with open('with.text', 'r')as file: json.load(file) # print(dict['1']['name']) for i in dict: print(i, dict[i]) #将json类型转换为python类型,并读出想要的数据: def get_data(route): with open(route) as f: pop_data = json.load(f) # print(pop_data) # print("DEBUG:%s" % type(pop_data)) for pop_dict in pop_data: year = pop_dict['Year'] if year == '2000': name = pop_dict['Country Name'] code = pop_dict['Country Code'] value = pop_dict['Value'] # result = name + code + value # print(result) print("%s:%s:%s" % (name, code, value)) # return "%s:%s:%s" % (name, code, value) path = 'D:\json\population_data.json' data = get_data(path)
false
912b7faf5790610d24e430deb401bf1cd402928d
cuauhfer/python-lessons
/Class1/ej1.py
2,040
4.3125
4
# Arreglo vacio myArray = [] # Arreglo inicializado myInitializedArray = [1, 2, 3, 'Cuarto', 'Quinto', True, {'dic1': 'Elemento del diccionario'}, ['Another Array']] """ # Acceso a elementos por posiciones myFirstElement = myInitializedArray[0] print( myFirstElement ) myLastElement = myInitializedArray[-1] print( myLastElement ) """ """ # Obtener subarreglos subarray = myInitializedArray[0:3] print( subarray ) subarray = myInitializedArray[-3:] print( subarray ) subarray = myInitializedArray[:3] print(subarray) """ """ # Obtener subarreglos con salto de elementos subarray = myInitializedArray[::2] print(subarray) """ # Manipular arreglos ya inicializados """ #Insertar al final myArray.append('MyItem') myArray.append('Other item') print( myArray ) # Insertar en una posición especifica myArray.insert(0, 'New item') myArray.insert(1, 'second item') print( myArray ) # Clonar un arreglo myEqualArray = myArray myCloneArray = myArray.copy() print(myEqualArray) print(myCloneArray) # Eliminar elemento al final de un arreglo myArray.pop() # Eliminar elemento especifico de un arreglo myArray.remove('New item') print(myArray) print(myEqualArray) print(myCloneArray) # Limpiar un arreglo myArray.clear() print( myArray ) # Contar repeticiones de x elemento en el arreglo myCloneArray.append('New item') elements = myCloneArray.count('New item') print(elements) # Unir arreglos myOtherarray = [1, 2, 3] myCloneArray.extend(myOtherarray) print(myCloneArray) # Obtener indice de un item, solo toma la primer coincidencia print( myCloneArray.index('New item') ) # Invertir el arreglo myCloneArray.reverse() print( myCloneArray ) # Ordenar el arreglo (El arreglo debe ser del mismo tipo) myIntArray = [12, 45, 23, 1, 8, 234, 7, 34] myIntArray.sort() print( myIntArray ) myIntArray.sort(reverse=True) print(myIntArray) """ # Recorrer arreglos # for in for element in myInitializedArray: print(element) # for con indice for index in range(len(myInitializedArray)): print(index, ": ", myInitializedArray[index])
false
645f49756fa2b6bef0fc0ebf09eafe3c2f255996
NikhilCPatil/Data-Structures-Algorithms-Python
/mergesort.py
2,383
4.125
4
# Python program for implementation of MergeSort # Merges two subarrays of arr[]. # First subarray is arr[l..m] # Second subarray is arr[m+1..r] def merge(arr, l, m, r): n1 = m - l + 1 n2 = r - m # create temp arrays L = [] R = [] # Copy data to temp arrays L[] and R[] for i in range(0, n1): L[i] = arr[l + i] for j in range(0, n2): R[j] = arr[m + 1 + j] # Merge the temp arrays back into arr[l..r] i = 0 # Initial index of first subarray j = 0 # Initial index of second subarray k = l # Initial index of merged subarray while i < n1 and j < n2: if L[i] <= R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 # Copy the remaining elements of L[], if there # are any while i < n1: arr[k] = L[i] i += 1 k += 1 # Copy the remaining elements of R[], if there # are any while j < n2: arr[k] = R[j] j += 1 k += 1 # l is for left index and r is right index of the # sub-array of arr to be sorted def mergeSort(arr, l, r): if l < r: # Same as (l+r)/2, but avoids overflow for # large l and h m = round((l + (r - 1)) / 2) # Sort first and second halves mergeSort(arr, l, m) mergeSort(arr, m + 1, r) merge(arr, l, m, r) # Driver code to test above # arr = [12, 11, 13, 5, 6, 7] # n = len(arr) # print ("Given array is") # print (arr) # mergeSort(arr, 0, n - 1) # print ("\n\nSorted array is") # print (arr), # This code is contributed by Mohit Kumra def mer(a, l, m, r): n1 = m - l + 1 n2 = r - m L = [0] * (n1) R = [0] * (n2) for i in range(0, n1): L[i] = a[i + l] for j in range(0, n2): R[j] = a[j + 1 + m] print(L) print(R) i = 0 j = 0 k = l while i < n1 and j < n2: if L[i] <= R[j]: a[k] = L[i] i +=1 else: a[k] = R[j] j+=1 k +=1 while i < n1: a[k] = L[i] i+=1 k+=1 while j < n1: a[k] = R[j] j+=1 k+=1 print(a) def merS(a, l, r): if l < r: m = int((l + (r - 1)) / 2) merS(a, l, m) merS(a, m+1, r) mer(a, l, m, r) a = [83, 45, 99, 46, 23, 74, 75, 35] merS(a, 0, len(a) - 1)
false
66115461812a8c6676c9240a02bf5aaafdcb8817
omkar-28/python
/lambbda.py
823
4.375
4
#basic example of lambda double= lambda x: x*2 print(double(5)) #Lambda filter list mylist = [2,20,30,58,103,139,140,15] result = list(filter(lambda x: (x%2==0),mylist)) print("the number divied by 2 is",result) #lambda Map function my_list= [2,20,30,58,103,139,140,15] new_list=list(map(lambda x: x*3,my_list)) print("the new list is",new_list) #take a list of numbers mylist = [12,65,78,34,56,102,339,221] #use anonymous function result = list(filter(lambda x: (x % 13 == 0 ), mylist)) print("the NUmber divided by 13 are",result) #Print power to 2 ussing lambda function terms = int(input("How many terms? ")) result = list(map(lambda x: 2 ** x, range(terms))) print("The total terms is:",terms) for i in range(terms): print("2 raised to power of", i,"is",result[i])
false
e723696b4db1c8e8e2cca007daed99077b4d3419
omkar-28/python
/str_format.py
341
4.34375
4
name = input("What is your name ") age = input("Whatis your age ") program = input("which programm language are you learning ") print("Your name is {}, aged {} and your are interested in learning {} program language.".format(name, age, program)) print(f"your name is {name} and your age is {age}, and your interested in {program} language.")
true
9f866a0ee4d9fca7321744c98c0dfdd5e7572f12
Sa4ras/amis_python71
/km71/Soloviev_Vladislav/3/task1.py
377
4.125
4
print ("Эта программа считает сумму 3 чисел.") x = float(input('Введите первое число: ')) y = float(input('Введите второе число: ')) z = float(input('Введите третье число: ')) print ('Сумма 3 чисел равен: ', x + y + z) input ('Нажмите Enter чтобы выйти.')
false
789455c72a6929b2279a5cfbd434ecf25b39825a
ShaikAbdulArafat/Python_Practice
/src/concepts/DataTypes/mutable_datatypes.py
2,437
4.6875
5
""" A first fundamental distinction that Python makes on data is about whether or not the value of an object changes. If the value can change, the object is called mutable, while if the value cannot change, the object is called immutable. ********* Mutable Data Types ************* 1. list 2. bytearray 3. set 5. dictionaries """ # Every object in Python has an ID (or identity), a type, and a value '''(1) List ''' # list data type is a mutable data type list_a = [10,20,30] print('id of th list object is : ',id(list_a)) # Once id is created, The id of an object never changes. It is unique.. print(type(list_a)) # The type also never changes. It tells what operations are supported by the object. # And the possible values that can be assigned to it. print(list_a) # The value can either cahnge or not. If it can change it is said to be mutable, # While it can't, The value is said to be immutable list_a.pop() print(list_a) print('id of the list ofter changing its value is : ',id(list_a)) list_a.append('hero') print(list_a) print('id of the list object after changing its value again is : ',id(list_a)) '''(2) ByteArray ''' # bytes data type is a mutable data type bytearray_a = bytearray(b'ByteArrray') print(type(bytearray_a)) print('id of the bytearray data type is : ',id(bytearray_a)) print(bytearray_a) bytearray_a.reverse() print(bytearray_a) print('id of bytearray after changing its value is : ',id(bytearray_a) ) '''(3) Set ''' # set data type is a mutable data type set_a = {'a','b'} set_b = set(('a','b')) print(type(set_a)) print('id of set - a datatype is : ',id(set_a)) print(set_a) set_a.add('c') print('id of set - a data type after changing its value is : ',id(set_a)) print(set_a) print(type(set_b)) print('id of set - b data type is : ',id(set_b)) print(set_b) set_b.discard('a') print("id of set - b data type after changing it's value is : ",id(set_b)) print(set_b) '''(4) Dictionaries ''' # dict data type is a mutable data type dict_a = {'a':'alpha','b':'beta','c':'gamma'} print(type(dict_a)) print('id of dict data type is : ', id(dict_a)) print(dict_a) dict_a.update({'d':'bella'}) print('id of dict data type after changing its value is : ', id(dict_a)) print(dict_a)
true
498f138f5bf8a9584ddeeb5bdaeb6ea6a356ca35
ShaikAbdulArafat/Python_Practice
/src/concepts/DataTypes/frozenset_functions.py
1,413
4.125
4
""" frozenset is 'immutable' data type. Hence we can't enhance the data of a frozenset * Like we can't append more elements to a frozenset * Can't Insert an element to a frozenset * Can't remove an element from a frozenset * Can't extend the frozenset * Can't clear a frozenset frozenset can be created from a set frozenset can't have duplicate elements frozenset will alow a None (null) value also Only operation that can be performed on a frozenset is loop over a frozenset and retrive its elemets """ set_creation = {1, 33, 5, 43, None, -0.43, 'a', 3.04, 25, 'hello', 'd',None} set_creation1 = { 1,2,34,3,37,3,7,233,7832,7,.78,-.45,34.45,-35.434} frozenset_creation = frozenset(set_creation) print(frozenset_creation) print(type(frozenset_creation)) print(len(frozenset_creation)) frozenset_creation1 = frozenset(set_creation1) f = sorted(frozenset_creation1) print(f) f = sorted(frozenset_creation1, reverse = True) print(f) """ We can use all default python methods which doesn't modify the values of a frozenset Like we can use max ,min functions we can use len function we can sort a frozenset for ascending order , for decsnding order we can use reverse=True """
true
46a5270700a06eada24a1f26a78dfe9b6817c4f5
Farhad16/Python
/Data Structure/dictionary_comprehension.py
386
4.21875
4
# Simple lopping values = {} for x in range(5): print(x*2) # comprehesion # [expression for item in items] # expression = x*2 # item = x # items = range # for list comprehension values = [x * 2 for x in range(5)] print(values) # for dictionary comprehension values = {x: x*2 for x in range(5)} print(values) # For set comprehension values = {x*2 for x in range(4)} print(values)
true
609cf443cec2a9c02e9b913590ff461c7fa6737c
wilbertgeng/LintCode_exercise
/BFS/611.py
2,761
4.15625
4
"""611. Knight Shortest Path """ """ Definition for a point. class Point: def __init__(self, a=0, b=0): self.x = a self.y = b """ class Solution: """ @param grid: a chessboard included 0 (false) and 1 (true) @param source: a point @param destination: a point @return: the shortest path """ def shortestPath(self, grid, source, destination): # write your code here ## Practice: if not grid or grid[source.x][source.y] == 1: return -1 if source.x == destination.x and source.y == destination.y: return 0 self.directions = [(1, 2), (1, -2), (-1, 2), (-1, -2), (2, 1), (-2, 1), (2, -1), (-2, -1)] queue = collections.deque([(source.x, source.y)]) steps = {(source.x, source.y): 0} while queue: i, j = queue.popleft() if i == destination.x and j == destination.y: return steps[(i, j)] for dx, dy in self.directions: x = i + dx y = j + dy if not self.isValid(x, y, grid, steps): continue steps[(x, y)] = steps[(i, j)] + 1 queue.append((x, y)) return -1 def isValid(self, i, j, grid, steps): m = len(grid) n = len(grid[0]) if i < 0 or i >= m or j < 0 or j >= n or grid[i][j] == 1 or (i, j) in steps: return False return True #### if not grid or grid[destination.x][destination.y] == 1: return -1 if source.x == destination.x and source.y == destination.y: return 0 self.directions = [(1, 2), (1, -2), (-1, 2), (-1, -2), (2, 1), (2, -1), (-2, 1), (-2, -1)] queue = collections.deque([(source.x, source.y)]) steps = {(source.x, source.y): 0} while queue: x, y = queue.popleft() for i, j in self.directions: newX = x + i newY = y + j if newX == destination.x and newY == destination.y: return steps[(x, y)] + 1 if not self.isValid(newX, newY, grid, steps): continue queue.append((newX, newY)) steps[(newX, newY)] = steps[(x, y)] + 1 ### if self.isValid(newX, newY, grid, steps): queue.append((newX, newY)) steps[(newX, newY)] = steps[(x, y)] + 1 return -1 def isValid(self, i, j, grid, steps): m = len(grid) n = len(grid[0]) if i < 0 or i >= m or j < 0 or j >= n or grid[i][j] == 1 or (i, j) in steps: return False return True ###
true
8fcdd469802782ace737efaa245ee6dba51fa62c
Stuming/Harbor
/Sorting/sorting.py
472
4.1875
4
# -*- coding: utf-8 -*- """ Created on Thu Apr 12 15:49:07 2018 @author: Administrator """ def quick_sort(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] left = [x for x in arr if x < pivot] middle = [x for x in arr if x == pivot] right = [x for x in arr if x > pivot] return quick_sort(left) + middle + quick_sort(right) if __name__ == '__main__': test_arr = [3,6,8,10,1,2,1] print(quick_sort(test_arr))
true
5a3c2073e14b310a8cd8cfc79140b476ef47e806
fborrasumh/seminario-python
/codigo/arrays.py
296
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- lista = [4,"8","15",16,23,42, "isla", True] for elemento in lista: print(elemento) print(lista[:-1]) print(lista[0:6:2]) print(lista[4:]) lista.reverse() lista.sort() lista.count() sum(lista[:3]) lista.remove() #TODO: morir personajes GoT
false
4a487bd16dad9ab9dcac2eee53ab3a948b65df86
fborrasumh/seminario-python
/codigo/Scripts-Informatica/Factorial.py
291
4.125
4
# -*- coding: utf-8 -*- """ Created on Mon Oct 27 18:30:50 2014 @author: Dani """ numero = int(raw_input('Escribe un número para hacer su factorial: ')) factorial = 1 for x in range(1, numero+1): factorial = factorial*x print "Pues este es el factorial de %s: %s" %(numero, factorial)
false
9768bf349238e9c0eb9c20a85124eb9ae53a684c
vivisidea/python-beginner
/demos/csvfile.py
1,651
4.34375
4
#!/usr/bin/env python # -*- encoding:utf8 -*- # __author__ = 'vivi' """ this is a simple code snipet manipulating csv file csv = comma separated values http://en.wikipedia.org/wiki/Comma-separated_values 一般来说,csv文件每行一条记录,一般来说每条记录的field的数量是相同的 field之间使用delimiter来分割,如果field里面有delemiter,field需要使用quotechar包起来,field里面的quotechar使用两个quote表示 """ import csv def write_csv_file(rows, filepath='file-out.csv'): """ write the data into a csv file. """ with open(filepath, 'wb') as csvfile: csvwriter = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) for row in rows: csvwriter.writerow(row) def read_csv_file(filepath='file.csv'): """ reads the csv file and process """ rows = [] with open(filepath, 'rb') as f: csvreader = csv.reader(f, delimiter=',', quotechar='"') # reader 可以接收一个file-like-obj for row in csvreader: rows.append(row) print '-'.join(row) return rows def usewith(): with with_file() as f: for line in f: print line, class with_file: """ this is how with statement works maybe. """ def __enter__(self): print 'inside enter.' return 'abcdef' def __exit__(self, exc_type, exc_val, exc_tb): print 'inside exit block' return if __name__ == '__main__': usewith() # rows = [x for x in xrange(1,10,1)] # write_csv_file(rows) rows = read_csv_file('file.csv') write_csv_file(rows)
false
469b62b27019fc034232a589faa145cc5c55e16a
salihayildiz/BBY162
/Uygulama.04.py
1,037
4.125
4
#"Kadın adı" , "Erkek adı" , "Mısra sayısı" belirterek otomatik şarkı/şiir sözü oluşturma. kadinadi = input("Bir kadın adı giriniz :") erkekadi = input("Bir erkek adı giriniz :") misra = int(input("Mısra sayısı giriniz. Maksimum 8 mısra yazdırılabilir :")) print("-"*60) print("") siir = ["Çalıkuşu yaban gülü", "Mekan tutmuş " + erkekadi + " çölü " , kadinadi + kadinadi + " açar gülü" ,kadinadi + " diyen " + erkekadi + " olur ", erkekadi + " başka" + kadinadi + " başka", "son yolcusu düşe kalka", "Sabr-ı Eyyüp gerek aşka" , kadinadi + " diyen " + erkekadi +" olur"] for olusturulacak_siir in siir[:misra]: print(olusturulacak_siir) print("") print("-"*60) if misra > 8: print("Geçerli bir mısra sayısı girmediniz..") print("Yazdırılan mısra sayısı: 8") print("Bu şiir Bilal Özcan'dan alınmıştır.") else: print("Yazdırılan mısra sayısı:", misra) print("Bu şiir Bilal Özcan'dan alınmıştır.")
false
1af92e054fcc7f43725fe74bc2de54cd8fb431c8
fidansamet/code-for-fun
/fibonacci_with_dictionary.py
251
4.28125
4
"""Calculates the fibonacci number in given index.""" fib_dict = {0: 0, 1: 1} def fibonacci(n): if n in fib_dict: return fib_dict[n] res = fibonacci(n-1) + fibonacci(n-2) fib_dict[n] = res return res print(fibonacci(5))
false
5de23e75cb4698e99fbe797f2caa6814f03ef8fc
LukaszMajkut/Projects
/SUDOKU.py
1,848
4.15625
4
#Sudoku solver using BACKTRACKING ALGORITHM puzzle = [[5,3,0,0,7,0,0,0,0], [6,0,0,1,9,5,0,0,0], [0,9,8,0,0,0,0,6,0], [8,0,0,0,6,0,0,0,3], [4,0,0,8,0,3,0,0,1], [7,0,0,0,2,0,0,0,6], [0,6,0,0,0,0,2,8,0], [0,0,0,4,1,9,0,0,5], [0,0,0,0,8,0,0,7,9]] def show_board(puzzle): for i in range(len(puzzle)): if i % 3 == 0 and i != 0: print ("---------------------") for j in range(len(puzzle[0])): if j % 3 == 0 and j != 0: print ("|", end=" ") print (puzzle[i][j], end=" ") elif j == 8: print (puzzle[i][j]) else: print (puzzle[i][j], end=" ") def find_empty(puzzle): for i in range(len(puzzle)): for j in range(len(puzzle[0])): if puzzle[i][j] == 0: return (i,j) return None def valid(puzzle, num, pos): #checking row for i in range(len(puzzle[0])): if puzzle[pos[0]][i] == num and pos[1] != i: return False #checking column for i in range(len(puzzle)): if puzzle[i][pos[1]] == num and pos[0] != i: return False #checking box x_box = pos[1] // 3 y_box = pos[0] // 3 for i in range(y_box*3,y_box*3 + 3): for j in range(x_box*3,x_box*3 + 3): if puzzle[i][j] == num and (i,j) != pos: return False return True def solve(puzzle): find = find_empty(puzzle) if not find: return True else: row,col = find for i in range(1,10): if valid(puzzle, i, (row,col)): puzzle[row][col] = i if solve(puzzle): return True puzzle[row][col] = 0 return False print(solve(puzzle)) show_board(puzzle)
false