blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
0d243dea93c5690939cab2e3696c94e5fd3d170d
mohmur/helloworld
/lar_occ.py
350
4.1875
4
str = input("Enter a String:") length = len( str ) check = str[0] largest = "" for i in range(1,length): if len(check) > len(largest): largest = check if str[i] >= str[i-1]: check = check + str[i] else: check = str[i]; print("largest occurrence of string in alphabetic order is :") print(largest)
true
cd4b4b6d25329efe479e3311220fff2c6fcc4504
Ansanqi/beginning-python-for-bioinformatics
/scripts/original_scripts/code_10.py
493
4.125
4
#! /usr/bin/env python ''' Python functions ''' def add_tail(seq): '''function that adds a poly-T tail to sequences''' result = seq + 'TTTTTTTTTTTTTTTTTTTTT' return result #opening the file dnafile = 'AY162388.seq' file = open(dnafile, 'r') #reading the sequence from the file sequence = '' for line in file: sequence += line.strip() #printing result print sequence #calling the function to add the tail sequence = add_tail(sequence) #printing new sequence print sequence
true
910ab3ab8082422bcd5066d3d7059924971f0f20
redfive/python-sandbox
/mergesort/mergesort.py
1,855
4.3125
4
#!/bin/env python ''' Simple implementation of the mergesort algorithm. Performance should be O(n log n) in the worst case. Algorithm pulled from _Algorithms_ by Dasgupta, Papadimitriou and Vazirani (C) 2008. ''' # TODO: add -debug support # add comparison function support # make callable from external code # suppport more than just a list (?) - perhaps the collection api is # appropriate. # the deque (pronounced deck) supports left/right pop/append # so can support the actual queue behavior needed. The builtin # list appears to pop/append from the same end. :-\ from collections import deque def mergesort ( listA, listB, depth = "" ): ''' Sorts the contents of two input lists and returns the sorted contents in a new sorted list. ''' print "%sMerging %s and %s" % (depth, listA, listB) if len(listA) == 0: return listB if len(listB) == 0: return listA retList = [] if listA[0] <= listB[0]: retList.append(listA[0]) retList.extend( mergesort( listA[1:], listB, depth + " " ) ) else: retList.append(listB[0]) retList.extend( mergesort( listA, listB[1:], depth + " " ) ) return retList def sort ( list ): print "Sorting %s" % (list) listQ = deque() for item in list: # add the items as lists so the merge operation can assume list inputs listQ.append([item]) print "Starting listQ %s" % (listQ) # once we get to one item in the queue we've been fully sorted while len(listQ) > 1: # pop the top two items and sort them, then append the resulting # list item to the end of the queue. listQ.append( mergesort( listQ.popleft(), listQ.popleft() ) ) print "Current listQ %s" % (listQ) print listQ if __name__ == "__main__": sorted = sort( [ 5, 8, 4, 14, 3, 20, 2, 1, 100] ) #sorted = sort( [ 3, 2, 1] )
true
20c805eedfd4e5e00ace965c4514f6b044f67a56
HDKidd/Python
/030_class.instance_p162.py
1,699
4.1875
4
# !usr/bin/env python3 # -*- coding:utf-8 -*- # 类和实例 Class & Instance # 1.1 定义类,创建实例 print('========1.1========') class Student1(object): # 类名通常是大写的单词,object是所有类最终都会继承的类 pass bart1 = Student1() print(bart1) # 输出的 0x0000028BF695FF28 是内存地址 print(Student1) # 1.2.1 给一个实例绑定属性 print('========1.2.1========') bart1.name = 'Bart Simpsn' print(bart1.name) # 1.2.2 定义类的时候强制定义属性,此时在创建实例时必须传入匹配的参数 print('========1.2.2========') class Student2(object): def __init__(self, name, score): # __init__的第一个参数永远是self表示实例本身 self.name = name self.score = score bart2 = Student2('A', 59) # 此时创建实例的话必须传入匹配的参数 print(bart2.name) print(bart2.score) # 2.1 数据封装: 直接在类的内部定义访问数据的函数(这种函数称为方法Method) print('========2.1========') class Student3(object): def __init__(self, name, score): self.name = name self.score = score def print_score(self): print('%s: %s' % (self.name, self.score)) bart3 = Student3('B', 66) print(bart3.name) bart3.print_score() # 3.1.1 访问限制:实例的变量名以__开头,使其变为私有变量 print('========3.1.1========') class Student4(object): def __init__(self, name, score): self.__name = name self.__score = score def print_score(self): print('%s: %s' % (self.__name, self.__score)) bart4 = Student4('D', 99) # print(bart4.__name) # 此处会报错,无法从外部访问实例变量
false
3774da3d746ac807e5f8312e335585b4f1aef252
BNawabi/Exercises
/lesson_4/lesson_4_multi_sentenceslicer.py
649
4.15625
4
# asking the user for a sentence, counts the length of their answer sentence = input("What do you want to tell me? ") sentence_len = len(sentence) start = round(sentence_len * 0.25) end = round(sentence_len + 0.75) sentence_new = sentence[start:end] # printing the new string (0.25% and 0,75% of the users sentence) print(sentence_new) # this splits the sentence into a list and counts the length words_list = sentence.split(" ") words_len = len(words_list) start = round(words_len * 0.25) end = round(words_len * 0.75) new_list = words_list[start:end] # this converts the list back to a string using join and prints it print(" ".join(new_list))
true
f662c77e8b2766990a8bdd2236fe066644286b99
BNawabi/Exercises
/lesson_4/lesson_4_multi_snacknames.py
670
4.40625
4
# list of friends friends = [ ["Barrie"], ["Sjaak"], ["Hans"] ] # loop the items in the list friends and gives the characters of each name individually for friend in friends: name = friend[0] name_len = len(name) print("The name " + name + " consists " + str(name_len) + " characters" ) # ask for favorite snack and add them to a new list favo_snack = input(name + ", What is your favo snack? ") friend.append(favo_snack) # loop the items in the list friends and show what they like (based on their answer on favo_snack input in a new list) for friend in friends: print(friend[0] + "'s favorite snack is: " + friend[1])
true
6120ef02ac6ab125e2fbb2c672fda06256b7b5b8
PayelSelfStudy/Python-C104
/mean.py
2,035
4.1875
4
# Python program to print # mean of elements # list of elements to calculate mean import csv from collections import Counter with open('height-weight.csv', newline='') as f: reader = csv.reader(f) file_data = list(reader) file_data.pop(0) # print(file_data) # sorting data to get the height of people. new_data=[] for i in range(len(file_data)): n_num = file_data[i][1] new_data.append(float(n_num)) # Mean Calculation n = len(new_data) total =0 for x in new_data: total += x mean = total / n # print("Mean / Average is: " + str(mean)) # Median Calculation new_data.sort() #using floor division to get the nearest number whole number # floor division is shown by // if n % 2 == 0: #getting the first number median1 = float(new_data[n//2]) #getting the second number median2 = float(new_data[n//2 - 1]) #getting mean of those numbers median = (median1 + median2)/2 else: median = new_data[n//2] print("Median is: " + str(median)) #Calculating Mode num_list = [51, 63, 69, 73,69,51] data = Counter(num_list) print("Mode data") print(data.items()) mode_data_for_range = { "50-60": 0, "60-70": 0, "70-80": 0 } for height, occurence in data.items(): #print(height) #print(occurence) if 50 < height < 60: mode_data_for_range["50-60"] += occurence elif 60 < height < 70: mode_data_for_range["60-70"] += occurence elif 70 < height < 80: mode_data_for_range["70-80"] += occurence print(mode_data_for_range) mode_range, mode_occurence = 0, 0 #print(mode_range) print(mode_data_for_range.items()) for range, occurence in mode_data_for_range.items(): if occurence > mode_occurence: mode_range, mode_occurence = [int(range.split("-")[0]), int(range.split("-")[1])], occurence print(mode_range) mode = float((mode_range[0] + mode_range[1]) / 2) print(f"Mode is -> {mode:2f}")
true
4527903454524901380585f8836dafe3fb3528c2
Rajahx366/Codewars_challenges
/6kyu_Twisted_Sum.py
389
4.125
4
""" Find the sum of the digits of all the numbers from 1 to N (both ends included). Examples # N = 4 1 + 2 + 3 + 4 = 10 # N = 10 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + (1 + 0) = 46 # N = 12 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + (1 + 0) + (1 + 1) + (1 + 2) = 51 """ def compute_sum(n): ans = 0 for i in range(n+1): for j in str(i): ans += int(j) return ans
false
6e08842b075e707fcb36c0c1f71f9c7317e780ee
Rajahx366/Codewars_challenges
/5kyu_Greed_is_Good.py
1,549
4.25
4
""" Greed is a dice game played with five six-sided dice. Your mission, should you choose to accept it, is to score a throw according to these rules. You will always be given an array with five six-sided dice values. Three 1's => 1000 points Three 6's => 600 points Three 5's => 500 points Three 4's => 400 points Three 3's => 300 points Three 2's => 200 points One 1 => 100 points One 5 => 50 point A single die can only be counted once in each roll. For example, a given "5" can only count as part of a triplet (contributing to the 500 points) or as a single 50 points, but not both in the same roll. Example scoring Throw Score --------- ------------------ 5 1 3 4 1 250: 50 (for the 5) + 2 * 100 (for the 1s) 1 1 1 3 1 1100: 1000 (for three 1s) + 100 (for the other 1) 2 4 4 5 4 450: 400 (for three 4s) + 50 (for the 5) In some languages, it is possible to mutate the input to the function. This is something that you should never do. If you mutate the input, you will not be able to pass all the tests. """ points = { 1: 1000, 6: 600, 5: 500, 4: 400, 3: 300, 2: 200, "1" : 100, "2" : 0, "3" : 0, "4" : 0, "5" : 50, "6" : 0 } def score(dice): s = 0 for i in set(dice): if dice.count(i) >= 3: s += points[i] if i in [1,5]: if dice.count(i) >= 3: s += (dice.count(i)-3) * points[str(i)] else: s += (dice.count(i)) * points[str(i)] return s
true
9c5e700b88ba1bb1cdaf1c2b575db216ac9f5e29
Rajahx366/Codewars_challenges
/6kyu_Custom_FizzBuzz_array.py
1,529
4.3125
4
""" Write a function that returns a (custom) FizzBuzz sequence of the numbers 1 to 100. The function should be able to take up to 4 arguments: The 1st and 2nd arguments are strings, "Fizz" and "Buzz" by default; The 3rd and 4th arguments are integers, 3 and 5 by default. Thus, when the function is called without arguments, it will return the classic FizzBuzz sequence up to 100: [ 1, 2, "Fizz", 4, "Buzz", "Fizz", 7, ... 14, "FizzBuzz", 16, 17, ... 98, "Fizz", "Buzz" ] When the function is called with (up to 4) arguments, it should return a custom FizzBuzz sequence, for example: ('Hey', 'There') --> [ 1, 2, "Hey", 4, "There", "Hey", ... ] ('Foo', 'Bar', 2, 3) --> [ 1, "Foo", "Bar", "Foo", 5, "FooBar", 7, ... ] Examples fizz_buzz_custom()[15] # returns 16 fizz_buzz_custom()[44] # returns "FizzBuzz" (45 is divisible by 3 and 5) fizz_buzz_custom('Hey', 'There')[25] # returns 26 fizz_buzz_custom('Hey', 'There')[11] # returns "Hey" (12 is divisible by 3) fizz_buzz_custom("What's ", "up?", 3, 7)[80] # returns "What's " (81 is divisible by 3) The function must return the sequence as a list. """ def fizz_buzz_custom(string_one='Fizz', string_two='Buzz', num_one=3, num_two=5): ans = [] s = '' for i in range(1, 101): if i % num_one == 0: s += string_one if i % num_two == 0: s += string_two ans.append(i) if len(s) == 0 else ans.append(s) s = '' return ans
true
2645e010e6595010a65708b04fbea6fb980baab2
Rajahx366/Codewars_challenges
/5kyu_Valid_Parentheses.py
858
4.375
4
""" Write a function that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return true if the string is valid, and false if it's invalid. Examples "()" => true ")(()))" => false "(" => false "(())((()())())" => true Constraints 0 <= input.length <= 100 Along with opening (() and closing ()) parenthesis, input may contain any valid ASCII characters. Furthermore, the input string may be empty and/or not contain any parentheses at all. Do not treat other forms of brackets as parentheses (e.g. [], {}, <>). """ def valid_parentheses(string): opn = 0 close = 0 for i in string: if i == "(": opn+=1 elif i == ")": close += 1 if close > opn: return False return opn==close
true
2a506769fe83284f4f16a35be5a5d55952f25dc0
Rajahx366/Codewars_challenges
/6kyu_The_deaf_rats_of_Hamelin.py
762
4.1875
4
""" Story The Pied Piper has been enlisted to play his magical tune and coax all the rats out of town. But some of the rats are deaf and are going the wrong way! Kata Task How many deaf rats are there? Legend P = The Pied Piper O~ = Rat going left ~O = Rat going right Example ex1 ~O~O~O~O P has 0 deaf rats ex2 P O~ O~ ~O O~ has 1 deaf rat ex3 ~O~O~O~OP~O~OO~ has 2 deaf rats """ def count_deaf_rats(town): rats = town.replace(" ", "").split('P') return count_left_right(rats[0], left=True) + count_left_right(rats[1], left=False) def count_left_right(s, left=True): counts = {'~O': 0, 'O~': 0} for i in range(0, len(s)-1, 2): counts[s[i:i+2]] += 1 return counts['O~'] if left else counts['~O']
false
f2ed023e6a65ebd3d5ac4a7b75191f33db5f96a9
Rajahx366/Codewars_challenges
/4kyu_Most_frequently_used_words_in_a_text.py
2,045
4.125
4
""" Write a function that, given a string of text (possibly with punctuation and line-breaks), returns an array of the top-3 most occurring words, in descending order of the number of occurrences. Assumptions: A word is a string of letters (A to Z) optionally containing one or more apostrophes (') in ASCII. (No need to handle fancy punctuation.) Matches should be case-insensitive, and the words in the result should be lowercased. Ties may be broken arbitrarily. If a text contains fewer than three unique words, then either the top-2 or top-1 words should be returned, or an empty array if a text contains no words. Examples: top_3_words("In a village of La Mancha, the name of which I have no desire to call to mind, there lived not long since one of those gentlemen that keep a lance in the lance-rack, an old buckler, a lean hack, and a greyhound for coursing. An olla of rather more beef than mutton, a salad on most nights, scraps on Saturdays, lentils on Fridays, and a pigeon or so extra on Sundays, made away with three-quarters of his income.") # => ["a", "of", "on"] top_3_words("e e e e DDD ddd DdD: ddd ddd aa aA Aa, bb cc cC e e e") # => ["e", "ddd", "aa"] top_3_words(" //wont won't won't") # => ["won't", "wont"] Bonus points (not really, but just for fun): Avoid creating an array whose memory footprint is roughly as big as the input text. Avoid sorting the entire array of unique words. """ def top_3_words(text): for i in text: if (not i.isalpha()) and (i != "'"): text = text.replace(i, " ") while " ''" in text: text = text.replace(" ''", " ") if " ' " in text: text = text.replace(" ' ", " ") lst = text.lower().split() if not lst: return [] most = max(set(lst), key=lst.count) if len(set(lst)) < 2: return [most] second = max(set(lst)-set([most]), key=lst.count) if len(set(lst)) < 3: return [most, second] third = max(set(lst)-set([most, second]), key=lst.count) return [most, second, third]
true
a2987dfb8ca75e80508634dcd22a4c771480d67f
Rajahx366/Codewars_challenges
/6kyu_Calculate_string_rotation.py
831
4.53125
5
""" Write a function that receives two strings and returns n, where n is equal to the number of characters we should shift the first string forward to match the second. The check should be case sensitive. For instance, take the strings "fatigue" and "tiguefa". In this case, the first string has been rotated 5 characters forward to produce the second string, so 5 would be returned. If the second string isn't a valid rotation of the first string, the method returns -1. Examples: "coffee", "eecoff" => 2 "eecoff", "coffee" => 4 "moose", "Moose" => -1 "isn't", "'tisn" => 2 "Esham", "Esham" => 0 "dog", "god" => -1 """ def shifted_diff(first, second): ans = 0 for i in range(len(first)): test = first[-ans:] + first[:-1*ans] if test == second: return ans ans += 1 return -1
true
bd349cd74ef1491a1b10415af634504f8eab6075
Rajahx366/Codewars_challenges
/6kyu_Break_camelCase.py
446
4.40625
4
""" Complete the solution so that the function will break up camel casing, using a space between words. Example solution("camelCasing") == "camel Casing" """ import re def solution(s): first_word = re.findall('[^A-Z]*[A-Z]',s) words = re.findall('[A-Z][^A-Z]*',s) words.insert(0,first_word[0][:-1]) return " ".join(words) '''better : def solution(s): return ''.join(' ' + c if c.isupper() else c for c in s) '''
true
6dd229ad36c013cb4ab3f19a20cf48590fdac480
Rajahx366/Codewars_challenges
/6kyu_Maze_runner.py
1,998
4.375
4
""" Welcome Adventurer. Your aim is to navigate the maze and reach the finish point without touching any walls. Doing so will kill you instantly! Task You will be given a 2D array of the maze and an array of directions. Your task is to follow the directions given. If you reach the end point before all your moves have gone, you should return Finish. If you hit any walls or go outside the maze border, you should return Dead. If you find yourself still in the maze after using all the moves, you should return Lost. The Maze array will look like maze = [[1,1,1,1,1,1,1], [1,0,0,0,0,0,3], [1,0,1,0,1,0,1], [0,0,1,0,0,0,1], [1,0,1,0,1,0,1], [1,0,0,0,0,0,1], [1,2,1,0,1,0,1]] ..with the following key 0 = Safe place to walk 1 = Wall 2 = Start Point 3 = Finish Point direction = ["N","N","N","N","N","E","E","E","E","E"] == "Finish" Rules 1. The Maze array will always be square i.e. N x N but its size and content will alter from test to test. 2. The start and finish positions will change for the final tests. 3. The directions array will always be in upper case and will be in the format of N = North, E = East, W = West and S = South. 4. If you reach the end point before all your moves have gone, you should return Finish. 5. If you hit any walls or go outside the maze border, you should return Dead. 6. If you find yourself still in the maze after using all the moves, you should return Lost. """ import numpy as np dic = {"N": [-1, 0], "S": [1, 0], "W": [0, -1], "E": [0, 1]} def maze_runner(maze, directions): maze = np.array(maze) pos = np.where(maze == 2) for i in directions: pos = pos + np.array(dic[i]).reshape(-1,1) if pos[0] >= maze.shape[0] or pos[1] >= maze.shape[0] or any(pos < 0): return "Dead" elif maze[pos[0],pos[1]] == 1: return "Dead" elif maze[pos[0],pos[1]] == 3: return "Finish" return "Lost"
true
ad5b7ff895f4d921715de52eed51e5fba03d2de5
himanij11/Python---Basic-Programs
/Basic Programs/OperationOnTheSet.py
897
4.3125
4
#Operations on the Set #Indiabigs######Site for learning coding #Union set1={1, 2, 3, 4} set2={5, 6, 7, 8} print(set1 | set2) #OR operator '|' unions the set #Another way #Using Union Operator print(set1.union(set2)) #Intersection on the set s1={1, 2, 3, 4} s2={4, 5, 6, 7} print(s1 & s2) #And operator '&' intersects common values from both set #Another way #Using Intersection Operator print(s1.intersection(s2)) #Difference on the set s1={1, 2, 3, 4, 5} s2={4, 5, 6, 7, 8} print(s1.difference(s2)) #Another way print(s1-s2) #Symmetric Difference on the set s1={1, 2, 3, 4, 5} s2={4, 5, 6, 7} print(s1^s2) #Another way print(s1.symmetric_difference(s2)) #Subset x={1, 2, 3, 4, 5, 6} y={4, 5, 6} print("Set x is subset of y? : ", x.issubset(y)) print("Set y is subset of x? : ", y.issubset(x))
false
22630ed7f410bdd3d952e0fc8f248264db9ec96d
himanij11/Python---Basic-Programs
/Basic Programs/listSquare.py
539
4.28125
4
#Squaring of element in the list s=[4,3,2,1] ss=[] for i in s: ss.append(i**2) print(ss) #The above list can be performed in another way using List Comprehension:- #List Comprehensions provide a concise way to create list. #Common Applications are to make new lists where each element is the result of some operations applied to each member of an # squares=[i**2 for i in range(4)] print(squares) #list_name=[operations in left side///// conditions in right side] even=[i for i in range(10) if i%2==0] print(even)
true
2c5d5b26c6a2e2bae30cd644f293a4631ebeee02
himanij11/Python---Basic-Programs
/Basic Programs/DictionaryComprehensionDemo.py
432
4.15625
4
#Dictionary is unordered #Dictionary Comprehension d={'a':1,'b':2,'c':3} for pair in d.items(): print(pair) d={'a':1,'b':2,'c':3,'d':4,'e':5} new_d={k:v for k,v in d.items() if v>2} print(new_d) #we can also perform operations on the key value pairs d={'a':1,'b':2,'c':3,'d':4,'e':5,'f':6} d={k + 'c':v*2 for k,v in d.items() if v>2} #we can also add special characters($,*,#,@,!) instead of 'c' print(d)
false
87de39fa3bbd946bdef0bec46b6f1750edb3eb53
amruldin/somePython
/bmi.py
1,781
4.4375
4
# Author : # Date : # Description #Psudocode # Ask user to Enter their height in inches # Ask User to Enter their weight in pounds # Compute the BMI as ((weight/height^2)*703) # Print BMI to the user # def prompt and getIntInput -> int # Def computeBMI , takes weight and height as argements and returns BMI # Def Main calls the functions above to ask the user for height and weight, compute the BMI and print it out # Write test case below each function # Write header comments for each function """ The following function will take input as a float value from the user and then return it back. You could also take an integer however float would more accurate """ def getIntInput(prompt): # get user input return float(input(prompt)) """ The following function will compute the body mass index and then return the result as an integer """ def computeBMI(weight, height): return int(((weight/(height*height)*703))) def main(): # Call getIntInput to prompt and store users height height = getIntInput("\nPlease Enter Your Height In Inches : ") # Call getIntInput to prompt and store users weight weight = getIntInput("\nPlease Enter your Weight In Pounds : ") # Call computeBMI function to calculate and store BMI userBMI = computeBMI(weight, height) print("\nYour BMI is : " + str(userBMI)) main() """ Some test scenario are as following Please Enter Your Height In Inches : 65 Please Enter your Weight In Pounds : 230 Your BMI is : 38 Please Enter Your Height In Inches : 55.5 Please Enter your Weight In Pounds : 215.2 Your BMI is : 49 This program will only take float and integer values as input. All other types are invalid and will cause the program to crash! """
true
febfaadd2ec38def4624ad6d105441bb76a77143
KevinTitco/python
/Functions/motorbike.py
581
4.15625
4
bike = {"make": "Honda", "model": "250 dream", "color": "red", "engine_size": 250 } def quick_sort(sequence): length = len(sequence) if length <= 1: return sequence else: pivot = sequence.pop() items_greater = [] items_lower = [] for item in sequence: if item > pivot: items_greater.append(item) else: items_lower.append(item) return quick_sort(items_lower) + [pivot] + quick_sort(items_greater) print(quick_sort([1, 5, 2, 1, 7, 3, 1, 9, 6, 1, 5, 4, 8, 5]))
true
304d6cfdd37065f1d89d13236bbb4a388450c569
JojoPedro/Exercicio-de-python
/equação_raíz.py
1,555
4.3125
4
""" Faça um programa que calcule as raízes de uma equação do segundo grau, na forma ax2 + bx + c. O programa deverá pedir os valores de a, b e c e fazer as consistências, informando ao usuário nas seguintes situações: a) Se o usuário informar o valor de A igual a zero, a equação não é do segundo grau e o programa não deve fazer pedir os demais valores, sendo encerrado; b) Se o delta calculado for negativo, a equação não possui raizes reais. Informe ao usuário e encerre o programa; c) Se o delta calculado for igual a zero a equação possui apenas uma raiz real; informe-a ao usuário; d) Se o delta for positivo, a equação possui duas raiz reais; informe-as ao usuário; """ import math print('digite os termos a, b, c da equação ax² + bx + c') a = int(input('digite o termo a = ')) if a == 0: print('Não é uma equação do segundo grau') else: b = int(input('digite o termo b = ')) c = int(input('digite o termo c = ')) delta = b*b - 4*a*c if delta < 0: print('A equação não possui raízes reais') if delta == 0: print('Delta =', delta , '\nA equação possui apenas uma raiz real') raiz = ((-1)*b + delta/2) print('A raiz da equação é =', raiz) if delta > 0: print('Delta =', delta, 'A equação possui duas raizes reais') raiz1 = (-b + math.sqrt(delta)) / (2*a) raiz2 = (-b - math.sqrt(delta)) / (2*a) print('A primeira raiz é = ', raiz1) print('A segunda raiz é = ', raiz2)
false
e827c01af7c4880422c7571785854a02a93d99a6
vicch/leetcode
/0100-0199/0124-binary-tree-maximum-path-sum/0124-binary-tree-maximum-path-sum-1.py
2,004
4.21875
4
""" For any in the tree, in the perspective of its parent node, there are 2 types of max path: - A path that can be connected to the parent node, i.e. a path that runs through current node and runs down either branch of current node. Refer to this type as flex path (because it can still extend to parent node). - A path that cannot be connected to the parent node, i.e. a path that doesn't even pass through current node (the path is passed up from a child node of current node), or a path that runs both child nodes and current node. Refer to this type as fixed path (because it cannot extend to parent node anymore). The max path of each type can be calculated based on the max path of its branches. Then return the max paths of current node up to parent node. The final result is the larger of these max paths on the root node. """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def maxPathSum(self, root): """ :type root: TreeNode :rtype: int """ def recursion(node): if not node: return [None, None] l, r = recursion(node.left), recursion(node.right) # Fixed max candidates: # - Fixed max on either branch # - Flex max on either branch (when root value is negative) # - Sum of both flex max plus the root fixedMax = max(l[0], r[0], l[1], r[1], (l[1] + r[1] + node.val if (l[1] and r[1]) else None)) # Flex max candidates: # - Flex max of either branch (if positive, otherwise 0 is better) # Flex max always need to include the current node, because it needs to be able to extend to upper level flexMax = max(max(l[1], 0), max(r[1], 0)) + node.val return [fixedMax, flexMax] return max(recursion(root))
true
c5ff5a3e629f381599923c1406cf16ef9ca5e4c3
vicch/leetcode
/0400-0499/0417-pacific-atlantic-water-flow/0417-pacific-atlantic-water-flow.py
2,484
4.46875
4
""" If one cell can flow to the ocean, all its adjacent cells with higher or same heights can flow to the ocean. So by visit the cells that can flow to the ocean and recursively their adjacent oceans, we can find all cells that can flow one ocean. Note that even if one adjacent cell cannot flow to current cell, it doesn't mean that cell cannot have another path to flow into the ocean, so we should only positively mark cells as flowable to the ocean, and leave the currently unflowable cells as unvisited, and visit them again from other adjacent cells. There won't be deadlock because if one cell is currently unflowable, the visit will stop and won't continue to its adjacent cells. By keeping 2 matrix to mark cells that can flow to one of the oceans, and compare the matrix to collect the cells that can flow to both, we can get the result. """ class Solution(object): def pacificAtlantic(self, heights): """ :type heights: List[List[int]] :rtype: List[List[int]] """ m, n = len(heights), len(heights[0]) # Matrix to mark each cell as flowable to either of the 2 oceans m1 = [[None] * n for _ in range(m)] m2 = [[None] * n for _ in range(m)] # DFE visit a cell and check if it can flow to the given ocean def visit(matrix, i, j, height): if i < 0 or i >= m or j < 0 or j >=n: return # If already visited, or this cell cannot flow to the upper level cell, stop here if matrix[i][j] is not None or heights[i][j] < height: return # This cell can flow to the given ocean matrix[i][j] = 1 # Check if its adjacent cells can flow to this cell, i.e. can eventually flow to the same ocean visit(matrix, i-1, j, heights[i][j]) visit(matrix, i+1, j, heights[i][j]) visit(matrix, i, j-1, heights[i][j]) visit(matrix, i, j+1, heights[i][j]) # Visit left and right borders for i in range(m): visit(m1, i, 0, 0) visit(m2, i, n-1, 0) # Visit top and bottom borders for i in range(n): visit(m1, 0, i, 0) visit(m2, m-1, i, 0) # Collect cells that can flow to both oceans cells = [] for i in range(m): for j in range(n): if m1[i][j] == 1 and m2[i][j] == 1: cells.append([i, j]) return cells
true
2fab4d5f487081f9ab51d3515305d7fb72b5b220
vicch/leetcode
/0300-0399/367/367.py
1,084
4.1875
4
""" Problem: Given a positive integer, write a function to determine if it is a perfect square. Do not use any built-in library function such as sqrt(). Solution: If 2^n < x < 2^(n+1) Then 2^(n/2) < x^(1/2) < 2^((n+1)/2) So by right shifting a number half the number of its binary digits, we can get the lower boundary of its possible square root. - Get the number of binary digits n. - Right shift the number ceil(n/2) bits to get lower boundary of square root. - Increment the value and calculate its square. - Once the sqaure is greater than the integer, it's not a perfect square. """ class Solution(object): def isPerfectSquare(self, num): """ :type num: int :rtype: bool """ n = self.getBinaryDigits(num) base = num >> ((n + 1) >> 1) while base * base < num: base += 1 return base * base == num def getBinaryDigits(self, num): """ :type num: int :rtype: int """ n = 0 while num != 0: n += 1 num >>= 1 return n
true
49c9e6fe57d7e8501b32ab7afc5bffa14f0c257e
vicch/leetcode
/0200-0299/0234-palindrome-linked-list/0234-palindrome-linked-list.py
2,114
4.25
4
""" For O(1) space and O(n) time, the only way is to reverse half of the list, and compare its the 2 halves are equal. Reversing a list is essentially building a new list backwards, by taking nodes off the head of the old list, and attach to the head of the new list. To find the middle location of the original list, use fast and slow pointers. """ # Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def isPalindrome(self, head): """ :type head: ListNode :rtype: bool """ def reverse(head): """ Reverse given list and return new head. """ # Init head of the new list. newHead = None while head: # Take head of old list and attach to head of new list. node = head head = head.next node.next = newHead newHead = node return newHead def isEqual(head, tail): # If the original list has even number of nodes, the last node of the head list will point to the last node # of the tail list, which means the head list has one more node that should be ignored. The fast and slow # pointers already guarantee that the head list has at most one more node in this case, so just checking if # it reaches the end of the tail list is enough. while tail: if head.val != tail.val: return False head = head.next tail = tail.next return True if not head: return False if not head.next: return True # The slow pointer points to the start of the later half when fast pointer reaches the end. fast = slow = head while fast and fast.next: fast = fast.next.next slow = slow.next tail = reverse(slow) return isEqual(head, tail)
true
d8f44adc44817a27687f87741052d2404402df53
vicch/leetcode
/0200-0299/0238-product-of-array-except-self/0238-product-of-array-except-self.py
1,402
4.21875
4
""" Consider array [1, 2, 3, 4], the calculation of products array is basically: 1 -+ 1 2 | 1 2 3 -+- The "left hand" numbers multiplied incrementally products = [_, _, _, _] 2 3 4 -+ 3 4 | 4 -+- The "right hand" numbers multiplied incrementally By "incrementally" it means: 2 x 3 x 4 = (3 x 4) x 2, so if the result of 3 x 4 is already in a variable, it only needs to multiply by 2 to get the next value, and so on. So with 2 rounds (one for "left hand" numbers and one for "right hand" numbers) of incremental multiplication, the products array can be obtained. """ class Solution(object): def productExceptSelf(self, nums): """ :type nums: List[int] :rtype: List[int] """ products = [1] * len(nums) # Multiply "left hand" numbers accum = 1 for i in range(1, len(nums)): accum *= nums[i - 1] products[i] *= accum # As product[i - 1] if just the accumulated value of last loop, the use of "accum" can be avoided by: # products[i] = products[i - 1] * nums[i - 1] # Multiple "right hand" numbers accum = 1 for i in range(len(nums) - 2, -1, -1): accum *= nums[i + 1] products[i] *= accum return products
true
9d38d207da9a3943a492f9ec9b88533a1e77f8f2
herculeshssj/python
/udemy-curso-python-projetos-reais/AulaIteracaoStringsWhile/AulaIteracaoStringsWhile.py
1,065
4.15625
4
if __name__ == '__main__': print('Iterando strings com while') frase = 'o rato roeu a roupa do rei de roma.' # Valor iterável tamanho_frase = len(frase) contador = 0 nova_string = '' print(f'Frase: {frase}') print(f'Tamanho: {tamanho_frase}') while contador < tamanho_frase: # Iteraćão print(f'Letra: {frase[contador]} - índice: {contador}') contador += 1 print() contador = 0 while contador < tamanho_frase: print(f'Nova string: {nova_string}') nova_string += frase[contador] contador += 1 print(f'Nova string: {nova_string}') print('*** Exercício ***') print(f'Frase: {frase}') input_do_usuario = input('Qual letra deseja colocar em maiúscula? ') contador = 0 nova_string = '' while contador < tamanho_frase: letra = frase[contador] if letra == input_do_usuario: nova_string += input_do_usuario.upper() else: nova_string += letra contador += 1 print(f'Nova frase: {nova_string}')
false
d1d09ece16de993cbb940c1099198a5a61615bcf
herculeshssj/python
/udemy-curso-python-projetos-reais/Desafio2/Desafio2.py
1,813
4.46875
4
""" Faća um programa que peća ao usuário para digital um número inteiro, informe se este número é par ou ímpar. Caso o usuário não digite um número inteiro, informe que não é um número inteiro. """ """ Faća um programa que pergunte a hora ao usuário e, baseando-se no horário descrito, exiba a saudaćão apropriada. Ex. Bom dia 0-11, Boa tarde 12-17 e Boa noite 18-23. """ """ Faća um programa que peća o primeiro nome do usuário. Se o nome tiver 4 letras ou menos escreva "Seu nome é curto"; se tiver entre 5 e 6, escreva "Seu nome é normal"; maior que 6 escreva "Seu nome é muito grande". """ from AulaFuncoesBuiltIn.AulaFuncoesBuiltIn import * if __name__ == '__main__': print('##### Desafio 2 #####') print('***** Exercício 1 *****') numero = input('Digite um número inteiro: ') if is_int(numero): numero = int(numero) if numero % 2 == 0: print('É par!') else: print('É ímpar!') else: print('Não é um número inteiro!') print('***** Exercício 2 *****') hora_atual = input('Informe a hora atual (0-23): ') if is_int(hora_atual): hora_atual = int(hora_atual) if 0 <= hora_atual <= 23: if 0 <= hora_atual <= 11: print('Bom Dia!') elif 11 < hora_atual <= 17: print('Boa Tarde!') else: print('Boa Noite!') else: print('Hora fora do intervalo!') else: print('Hora inválida!') print('***** Exercício 3 *****') nome_usuario = input('Digite seu nome: ') if len(nome_usuario) <= 4: print('Seu nome é curto.') elif 4 < len(nome_usuario) <= 6: print('Seu nome é normal.') else: print('Seu nome é muito grande.')
false
f6e9489407041140d4d60dd11c7a500538ce0996
herculeshssj/python
/udemy-curso-python-projetos-reais/AulaDesempacotamentoLista/AulaDesempacotamentoLista.py
1,062
4.3125
4
""" Desempacotamento de listas em Python """ if __name__ == '__main__': print('Desempacotamento de listas') lista = ['Luiz', 'João', 'Maria'] n1, n2, n3 = lista print(f'Valor de n1: {n1}') print(f'Valor de n2: {n2}') print(f'Valor de n3: {n3}') print() # Desempacotando quando a lista tem mais valores que a quantidade de variáveis atribuídas n1, n2, *outra_lista = lista print(f'Valor de n1: {n1}') print(f'Valor de n2: {n2}') print(f'Outra lista, com o restante dos valores: {outra_lista}') print() # Obtendo o último valor da lista lista = ['Luiz', 'João', 'Maria', 'José', 'Tomas', 'Cristina'] n1, n2, *outra_lista, ultimo_da_lista = lista print(f'Valor de n1: {n1}') print(f'Valor de n2: {n2}') print(f'Outra lista, com o restante dos valores: {outra_lista}') print(f'Último da lista: {ultimo_da_lista}') # Indicar que você não irá utilizar o restante dos valores da lista n1, n2, *_ = lista print(f'Valor de n1: {n1}') print(f'Valor de n2: {n2}')
false
ccef5b8d9c87d077772ccaeb3abc535a4b7aca22
Environmental-Informatics/building-more-complex-programs-with-python-ankitghanghas
/problem5_2.py
878
4.375
4
""" Created on Sunday Jan 19 2020 by Ankit Ghanghas Exercise 5.2 ThinkPython This code takes 4 integer inputs from the user and tests the validity of feramt's theorem using these 4 inputs. Fermat's Theorem: For any input values a, b, c and power n, given n is greater than 2 a^n + b^n = c^n : # ^ indicates raised to power Fermat's Theorem """ def check_fermat(a,b,c,n): n=int(n) if n<=2: # this steps if the power (exponent) specified is greater than 2 print("Provide n greater than 2") return if int(a)**n + int(b)**n == int(c)**n: print("Holy smokes, Fermat was wrong!") else: print("No, that dosen't work") a=input("Input a integer value of 'a' \n") b=input("Input a integer value of 'b' \n") c=input("Input a integer value of 'c' \n") n=input("Input a integer value of 'n' \n") check_fermat(a,b,c,n)
true
04f6fcc3bae17d8a20115e66d2671c16e1fcfad0
fry404006308/fry_course_materials
/python、js、php语法区别/5、存储结构/a、存储结构.py
2,426
4.34375
4
""" 1、字符串 2、列表(就像js和php中的索引数组) 3、元组(元组可以看做不能修改的列表) 4、字典(就像js和php中的关联数组) 5、集合 """ # 1、字符串 # a = "hello" # b = "python" # print("a + b 输出结果:", a + b) # print("a * 2 输出结果:", a * 2) # print("a[1] 输出结果:", a[1]) # print("a[1:4] 输出结果:", a[1:4]) # if( "h" in a) : # print("h 在变量 a 中") # else : # print("h 不在变量 a 中") # if( "m" not in a) : # print("m 不在变量 a 中") # else : # print("m 在变量 a 中") # c = a.capitalize() # print(c) # 2、列表 # list1 = ["a", "a", "c", "d", "d"] # print(list1) # # 增 # # list1[10] = "f" #IndexError: list assignment index out of range # # #将对象插入列表 # list1.append("f") # print(list1) # # 删 # del list1[2] # print(list1) # # 改 # list1[1] = "b" # print(list1) # # 查 # print(list1[0]) # # 留头不留尾 # print(list1[1:3]) # # 循环 # for i in list1: # print(list1.index(i),i) # # 方法 # list1.reverse() # print(list1) # 3、元组 # tuple1=(1,2,3,4,5) # tuple1[1]=22 #TypeError: 'tuple' object does not support item assignment # del tuple1[1] #TypeError: 'tuple' object doesn't support item deletion # tuple2=("a","b") # tuple3=tuple1+tuple2 # print(tuple3) # print(len(tuple3)) # 增 # 删 整个元组 # del tuple1 # print(tuple1) #NameError: name 'tuple1' is not defined # 改 # 查 # print(tuple1[0]) # 1 # print(tuple1[1:3]) # (2, 3) # 循环 # for i in tuple1: # print(i) # 函数 # print(max(tuple1)) # 4、字典 # dict1={"name":"孙悟空","age":11} # print(dict1) # # 增 # dict1["aa"]="bb"; # print(dict1) # # 删 # del dict1["age"] # print(dict1) # # 改 # dict1["name"]="齐天大圣" # print(dict1) # # 查 # print(dict1["name"]) # # 循环 # print(dict1.items()) # # items() 方法以列表返回可遍历的(键, 值) 元组数组 # for key,val in dict1.items(): # print(key,val) # 5、集合 # 集合就是数学中的集合,元素不会重复 # 集合为啥可以和字典同时都用{} # 因为字典是键值对,集合就是值,所以不冲突 # set1={1,2,3,1,24,52,2,3} # print(set1) # {1, 2, 3, 52, 24} # # 增 # set1.add(9); # print(set1) # # 删 # set1.remove(24) # print(set1) # # # 改 # # 查 # print(9 in set1) #True # print(18 in set1) #false # # 循环 # for i in set1: # print(i)
false
af506000d1bb9fae4908915929b8d717b82cc310
fry404006308/fry_course_materials
/python、js、php语法区别/7、面向对象/a、面向对象.py
676
4.28125
4
""" 需求: 创建Animal类(name属性,say方法) 创建Animal类的子类Bird类(age属性,say方法) """ class Animal: def __init__(self,name): self.name = name pass def say(self): print("我是{}".format(self.name)) animal1 = Animal("大动物") animal1.say() class Bird(Animal): def __init__(self,name,age): # Animal.__init__(self,name) # super(Bird,self).__init__(name) super().__init__(name) self.age = age pass def say(self): print("我是{},我今年{}岁,我在自由自在的飞翔".format(self.name,self.age)) monkey=Bird('大飞猴',15); monkey.say();
false
5a3df41d0404913fe235ff0d4c712f3beff129ad
vijaypatha/Python_AI
/python_fundamentals/zip_unzip_enumerate.py
2,307
4.59375
5
# Zip name = [ "Manjeet", "Nikhil", "Shambhavi", "Astha" ] roll_no = [ 4, 1, 3, 2 ] marks = [ 40, 50, 60, 70 ] # using zip() to map values mapped = zip(name, roll_no, marks) mapped = list(mapped) print(mapped) # initializing list of players. players = [ "Sachin", "Sehwag", "Gambhir", "Dravid", "Raina" ] scores = [100, 15, 17, 28, 43 ] #print(list(zip(players, scores))) lists = [] for lst in zip(players, scores): lists.append(lst) for lst in lists: print(lst) ''' Use zip to write a for loop that creates a string specifying the label and coordinates of each point and appends it to the list points. Each string should be formatted as label: x, y, z. For example, the string for the first coordinate should be F: 23, 677, 4. ''' x_coord = [23, 53, 2, -12, 95, 103, 14, -5] y_coord = [677, 233, 405, 433, 905, 376, 432, 445] z_coord = [4, 16, -6, -42, 3, -6, 23, -1] labels = ["F", "J", "A", "Q", "Y", "B", "W", "X"] points = [] # write your for loop here for point in zip(labels, x_coord, y_coord, z_coord): points.append("{}: {}, {}, {}".format(*point)) for point in points: print(point) #Enummerate ''' Enumerate enumerate is a built in function that returns an iterator of tuples containing indices and values of a list. You'll often use this when you want the index along with each element of an iterable in a loop.''' letters = ['a', 'b', 'c', 'd', 'e'] for index, letter in enumerate(letters): print(index, letter) daily_chores = ["eat", "sleep", "repeat"] for chore in enumerate(daily_chores): print (chore) # chaning the counter to start at 300 for chore in enumerate(daily_chores,300): print (chore) # STRING animal = "dog" action = "bite" print("Does your {} {}?".format(animal, action)) print("does your {} {}?".format(animal, action)) ''' Map function ''' #Proble 1 # Return double of n def addition(n): return(n + n) # We double all numbers using map() numbers = (1, 2, 3, 4) result = map(addition, numbers) print(list(result)) numbers = [ [34, 63, 88, 71, 29], [90, 78, 51, 27, 45], [63, 37, 85, 46, 22], [51, 22, 34, 11, 18] ] def mean(num_list): return sum(num_list) / len(num_list) averages = list(map(mean, numbers)) print(averages)
true
7af15e9aec3ec2a5421e2b50ab74ce8d1190c083
Suryaphalle/python_practice
/python/group.py
546
4.3125
4
''' Write a function group(list, size) that take a list and splits into smaller lists of given size. output >>> group([1, 2, 3, 4, 5, 6, 7, 8, 9], 3) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> group([1, 2, 3, 4, 5, 6, 7, 8, 9], 4) [[1, 2, 3, 4], [5, 6, 7, 8], [9]] ''' list = [1,2,3,4,5,6,7,8,9] def group(list,n): l = len(list) for i in range(0,l): for j in range(i,n): print((list[:n])(list[n:(l-n)])) group(list,3) '''def group(l, size): ... return [l[i:i+size] for i in range(0, len(l), size)] '''
false
ca231d1b2d318397978544b82e54a68688f84f13
chrisjcoder/python-Challenge
/PyBank/main.py
2,688
4.15625
4
#In this challenge, you are tasked with creating a Python script for analyzing the financial records of your company. #You will give a set of financial data called budget_data.csv. The dataset is composed of two columns: Date and Profit/Losses. #(Thankfully, your company has rather lax standards for accounting so the records are simple.) # #Your task is to create a Python script that analyzes the records to calculate each of the following import os import csv from decimal import Decimal, ROUND_05UP, ROUND_HALF_UP budget_csv = os.path.join("Resources", "budget_data.csv") # tot=0 net=[]#** dev=[]#** with open(budget_csv,newline="") as csvBudget: csvreader=csv.reader(csvBudget,delimiter=",") next(csvreader, None) # skip the headers min_max = list(csvreader)#**creating a list from csvreader min_max.sort#** trying to sort list by date( not sure if this actually works) for row in min_max: tot=tot+1 #**The total number of months included in the dataset net.append(int(row[1]))#** in this list I gather all values in the profit/loss column for i in range(1,len(net)): dev.append(net[i]-net[i-1])#** add to list all profit/loss changes by each day # use this to convert average change to a currency format with 2 decimals cents = Decimal('0.01') avgChg=Decimal(sum(dev)/(tot-1)).quantize(cents, ROUND_HALF_UP) # now it's in memory, so we can reuse it #get entire row of min and max values profit/loss and the date profit= max(min_max, key=lambda row: int(row[1])) loss= min(min_max, key=lambda row: int(row[1])) # print(profit[0]) # print(profit[1]) # print(loss[0]) # print(loss[1]) #- Replicate the to terminal and file print("Financial Analysis") print(".......................................") print("Total Months: "+ str(tot)) print("Total: $"+ str(sum(net))) print("Average Change: $" + str(avgChg)) print("Greatest Increase in Profits: "+ profit[0] +" " +"($"+ profit[1]+")") print("Greatest Decrease in Profits: "+ loss[0] +" " +"($"+ loss[1]+")") # wrting a function to write contents to file def main(): f=open("FinancialAnalysis.txt","w+") f.write("Financial Analysis"+ "\r\n") f.write("......................................."+ "\r\n") f.write("Total Months: "+ str(tot)+ "\r\n") f.write("Total: $"+ str(sum(net))+ "\r\n") f.write("Average Change: $" + str(avgChg)+ "\r\n") f.write("Greatest Increase in Profits: "+ profit[0] +" " +"($"+ profit[1]+")"+ "\r\n") f.write("Greatest Decrease in Profits: "+ loss[0] +" " +"($"+ loss[1]+")") f.close if __name__ == "__main__": main()
true
518ea773e1125ec6930e458aad599329a7b6a187
u4atharva/coursera
/TensorFlow Specialization/Neural Nets with TensorFlow/Computer_Vision_Fashion_MNIST.py
2,520
4.625
5
# Beyond Hello World, A Computer Vision Example # # In the previous exercise you saw how to create a neural network that figured out the problem you were trying to solve. This gave an explicit example of learned behavior. Of course, in that instance, it was a bit of overkill because it would have been easier to write the function Y=2x-1 directly, instead of bothering with using Machine Learning to learn the relationship between X and Y for a fixed set of values, and extending that for all values. # But what about a scenario where writing rules like that is much more difficult -- for example a computer vision problem? Let's take a look at a scenario where we can recognize different items of clothing, trained from a dataset containing 10 different types. __author__ = "compiler" import tensorflow as tf import numpy as np import matplotlib.pyplot as plt print(tf.__version__) mnist = tf.keras.datasets.fashion_mnist (training_images, training_labels), (test_images, test_labels) = mnist.load_data() plt.imshow(training_images[0]) print(training_labels[0]) print(training_images[0]) training_images = training_images / 255.0 test_images = test_images / 255.0 model = tf.keras.models.Sequential([tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation=tf.nn.relu), tf.keras.layers.Dense(10, activation=tf.nn.softmax)]) # Sequential: That defines a SEQUENCE of layers in the neural network # Flatten: Remember earlier where our images were a square, when you printed them out? Flatten just takes that square and turns it into a 1 dimensional set. # Dense: Adds a layer of neurons # Each layer of neurons need an activation function to tell them what to do. There's lots of options, but just use these for now. # Relu effectively means "If X>0 return X, else return 0" -- so what it does it it only passes values 0 or greater to the next layer in the network. # Softmax takes a set of values, and effectively picks the biggest one, so, for example, if the output of the last layer looks like [0.1, 0.1, 0.05, 0.1, 9.5, 0.1, 0.05, 0.05, 0.05], it saves you from fishing through it looking for the biggest value, and turns it into [0,0,0,0,1,0,0,0,0] -- The goal is to save a lot of coding! model.compile(optimizer = tf.optimizers.Adam(), loss = 'sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(training_images, training_labels, epochs=5) model.evaluate(test_images, test_labels)
true
34c0b3e1bc0e8306c59acc8fbf0d4bd018aac9fc
luisnepo/Voting-System-
/Starter.py
1,065
4.1875
4
from tkinter import * import tkinter as tk # defines the StartWindow where the user can select if he wants to vote or to check the results of the election. # Done by Luis Nepomuceno lg6598x class StartWindow(tk.Frame): def __init__(self,parent,controller): tk.Frame.__init__(self,parent) self.controller = controller self.Header = Label(self,text = "Voting menu",width = 25,font= ("bold",20)) self.Header.place (x=35,y=40) self.vote = Button(self,text ="Vote",width = 20,bg ="black",fg = "white", command=lambda: self.vote_clicked(controller)).place(x = 160,y = 150) self.vote = Button(self, text="Show Results", width=20, bg="black", fg="white", command=lambda: self.results_clicked(controller)).place(x=160, y=200) #Shows the voting Window def vote_clicked(self,controller): controller.show_window("VoteWindow") #Shows the Results window def results_clicked(self,controller): controller.show_window("ShowResults")
true
cbe9b5f127f57e8690d142e2c689f8e2a4289225
Anchal-Mittal/Python
/shiftingString.py
926
4.125
4
def fun(): print("CONVERSION INT TO CHAR AND VICE - VERSA ") # ord() function will convert char to int print(ord('A')) # chr() function will convert int to char print(chr(98)) print("SHIFTING A CHARACTER BY 2") print(chr(ord('k')+2)) print("SHIFTING z CHARACTER DOES NOT RETURN ANOTHER CHARACTER") print(chr(ord('z')+2))#return | print("CREATING CIRCULAR SHIFT") print(chr((((ord('z')+2)-ord('a'))%26)+ord('a'))) print("TRANSLATING THE WHOLE STRING ") result= " " raw ="g fmnc 123s bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle grgl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj." print(raw) for c in raw: if c < 'a' and c > 'z': result +=chr((((ord('z')+2)-ord('a'))%26)+ord('a')) else : result += c print(result) fun();
false
d58ac09affbb5257ce17bc321b395b73f34cb89c
Anchal-Mittal/Python
/extend and count.py
868
4.1875
4
import array def arrayFun(): arr1=array.array('I',[1,2,8,9,4,1,3])#creating unsigned array;**ERROR WHEN WE INSERT SIGNED VALUE for i in range(0,7): print(arr1[i],end=" ")#for space we r using end print("\r") #print in next line print(arr1.count(1))#count the number of 1 in the array print("\r") arr2=array.array('I',[1,2,3,4,5]) print("extend arr1 to arr2") arr1.extend(arr2)#reverse the array's element for i in range(0,12): print(arr1[i],end=" ")#for space we r using end """arr3=array.array('i',[1,2,3,4,5]) print("extend arr1 to arr2") arr1.extend(arr3)#reverse the array's element for i in range(0,12): print(arr1[i],end=" ")#for space we r using end """#because we can extend the array of same kind arrayFun();
true
98c66f2f803e2d9a0ab1598fac7da6e8d30e315a
spiritedwolf/Learning
/Python/read.py
656
4.1875
4
#It's importing argv from sys module from sys import argv #Arguments name decleration script, filename = argv #Declaring variable #txt which is opening file of our "Argument 2". txt = open(filename) #It will print/read the file $txt print txt.read() #Normal print line. print "Type the filename again" #Declaring new variable $file_again which will read the input from the user file_again = raw_input("$ ") #Declaring new variable $txt_again which will open the file the name we passed to file_again txt_again = open(file_again) print txt_again.readline() #It will read the $txt_again varible-> the file whihc we have passed #print txt_again.read()
true
47fe88ba62a872ac84a63c83894eaca18c4b8541
mohammadr63/fun-python
/word.py
1,871
4.625
5
# In the first step, we have to give the computer # a list from which to choose the word show. There are many ways to do this. # I did this by defining a list and selecting one with a random module. import random name = input("What is your name? ") print ("Hello, {} Time to play hangman!".format(name)) print ("Start guessing...\n") # I also want to give the user five chances to guess that with each wrong # letter one of the chances decreases and when the game reaches zero, the game is over. words = ['python','php','swif','katolin','matlab' , 'java' , 'javascrip'] # The next thing is that the user did not make any guesses at the beginning # of the game, so her guess is empty and is added to it during the game. print(words) # There are two things that need to be done in this section. # One is to show us the number of letters. Second, for each correct letter # that the user guessed, remember to display the letter, # otherwise leave a space. word = random.choice(words) guesses = '' turns = 5 # Let's see what happens if the player guesses wrong # . Suffice it to say that if his guess is wrong, # one of his chances will be lost while turns > 0: failed = 0 for char in word: # In this section, we also want to see if the user has won or not? # If his chance is over, the game is over. if char in guesses: print (char,end=("")) else: print ("",end=""), failed += 1 if failed == 0: print (' You won' ) break guess = input("\n \n guess a character:") guesses += guess if guess not in word: turns -= 1 print("\n Wrong") print('\n You have {} more guesses'.format(turns)) if turns == 0: print ("\nYou Lose")
true
72f2f41a75f73614194cd4340440e0329dae0a5d
rahuldalal/NeuralNetwork
/model/perceptron.py
1,097
4.1875
4
import activation as a class Perceptron: def __init__(self, n, learning="PERCEPTRON", activation="TANH"): self.n = n self.learning = learning self.activation = activation def train(self, train_data): """ Trains the perceptron by using the learning and activation specified in the model. :param train_data: array of training data vectors. Each vector of length 'n' :return: weight vector and theta. """ print("Training method") def test(self, observation): """ Tests the given observation against the perceptron model and returns the activation result :param observation: test vector of length 'n' :return: activation function result """ print("Testing method") def _winnow_update(self): """ Winnow update rule implementation :return: Updated weight vector and theta """ def _perceptron_update(self): """ Perceptron update rule implementation :return: Updated weight vector and theta """
true
ac33db0681de0bf007d4982ce1be37e7948c1422
gitmj/fun_problems
/num_of_steps.py
1,131
4.28125
4
""" A child is running up a staircase with n steps and can hop either 1 step or 2 steps or 3 steps at a time. How many possible ways chile can run up the N stairs. """ def book_sol(n): if n < 0: return 0 if n == 0: return 1; return book_sol(n - 1) + book_sol(n - 2) + book_sol(n - 3) # Recursive version def num_steps(n): if n <= 0: return 0 elif n == 1: return 1 elif n == 2: return 2 elif n == 3: return 4 return (num_steps(n - 1) + num_steps(n - 2) + num_steps(n - 3)) def num_steps_mem(n, cache): if n <= 0: return 0 if n == 1: return 1 if n == 2: return 2 if n == 3: return 4 if n in cache: return cache[n] else: cache[n] = (num_steps_mem(n - 1, cache) + num_steps_mem(n - 2, cache) + num_steps_mem(n - 3, cache)) return cache[n] if __name__ == "__main__": var = raw_input("Please enter something: ") print "book sol: ", book_sol(int(var)) print num_steps(int(var)) cache = dict() print num_steps_mem(int(var), cache)
false
0d92620fcb9420fb69d814e7ee144f0efef58740
esjoman/Puzzles
/ProjectEuler/pe9.py
710
4.1875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # # pe9.py problem = ('9. There exists exactly one Pythagorean triplet ' '(a^2 + b^2 = c^2) for which a+b+c=1000. Find the ' 'product abc.') def find_pyth(n): """Finds Pythagorean triplet for a+b+c=n if it exists, else None""" for a in range(n//2): for b in range(a, n//2): c = (a**2 + b**2) ** 0.5 if a + b + c == n: return (a, b, int(c)) return None def solution(n=1000): """Returns product of Pythagorean triplet for a+b+c=n""" return reduce(lambda x,y: x*y, find_pyth(n)) if __name__ == '__main__': print problem print solution() # 31875000 (200, 375, 425)
true
beb12d92ede93049c535a8f5acd6542e050130cb
hackingmath/puzzles
/N_Queens_Problem.py
2,947
4.125
4
'''N Queens problem using backtracking June 29, 2019''' import time import random start = time.time() N = 10 #number of rows/cols def stack_board(board): output = [] for i in range(N): output.append([]) for j in range(N): output[i].append(board[N * i + j]) return output def row(board,n): '''returns values in row n of board''' newboard = stack_board(board) return newboard[n] def col(board,n): '''returns values in col n of stacked board''' newboard = stack_board(board) return [r[n] for r in newboard] def diag(board,n): '''The diagonals start in the top left corner [0][0] and end with [N-1][N-1]. Then they start in the lower left with [N-1][0] and end with [0][N-1]''' board = stack_board(board) output = [] half = 2*N - 1 for i in range(N): for j in range(N): if n < half: if i + j == n: output.append(board[i][j]) else: if i - j == half - n + N - 1: output.append(board[i][j]) return output def print_board(solution_board): '''Prints from flat boardlist''' print() for i in range(N): for n in row(solution_board,i): print(n," ",end = "") print() print() #blank line def check_no_conflicts(solution_board): for i in range(N): if row(solution_board,i).count('Q')>1 or col(solution_board,i).count('Q')>1: return False for j in range(4*N-2): if diag(solution_board,j).count('Q')>1: return False if solution_board.count(0) == 0: if solution_board.count("Q") != N: return False return True def solve(values,safe_up_to,size): solution = [0]*size def extend_solution(position): for value in values: solution[position] = value print_board(solution) if safe_up_to(solution): if position >= size - 1 or extend_solution(position + 1): return solution else: solution[position] = 0 if value == values[-1]: solution[position-1] = 0 if position < size -1: solution[position + 1] = 0 return None return extend_solution(0) print_board(solve(["Q",'.'],check_no_conflicts,N**2)) '''test_board = ['Q',0,0,0, 0,'Q',0,0, 0,0,'Q',0, 0,0,0,'Q'] print_board(test_board) for i in range(4*N-2): print(diag(test_board,i),diag(test_board,i).count("Q")) print(check_no_conflicts(test_board))''' elapsed = time.time()-start if elapsed < 60: print("Time (secs):",round(elapsed,1)) else: mins = elapsed // 60 secs = int(elapsed) % 60 print("Time:",mins,"minutes,",secs,"seconds.")
false
1bce12a5216e9ace7949f5391ab77a72f9d833d6
oliviagardiner/green-fox-projects-oliviaisarobot
/week-04/day-01/01_io/basics.py
1,507
4.25
4
# 1. Create a method that reads all contents of a file when its name given as param def readfile(file_name): f = open(file_name) result = f.read() f.close() return result #print(readfile('texts/zen_of_python.txt')) # 2. Create a method that gets a file_name and a number as param and reads the numberth line of the file def readline(file_name, number): f = open(file_name) result = f.readlines()[number-1].rstrip() return result #print(readline('texts/zen_of_python.txt', 7)) # 3. Create a method that gets a long sentence as param and gives back the contained words in a list def words(sentence): sentence = sentence[0:-1] result = sentence.split(" ") return result #print(words("This is a long sentence.")) # 4. Create a method that gets a list of words and creates a sentence with the words separated by spaces def sentence(words): result = "" for item in words: result += " " + item result += "." return result[1:len(result)] #print(sentence(['This', 'is', 'a', 'long', 'sentence'])) # 5. Create a method that gets a string and gives back the character codes in a list def char_codes(string): result = [] for a in string: result.append(ord(a)) return result # 6. Create a method that gets a list of integers and gives back a string which characters are created from the numbers used as character codes def string(char_codes): result = "" for a in char_codes: result += chr(a) return result
true
cce4c0e225337371e138599373b9cbcd4bc1423a
oliviagardiner/green-fox-projects-oliviaisarobot
/week-05/day-04/elevator/elevator_view.py
2,937
4.15625
4
# Create a class the displays the Elevator art and navigation (list of commands) class View(): building_levels = 12 building_width = 35 def intro(self, position, people): print("\n----- THE MIGHTY ELEVATOR -----\n") print("People in the elevator: {} (max. 5)\nElevator position: {}\n".format(people, position)) print(self.draw_top()) print(self.draw_levels(position, people)) print(self.draw_bottom()) print(self.nav()) print("\nWhat would you like to do?") def draw_top(self): top1 = "" for i in range(self.building_width): top1 += "_" top2 = "'" for j in range(1, self.building_width-1): top2 += " " top2 += "'" top3 = " '" for i in range(2, self.building_width-2): top3 += "_" top3 += "'" return top1 + "\n" + top2 + "\n" + top3 def draw_levels(self, position, people): levels = "" for i in range(self.building_levels, 0, -1): if i == 1 and position != 1: levels += " "*2 + "_" + "||_"*2 + "_"*6 + "||_"*2 + "_"*6 + "||_"*2 elif i == position and position != 1: levels += self.draw_elevator(position, people) elif i == position and position == 1: levels += self.draw_elevator(position, people) else: levels += " "*3 + "|| "*2 + " "*6 + "|| "*2 + " "*6 + "|| "*2 + "\n" return levels def draw_bottom(self): line2 = "'" for j in range(1, self.building_width-1): line2 += " " line2 += "'" line3 = "|" for i in range(1, self.building_width-1): line3 += "_" line3 += "|" return line2 + "\n" + line3 def draw_elevator(self, position, people): elevator = "" if position != 1 and people == 0: elevator += " "*3 + "|| "*2 + "[ ] " + "|| "*2 + " "*6 + "|| "*2 + "\n" elif position == 1 and people == 0: elevator += " "*2 + "_" + "||_"*2 + "[___]_" + "||_"*2 + "_"*6 + "||_"*2 elif position != 1 and people > 0: elevator += " "*3 + "|| "*2 + "[ X ] " + "|| "*2 + " "*6 + "|| "*2 + "\n" elif position == 1 and people > 0: elevator += " "*2 + "_" + "||_"*2 + "[_X_]_" + "||_"*2 + "_"*6 + "||_"*2 return elevator def nav(self): return("\n---- CONTROLS ----\n\nto X - enter a number to move to floor\nin X - enter a number to add people to the elevator\nout X - enter a number to remove people from the elevator\nexit - exit the application") def invalid_command(self): print("Please enter a valid command.") print("\nPress a button to refresh!") user_error = input() #newele = View() #print(newele.draw_top()) #print(newele.draw_levels(1, 1)) #print(newele.draw_bottom()) #print(newele.nav())
false
a850888034b9a6179cac9e6080771c9858a2bdac
oliviagardiner/green-fox-projects-oliviaisarobot
/week-04/day-04/12.py
350
4.1875
4
# 12. write a recursive function that can add numbers in # [1, 2, [3, 4], 1, [1, [2, 4]]] def add_number(list): if len(list) == 0: return 0 elif type(list[0]) == list: return add_number(list[0]) + add_number(list[1:]) else: return list[0] + add_number(list[1:]) print(add_number([1, 2, [3, 4], 1, [1, [2, 4]]]))
true
aeec753dd0f12281841b052d2fd363c3d1bd82be
devimonica/UCSD_Python_Excercise
/2. odd_or_even.py
1,058
4.4375
4
# Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. Hint: how does an even / odd number react differently when divided by 2? # Extras: # If the number is a multiple of 4, print out a different message. # Ask the user for two numbers: one number to check (call it num) and one number to divide by (check). If check divides evenly into num, tell that to the user. If not, print a different appropriate message. # Solution: number = input('Enter a number: ') value_2 = int(number) % 2 value_4 = int(number) % 4 if value_2 == 0 and value_4 == 0: print('The number is even and multiple of 4') elif value_4 == 0: print('The number is multiple of 4') elif value_2 == 0: print('The number is even') else: print('The number is odd') num = input('Enter a number: ') check = input('Enter another number to check :') result = int(num) / int(check) if result % 2 == 0: print('The numbers are evenly divisible') else: print('The numbers are not evenly divisible')
true
7e1cb7a8f72617abcfb7221b1b64cd8a54f4d2fe
devimonica/UCSD_Python_Excercise
/13. fibonacci.py
994
4.5625
5
# Write a program that asks the user how many Fibonacci numbers to generate and then generates them. # Take this opportunity to think about how you can use functions. Make sure to ask the user to enter the number of numbers in the sequence to generate. # (Hint: The Fibonacci seqence is a sequence of numbers where the next number in the sequence is the sum of the previous two numbers in the sequence. # The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …) # Solution: sequence = int(input('Enter the length of sequence: ')) def generate_fibonacci(): start_number = 1 fibonacci = [] if sequence == 0: fibonacci = [] elif sequence == 1: fibonacci = [1] elif sequence == 2: fibonacci = [1, 1] elif sequence > 2: fibonacci = [1, 1] while len(fibonacci) < sequence: fibonacci.append(fibonacci[start_number]+fibonacci[start_number-1]) start_number += 1 return fibonacci print(generate_fibonacci())
true
e2dd3a4101083d71e3e7c8c3c94fcea763fbfb1c
devimonica/UCSD_Python_Excercise
/14. list_remove_duplicates.py
632
4.1875
4
# Write a program (function!) that takes a list and returns a new list that contains all the elements of the first list minus all the duplicates. # Extras: # Write two different functions to do this - one using a loop and constructing a list, and another using sets. # Go back and do Exercise 5 using sets, and write the solution for that in a different function. # Solution: def remove_duplicates(): first_list = input('Enter a list: ') second_list = [] for number in first_list: if number not in second_list: second_list.append(number) return second_list print(remove_duplicates())
true
a8073abc53f14587494adce37eaa6fdb8ca3f1f6
animformed/maya-py-book-exercises
/P_maya_c5_human.py
2,234
4.21875
4
class Human(object): """ A basic class to demonstrate some properties of Python classes """ # Constant factor to convert pound to kilograms kPoundsToKg = 0.4563 # Constant factor to convert feet to metres kFeetToMetres = 0.3048 def __init__(self, *args, **kwargs): """ Initialize data attributes from keyword arguments """ self.first_name = kwargs.setdefault('first') self.last_name = kwargs.setdefault('last') self.height = kwargs.setdefault('height') self.weight = kwargs.setdefault('weight') def bmi(self): """ Compute body mass index assuming metric units """ return self.weight / float(self.weight)**2 @staticmethod def get_taller_person(human1, human2): """ Return which of the two instances is taller """ if human1.height > human2.height: return human1 else: return human2 @classmethod def create_adam(cls): """ Constructor to create Adam Mechtley """ return cls(first='Adam', last='Mechtley', height=6.083*cls.kFeetToMetres, weight=172*cls.kPoundsToKg) # Begin properties def fn_getter(self): """ Getter for full name """ return '%s %s' % (self.first_name, self.last_name) def fn_setter(self, val): """ Setter for full name """ self.first_name, self.last_name = val.split() def __str__(self): return '%s %s, %s metres, %s kgs' % (self.first_name, self.last_name, self.height, self.weight) # property for getting and setting the full name full_name = property(fn_getter, fn_setter) # End properties # Alternate property defs for py2.6 """ @property def full_name(self): return '%s %s' % (self.first_name, self.last_name) @full_name.setter def full_name(self, val): self.first_name, self.last_name = val.split() """ if __name__ == '__main__': k = Human() d = k.create_adam() print d print d.full_name d.full_name = 'Bob Mason' print d
false
5540900c9c5d2928605947541abceba3dc572477
mial0/py-mood_checker
/main.py
402
4.125
4
mood=input("Hello, how do you feel?").lower() if mood=="happy": print("It is great to see you happy!") elif mood=="nervous": print("Take a deep breath 3 times.") elif mood=="sad": print("Cheer up!") elif mood=="excited": print("I am glad that you are excited!") elif mood=="relaxed": print("It is great to see you feeling like that!") else: print("I don't recognize this mood.")
true
4f1062134079fac9a27cb2aa8c66e64e7c19e2b9
kswissmckquack/MIT_Intro_to_CS
/pset0/ps0.py
297
4.21875
4
""" 1. Asks user to enter number "x" 2. asks user to enter number "y" 3. print out number "x", raised to power "y" 4. Prints out log (base2) of "x" """ import math x = float(input('Enter number x:')) y = float(input('Enter number y:')) print('x**y = ',x**y) print('log(x) = ', math.log(x,2))
true
01719058e89a4fddfbb51a6a5befc791d9c6e34e
seokjaehong/albs_study
/project/hotel_project/utils.py
1,199
4.125
4
import datetime import re def convert_string_datetime(str): year, month, day = map(int, str.split('-')) result = datetime.date(year, month, day) return result def get_fr_to_date(): while True: try: print('시작날짜: YYYY-MM-DD 형식으로 입력해주세요') string_fr_date = input() fr_date = convert_string_datetime(string_fr_date) print('종료날짜: YYYY-MM-DD 형식으로 입력해주세요') string_to_date = input() if string_to_date > string_fr_date: to_date = convert_string_datetime(string_to_date) else: raise Exception except ValueError: print('날짜형식에 맞춰서 입력해주세요') continue except Exception as to_data: print('체크아웃 날짜는 체크인 날짜보다 작을수 없습니다.') continue else: break return { 'fr_date': fr_date, 'to_date': to_date } def is_valid_email(email): if len(email) > 7: return bool(re.match("^.+@(\[?)[a-zA-Z0-9-.]+.([a-zA-Z]{2,3}|[0-9]{1,3})(]?)$", email))
false
3437c6dbfc4382c7e710a4943ffa160f4941ddd1
DemetrioCN/programmingExercises
/python_platzi_retos/semana1/4_suma_multiplicacion.py
361
4.125
4
print("Operaciones \n") #num1 = float(input("Ingrese un numero: ")) #num2 = float(input("Ingrese otro numero: ")) #num3 = float(input("Ingrese un numero mas: ")) print("Ingrese tres numeros separados por un ENTER ") num1, num2, num3 = float(input()), float(input()), float(input()) resultado = (num1+num2)*num3 print("El resultado es: ", round(resultado,2))
false
04099fbdf8dc4b653ef60fb18b9fd04736bcaa8a
DemetrioCN/programmingExercises
/python_platzi_retos/semana2/2_rango.py
321
4.1875
4
num_limite = float(input("Introduce un número limite: ")) num_comparar = float(input("Introduce un número para comparar: ")) if num_comparar < num_limite: print("El número {} se encuentra en el rango, gracias".format(num_comparar)) else: print("El número {} excede el límite permitido".format(num_comparar))
false
32f91377bb0fe2d85535452f819f81c944d77658
Abe2G/Pandas-DataFrame-Tools
/Plotting/Histogram/hist_columns.py
1,079
4.15625
4
import pandas as pd import matplotlib.pyplot as plt #-------------------- #Language: Python #Function: hist_columns() #Purpose: Easily generate a Histogram pyplot from a DataFrame and list of columns #Inputs: Pandas DataFrame, Log condition(T/F), Rotation value, single or variable column names #Outputs: Histogram plots of given column in Pandas DataFrame #-------------------- def hist_columns(df, log, rot, *args): # For each column name given, check if log axes chosen, plot histogram for arg in args: #Check if user passed a logarithmic scale designation if log == "True": #Create Histogram plot df[arg].plot(kind='hist', logx=True, logy=True, rot=rot) #Add x-axis label plt.xlabel(str(arg)) #Show plot plt.show() #No log scale specified else: #Create Histogram plot df[arg].plot(kind='hist', logx=False, logy=False, rot=rot) #Add x-axis label plt.xlabel(str(arg)) #Show plot plt.show()
true
6c2d6764664ac5a3fbddba5d569168628a9d4e07
sol83/python-code_in_place-assignment3
/Images/warhol_filter.py
1,382
4.21875
4
""" This program generates the Warhol effect based on the original image. """ import random from simpleimage import SimpleImage N_ROWS = 2 N_COLS = 3 PATCH_SIZE = 222 WIDTH = N_COLS * PATCH_SIZE HEIGHT = N_ROWS * PATCH_SIZE PATCH_NAME = 'images/simba-sq.jpg' MAX_RANDOM = 1.5 def make_recolored_patch(red_scale, green_scale, blue_scale): # making and returning colored patch patch = SimpleImage(PATCH_NAME) for pixel in patch: pixel.red *= red_scale pixel.green *= green_scale pixel.blue *= blue_scale return patch def place_patch(pos_x, pos_y, final_image, patch): # placing the patch in passed initial coordinates in the matrix for x in range (patch.width): for y in range (patch.height): final_image.set_pixel(x + pos_x, y + pos_y, patch.get_pixel(x, y)) def main(): final_image = SimpleImage.blank(WIDTH, HEIGHT) for x in range (N_COLS): for y in range (N_ROWS): # applying colorization to the patch patch = make_recolored_patch(random.uniform(0, MAX_RANDOM), random.uniform(0, MAX_RANDOM), random.uniform(0, MAX_RANDOM)) # placing the colored patch to the final matrix passing initial coordinates to the function place_patch(x * PATCH_SIZE, y * PATCH_SIZE, final_image, patch) final_image.show() if __name__ == '__main__': main()
true
a7c9cc1fe78a52b5895e5750d0bc694681a1fbb5
sandeepkumar8713/pythonapps
/25_fifthFolder/08_stock_span.py
1,754
4.21875
4
# https://www.geeksforgeeks.org/the-stock-span-problem/ # Similar : https://leetcode.com/problems/daily-temperatures/ # Question : The stock span problem is a financial problem where we have a series of n daily price # quotes for a stock and we need to calculate span of stock’s price for all n days.The span Si # of the stock’s price on a given day i is defined as the maximum number of consecutive days # just before the given day, for which the price of the stock on the current day is less than # or equal to its price on the given day. # # Example : Input : {100, 80, 60, 70, 60, 75, 85} # Output : {1, 1, 1, 2, 1, 4, 6} # # Question Type : Generic # Used : Loop over the given inpArr. If current element is higher than previous element, # add its span to current span. Jump in left by current span value. # Repeat the above process. # calculateSpan(inpArr): # n = len(inpArr), span = [0] * n # span[0] = 1 # for i in range(1, n): # counter = 1 # while (i - counter) >= 0 and inpArr[i] >= inpArr[i - counter]: # counter += span[i - counter] # span[i] = counter # return span # Complexity : O(2n) def calculateSpan(inpArr): n = len(inpArr) span = [0] * n # Span value of first element is always 1 span[0] = 1 # Calculate span values for rest of the elements for i in range(1, n): counter = 1 while (i - counter) >= 0 and inpArr[i] >= inpArr[i - counter]: counter += span[i - counter] span[i] = counter return span if __name__ == "__main__": price = [10, 4, 5, 90, 120, 80] print(calculateSpan(price)) price = [100, 80, 60, 70, 60, 75, 85] print(calculateSpan(price))
true
2ff5176fc766293a94c6636da86def92aef9397a
sandeepkumar8713/pythonapps
/21_firstFolder/09_first_non_repeat_char.py
1,027
4.28125
4
# https://www.geeksforgeeks.org/given-a-string-find-its-first-non-repeating-character/ # Question : Given a string, find the first non-repeating character in it. For example, if # the input string is "GeeksforGeeks", then output should be 'f' # # Question Type : Easy, SimilarAdded # Used : Used a map to store each character as key and count & index as its value. Loop again # to find the first character with count 1 and return. # Complexity : O(n) def makeTable(inpStr): strMap = dict() for i in range(len(inpStr)): if inpStr[i] in strMap: strMap[inpStr[i]]['count'] += 1 else: strMap[inpStr[i]] = {"count": 1, "index": i} return strMap def firstNonRepeat(inpStr): strMap = makeTable(inpStr) for i in range(len(inpStr)): if strMap[inpStr[i]]['count'] == 1: return strMap[inpStr[i]]['index'] return -1 if __name__ == "__main__": inpStr = "geeksforgeeks" print('First non repeating character =', firstNonRepeat(inpStr))
true
2b0aaeb6018c0a670174624982d13910b4c4ad9b
sandeepkumar8713/pythonapps
/02_string/27_substring_rotation.py
1,032
4.3125
4
# CTCI : Q1_09_String_Rotation # Question : Assume you have a method isSubString which checks if one word is a substring # of another. Given two strings, S1 and S2, write code to check if S2 is a rotation of S1 using only one # call to iSSubString (e.g., "waterbottle" is a rotation of" erbottlewat") # # Question Type : Easy # Used : So, we need to check if there's a way to split s1 into x and y such that xy = s1 # and yx = s2. Regardless of where the division between x and y is, we can see that # yx will always be a substring of xyxy.That is, s2 will always be a substring of s1s1. # Complexity : O(n^2) def isSubtring(big, small): if big.find(small) >= 0: return True return False def isRotation(s1, s2): if len(s1) == len(s2) and len(s1) > 0: return isSubtring(s1+s1, s2) return False if __name__ == "__main__": pairs = [["apple", "pleap"], ["waterbottle", "erbottlewat"], ["camera", "macera"]] for pair in pairs: print(pair, isRotation(pair[0], pair[1]))
true
85022223193a6df4fd21d916b6c0f31d8aa1e4ac
sandeepkumar8713/pythonapps
/07_hashing/17_sort_linked_list_as_array.py
2,031
4.28125
4
# https://www.geeksforgeeks.org/sort-linked-list-order-elements-appearing-array/ # Question : Given an array of size N and a Linked List where elements will be from the # array but can also be duplicated, sort the linked list in the order, elements # are appearing in the array. It may be assumed that the array covers all elements # of the linked list. # # Input : Linked list : 3 2 5 8 5 2 1 # array : 5, 1, 3, 2, 8 # Output: Sorted Linked List : 5 5 1 3 2 2 8 # # Question Type : ShouldSee # Used : First, make a hash table that stores the frequencies of elements in linked list. # Then, simply traverse array and for each element of arr[i] check the frequency # in the has table and modify the data of list by arr[i] element up to its # frequency and at last Print the list. # Complexity : O(n) class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def printList(self): temp = self.head while temp: print(temp.data, end=" ") temp = temp.next print("") def sortAsPerArray(self, inpArr): freqDict = dict() temp = self.head while temp: if temp.data in freqDict.keys(): freqDict[temp.data] += 1 else: freqDict[temp.data] = 1 temp = temp.next temp = self.head for ele in inpArr: freq = freqDict[ele] for i in range(freq): temp.data = ele temp = temp.next if __name__ == "__main__": inpArr = [5, 1, 3, 2, 8] lList = LinkedList() lList.push(1) lList.push(2) lList.push(5) lList.push(8) lList.push(5) lList.push(2) lList.push(3) lList.printList() lList.sortAsPerArray(inpArr) lList.printList()
true
c1cea9cc63dd0860ecb65ad9a48b5cb9bbbfc689
sandeepkumar8713/pythonapps
/12_backtracking/05_generate_valid_ip.py
1,929
4.28125
4
# https://www.geeksforgeeks.org/program-generate-possible-valid-ip-addresses-given-string/ # Question : Given a string containing only digits, restore it by returning all possible # valid IP address combinations. # # A valid IP address must be in the form of A.B.C.D, where A, B, C, and D are numbers from # 0-255. The numbers cannot be 0 prefixed unless they are 0. # # Question Type : Easy # Used : Run 3 loops from : 0 to n - 2, i + 1 to n - 1 and j + 1 to n. # By running these 3 loops split the given string into 4 parts that will give you # a ip address. Check if ip is valid, if true then print it. # Condition for valid ip: Spilt the ip in 4 parts can check for # Sub part should not be of length more than 3. It should be between 0 to 255. # It should not be 00 or 000. # It should not have 0 as prefix. # Complexity : O(n^3) def is_valid(ip): ip = ip.split(".") # Checking for the corner cases for i in ip: if len(i) > 3 or int(i) < 0 or int(i) > 255: return False if len(i) > 1 and int(i) == 0: return False if len(i) > 1 and int(i) != 0 and i[0] == '0': return False return True def convert(s): sz = len(s) if sz < 4: return [] if sz > 12: return [] snew = s l = [] # Generating different combinations. for i in range(1, sz - 2): for j in range(i + 1, sz - 1): for k in range(j + 1, sz): snew = snew[:k] + "." + snew[k:] snew = snew[:j] + "." + snew[j:] snew = snew[:i] + "." + snew[i:] # Check for the validity of combination if is_valid(snew): l.append(snew) snew = s return l if __name__ == "__main__": A = "25525511135" print(convert(A)) B = "25505011535" print(convert(B))
true
d9869133c49260d621d4b2d8824f30b45b45ff1b
sandeepkumar8713/pythonapps
/29_ninthFolder/03_caesar_cipher_encryption.py
1,436
4.28125
4
# https://leetcode.com/discuss/interview-question/395045/Facebook-or-Phone-Screen-or-Caesar-Cipher # Question : You are given a list of string, group them if they are same after using Ceaser Cipher Encrpytion. # Definition of "same", "abc" can right shift 1, get "bcd", here you can shift as many time as you want, # the string will be considered as same. # # Example: Input: ["abc", "bcd", "acd", "dfg"] # Output: [["abc", "bcd"], ["acd", "dfg"]] # # Question Type : Easy # Used : Note that diff b/w the characters is same for "same" words. # We will use this diff as key in map to group the words. # Logic: for word in words: # n = len(word), diff_list = [] # for i in range(1, n): # diff_list.append(str(ord(word[i]) - ord(word[0]))) # diff = "".join(diff_list) # record[diff].append(word) # return list(record.values()) # Complexity : O(n * m) n is word count, m is length of longest word. from collections import defaultdict def caesar_encryption(words): record = defaultdict(list) for word in words: n = len(word) diff_list = [] for i in range(1, n): diff_list.append(str(ord(word[i]) - ord(word[0]))) diff = "".join(diff_list) record[diff].append(word) return list(record.values()) if __name__ == "__main__": inp_arr = ["abc", "bcd", "acd", "dfg"] print(caesar_encryption(inp_arr))
true
2e7e162649ae9b31613f09a0808cc88a085adf9d
sandeepkumar8713/pythonapps
/20_initialFiles/02_find_pair_in_array.py
1,650
4.15625
4
# Question : Find a pair in given array whose sum is equal to the given number # # Question Type : Easy # Two methods are given below # quick sort # hashing # TODO :: add used def quickSort(array, start, end): # (complexity : n log n) if start < end: pivot = partition(array, start, end) quickSort(array, start, pivot - 1) quickSort(array, pivot + 1, end) def partition(array, left, right): while left < right: if array[left] < array[right]: right -= 1 else: array[left], array[right] = array[right], array[left] left += 1 return left def findTwoElements(array,num): # (complexity : n) left=0 right=len(array)-1 while left<right: if array[left] + array[right] == num: print('The two elements are',array[left],'and',array[right]) return elif array[left] + array[right] < num: left+=1 else: right-=1 print('Pair not found') # It checks the presence of required element # The elements should be of known numbers def hashMap(array,num): # (complexity : n, space complexity: max integer) constantMax = 100000 binMap = [0]*constantMax for i in range(0,len(array)): if binMap[num-array[i]] == 1: print('The two elements are',array[i],'and',num-array[i]) return binMap[array[i]]=1 print('Pair not found') if __name__ == '__main__': array = [1, 4, 45, 6, 10, -8] num = 16 #method 1 quickSort(array, 0, len(array) - 1) findTwoElements(array,num) #method 2 hashMap(array, num)
true
51b235cdedd8a596a11262a4805f410edfa99176
sandeepkumar8713/pythonapps
/02_string/30_find_extra_character.py
1,039
4.34375
4
# https://www.geeksforgeeks.org/find-one-extra-character-string/ # Question : Given two strings which are of lengths n and n+1. The second string contains # all the character of the first string, but there is one extra character. Your task to # find the extra character in the second string. # # Question Type : Easy # Used : Add the character of both strings. Their difference will give ascii of extra character. # Complexity : O(n) def charToIndex(ch): return ord(ch) - ord('a') def indexToChar(index): return chr(index + ord('a')) def findExtraChar(s1,s2): if len(s1) < len(s2): big = s2 small = s1 else: big = s1 small = s2 asciiSumBig = 0 asciiSumSmall = 0 for char in big: asciiSumBig += charToIndex(char) for char in small: asciiSumSmall += charToIndex(char) extraAsciiChar = asciiSumBig - asciiSumSmall return indexToChar(extraAsciiChar) if __name__ == "__main__": s1 = "abcd" s2 = "cbdae" print(findExtraChar(s1, s2))
true
ba825cd66138efb9c4026d656c49abe108378169
sandeepkumar8713/pythonapps
/02_string/25_palindrome_permutation.py
1,388
4.125
4
# CTCI : Q1_04_Palindrome_Permutation # Question : Given a string, write a function to check if it is a permutation of a palindrome. # A palindrome is a word or phrase that is the same forwards and backwards. # A permutation is a rearrangement of letters. # # Input : rats live on no evil star # Output : True # # Question Type : ShouldSee # Used : Here we have to make sure that frequency of each character is even. At most only # one character can have odd frequency. Use a bit vector and keep flipping its bits. # At end bit vector must be 0 as bits will be flipped even number of times. # For 1 odd use this logic : (bitVector & (bitVector - 1)) == 0 # Complexity : O(n) def toggle(bitVector, index): if index < 0: return bitVector mask = 1 << index if (bitVector & mask) == 0: bitVector |= mask else: bitVector &= ~mask return bitVector def createBitVector(phrase): bitVector = 0 for char in phrase: x = ord(char) bitVector = toggle(bitVector, x) return bitVector def checkAtMostOneBitSet(bitVector): return (bitVector & (bitVector - 1)) == 0 def isPermutationOfPalindrome(phrase): bitVector = createBitVector(phrase) return checkAtMostOneBitSet(bitVector) if __name__ == "__main__": pali = "rats live on no evil star" print(isPermutationOfPalindrome(pali))
true
0eb614cb426fccbecca37f01084c23bab1c24123
sandeepkumar8713/pythonapps
/03_linkedList/22_evaluate_postfix.py
1,519
4.1875
4
# https://www.geeksforgeeks.org/stack-set-4-evaluation-postfix-expression/ # Question : The Postfix notation is used to represent algebraic expressions. The expressions # written in postfix form are evaluated faster compared to infix notation as parenthesis # are not required in postfix # # Question Type : Easy # Used : Maintain a stack. Loop over the input expression. If ch is digit push in stack else # pop two values from stack, do the operation over them and push it back to stack: # stack.push(str(eval(val1 + ch + val2))). # Remember while pop, assign val2 then val1 # After the loop ends pop the an element from stack and return: return int(stack.pop()) # Complexity : O(n) class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def pop(self): if self.head is None: return None data = self.head.data self.head = self.head.next return data def evaluate(exp): stack = LinkedList() for ch in exp: if ch.isdigit(): stack.push(ch) else: val2 = stack.pop() val1 = stack.pop() stack.push(str(eval(val1 + ch + val2))) return int(stack.pop()) if __name__ == "__main__": exp = "231*+9-" print(evaluate(exp))
true
fe51d3b7ecdfadf97a1cab1e90f26aa49a494088
sandeepkumar8713/pythonapps
/14_trie/03_print_all_anagram_together.py
2,366
4.28125
4
# CTCI : Q10_02_Group_Anagrams # https://www.geeksforgeeks.org/given-a-sequence-of-words-print-all-anagrams-together-set-2/ # Question : Given an array of words, print all anagrams together. For example, if the given array is # {"cat", "dog", "tac", "god", "act"}, then output may be "cat tac act dog god". # # Question Type : Asked # Used : In trie Node add two fields : children (list of size 26) and wordEndingID # (list of id of words ending at this node) # Loop over the given list of words. Sort the word and insert it in Trie and also insert its id, # where the word ends. # Now traverse the Trie again (DFS) and if there are id in wordEndingID: print them # Logic: def traverseUtils(self, root, res, inp_strs): # temp = root # for child in temp.children.values(): # self.traverseUtils(child, res, inp_strs) # res_2 = [] # for index in child.index_list: # res_2.append(inp_strs[index]) # if len(res_2) > 0: # res.append(res_2) # return res # Complexity : O(n * m * log m) + O(m * n) m is MAX_CHAR and n is word count class TrieNode: def __init__(self): self.children = dict() self.index_list = [] class Trie: def __init__(self): self.root = TrieNode() def insert(self, inpStr, wordId): temp = self.root for ch in inpStr: if ch not in temp.children: temp.children[ch] = TrieNode() temp = temp.children[ch] temp.index_list.append(wordId) def traverseUtils(self, root, res, inp_strs): temp = root for child in temp.children.values(): self.traverseUtils(child, res, inp_strs) res_2 = [] for index in child.index_list: res_2.append(inp_strs[index]) if len(res_2) > 0: res.append(res_2) return res def traverse(self, inp_strs): res = [] self.traverseUtils(self.root, res, inp_strs) return res def group_similar(inp_strs): trie = Trie() wordId = 0 for word in inp_strs: trie.insert(sorted(word), wordId) wordId += 1 return trie.traverse(inp_strs) if __name__ == '__main__': inpWords = ["cat", "dog", "tac", "god", "act", "gdo"] print(group_similar(inpWords))
true
7364ec2ebaec4e77230228f7a7ff3de3f302441b
softsun-tomorrow/FlapPyBird-master
/lesson_02.py
1,372
4.375
4
# 课程2 目标 # 1.了解Python的基础数据结构 # 2.掌握python中的str、list、tuple、set、dict # 字符串:str # a_string = "I am a string" # type(a_string) # 列表:list、tuple、set # list 一种可变的数组 # a_list = [1,2,3,4] # type(a_list) # a_list.append(5) # tuple 一种不可变的数组 # a_tuple = (1,2,3,4) # type(a_tuple) # a_tuple.append(5) #error # a_tuple[0] = 2 #error # set 一种可变的数组元素唯一的数组 # a_set = set(a_list) # or set([1,2,1,2]) # type(a_set) # 字典:dict # dict 简单的 key => value 存储结构 # a_dict = {'1':'a', '2':'b'} # a_dict.keys() # a_dict.values() # 3.了解高级特性简单介绍 # 生成器 generator,比如range 生成10个元素,放到内存中供使用 # for i in range(10): # 一次执行完成 比较消耗内存 # print i # for i in xrange(10): # 每执行一步产生一个 适合生成大数组 # print i # 迭代器 iterator # 切片 # a_list = [1, 4, 9, 16, 25, 36, 49, 64, 81] # a_list[5: 7] # a_list[-2:]
false
6b83fd24a321d415bbb24f5f28a864793b24f452
terracenter/Python3-CodigoFacilito
/Scripts/POO/Clases04.py
795
4.1875
4
#TEMA: VARIABLES DE CLASE ######################################################## class Circulo: _pi = 3.1416 #Es una variable de clase -> No hay nesecidad de crear instancias def __init__(self, radio): self.radio = radio def area(self): return self.radio * self.radio * Circulo._pi ######################################################## print(Circulo._pi) print() print() #Puedo modificar la Variable de clase #_Variable -> Indica que no se debe cambiar el valor de esa Variable #Instanciando la clase circulo circulo01= Circulo(3) circulo02= Circulo(4) print(circulo01.radio) print(circulo02.radio) print() print() #print(circulo01.__dict__) #->Retorna diccionario con los atributos de circulo01 #Metodo usando la variable de clase print(circulo01.area())
false
5c94068f10fb5fef8dafda7bb831600499d85c3f
terracenter/Python3-CodigoFacilito
/Scripts/Variables/StringsListas.py
856
4.375
4
#String como array de caracteres #Las listas comienzan en la posicion 0 myString = 'Curso de Codigo Facilito!' print(myString) print() #Imprimir por caracteres print(myString[0]) #Retorma C print(myString[1]) #Retorma u print(myString[16]) #Retorma F print(myString[5]) #Los espacios cuentan como caracteres print() #Imprimir Cadena al Reves print(myString[-1]) #Retorma ! print(myString[-2]) #Retorma o print(myString[-10]) #Retorma _ Un espacio print() #Mostrar una Subcadena print(myString[0:10]) #Imprime desde el caracter 0 hasta el 10 print(myString[5:12]) #Imprime desde el caracter 5 hasta el 12 print(myString[-2:-1]) #Imprime desde el caracter -2 hasta el -1 print() #Saltos print(myString[0:10:2]) #Imprime desde el caracter 0 hasta el 10, Haciendo Saltos de 2 print() #Cadena al Reves print(myString[::-1]) #Imprime la cadena al reves :v
false
3f4be9774a4677d22a34e97a6a514b98bd2416f2
terracenter/Python3-CodigoFacilito
/Scripts/Funciones/Decoradores.py
2,378
4.15625
4
#Un decorador permite añadir funcionalida a las funciones #En si un decorador en una funcion que recibe como parametro una funcion y devuelve otra funcion #A, B, C son funciones #A recibe como parametro B para poder crear C ################################################################# #Basico def decorador(func): def nuevaFuncion(): print("Vamos a ejecutar la funcion") #Agregar Codigo func() # Agregar Codigo print("Se ejecuto la funcion") return nuevaFuncion @decorador #Nos indica para poder decorarla def saluda(): print("Hola mundo") saluda() print() print() ################################################################## #Para manejar argumentos tengo que realizar algunas modificaciones def decoradorSuma(func): def nuevaFuncion(*args, **kwargs): print("Vamos a ejecutar la funcion") #Agregar Codigo func(*args, **kwargs) # Agregar Codigo print("Se ejecuto la funcion") return nuevaFuncion @decoradorSuma #Nos indica para poder decorarla def suma(num01, num02): print(num01 + num02) suma(12,12) print() print() ################################################################# #Trabajar con retorno de valores def decoradorSuma02(func): def nuevaFuncion(*args, **kwargs): print("Vamos a ejecutar la funcion") resultado = func(*args, **kwargs) print("Se ejecuto la funcion") return resultado return nuevaFuncion @decoradorSuma02 #Nos indica para poder decorarla def suma02(num01, num02): return (num01 + num02) resultado = suma02(2,232) print(resultado) print() print() ################################################################# #Los decoradores tambien reciben parametro def decorador02(isValid): def decorador03(func): def beforeAction(): print("Vamos a ejecutar la funcion") def afterAction(): print("Se ejecuto la funcion") def nuevaFuncion(*args, **kwargs): if isValid: beforeAction() resultado = func(*args, **kwargs) afterAction() return resultado return nuevaFuncion return decorador03 @decorador02(isValid = False) def multiplicacion(num01, num02): return num01 * num02 resultado = multiplicacion(98, 12) print(resultado) print() print()
false
35db464b40605f6f327fccfdadd88dfd6190d654
dsli208/ScriptingLanguages
/CSE 337 Python Programs/lecture3.py
2,664
4.25
4
Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> 5 / 2 2 >>> 10 / 7 1 >>> 5 / 2.0 2.5 >>> sum = 0 >>> count = 0 >>> num = input("Enter your number: ") Enter your number: 10 >>> while num != -1: sum = sum + num count = count + 1 num = input("Enter your number: ") Enter your number: 20 Enter your number: 14 Enter your number: 36 Enter your number: 17 Enter your number: -1 >>> print "The average is", sum / count The average is 19 >>> # CANNOT DO INCREMENTING SYNTAX IN PYTHON >>> # If we enter -1, doesn't work --> 0 DIVISION >>> while True: num = input("Enter number: ") if num == -1: break Enter number: 0 Enter number: 0 Enter number: -1 >>> for num in range (2, 6): if num % 2 == 0: print "Found an even number" continue print "Found a number", num Found an even number Found a number 3 Found an even number Found a number 5 >>> def area_of_rect(w, h): return w * h print 'the area of the rectangle with dimensions 2x3 is', area_of_rect(2, 3) SyntaxError: invalid syntax >>> def area_of_rect(w, h): return w * h print 'the area of the 2x3 rectangle is', area_of_rect(2, 3) SyntaxError: invalid syntax >>> def area_of_rect(w, h): return w * h >>> print 'the area of the 2x3 rectangle is', area_of_rect(2, 3) the area of the 2x3 rectangle is 6 >>> import math >>> def vol_of_radius(r): return 4 * math.pi * r * r * r / 3.0 >>> print vol_of_radius(5) 523.598775598 >>> def factorial(n): if n == 0: return 0 else: return n * factorial(n - 1) >>> print factorial(6) 0 >>> def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) >>> print factorial(6) 720 >>> lst = [4, 2, 1, 6, 19] >>> lsttwo = [5, 'hello', lst] >>> def list_sum(lst): if len(lst) == 0: return 0 else: return lst[0] + list_sum(lst[1:]) >>> print list_sum(lsttwo) Traceback (most recent call last): File "<pyshell#62>", line 1, in <module> print list_sum(lsttwo) File "<pyshell#61>", line 5, in list_sum return lst[0] + list_sum(lst[1:]) File "<pyshell#61>", line 5, in list_sum return lst[0] + list_sum(lst[1:]) File "<pyshell#61>", line 5, in list_sum return lst[0] + list_sum(lst[1:]) TypeError: can only concatenate list (not "int") to list >>> print list_sum(lst) 32 >>> # list_sum only works with ints, lsttwo has strings and lists also >>> lsttwo [5, 'hello', [4, 2, 1, 6, 19]] >>> lst1 = [1, 2] >>> lst2 = [1, 2, lst1] >>> lst2 [1, 2, [1, 2]] >>> lst1.append(lst2) >>> lst1 [1, 2, [1, 2, [...]]] >>> # ^ "Black hole" because the lists refer to each other in memory" >>> lst[:2] [4, 2] >>>
true
6c4a28632ca45e6c315212f3b4f966bfee325f4d
arkellmer/python-4-5-class
/password.py
2,218
4.34375
4
#andrew kellmer 10/1/18 #password and username program #menu is running main and letting you in or not def main(): login = False password, username, login = menu() if login == True: print("you're in") else: print("access denied") menu() #menu has the bulk of the program running in it. def menu(): choice = 0 while choice == 0: print("to sign up enter 1") print("to sign in enter 2") choice = int(input()) if choice == 1: print ("choice 1") username = get_username() password = get_password() choice = 0 elif choice == 2: print("choice 2") login = check_info(username, password) return password, username, login else: print("thats not a valid option") menu() #gets the username from the user def get_username(): print("""username can only contain numbers and letters and can only contain 10 characters and no less than 3 characters""") username = input("enter your username") if username.isalnum() and len(username)<=10 and len(username)>=3: print("username is set") return username else: print("your username didn't meet the requirements") get_username() #gets the password from the user def get_password(): print("""your password must start with a capital letter and must contain at least one symbol and must be 10 characters long.""") password = input("enter password") if password.istitle() and not password.isalnum() and len(password)>=10: print("password is set") return password else: print("your password didn't meet the requirements") get_password() #checks the information def check_info(username, password): username = username password = password input_username = input("enter your username") input_password = input("enter your password") if input_username == username and input_password == password or input_username == "admin": return True else: return False main()
true
0e42db1a546493f3401865f46620949496365e0f
Mudit-Shukla/projects
/mini-projects/turtlemodulepractice/turtle_racing_game/main.py
938
4.1875
4
from turtle import Turtle, Screen import random screen = Screen() is_race_on = False screen.setup(width = 500, height = 400) user_choice = screen.textinput(title= "Turtle race", prompt="Bet on you turtle") colors = ["red", "green", "blue", "yellow","orange", "purple"] all_turtle = [] for i in range(0,6): turtle_name = Turtle("turtle") turtle_name.penup() turtle_name.color(colors[i]) turtle_name.goto(-235, -100 + (i*45)) all_turtle.append(turtle_name) if user_choice: is_race_on = True while is_race_on: for turtle in all_turtle: if turtle.xcor() >= 230: is_race_on = False color = (turtle.pencolor()) if color == user_choice: print(f"You won. {color} is the wining turtle") else: print(f"You lost. {color} is the winner") dist = random.randint(0,10) turtle.forward(dist) screen.exitonclick()
true
954b73dda712acaa2eec9c3feb57b83bea2aa496
VenkatVuddagiri/100-days-of-code
/Day38/reverse.py
289
4.21875
4
# Write a function named reverse which accpets a string input and reverses the string using recursion def reverse(strng): if len(strng)==0: return "" else: return strng[len(strng)-1]+reverse(strng[:len(strng)-1:]) print(reverse("python")) print(reverse("Venkat"))
true
9ba4f4d5c757eb3c70d2a092775c2b7235222a4e
AcudoDev/FinanceToolbox
/MachineLearning/LinearRegression/ConvertToPolynomial.py
787
4.46875
4
import pandas as pd def ConvertToPolynomial(df, degrees): """ This function convert a dataframe of variables to its polynomial equivalence Argument: ---------- - df: pandas dataframe The dataframe to convert - degress: list The list of degrees to generate. Providing [1, 2, 3] for df only containing a column X, output X, X^2, X^3. NOTE: if you don't put 1 in the list, you loose the original column (i.e. X^1) Return: ---------- - df_poly: pandas dataframe the dataframe converted in the polynomial form """ InitialColumns = df.columns for col in InitialColumns: for degree in degrees: df[col + "_^" + str(degree)] = df[col] ** degree return df
true
e7613d249b8d257546cbe8d5c111ea4e33ea0530
HarakaRisasi/python_code
/python_problems_old/003_logic.py
784
4.21875
4
#initialization variable a = True b = False #get instruction AND print( 'AND Logic:') print( 'a and b = ', a and a) print( 'a and b = ', a and b) print( 'a and b = ', b and b) #get instruction OR print( '\nOR Logic:' ) print( 'a or a = ', a or a) print( 'a or b = ', a or b) print( 'b or b = ', b or b) #get instruction NOT print( '\nNOT Logic:' ) print( 'a = ', a, 'not a = ', not a) print( 'b = ', b, 'not b = ', not b) #Ternary operator #(test expression) ? if TRUE return this : if FALSE return this #if TRUE return this if (test expression) else if FASLE return this #c = a if (a < b) else b a = 3 b = 4 c = a if (a > b) else b print (c) d = a if ( a % 2 != 0) else b print (d)
false
988913916afb1b8e3e6a6dd2c2fd1b24a72d306c
HarakaRisasi/python_code
/python_learn/003_function.py
973
4.125
4
#--------------------------- def least_difference(a, b, c): diff1 = abs(a - b) diff2 = abs(b - c) diff3 = abs(a - c) return min(diff1, diff2, diff3) print(least_difference(1, 10, 100), end=" ") print(least_difference(1, 10, 10), end=" ") print(least_difference(5, 6, 7)) #>> 9 0 1 #--------------------------- #--------------------------- print(1, 2, 3, sep = ' < ') #>> 1 < 2 < 3 #--------------------------- #--------------------------- def greet(who = 'World!!!'): print('Hello,', who) greet() #>> Hello, World!!! greet(who = 'Haraka') #>> Hello, Haraka #--------------------------- #--------------------------- def mult_by_five(x): return 5 * x def call(fn, arg): return fn(arg) def squared_call(fn, arg): return fn(fn(arg)) print( call(mult_by_five, 1), #>> 5 squared_call(mult_by_five, 1) #>> 25 ) # Exercises # round def round_to_two_places(num): return round(num, 2) print(round_to_two_places(3.14159)) #>> 3.14
false
3d3f3a265d05a58cbc0113ba71178465dc8d0310
HarakaRisasi/python_code
/python_problems_old/018_return.py
1,153
4.1875
4
#_*_coding: utf-8_*_ #return - возвращает указанное значени оператору вызвавшему # инструкцию return #в данном случае, если первый аргумент меньше пяти, то функция #вернет (None), а последняя инструкция не станет исполняться. def sum( a, b ) : if a < 5: return return a + b print( 'Sum of two numbers is:', sum( 2, 43 ) ) print( 'Sum of two numbers is:', sum( 6, 3 ) ) #home work #Raw_input () обрабатывает все входные данные как строку и возвращает# тип строки. #num = raw_input() num = raw_input( 'Enter an integer: ' ) #.isdigit - метод проверяет переданное значение аргументу, является # ли оно числом. # isgit() is a method of a str class. def square(num) : if num.isdigit() : num = int(num) return num * num return( 'input number is not digit' ) print( num, 'Squared is: ', square( num ) )
false
06f3a35d039c0aeb687aabb4758a90b59c2ecd08
williamjbf/python-collections
/dicionarios/dicionario.py
268
4.21875
4
meuDicionario = {1:'William',2:'Paulo',3:'Maria',4:'Daniely'} print(meuDicionario) meuDicionario2 = dict({1:'William',2:'Paulo',3:'Maria',4:'Daniely'}) print(meuDicionario2) for chave,valor in meuDicionario.items(): print(f"A chave é {chave} e o valor {valor}")
false
cdf90e1d0796a4cb18492dfc78bacc318d9103c6
williamjbf/python-collections
/ranges/range.py
228
4.1875
4
range1 = range(5) range2 = range(2,10) range3 = range(2,10,2) print(range1) for i in range1: print(i) print(30*'-') print(range2) for i in range2: print(i) print(30*'-') print(range3) for i in range3: print(i)
false
c3bf7a6636b58585c60ca4d57ab563be71829ae0
allan918/HMM
/input.py
568
4.15625
4
ans = input("If you want to use our data, enter 'Y' or 'y', enter anything else, you will generate your own data with prompt") list = [] if not (ans == "Y" or ans == "y"): while True: val = input("Please enter 0 represents Sunny, 1 represents Rainy, 2 represents Cloudy, other to finish\n") if val == "0": list.append("Sunny") elif val == "1": list.append('Rainy') elif val == "2": list.append('Cloudy') else: break for i in list: print(i) else: print("here")
true
6f527650f82792c64b8a05c22aaa62e868833b03
Yaroslav882/Python_ITEA
/itea_python_adv/my_chat/threads.py
1,552
4.15625
4
# Базовый пример Python Threading # # Установить скрипт как исполняемый через: chmod +x threads.py import sys import threading # Класс потока в стиле Python class ThreadDemo(threading.Thread): def __init__(self, name, startNum): threading.Thread.__init__(self) # Установите любые переменные, которые вы хотите в своем конструкторе self.name = name self.startNum = startNum def run(self): print("Running thread '%s' starting at %d" % (self.name, self.startNum)) i=self.startNum while(i < (self.startNum+10)): print(self.name + ", Count " + str(i)) i=i+1 j=0 while(j<400000): j=j+1 # Чтобы выйти из нити, просто вернитесь из run() метод def main(): print("Running in main()...") print("Launching two threads...") thread1 = ThreadDemo("Thread 1", 100) thread1.start() thread2 = ThreadDemo("Thread 2", 200) thread2.start() print("Launched two threads...") all_threads=[] all_threads.append(thread1) all_threads.append(thread2) print("Waiting for all threads to finish") for one_thread in all_threads: one_thread.join() print("All threads have finished") print("Exiting main()...") if __name__ == "__main__": sys.exit(main())
false
a5ca881ceae02759c6b64ca55ff00398b4b210b5
thestrawberryqueen/python
/2_intermediate/chapter13/examples/coordinateGrid.py
1,654
4.125
4
class coordinateGrid: def __init__( self, x_start: int = 0, x_end: int = 10, y_start: int = 0, y_end: int = 10, ): """ Creates a list of coordinates similar to a coordinate grid. Each item in self.coordinates is a list representing one row in a coordinate grid. each item within that row is a point (tuple) of x, y ex: coordinateGrid(0, 1, -1, 1)'s coordinates would be [ [(0, 1), (1, 1)], [(0, 0), (1, 0)], [(0, -1), (1, -1)] ] Arguments: x_start, x_end, y_start, and y_end are all inclusive """ self.coordinates = [ [(x, y) for x in range(x_start, x_end + 1)] for y in range(y_end, y_start - 1, -1) ] def __contains__(self, item: tuple) -> bool: """ Checks to see if the provided tuple (or list) of length 2 (the tuple/list represents a point of x,y) is in self.coordinates. """ return True in [item in row for row in self.coordinates] def __len__(self) -> bool: """ In this case, we're saying that the length of the coordinateGrid is its area. Thus, we do height * width height = len(self.coordinates) and width = len(self.coordinates[0]) (or any row's length) """ return len(self.coordinates) * len(self.coordinates[0]) grid1 = coordinateGrid(-1, 1, -1, 1) grid2 = coordinateGrid(-10, 10, -10, 10) point1 = (10, 10) print(point1 in grid1) print(point1 in grid2) print(len(grid1)) print(len(grid2))
true
b6bc19adaf777771d9ee81f4572206aa7e02db33
thestrawberryqueen/python
/1_beginner/chapter6/examples/lists.py
1,159
4.53125
5
# Lists my_list = [1, 2, "oh no", 4, 5.62] # list indexing print(my_list[1]) # prints 2 print(my_list[3]) # prints 4 # list slicing print(my_list[1:3]) # prints [2, "oh no"] # manipulating lists my_list = [] # empty list # append() adds elements to the end of the list my_list.append("live") my_list.append("long") my_list.append("and") my_list.append("prosper") print(my_list) # copy() returns a copy of the list copy_of_my_list = my_list.copy() print(copy_of_my_list) # pop() removes the element at the specified index my_list.pop(2) print(my_list) # remove() removes the first item with the specified value my_list.remove("live") print(my_list) # index() returns the index of the first element # with the specified value print(my_list.index("prosper")) # insert() adds an element at the specified position my_list.insert(0, "live") print(my_list) # reverse() reverses the order of the list my_list.reverse() print(my_list) # sort() sorts the list my_list.sort() print(my_list) # clear() removes all elements from the list my_list.clear() print(my_list) # for each item in my_list for item in my_list: # print that item print(item)
true
a70e7ac44908c0ef4a1498e3581a4775d0d3bb3a
thestrawberryqueen/python
/2_intermediate/chapter13/solutions/polar_coordinates.py
769
4.375
4
""" Write a class called PolarCoordinates which will take a value called radius and angle. When we print this class, we want the coordinates in Cartesian coordinates, or we want you to print two values: x and y. (If you don't know the conversion formula, x = radius * cos(angle), y = radius * sin(angle). Use Python's built-in math library for the cosine and sine operators) """ # write your code below import math class PolarCoordinates: def __init__(self, radius, angle): self.radius = radius self.angle = angle def __str__(self): self.x = self.radius * math.cos(self.angle) self.y = self.radius * math.sin(self.angle) return "{},{}".format(self.x, self.y) group = PolarCoordinates(2, math.pi) print(str(group))
true
700dd9867d76709a81001566d12eff032d207127
thestrawberryqueen/python
/1_beginner/chapter5/solutions/add_all_the_way.py
453
4.40625
4
# Add All the Way # Take a number from the user and # add every number up from 1 to that number. # Print the result. # You can use a for or while loop. # for loop solution sum = 0 n = int(input("Please enter a number: ")) for i in range(1, n + 1): sum += i print("Sum is:", sum) # while loop solution # sum = 0 # count = 1 # n = int(input("Please enter a number: ")) # while count <= n: # sum += count # count += 1 # print("Sum is:", sum)
true
6679b44175566efd971880cd47b2dda0447ac768
thestrawberryqueen/python
/2_intermediate/chapter11/solutions/case.py
646
4.65625
5
""" Case Display the string "Apple" in the following formats: 1) normally 2) all uppercase 3) all lowercase Display the string "mRoWiE" in the same 3 formats. Ask the user to input a sentence, and display this input in the same 3 formats. Do this in AT MOST 8 lines of code. By the end of the program, 9 lines should have been displayed (3 formats for each of the 3 strings). Example of the 3 formats for one string: Apple APPLE apple """ # Define a function that prints the 3 formats. def display(str): print(str) print(str.upper()) print(str.lower()) display("Apple") display("mRoWiE") display(input("Enter a sentence: "))
true
7d42758b0b7ceaa108e771753c3f175cd31cd0d1
thestrawberryqueen/python
/3_advanced/chapter17/practice/compute_similarity.py
473
4.1875
4
# Given two sets of integers A and B (each element in these sets are # between 1 and 1000 inclusive), find the similarity of the two sets # (the sets are guaranteed to be nonempty). The similarity is a number # which is computed by dividing the size of the intersection of the # two sets by their union size. # Note: the intersection is the # of elements that both sets have in common. def compute_similarity(set1, set2): # put your code here; remove "pass" pass
true
643a93a91b41a31947820449b1f2018c93f2cd42
thestrawberryqueen/python
/1_beginner/chapter6/solutions/grades.py
680
4.28125
4
""" Grades Create a list called names and a list called grades. Ask the user to input a name, and then ask them to input the person's grade. Add the inputs to the corresponding lists. Use a for loop to ask for these inputs 5 times. Display the info as "[name]: [grade]". Example lists AFTER user input: names = ["John", "Belle", "Ria", "Steph", "Louis"] grades = [93, 85, 100, 82, 70] Example output: John: 93 Belle: 85 etc. """ names = [] grades = [] # Collect inputs. for i in range(5): names.append(input("Enter a name: ")) grades.append(input("Enter their grade: ")) # Format output correctly. for i in range(len(names)): print(names[i] + ": " + grades[i])
true
7d46246ee9ebcc0c891097bca69914fd3a1bb0a6
thestrawberryqueen/python
/3_advanced/chapter18/examples/fibonacci.py
2,254
4.59375
5
# Fibonacci # The Fibonacci sequence starts with 0 and 1. # The next number in the sequence is the sum of the previous 2 numbers. # Thus, the first 5 Fibonacci numbers are: 0, 1, 1, 2, 3. def recursive_fib(n): """ Returns the nth number in the Fibonacci sequence recursively Args: n (int): the position of the number in the Fibonacci sequence you want Returns: int: the nth number in the Fibonacci sequence For example, recursive_fib(5) will return 3 """ if n <= 0: # Base Case 1: out of bounds return None elif n == 1: # Base Case 2 return 0 elif n == 2: # Base Case 3 return 1 else: # Recursive Case return recursive_fib(n - 1) + recursive_fib(n - 2) def iterative_fib(n): """ Returns the nth number in the Fibonacci sequence iteratively Args: n (int): the position of the number in the Fibonacci sequence you want Returns: int: the nth number in the Fibonacci sequence For example, iterative_fib(5) will return 3 """ if n <= 0: return None # base case; out of bounds current = 0 next_term = 1 for i in range(n - 1): # this is equivalent to for i in range(1, n) current, next_term = next_term, current + next_term # this is just a slightly rewritten fib sequence; # instead of looking at the past 2 cases, it looks at the # current and next terms to determine the next next term return current # will be 0 if n is 1, 1 if n is 2, etc... def fib_sequence(n): """ Returns the fibonacci sequence as a list up to the nth fibonacci number Args: n (int): the position of the number in the Fibonacci sequence you want to go up to Returns: list: the nth number in the Fibonacci sequence For example, fib_sequence(5) will return [0, 1, 1, 2, 3] Adapted from: https://medium.com/@danfcorreia/fibonacci-iterative-28b042a3eec """ sequence = [0, 1] for i in range(2, n): sequence.append(sequence[i - 2] + sequence[i - 1]) return sequence print("Recursive fib:", recursive_fib(5)) print("Iterative fib:", iterative_fib(5)) print("Fib sequence:", fib_sequence(5))
true
188336a83dd78d756e9c8faa7c69c9edc12f093f
thestrawberryqueen/python
/1_beginner/chapter3/solutions/no_greater_than.py
406
4.375
4
""" Create a program that takes a POSITIVE integer as an input and checks if it is no greater than 100. Print True if it is, and False if it isn't YOU MAY NOT USE THE GREATER THAN or LESS THAN OPERATORS (>, <, >=, or <=). Find a way to do this problem only using only the == operator and any math operators you want. """ x = int(input("Enter you number here. It must be positive: ")) print(x // 100 == 0)
true
caead7971b49bafb4728a62b304b0169aa51514c
thestrawberryqueen/python
/1_beginner/chapter6/practice/integer_info.py
408
4.25
4
""" Integer Info Create a program that takes an integer as input and creates a list with the following elements: The number of digits The last digit A 'True' boolean value if the number is even, 'False' if odd Print the list. Some examples are given to help check your work. """ # Example 1: The input 123456 should print [6, 6, True] # Example 2: The input 101202303 should print [9, 3, False]
true
05aac049e69568d75d5b242076d94bbf51f0d410
thestrawberryqueen/python
/2_intermediate/chapter11/solutions/count_magical.py
1,069
4.5
4
# Write a function called count_magical # that returns the number of even numbers # in a given list. In the function, # if the number of evens is greater than # half of the length of the list, print "Magical" # Else, print "Not Magical" # # Write a function called main which tests # the count_magical function on at least # 3 different lists of integers. Use the main # function to test count_magical by calling main(). def count_magical(my_list): number_of_evens = 0 for n in my_list: if n % 2 == 0: number_of_evens += 1 if number_of_evens > len(my_list) / 2: print("Magical") else: print("Not Magical") return number_of_evens def main(): list_1 = [1, 2, 3, 4, 5, 6] # not magical, 3 evens list_2 = [0, 35, 1, 35, 2, 4] # not magical, 3 evens list_3 = [10, 20, 12, 3, -9] # magical, 3 evens print("Number of evens in list 1:", count_magical(list_1)) print("Number of evens in list 2:", count_magical(list_2)) print("Number of evens in list 3:", count_magical(list_3)) main()
true
3c693c24872fb972e8e44f911a3920188adf4028
thestrawberryqueen/python
/1_beginner/chapter3/solutions/lunch_tables.py
463
4.25
4
""" Lunch Tables Ask the user to input how many people are in the lunchroom, and how many people can sit at each table. Output the number of people that will be left without a table. """ # Get user input people = input("How many people are in the lunchroom? ") table_limit = input("How many people can sit at a table? ") # Calculate the number of outcasts (the remainder) outcasts = int(people) % int(table_limit) # Display output print("Outcasts:", outcasts)
true
c0e3e3140f01e8656d3d9b80419bf1a8744b5d72
thestrawberryqueen/python
/1_beginner/chapter2/examples/convert.py
333
4.15625
4
# Converting to Different Data Types x = "5" y = "6" sum = int(x) + int(y) # this is 11 because x and y were converted to integers print(sum) a = 5 message = "Hello!" a = str(a) # converts to string so that concatenation works print(message + " " + a) # print the type of a variable a = 5 print(type(a)) # prints <class 'int'>
true