blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
a0c345ef1bff86d36895d35a6291383a06ef8def
MayankVerma105/Python_Programs
/multiplication.py
305
4.125
4
def printTable(num, nMultiples = 10): for multiple in range(1, nMultiples + 1): product = num * multiple print(num,'*','%2d'% multiple, '=' , '%5d'% product) def main(): num = int(input('Enter the Number : ')) printTable(num) if __name__ == '__main__': main()
false
4d9a439a7e2c3eea5d6413139db67b685fb38e7a
Burrisravan/python-fundamentals.
/LIST/lists.py
1,013
4.1875
4
lst1=[1, 'sravan', 10.9] lst2 =[90,20,50,100,8,0] lst3 =[5,89,3,99,23,7] print(lst1) print(lst1[2]) print(lst1+lst2) print(lst1*5) print(max(lst2)) print(min(lst2)) print(len(lst2)) print(lst2[:]) # prints all in the list print(lst2[1:3]) print(lst2[-1]) # prints the last one for i in lst2: # looping print(i) print(lst1.remove(10.9)) # remove the element print(lst1) lst1.append('hyderabad') # ADDing to the list append print(lst1) lst1[2]=15.9 #updating data or replacing data print(lst1) del lst2[2] # delete the element in the list print(lst2) print(tuple(lst1)) # to convert list in to tuple print(lst1.clear()) # clears all the elements print(lst1.copy()) #copys all the elements print(lst3.sort()) print(lst3.reverse())
true
4ad7d619d47c08500341a4e860b95a11301f233f
enthusiasticgeek/common_coding_ideas
/python/exception.py
553
4.21875
4
#!/usr/bin/env python3 def divide_numbers(a, b): try: result = a / b print("Result:", result) except ZeroDivisionError: print("Error: Division by zero!") except TypeError: print("Error: Invalid operand type!") except Exception as e: print("An unexpected error occurred:", str(e)) # Example calls to the function divide_numbers(10, 2) # Valid division divide_numbers(10, 0) # Division by zero divide_numbers(10, "2") # Invalid operand type divide_numbers(10) # Missing second operand
true
3982d495e405bef4db0ae8a3787540f03ad38f01
mohanakrishnavh/Data-Structures-and-Algorithms-in-Python
/Searching/count_element.py
1,682
4.15625
4
from typing import List def find_min_index(A: List[int], x: int) -> int: """ Finds the max index of the element being searched :param A: Input Array :param x: Element to search in the array :return: Min Index of the element being searched """ min_index = -1 start = 0 end = len(A)-1 while start <= end: mid = start + (end-start)//2 if A[mid] == x: min_index = mid end = mid - 1 elif x < A[mid]: end = mid - 1 else: start = mid + 1 return min_index def find_max_index(A: List[int], x: int) -> int: """ Finds the max index of the element being searched :param A: Input Array :param x: Element to search in the array :return: Max Index of the element being searched """ max_index = -1 start = 0 end = len(A) - 1 while start <= end: mid = start + (end - start) // 2 if A[mid] == x: max_index = mid start = mid + 1 elif x < A[mid]: end = mid - 1 else: start = mid + 1 return max_index def count_element(A: List[int], x: int) -> int: """ Counts the number of occurrence of an element in the given sorted array :param A: Input Array :param x: Element to search in the array :return: Count of the element being searched Time Complexity: O(log n) """ min_index = find_min_index(A, x) max_index = find_max_index(A, x) return (max_index-min_index)+1 A = [1, 1, 3, 3, 5, 5, 5, 5, 9, 11] x = int(input("Enter the number:")) result = count_element(A, x) print("Count of the number: ", result)
true
e81faee5b80e46b9efa87794c8293d22638a20b1
mohanakrishnavh/Data-Structures-and-Algorithms-in-Python
/Sorting/insertion_sort.py
427
4.125
4
''' Insertion Sort Time Complexity : O(n^2) Best Case : O(n) Average Case : O(n^2) Worst Case : O(n^2) Space Complexity : O(1) ''' def insertion_sort(A): n = len(A) for i in range(1, n): value = A[i] hole = i while hole > 0 and A[hole - 1] > value: A[hole] = A[hole - 1] hole -= 1 A[hole] = value return A A = [2, 7, 4, 1, 5, 3] print(insertion_sort(A))
false
bbe4ea6780e4b3aa8bb98bd82fb38a9ea0bc678a
mohanakrishnavh/Data-Structures-and-Algorithms-in-Python
/datastructures/stack/Stack.py
1,282
4.15625
4
class Stack: def __init__(self): self.stack = [] self.top = -1 def push(self, x): ''' Push an element x into the stack :param x: input element ''' self.top += 1 self.stack.append(x) def pop(self): ''' Removes the topmost element from the stack ''' if self.top > -1: self.top -= 1 self.stack.pop() else: print("stack is empty.") def peek(self): ''' Returns the topmost element from the stack ''' if self.top > -1: return self.stack[self.top] else: print("stack is empty.") def is_empty(self): ''' Checks if the stack is empty :return: returns True if stack is empty, else False ''' return self.top == -1 def get_size(self): ''' Returns the size of the stack ''' return self.top+1 def main(): s = Stack() s.push(2) s.push(10) print(s.get_size()) print(s.peek()) s.pop() print(s.is_empty()) s.push(7) s.push(5) print(s.peek()) s.pop() s.pop() s.pop() s.pop() print(s.peek()) if __name__ == '__main__': main()
true
e8bac117e889770c1bae6fc994a73ea401096af0
Stephan-kashkarov/Number-classifier-NN
/neuron.py
1,393
4.28125
4
import numpy as np class Neuron: """ Neuron Initializer This method initalises an instance of a neuron Each neuron has the following internal varaibles Attributes: -> Shape | This keeps track of the size of the inputs and weights -> Activ | This is the function used to cap the range of the input between 1 and zero -> Weights | This is a 2D array containing the weights of the system -> Activation | This is the output of this neuron Kwargs: -> shape | The shape of the input row -> weights | The weights of system, if none provied will be random """ def __init__(self, **kwargs): self.shape = kwargs.get('shape', (3,)) self.prev_shape = kwargs.get('prev_shape', (3,)) weights = kwargs.get('weights') if weights == None: self.weights = np.array(list(np.random.rand(*self.prev_shape))) else: self.weights = weights self.activation = 0 def execute(self, inputs): """ Execute method This method takes a numpy 2D array as an input and returns a single value in the form of an activation. Arguments: -> inputs | The inputs given to the neuron network (Ideally of shape of self.shape) Returns: -> activation | The output for the neuron """ self.activation = np.sum(np.multiply(self.weights, inputs)) return self.activation
true
2be6c1dff2a08f4b38119d1094ab5b8b589ad699
Nimrod-Galor/selfpy
/823.py
615
4.4375
4
def mult_tuple(tuple1, tuple2): """ return all possible pair combination from two tuples :tuple1 tuple of int :type tuple :tuple2 tuple of int :type tuple :return a tuple contain all possible pair combination from two tuples :rtype tuple """ comb = [] for ia in tuple1: for ib in tuple2: comb.append((ia, ib)) comb.append((ib, ia)) return tuple(comb) first_tuple = (1, 2) second_tuple = (4, 5) print(mult_tuple(first_tuple, second_tuple)) first_tuple = (1, 2, 3) second_tuple = (4, 5, 6) print(mult_tuple(first_tuple, second_tuple))
true
0d3683efd8fc9dd8578928cda52114cc18204895
Dev-352/prg105
/chapter 10/practiec 10.1.py
1,760
4.6875
5
# Design a class that holds the following personal data: name, address, age, and phone number. # Write appropriate accessor and mutator methods (get and set). Write a program that creates three # instances of the class. One instance should hold your information and the other two should hold your friends' # or family members' information. Just add information, don't get it from the user. Print the data from each object, # make sure to format the output for clarity and ease of reading. class Person_data: def __init__(self, name, address, age, phone): self.__name = name self.__address = address self.__age = age self.__phone= phone def set_name(self, name): self.__name = name def set_address(self, address): self.__address = address def set_age(self, age): self.__age = age def set_phone(self, phone): self.__phone = phone def get_name(self): return self.__name def get_address(self): return self.__address def get_age(self): return self.__age def get_phone(self): return self.__phone def __str__(self): return 'Name: ' + self.__name + "\nAddress " + self.__address + "\nAge: " + self.__age + "\nPhone: " + \ self.__phone def main(): person1 = Person_data("Meri", "123 Disney Land, Florida", "15", "815-234-3221") person2 = Person_data("Tammy", "234 Hapsburg dr, Atlanta", "20", "224-444-4444") person3 = Person_data("Jason", "Camp Crystal lake", "71", "N/A") print(person1) print("------------------------------") print(person2) print("------------------------------") print(person3) main()
true
570f38c28c680b599d34897d1988f74196f61225
Dev-352/prg105
/chapter 9/practice 9.2.py
1,161
4.15625
4
# Create a dictionary based on the language of your choice with the numbers from 1-10 paired with the numbers # from 1-10 in English. Create a quiz based on this dictionary. Display the number in a foreign language and # ask for the number in English. Score the test and give the user a letter grade. def main(): count = 0 print("Enter the number in English which corresponds to the number in French") num = {"un": "one", "deux": "two", 'trois': 'three', 'quatre': "four", 'cinq': 'five', 'six': 'six', 'sept': 'seven', 'huit': 'eight', 'neuf': 'nine', 'dix': "ten"} for numbers in num: user = input("What is the equivalent of " + numbers + ": ") user = user.lower() if num[numbers] == user: print("Correct\n") count += 1 else: print("Incorrect.The answer was " + num[numbers] + "\n") print("You got " + str(count)) if count == 10 or count == 9: print("A") elif count == 8: print("B") elif count == 7: print("C") elif count == 6: print("D") else: print("F") main()
true
da5322901540169f5a33d233ab94b973430be4a7
Dev-352/prg105
/sales.py
787
4.5
4
# You need to create a program that will have the user enter in the total sales amount for the day at a coffee shop. # The program should ask the user for the total amount of sales and include the day in the request. # At the end of data entry, tell the user the total sales for the week, and the average sales per day. # You must create a list of the days of the week for the user to step through, see the example output. total = 0 for day in ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"): sales = float(input("What were the total sales for " + day + ":")) total += sales print("The total amount of sales for the week was: " + format(total, ',.2f')) print("The average amount of sales per day was: " + format((total / 7), ',.2f'))
true
aac34c61da8a66e9539c44318db89fa1ddf1a5fd
fatima-cyber/madlibs
/madlibs.py
939
4.46875
4
# MadLibs - String Concatenation #suppose we want to create a string that says "subscribe to ____" youtuber = "Fatima" #some string variable # a few ways to do this # print("subscribe to " + youtuber) # print("subscribe to {}".format(youtuber)) # print(f"subscribe to {youtuber}") # using this adj = input("Adjective: ") verb1 = input("Verb: ") verb2 = input("Verb: ") famous_person = input("Famous person: ") verb3 = input("verb: ") verb4 = input("verb: ") verb5 = input("verb: ") verb6 = input("verb: ") madlib = f"Computer programming is so {adj}! It makes me so excited all the time because \ I love to {verb1}. Stay hydrated and {verb2} like you are {famous_person}! My favorite thing \ to do in the morning is {verb3} and {verb4}. I want youto know that you are capable of \ {verb5} if you put your mind to it. The {verb6} about trying is get to find your strengths \ and weakness and learn how to grow. print(madlib)
true
c39bd54af1b2b184392b69d7712f7f06d77ed3df
Sampatankar/Udemy-Python
/280521.py
708
4.3125
4
# Odd or Even number checker: number = int(input("Which number do you want to check? ")) if number % 2 != 0: print("This is an odd number.") else: print("This is an even number.") # Enhanced BMI Calculator height = float(input("enter your height in m: ")) weight = float(input("enter your weight in kg: ")) bmi = weight / (height ** 2) b = round(bmi, 1) if b < 18.5: print(f"Your BMI is {b}, you are underweight.") elif b < 25: print(f"Your BMI is {b}, you are normal weight.") elif b < 30: print(f"Your BMI is {b}, you are slightly overweight.") elif b < 35: print(f"Your BMI is {b}, you are obese.") else: print(f"Your BMI is {b}, you are clinically obese.")
true
d5df4247029297677c33b8f8172b4e62d7369093
BillMaZengou/raytracing-in-python
/01_point_in_3d_space/mathTools.py
769
4.1875
4
def sqrt(x): """ Sqrt from the Babylonian method for finding square roots. 1. Guess any positive number x0. [Here I used S/2] 2. Apply the formula x1 = (x0 + S / x0) / 2. The number x1 is a better approximation to sqrt(S). 3. Apply the formula until the process converges. [Here I used 1x10^(-8)] """ S = x x_old = S x_new = S / 2 while abs(x_new-x_old) > 1e-8: x_old = x_new x_new = (x_old + S/x_old) / 2 return x_new def main(): import numpy as np numpyAnswer = np.sqrt(15) myAnswer = sqrt(15) print("Square root of 15 from numpy is {}, from scratch is {}".format(numpyAnswer, myAnswer)) print("Difference is {}".format((numpyAnswer - myAnswer))) if __name__ == '__main__': main()
true
3309ec514d0ae1ad9f84aab3f7f455836b91f5aa
ivaben/Intro-Python-I
/src/13_file_io.py
998
4.28125
4
""" Python makes performing file I/O simple. Take a look at how to read and write to files here: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files """ # Open up the "foo.txt" file (which already exists) for reading # Print all the contents of the file, then close the file # Note: pay close attention to your current directory when trying to open "foo.txt" filename = open('foo.txt', mode='r') for x in filename: print(x) filename.close() # with filename = 'foo.txt' with open(filename) as f_obj: contents = f_obj.read() print(contents) # Open up a file called "bar.txt" (which doesn't exist yet) for # writing. Write three lines of arbitrary content to that file, # then close the file. Open up "bar.txt" and inspect it to make # sure that it contains what you expect it to contain bar = open(file = "bar.txt", mode = 'w') bar.write('Mary had a little lamb') bar.write('Four score and seven years ago') bar.write('Run Forest run') bar.close()
true
5cd8bf7993bd2c5c4e297489e12ff22170f21297
WillLuong97/Back-Tracking
/countSortedVowelString.py
2,449
4.125
4
#Leetcode 1641. Count Sorted Vowel Strings ''' Problem statement: Given an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted. A string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alphabet. Example 1: Input: n = 1 Output: 5 Explanation: The 5 sorted strings that consist of vowels only are ["a","e","i","o","u"]. Example 2: Input: n = 2 Output: 15 Explanation: The 15 sorted strings that consist of vowels only are ["aa","ae","ai","ao","au","ee","ei","eo","eu","ii","io","iu","oo","ou","uu"]. Note that "ea" is not a valid string since 'e' comes after 'a' in the alphabet. Example 3: Input: n = 33 Output: 66045 Constraints: 1 <= n <= 50 ''' #Approach: math: ''' The solution is purely based on observations when building the desired strings : String of length n is constructed based on string of length n-1. So we can think of what are available options based on the character at position n-1th. There are 5 options after a (i.e (a, e, i, o, u). There are 4 options after e (i.e (e, i, o, u). There are 3 options after i (i.e (i, o, u). There are 2 options after o (i.e (o, u). There is 1 option after u (i.e (u). This solution beats 95.95% but I believe it's quite optimal unless there is a way to improve my python3 code. So, any comments are much appreciated. ''' def countVowelStrings(n): #base case: if not n: return None if n == 1: return 5 #available options to build a vowel strings count = [5,4,3,2,1] while n > 2: count = [sum(count[i:]) for i in range(5)] n-=1 return sum(count) #DP approach: through recursion def countVowelStrings_DP(n): #base case: if not n: return 1 #helper method to recursively counting the vowel string def recursion(k, n): if k == 1: return 1 if n == 1: return k result = 0 while k >= 1: result += recursion(k, n-1) k-=1 return result return recursion(5, n) #Main function to run the program: def main(): print("TESTING COUNT SORTED VOWEL STRING...") n_1 = 1 n_2 = 2 n_3 = 33 print(countVowelStrings(n_1)) print(countVowelStrings(n_2)) print(countVowelStrings(n_3)) print(countVowelStrings_DP(n_3)) print("END OF TESTING...") main()
true
911c4f8d06289dcbc836627b624afeba3ee01d59
nasimulhasan/3D-Tank-Implementation-with-Pygame
/frange.py
831
4.28125
4
def frange(x, y, jump=1.0): ''' Range for floats. Parameters: x: range starting value, will be included. y: range ending value, will be excluded jump: the step value. Only positive steps are supported. Return: a generator that yields floats Usage: >>> list(frange(0, 1, 0.2)) [0.0, 0.2, 0.4, 0.6000000000000001, 0.8] >>> list(frange(1, 0, 0.2)) [1.0] >>> list(frange(0.0, 0.05, 0.1)) [0.0] >>> list(frange(0.0, 0.15, 0.1)) [0.0, 0.1] ''' i = 0.0 x = float(x) # Prevent yielding integers. y = float(y) # Comparison converts y to float every time otherwise. x0 = x epsilon = jump / 2.0 yield x # yield always first value while x + epsilon < y: i += 1.0 x = x0 + i * jump yield x
true
ef113f468766d0b48cb18482b59871dbbba7f210
nguyenhuuthinhvnpl/met-cs-521-python
/instructor_code_hw_5/hw_5_5_1.py
670
4.125
4
def vc_cntr(sentence): """ Return count of vowels and consonants from input sentence :param sentence: :return: """ vowels = "AEIOU" sentence = sentence.upper() v_total = len([v for v in sentence if v in vowels]) c_total = len([c for c in sentence if c.isalpha() and c not in vowels]) return {'total_vowels': v_total, 'total_consonants': c_total} if __name__ == "__main__": user_input = input("Enter an English sentence: ") cnt_dict = vc_cntr(user_input) print("# vowels in sentence: {}".format(cnt_dict['total_vowels'])) print("# consonants in sentence: {}".format(cnt_dict['total_consonants']))
false
6c5155cd03a0219f37566a46e68b629720962910
RenanBertolotti/Python
/Curso Udemy/Modulo 02 - Pyhton Basico/Aula 04 - Dados Primitivos/aula04.py
636
4.15625
4
""" Tipos de dados String - str == Texto 'assim' ou "assim" Inteiro - int == 1, 2, 3, 4, 5 Float - real/flutuante = 1.12313, 2.465456, 3.465465 Bool - Booleane/logico = true or false """ print("Luiz", type("Luiz")) print(10, type(10)) print(10.5, type(10.5)) print(True, type(True)) print("Renan"=="Renan", type("Renan"=="Renan")) print("Renan", type("Renan"), bool("Renan")) print("10", type("10"), type(int("10"))) nome = "443.06347850" print(nome, float(nome)) ############################################################## print("Renan", type("Renan")) print(22, type(22)) print(1.75, type(1.75)) print(22 >= 18, type(22 >=18))
false
e1a422898de6efb51dd0081bb6b0c1fc798cd957
RenanBertolotti/Python
/Curso Udemy/Modulo 03 - Python Intermediário (Programação Procedural)/Aula 27 - Try, Except - Tratando Exceçoes em Python/Aula27.py
1,226
4.125
4
""" Try / Except em python #Try/Except basico try: a = 1/0 except NameError as erro: print("erro", erro) except (IndexError, KeyError) as erro: print("erro de indice", erro) except Exception as erro: print("ocorreu um erro inesperado") else: print("Seu codigo foi afetuado com sucesso") finally: print("Eu aconteço independende se der erro ou nao") print("bora continuar") ################################################################################### #Levantando exceçoes em Pyhton def divide(n1,n2): if n2 == 0 : raise ValueError("n2 noa pode ser 0.") return n1 / n2 try: print(divide(2,0)) except ZeroDivisionError as erro: print("erro", erro) """ ####################################################################################### #Try/except como condicional def convertenumero(valor): try: valor = int(valor) return valor except ValueError: try: valor = float(valor) return valor except ValueError: pass while(True): numero = convertenumero(input("Digite um numero: ")) if numero is not None: print(numero * 2) else: print("isso nao e numero.")
false
e3b1316f30318aefc72598f57ecaeaac86ca2409
NeniscaMaria/AI
/1.RandomVariables/lab1TaskC/main.py
2,428
4.21875
4
# -*- coding: utf-8 -*- """ Created on Sat Feb 29 15:54:46 2020 @author: nenis """ from sudoku import Sudoku from geometricForms import GeometricForms from cryptoarithmeticGame import CryptoarithmeticGame def showMenu(): print("\nPlease choose one from below:") print("0.Exit") print("1.Sudoku") print("2.Cryptarithmetic game") print("3.Geometric forms") def sudoku(): print("Welcome to Sudoku!") finished =False while not finished: try: trials = int(input("Please insert the number of trials.")) if trials==0: print("Please insert a non-negative number of trials.") else: size = int(input("Please enter the size of the board: ")) if size == 0: print("Please choose a non-negative size.") else: game = Sudoku(size,trials) game.start() finished = True except ValueError: print("Please insert a number.") def cryptoarithmeticGame(): print("Welcome to the Cryptoarithmetic Game!") try: trials = int(input("Please enter the number of trials:" )) if trials == 0: print("Please insert a non-negative number of trials.") else: game = CryptoarithmeticGame(trials) game.start() except ValueError: print("Please input a non-negative number.") def geometricForms(): print("Welcome to Geometric Forms!") try: trials = int(input("Please enter the number of trials:" )) if trials == 0: print("Please insert a non-negative number of trials.") else: game = GeometricForms(trials) game.start() except ValueError: print("Please input a non-negative number.") def main(): finished = False while not finished: showMenu() try: choice=int(input("Your choice: ")) if choice==0: finished=True elif choice==1: sudoku() elif choice==2: cryptoarithmeticGame() elif choice==3: geometricForms() else: print("Please choose a valid option.") except ValueError: print("The choice must be a number: 0, 1, 2 or 3") main()
true
cfd40b3aac0c66750c048a7c85dc3cfcdbd79e31
TsabarM/MIT_CS_Python
/analyze_song_lyrics.py
2,085
4.6875
5
# Analyze song lyrics - example for use python dictionaries ''' In this example you can see how to create a frequency dictionary mapping str:int. Find a word that occures the most and how many times. Find the words that occur at least X times. ''' def lyrics_frequencies(lyrics): ''' Creates a Dictionary with the lyrics words and the frequency of each word. Arguments: lyrics - text. ''' myDict = {} for word in str(lyrics).split(): if word in myDict: myDict[word] +=1 else: myDict[word] = 1 return myDict # Find the most common word - return a tuple (word, frequency). # In case that there is more than one word returns a list. def most_common_word(freqs): ''' Find the most common word - return a tuple (word, frequency). In case that there is more than one word returns a list. Arguments: freqs - a dictionary with words and frequncy of each word in the text. ''' values = freqs.values() best = max(values) words = [] for k in freqs: if freqs[k] == best: words.append(k) return (words, best) def words_often(freqs, minTimes): ''' Find the words that occur at least X times. Each itereation deletes the most frequent words as long as the most frequent words frequency is greater than the minTimes of occurences that the user gives. Arguments: freqs - a dictionary with words and frequncy of each word in the text. minTimes - {int} - set by the user. The minimum number of occurences for each word. ''' result = [] done = False while done == False: temp = most_common_word(freqs) if temp[1] >= minTimes: result.append(temp) for w in temp[0]: del(freqs[w]) else: done = True return result if __name__ == "__main__": with open(r'Muse_Invincible.txt', 'r') as f: Invincible = f.read() Invincible = lyrics_frequencies(Invincible) print(words_often(Invincible, 4))
true
0e61d1baa0e9ae984dd83cf27ac96d4c7e6c509f
JCode1986/python-data-structures-and-algorithms
/sorts/insertion_sort/insertion.py
430
4.21875
4
def insertion_sort(lst): """ Sorts list from lowest to highest using insertion sort method In - takes in a list of integers Out - returns a list of sorted integers """ for i in range(1, len(lst)): j = i - 1 temp = int((lst[i])) while j >= 0 and temp < lst[j]: lst[j + 1] = lst[j] j = j - 1 lst[j + 1] = temp return lst test_lst = [18,22,1,13,53,64] print(insertion_sort(test_lst))
true
a3154200beab4765d7c8177e01cc426ef4ec63b0
kfcole20/python_practice
/math_practice.py
1,021
4.625
5
# Assignment: Multiples, Sum, Average # This assignment has several parts. All of your code should be in one file that is well commented to indicate what each block of code is doing and which problem you are solving. Don't forget to test your code as you go! # Multiples # Part I - Write code that prints all the odd numbers from 1 to 1000. Use the for loop and don't use a list to do this exercise. for x in range(1, 1000): # below checks if current index is odd or not if x%2 != 0: print(x) # Part II - Create another program that prints all the multiples of 5 from 5 to 1,000,000. for x in range(5, 1000000): if x%5 == 0: print(x) # Sum List # Create a program that prints the sum of all the values in the list: a = [1, 2, 5, 10, 255, 3] a = [1, 2, 5, 10, 255, 3] sum=0 for x in a: sum+=x print(sum) # Average List # Create a program that prints the average of the values in the list: a = [1, 2, 5, 10, 255, 3] b = [1, 2, 5, 10, 255, 3] sum=0 for x in b: sum+=x print(sum/len(b))
true
404c5cd7f34836b70d2eb951764f4381d65f8eb8
Edre2/StarkeVerben
/main.py
2,763
4.15625
4
import csv import random as rando # The prompt the user gets when he has to answer PROMPT = "> " # The numbers of forms of the verbs in franch and german NUMBER_OF_FORMS_DE = 5 NUMBER_OF_FORMS_FR = 1 # Gets the verbs from verbs.csv def get_defs(): verbs = [] with open('verbs.csv', 'r') as verbs_file: reader = csv.reader(verbs_file) for row in reader: verbs.append(row) return verbs # returns a a tuple of the numbers from 1 to n in a random order def rand(n :int): # Creating a tuplu with all the integers from 1 to n : n_tabl = [] for i in range(1, n + 1): n_tabl.append(i) # creating the tuple who will store the final numbers randn = [] # n times, we pick a random number in the list and add it to the final list, then, in order to not have duplicates, we remove it from the original tuple for i in range(n): # Make sure there's no mistqke because iff len(n_tabl) = 1, we do % 0 wich is impossible if len(n_tabl) > 1: num = int(rando.random() * 1000 ) % (len(n_tabl) - 1) else: num = 0 randn.append(n_tabl[num]) n_tabl.pop(num) # we return the final tuple return randn def ask_n(lang :bool, n :int, verbs): # to know wether the given answer is correct correct = False # if lang = True, we test from DE to FR else, we test from FR to DE, in both cases, we get what we have to print and what the user has to answer DE_FORMS = verbs[n][0] for i in range(1, NUMBER_OF_FORMS_DE): DE_FORMS += ", " + verbs[n][i] FR_FORMS = verbs[n][NUMBER_OF_FORMS_DE] for i in range(NUMBER_OF_FORMS_DE + 1, NUMBER_OF_FORMS_DE + NUMBER_OF_FORMS_FR): FR_FORMS += ", " + verbs[n][i] if lang: to_print = DE_FORMS ans = FR_FORMS else: to_print = FR_FORMS ans = DE_FORMS # Printing what's to print & getting the user's answer print(to_print) rep = input(PROMPT) # testing if the user's answer is correct and returning True if rep == ans: print("Bien") return True # If it isn't, making him type it to remeber and returning False else: while rep != ans: print("Recopiez ", ans, " : ") rep = input(PROMPT) return False def learn(): # Letting the user to choos wich way he wants to learne print("Que voulez-vous faire ?\n1 - Apprendre FR => DE\n2 - Apprendre DE => FR") choice = int(input(PROMPT)) if choice == 2: choice = True else: choice = False # Getting the verbs to learn verbs = get_defs() # Geeting the order to ask the questions questions_n = rand(len(verbs)) # Asking the questions for i in questions_n: ask_n(choice, i, verbs) if __name__ == '__main__': learn()
true
584c5f4001acaf49483381af86083d9453c755db
eSuminski/Python_Primer
/Primer/examples/key_word_examples/key_word_examples.py
987
4.125
4
from to_import import MyClass as z # from indicates where the code is coming from # import tells you what code is actually being brought into the module # as sets a reference to the code you are importing my_list = ["eric", "suminski"] for name in my_list: print(name) # for is used to create a loop, and in is used when you want to access elements within a list or other collection x = 0 while x < 5: print(x) x = x + 1 long_word = "thdufoewnd;wndd;" for number in range(len(long_word)): print(number) my_class = z("my imported class") print(my_class.say_my_name()) name_one = "Eric" name_two = "Sam" if name_one is name_two: print("these are the same") elif name_one is not name_two: print("these are not the same") else: print("these are not the same") if name_one is name_two: print("these are the same") elif name_one is name_two and len(name_one) <= 10: print("the second condition was met") else: print("these are not the same")
true
f294b5d241e782c77cf243666f82a043f7ae2c8b
Jitender214/Python_basic_examples
/02-Python Statements/03-while Loops, break,continue,pass.py
808
4.1875
4
# while loops will continue to execute a block of code while some condition remains true #syntax #while some_boolean_condition: #do something #else #some different x = 0 while x < 4: print(f'x value is {x}') x = x+1 else: print('x is not less than 5') x = [1,2,3] for num in x: #if we put comment after for loop indentation is expecting something afert the colon #will get error if we write pass then we dont get any error, its does nothing at all pass print('end of my script') name = 'Jithu' for letters in name: if letters == 'i': continue #continue goes to the top of the closet enclosing loop print(f'letters are: {letters}') for letters in name: if letters == 'i': break #breaks out of the current closet enclosing loop print(f'{letters}')
true
96f4c4be86ed6e56acf3864c6131dfda9f33e5c1
Jitender214/Python_basic_examples
/02-Python Statements/02-for Loops.py
956
4.375
4
# we use for loop to iterate the elements from the object #syntax: #my_iterate = [1,2,3] #for itr_name in my_iterate: #print(itr_name) mylist = [2,4,5,7,9,10] for num_list in mylist: print(num_list) for num in mylist: if num % 2 == 0: print(f'number is even: {num}') else: print(f'number is odd: {num}') mylist_sum =0 for num_list in mylist: mylist_sum = mylist_sum+num_list print(mylist_sum) mystr = 'Hello world' for letters in mystr: print(letters) my_list = [(1,2),(3,4),(5,6),(7,8)] for items in my_list: print(items) my_list1 = [(1,2,3),(4,5,6),(7,8,9)] for a,b,c in my_list1: # iterate all but we print only b,c values print(b,c) my_dict = {'k1':'value1','k2':'value2'} for dict_items in my_dict: #it will iterate only keys print(dict_items) for dict_items in my_dict.items(): # dict.items() will iterate keys & values print(dict_items) for key,value in my_dict.items(): print(value)
false
c9ffaee4d2e9fc627f2586c709ab3ee3e007f8c0
Jitender214/Python_basic_examples
/00-Python Object and Data Structure Basics/04-Lists.py
1,098
4.125
4
my_list = [1,2,3,4,5] print(my_list) my_list = ['string',100,13.5] print(my_list) print(type(my_list)) print(len(my_list))#length of list my_list = ['one','two','three','four'] print(my_list[0]) print(my_list[1:]) #slicing using index print(my_list[-2:])#reverse slicing another_list = ['five','six'] new_list = my_list+another_list #concetenation of list print(new_list) new_list[0] = 'ONE IN CAPS' #modifying the list print(new_list) print(new_list.__contains__('six')) #contains checks the element is there in list or not new_list.append('seven') #append will add new element to list print(new_list) new_list.pop() #pop remove the item from end of the list print(new_list) popped_item = new_list.pop() print(popped_item) new_list.pop(2) #removing the particular element from the list print(new_list) letters_list = ['a','e','r','k','b'] print(letters_list.sort()) #it will just sort the list doesn't return anything thats why None in result print(letters_list) num_list = [4,1,7,2,8] num_list.sort() my_sorted_list = num_list print(my_sorted_list) num_list.reverse() print(num_list)
true
8d6570ca6f135bcf1fa8caf94c374e4f2efbd4d7
longmen2019/Challenges-
/Euler_Project_Problem_4.py
736
4.125
4
# -*- coding: utf-8 -*- """ Created on Tue Jun 8 21:22:28 2021 @author: men_l""" """A palindromic number reads the same both ways. The largest plindrome made from the product of two 2-digit numbers is 9009 = 91 x 99. Find the largest palindrome made from the product of two 3-digit numbers""" def is_palindrome(i): #convert integer i into string and compare the char # look at that text string and read it backward return str(i) == "".join(reversed(str(i))) max_p = 0 for i in range(100, 1000): #three digit numbers for j in range(i, 1000): #looping through the number and adding 1 each time p = i * j if is_palindrome(p) and p > max_p: max_p = p print(max_p)
true
8eff7d0e679b2c30ac2f704e9480ff346dd0883f
Lomilpda/Lab_Python
/first_lab/1-21.py
783
4.21875
4
""" 21. Напишіть програму, яка створить стрічку в якій будуть записані другі символи всіх слів з стрічки silly. """ silly = "newly formed bland ideas are inexpressible in an infuriating way" silly = silly.split() # создаем из строки список, разделяя по пробелу new_str = '' for word in silly: # перебор всех слов в списке if len(word) >= 2: # проверяем что бы в слове было хотя бы 2 символа new_str = new_str + word[1:2] # перезаписываем строку добвляя второй символ в списке else: pass # необязательно print(new_str)
false
608a20a4d01b96b04db2f8cdccea6f9a73e078ad
rockchar/OOP_PYTHON
/PythonRegularExpressions.py
2,146
4.5625
5
#here we will discuss the regular expresssions in python #import the regular expression module import re pattern = "phone" text = "the agents phone number is 400-500-600" print(pattern in text) #now lets search the pattern using regular expressions print(re.search(pattern,text)) #lets assign a match object match = re.search(pattern,text) #now we can use the inbuilt functions in the match object like span,start(start of index),end(end of index) print(match.span()) print(match.start()) print(match.end()) #NOTE: Match ends at the first match. For multiple matches we need #match all #now lets check multiple matches text = "My phone once and my phone twice " matches = re.findall(pattern,text) print(matches) print(len(matches)) #we can also get the iterator for getting more detailed information #so for that we have a for loop for match in re.finditer(pattern,text): print(match) print(match.span()) print(match.group())#actual text of the pattern #************************************** Regular expressions for general patterns ************************************** ''' Problem statement : a phone number is of the format 555-555-5555 Lets write a regular expression to parse phone numbers in a text REMEMBER THE FOLLOWING TABLE FOR REGULAR EXPRESSIONS Character Description Example Pattern Code Example Match \d A digit file_\d\d file_25 \w Alphanumeric \w-\w\w\w a-123, b-12_3, b-1_23 etc. \s whitespace \w\s\w\s\w a b c , 1 2 3 , _ _ _ etc \D A non digit \D\D\D ABC, abc etc \W a non alphanum \W\W\W\W\W **#>*,*()#& \S A non-whitespce \S\S\S\S yoyo ''' text = "Phone number home is 111-222-3344 and office is 222-333-4455" #now we create a regular expression for the same thing pattern=r"\d\d\d-\d\d\d-\d\d\d\d" matches=re.findall(pattern,text) print(len(matches)) for match in re.finditer(pattern,text): print (match.group()) print (match.span())
true
01c3d559c8a51349938c70400e6b996d417861d6
rockchar/OOP_PYTHON
/ClassInheritance.py
637
4.40625
4
''' here we will discuss class inheritance ''' class Animal(): def __init__(self,type,name): print("animal created") self.type=type self.name=name def who_am_i(self): print("I am an animal") def eat(self): print("I am an animal eating") class Dog(Animal): def __init__(self): Animal.__init__(self,type="Domestic",name="dog") print("Dog Created") #overriding the class method def eat(self): print("I am a Dog eating food") def bark(self): print("woof") dog = Dog() print(dog.name) print(dog.type) dog.eat() dog.bark() dog.who_am_i()
false
df1dad41db36bfa1940c8a43d6a278b8e4a30b7f
kwmoy/py-portfolio
/pre_2022/sort_array.py
748
4.40625
4
def sort_array(arr): """This function manually sorts an input array from ascending to descending order.""" sorted_arr = [] # Start off our list sorted_arr.append(arr.pop()) print(sorted_arr) for number in arr: # With input arr, we compare it to each number currently in the list. for i in range(len(sorted_arr)): if number < sorted_arr[i]: if i==0: # based on conditions, we add it to the list. sorted_arr = [number] + sorted_arr break else: sorted_arr = sorted_arr[0:i]+[number]+sorted_arr[i:] break elif number >= sorted_arr[i] and i==(len(sorted_arr)-1): sorted_arr = sorted_arr + [number] break return sorted_arr
true
d1933edbf3ef92526b5c2ba35c36e6bbf8e012b7
madsaken/forritunh19
/move.py
1,595
4.34375
4
Left = 1 Right = 10 def moverFunction(x): #This function makes a new board. newLocation = x newX_left = newLocation-Left newX_right = Right-newLocation newBoard = "x"*newX_left + "o" + "x"*newX_right print(newBoard) ans = 'l' placement = int(input("Input a position between 1 and 10: ")) x_right = Right-placement #Math to determine where to place the 'o' x_left = placement-Left # ---||--- board = "x"*x_left + "o" + "x"*x_right #Construction of the board. print(board) print("l - for moving left") print("r - for moving right") print("Any other letter for quitting") while ans == 'l' or ans == 'r': ans = input("Input your choice: ") if ans == 'l': #Moves the 'o' one place to the left if the user entered 'l' if placement != 1: #If the 'o' is on the far left, it won't change the placement placement = placement-1 #and will call on 'moverFunction' to print the board. moverFunction(placement) else: moverFunction(placement) elif ans == 'r': #This elif does the same as the one above it except it handles the if placement != 10: #right movement. placement = placement+1 moverFunction(placement) else: moverFunction(placement) else: moverFunction(placement) #When the user enters anything other than 'l' or 'r' the current board #will print and the session will end.
true
04b90cc05f322dd3ef3527877f24d64d196ebced
madsaken/forritunh19
/int_seq.py
910
4.4375
4
#Variables that will store data from the user. count = 0 summary = 0 even = 0 odd = 0 largest = 0 current = 1 #Note that 'current' must start with the value 1 otherwise the loop will never start. #A loop that will end when the user types in either 0 or less than zero. while current > 0: current = int(input('Enter an integer: ')) #The listener for 0 or less if current <= 0: break #If count is 0, the end result will not display. count += 1 #Even or odd numbers counter if current % 2 == 0: even += 1 else: odd += 1 #Listener for the largest number if current > largest: largest = current #Sum of all numbers summary += current print('Cumulative total: ', summary) #End result if count > 0: print('Largest number: ', largest) print('Count of even numbers: ', even) print('Count of odd numbers: ', odd)
true
0564c1eda7c4e05af33f529322b5f51dec67cb0f
rembold-cs151-master/Lab_SetSieve
/Lab20.py
1,415
4.1875
4
""" Investigating the number of words in the english language that can be typed using only a subset of modern keyboard layouts. """ from english import ENGLISH_WORDS import time QWERTY_TOP = "qwertyuiop" QWERTY_HOME = "asdfghjkl" QWERTY_BOT = "zxcvbmn" DVORAK_TOP = "pyfgcrl" DVORAK_HOME = "aoeuidhtns" DVORAK_BOT = "qjkxbmwvz" PREDICTED_PERCENTAGE = 0 # <- Change this to your predicted % of english words using top 2 rows of QWERTY PREDICTED_SPEED_WINNER = "" # <- Change this to your predicted speed winner (loop or set?) def loop_word_check(word, string): """ Predicate function to determine if all letters in word are also in string using a loop. """ def set_word_check(word, string): """ Predicate function to determine if all letters in a word are also in a stirng using sets. """ def calc_percentage(string, function): """ Counts the number of words in the english language with length > 2 which have letters in string using the desired function. Should return a percentage of the number of english words. """ if __name__ == '__main__': print(loop_word_check("sad", QWERTY_HOME)) print(loop_word_check("flag", QWERTY_HOME)) # print(set_word_check("sad", QWERTY_HOME)) # print(set_word_check("flag", QWERTY_HOME)) # print(calc_percentage(QWERTY_HOME, loop_word_check)) # print(calc_percentage(DVORAK_HOME, set_word_check))
true
cb47d28fd0ef6dcedf87dd10543bb4906cd6acad
PascalUlor/code-challenges
/python/insertion-sort.py
930
4.21875
4
""" mark first element as sorted loop through unsorted array from index 1 to len(array) 'extract' the element X at index i as currentValue set j = i - 1 (which is the last Sorted Index) while index of sorted array j >= 0 and element of sorted array arr[j] > currentValue move sorted element to the right by 1 decrement last Sorted Index j by 1 else break loop and insert currentValue at arr[j + 1] in sorted array """ def insertionSort(arr): for i in range(1, len(arr)): currentVal = arr[i] # 'extract' the element X at index i as currentValue j = i - 1 # set j = i - 1 (which is the last Sorted Index) while j >= 0 and arr[j] > currentVal: arr[j+1] = arr[j] j -= 1 # decrement last Sorted Index j by 1 arr[j+1] = currentVal # insert currentValue at arr[j + 1] in sorted array print(arr) return arr insertionSort([2,1,9,76,4])
true
072a24baab732c2ad8cf526ad0432f958ab221ad
joshua9889/ENR120
/09.11.17/tempConv.py
209
4.21875
4
# A Celsius to Fahrenheit. conver print "Convert Celsius to Fahrenheit." degreeC = input("Please input celsius: ") degreeF = degreeC*9./5. +32 # Calculate Fahrenheit. print 'Fahrenheit value: ' + str(degreeF)
true
331390dde109a4b9779b31522e4adcb520b908a2
ticotheps/practice_problems
/code_signal/arcade/smooth_sailing/common_character_count/common_character_count.py
950
4.21875
4
""" ****** UNDERSTAND Phase ****** Given two strings, find the number of common characters between them. - Example: - Inputs: "aabcc", "adcaa" (2; string data type; "s1" & "s2") - Outputs: 3 (1; integer data type; "num_common_chars") """ def commonCharacterCount(s1, s2): s1_dict = {} s1_list = [x for x in s1] for i in s1_list: if i not in s1_dict: s1_dict[i] = 1 else: s1_dict[i] += 1 s2_dict = {} s2_list = [y for y in s2] for j in s2_list: if j not in s2_dict: s2_dict[j] = 1 else: s2_dict[j] += 1 count = 0 diff = 0 for k in s1_dict: if k in s2_dict: if s1_dict[k] <= s2_dict[k]: count += s1_dict[k] else: count += s2_dict[k] return count print(commonCharacterCount("aabcc", "adcaa")) # 3 print(commonCharacterCount("zzzz", "zzzzzzz")) # 4
false
cde036f6381893e9cd8cb5dde13155aa92194870
ticotheps/practice_problems
/edabit/medium/shared_letters/shared_letters.py
2,306
4.34375
4
""" LETTERS SHARED BETWEEN TWO WORDS Create a function that returns the number of characters shared between two words. Examples: - get_shared_letters('apple', 'meaty') -> 2 - get_shared_letters('fan', 'forsook') -> 1 - get_shared_letters('spout', 'shout') -> 4 """ """ PHASE I - UNDERSTAND THE PROBLEM Objective: - Create an algorithm that takes in two inputs, 'str_1' and 'str_2', and returns a single output, 'num_of_shared_letters'. Expected Inputs & Outputs: - Inputs: - Expected Number: 2 - Expected Data Types: string, string - Expected Var Names: 'str_1', 'str_2' - Outputs: - Expected Number: 1 - Expected Data Types: integer - Expected Var Names: 'num_of_shared_letters' Constraints: - Can either of the inputs be empty strings? - No. - Can the strings include non-alphanumeric characters? - No. They must be letters. """ # PHASE II - DEVISE A PLAN # PHASE III - EXECUTE THE PLAN # Create a function that takes in two string inputs def get_shared_letters(str_1, str_2): # Declare a var that will represent the output and initialize it with 0 num_of_shared_letters = 0 # Declare a dictionary that will store key:value pairs where the keys are # distinct letters from str_1 and the values are the numbers of # occurrences of that letter in str_1. str_1_dict = {} # Use a 'for' loop to iterate through the first input string for letter in str_1: # Check to see if each letter from str_1 exists in str_1_dict if letter in str_1_dict: str_1_dict[letter] += 1 # If it doesn't already exist, add the letter as a new entry else: str_1_dict[letter] = 1 # Use a 'for' loop to iterate through the second input string for letter in str_2: # Check to see if each letter from str_2 exists in str_1_dict # # If it does exist, add 1 to the value of 'num_of_shared_letters' if letter in str_1_dict: num_of_shared_letters += 1 return num_of_shared_letters """ PHASE IV - REFLECT/REFACTOR Asymptotic Analysis: - Time Complexity: - O(n) -> 'linear' - Space Complexity: - O(n) -> 'linear' """
true
19dedc6f1b9082fda0afe546aa7dbd1cab0ba384
ticotheps/practice_problems
/edabit/medium/a_circle_two_squares/a_circle_two_squares.py
1,732
4.375
4
""" A CIRCLE AND TWO SQUARES Imagine a circle and two squares: a smaller and a bigger one. For the smaller one, the circle is a circumcircle and for the bigger one, an incircle. Objective: - Create a function that takes in an integer (radius of the circle) and returns the square area of the square inside the circle.add() Examples: - find_area_of_inner_square(5) -> 50 - find_area_of_inner_square(6) -> 72 - find_area_of_inner_square(7) -> 98 Notes: - Use only positive integer parameters. """ """ UNDERSTAND PHASE Defining Terms: - "circumcircle": a circle that passes through each of the smaller square's four corners. - "incircle": a circle that passes through each of the larger's squares's four sides. Expected Inputs/Outputs: - Inputs: - Number: 1 - Data Type: integer - Variable Name: 'radius_of_circle' - Outputs: - Number: 1 - Data Type: integer - Variable Name: 'area_of_inner_square' Constraints: - Can the input be negative? - No. - Can the input be a floating point number? - No. - Can the input be empty? - No. """ # PLAN PHASE + EXECUTE PHASE import math def find_area_of_inner_square(radius_of_circle): side_of_outer_square = radius_of_circle * 2 area_of_outer_square = side_of_outer_square ** 2 side_of_inner_square = math.sqrt(side_of_outer_square ** 2 / 2) area_of_inner_square = round(side_of_inner_square ** 2) return area_of_inner_square """ REFLECT/REFACTOR PHASE Asymptotic Analysis: - Time Complexity: - O(1) -> "constant" - Space Complexity: - O(1) -> "constant" """
true
d0dff41d253ddeeecd09a2dc68948c5754c080c7
ticotheps/practice_problems
/edabit/hard/alphanumeric_restriction/alphanumeric_restriction.py
2,706
4.375
4
""" ALPHANUMERIC RESTRICTION Create a function that returns True if the given string has any of the following: - Only letters and no numbers. - Only numbers and no letters. If a string has both numbers and letters, or contains characters which don't fit into any category, return False. Examples: - alphanumeric_restriction("Bold") ➞ True - alphanumeric_restriction("123454321") ➞ True - alphanumeric_restriction("H3LL0") ➞ False - alphanumeric_restriction("ed@bit") ➞ False Notes: - Any string that contains spaces or is empty should return False. """ """ The 4 Phases of the U.P.E.R. Problem-Solving Framework ****** UNDERSTAND Phase ****** - Objective: - Write an algorithm that takes in a single string input and returns a single Boolean value as the output. - In order for the algorithm to return True, the given string must either: (a) contain only letters and no numbers. or (b) contain only numbers and no letters. - Expected Input(s): - Number Of: 1 - Data Types: string - Var Names: "s" - Expected Output(s): - Number Of: 1 - Data Types: Boolean value (True or False) - Var Names: "meets_criteria" - Edge Cases & Constraints - Can a given input string be empty or contain only spaces? - Yes. However, you should return False for those instances. ****** PLAN Phase ****** - First Pass Solution: (1) Define a function that takes in a single input, "s", and returns a single output, "meets_criteria". (2) Declare a var, "meets_critera", and initialize it with a Boolean value of False. (3) Use an "if" statement and the ".isalpha()" method to determine if all of the characters in the given input string are alphabetic. (a) If all the characters are alphabetic, set "meets_criteria" to True. (b) Otherwise, do nothing. (4) Use an "elif" statement and the ".isnumeric()" method to determine if all of the characters in the given input string are numeric. (a) If all the characters are numeric, set "meets_criteria" to True. (b) Otherwise, do nothing. (5) Return the value of "meets_criteria". ****** EXECUTE Phase ****** (Please see below) """ def alphanumeric_restriction(s): meets_criteria = False if s.isalpha() == True or s.isnumeric() == True: meets_criteria = True return meets_criteria """ ****** REFLECT/REFACTOR ****** - Asymptotic Analysis: - First Pass Solution: - Time Complexity: O(n) -> "linear time" - Space Complexity: O(1) -> "constant space" """
true
46d77997d86c15ac35859e8639710997dc6b1d63
ticotheps/practice_problems
/edabit/easy/time_for_milk_and_cookies/time_for_milk_and_cookies.py
2,939
4.6875
5
""" Is it Time for Milk and Cookies? Christmas Eve is almost upon us, so naturally we need to prepare some milk and cookies for Santa! Create a function that accepts a Date object and returns True if it's Christmas Eve (December 24th) and False otherwise. Objective: - Write an algorithm that takes in a single input, 'date', and can return a single output (either "True" or "False"). Expected Inputs & Outputs: - Inputs: - Number: 1 - Data Type: Python Dictionary (object) - Name: 'date_dict' - Outputs: - Number: 1 - Data Type: Python Bool (Boolean value) - Name: 'Christmas_eve' - Constraints: - Assume that all test cases will contain valid dates. - Examples: - time_for_milk_and_cookies(datetime.date(2013, 12, 24)) ➞ True - time_for_milk_and_cookies(datetime.date(2013, 1, 23)) ➞ False - time_for_milk_and_cookies(datetime.date(3000, 12, 24)) ➞ True Plan: (1) Create a function that takes in a single input (Python dictionary), 'date_dict', and returns a single output (Python bool), 'Christmas_eve'. (2) Create a variable, 'Christmas_eve', that is initialized with a value of False. This variable will be returned as the output. (3) Convert the 'date_dict' input from an object to a viewable Python string using the 'str()' method and set it equal to a new variable, 'date_str'. (4) Convert the 'date_str' string into a list of items separated by '-' using the '.split()' method and set it equal to a new variable, 'date_items_list'. (5) Use a conditional 'if' statement to determine if the passed in 'date_items_list' contains the string, '24', in it. (6a) If it does, return True. (6b) If it doesn't, return False. """ import datetime # takes in a date dictionary and returns True or False, depending on if the date # falls on Christmas Eve Day. def time_for_milk_and_cookies(date_dict): # returned output Christmas_eve = False # converts input dictionary into a Python string date_str = str(date_dict) # print(f"date_str = {date_str}") # splits converted string into a list of items (separated by hyphens) date_items_list = date_str.split('-') # print(f"date_items_list = {date_items_list}") # checks to see if the date is has month '12' and day '24' in it if '12' in date_items_list and '24' in date_items_list: return True else: return False return date_dict my_date1 = datetime.date(2020, 3, 26) # False my_date2 = datetime.date(1980, 12, 24) # True my_date3 = datetime.date(2020, 3, 25) # False my_date4 = datetime.date(2020, 12, 24) # True print(time_for_milk_and_cookies(my_date1)) print(time_for_milk_and_cookies(my_date2)) print(time_for_milk_and_cookies(my_date3)) print(time_for_milk_and_cookies(my_date4))
true
aeeafce1e20575ffba77b35953aec7f1c4482267
ticotheps/practice_problems
/algo_expert/hard/reverse_linked_list/reverse_linked_list.py
1,639
4.28125
4
""" REVERSE LINKED LIST Write a function that takes in the 'head' of a singly linked list, reverses the list in place (i.e. - doesn't create a brand new list), and returns its new 'head'. Each 'LinkedList' node has an integer, 'value', as well as a 'next' node pointing to the next node in the list or to 'None'/'null' if it's the tail of the list. You can assume that the input Linked List will always have at least one node; in other words, the head will never be 'None'/'null'. Sample Input: - head = 0 -> 1 -> 2 -> 3 -> 4 -> 5 # the 'head' node with value 0 Sample Output: - 5 -> 4 -> 3 -> 2 -> 1 -> 0 # the new 'head' node with value 5 """ def reverseLinkedList(head): # Define the first two pointers that will be used to reverse the linked list # at each node. p1, p2 = None, head # Iterate through the linked list so long as the 'p2' pointer does not # reach the end of the list. while p2 is not None: # Create a third pointer, p3, that will keep reference to the value of # p2.next before p2.next is overwritten to reverse the direction of the # linked list AT THIS NODE. p3 = p2.next # Point the 'p2.next' pointer to p2's previous node (i.e. - p1). p2.next = p1 # Move the 'p1' pointer forward to the next node to continue iterating # through the linked list. p1 = p2 # Move the 'p2' pointer forward to the next node to continue iterating # through the linked list. p2 = p3 # Return the value of the new 'head' node. return p1
true
8af1196d576fdc5bac1efa1bf73520f4ebdd60c6
ramnathpatro/OOPs
/Regular_Expression.py
2,153
4.21875
4
""" ****************************************************************************** * Purpose: Regular Expression * * @author: Ramnath Patro * @version: 1.0 * @since: 26-3-2019 * ****************************************************************************** """ import re def regex(string): constant1 = 0 while constant1 == 0: inp_name = input("Enter the name") check_name = re.search(r"^[A-Z][\w][\w]+$", inp_name) if check_name: print(check_name.group()) constant1 = 1 else: print("Invalid name ") string = re.sub(r"<+[\w]+>+", inp_name, string) constant2 = 0 while constant2 == 0: inp_full_name = input("Enter the full name") check_full_name = re.search(r"^[A-Z][\w][\w]+\s[A-Z][\w]+$", inp_full_name) if check_full_name: print(check_full_name.group()) constant2 = 1 else: print("Invalid full name") string = re.sub(r"<+[\w]+\s[\w]+>+", inp_full_name, string) constant3 = 0 while constant3 == 0: phone_num = input("Enter the phone Number") check_phone_num = re.search(r"^[\d]{10}$", phone_num) if check_phone_num: print(check_phone_num.group()) constant3 = 1 else: print("Invalid number") print("please enter 10 digit number only") string = re.sub(r"[x]{10}", phone_num, string) constant4 = 0 while constant4 == 0: date = input("Enter the date") check_date = re.search(r"^(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[0-2])/\d\d\d\d$", date) if check_date: print(check_date.group()) constant4 = 1 else: print("invalid date"+ " please enter like this:- dd/mm/yyyy") string = re.sub(r"\d\d/\d\d/\d\d\d\d", date, string) return string # print(string) if __name__ == '__main__': string = "Hello <<name>>, We have your full name as <<full name>> in our system. your contact number is 91­xxxxxxxxxx. Please,let us know in case of any clarification Thank you BridgeLabz 01/01/2016." print(regex(string))
false
f433fda6480fe3cac5afcb580f10457da4a1d65f
Nchia-Emmanuela/Average_Height
/Average height.py
587
4.15625
4
Student_Height = input("Enter a list of students heights :\n").split() print(Student_Height) # calculating the sum of the heights total_of_height = 0 for height in Student_Height: total_of_height += int(height) print(f"total heights = {total_of_height}") # calculating the number students number_of_students = 0 for student in Student_Height: number_of_students += 1 print(f"Number of students = {number_of_students}") # calculating the Average Average = total_of_height//number_of_students # // still acts like round function print(f"Average of student height is: {Average}")
true
a8d3aab468d7495659c15bfe709d93d9a437a1f3
thisisvarma/python3
/blog_learning/operators/membershipOperator.py
475
4.1875
4
print("\n ****** membership Operator examples **** ") print(''' in --> True if value or variable presents in list, string,tuple or dict not in --> True if value or variable not presents in list, string, tuple or dict ''') x=input("enter string what ever you like : ") y="aeiou" print("'H' in x is : ",'H' in x) print("'Hellow' in x is : ",'Hellow' in x) print("'Hellow' not in x is : ",'Hellow' not in x) for i in list(y): if i in x: print(i, "presents in ",x)
true
321d8e8034504d725070df509734088103708b85
Platypudding/Rando-stuff
/Gram-Ounce Calculator.py
940
4.1875
4
#Converts grams into ounces or vice versa def convert_gram(gram): ounce = gram / 28.35 print("Grams:", gram, "\n" + "Ounces:", ounce) def convert_ounce(ounce): gram = ounce * 28.35 print("Ounces:", ounce, "\n" + "Grams:", gram) gramounce = input("Input g to convert from grams, o to convert from ounces. ").lower() while True: if gramounce == "g" or gramounce == "o": break else: gramounce = input("input was not g or o.") if gramounce == "g": while True: try: gram = int(input("Input number of grams: ")) convert_gram(gram) break except ValueError: print("Not an int.") continue elif gramounce == "o": while True: try: ounce = int(input("Input number of ounces: ")) convert_ounce(ounce) break except ValueError: print("Not an int.") continue
false
d53eff888bd61bdf36303c232a8300f871de7654
NicciSheets/python_battleship_attempt
/ship.py
1,690
4.25
4
SHIP_INFO = { "Battleship": 2, "Cruiser" : 3, "Submarine" : 4, "Destroyer" : 5 } SHIP_DAMAGE = { "Battleship": 0, "Cruiser" : 0, "Submarine" : 0, "Destroyer" : 0 } # returns a list of all the keys in the dictionary, which you can then use to return a certain ship name from the SHIP_INFO dictionary (but that's not in this function defintion) def ship_list(): return list(SHIP_INFO.keys()) # print(ship_list()[1]) #this is how you would get the specific ship name - for future use, I think # returns a specific ship's length def ship_length(ship): return SHIP_INFO[ship] # adds one to the damage of a particular ship and returns the new damage count for that ship def hit_ship(ship): SHIP_DAMAGE[ship] += 1 return SHIP_DAMAGE[ship] def ship_sunk(ship): sunk = bool(SHIP_DAMAGE.get(ship) == ship_length(ship)) if sunk == True: SHIP_DAMAGE.pop(ship) if sunk == True: print(f"{ship} has been sunk! There are {len(SHIP_DAMAGE)} ships left.") return SHIP_DAMAGE # def bye_sunken_ship(ship): # if ship_sunk(ship) == True: # SHIP_DAMAGE.pop(ship) # return SHIP_DAMAGE ship1 = "Cruiser" ship2 = "Battleship" print(SHIP_DAMAGE) # print(ship_length(ship)) print(f"first hit cruiser is {hit_ship(ship1)}") # print(SHIP_DAMAGE) print(ship_sunk(ship1)) print(f"first hit battleship is {hit_ship(ship2)}") print(f"second hit cruiser is {hit_ship(ship1)}") # print(SHIP_DAMAGE) print(ship_sunk(ship1)) print(ship_sunk(ship2)) print(f"third hit cruiser is {hit_ship(ship1)}") # print(SHIP_DAMAGE) print(ship_sunk(ship1)) print(f"second hit battleship is {hit_ship(ship2)}") print(ship_sunk(ship2))
true
6d700b6b5f6ca80d260cbff864459cf49ca69cb1
keen-s/alx-higher_level_programming
/0x06-python-classes/101-square.py
2,387
4.5625
5
#!/usr/bin/python3 """Write a class Square that defines a square by: (based on 5-square.py) """ class Square: """Square class with a private attribute - size. """ def __init__(self, size=0, position=(0, 0)): """Initializes the size variable as a private instance artribute """ self.__size = size self.__position = position @property def size(self): """Instantiation with optional size of square""" return self.__size @size.setter def size(self, size_value): """Gets the size of the square""" self.__size = size_value if not isinstance(size_value, int): raise TypeError("size must be an integer") elif size_value < 0: raise ValueError("size must be >= 0") @property def position(self): """Get/set the current position of the square.""" return self.__position @position.setter def position(self, size_value): """Must be a tuple of 2 positive integers, otherwise raise a TypeError exception """ self.__position = size_value if (not isinstance(size_value, tuple) or len(size_value) != 2 or not all(isinstance(num, int) for num in size_value) or not all(num >= 0 for num in size_value)): raise TypeError("position must be a tuple of 2 positive integers") def area(self): """Returns the current square area""" return self.__size ** 2 def my_print(self): """Prints the square with the '#' character.""" if self.__size == 0: print("") return for i in range(0, self.__position[1]): [print("")] for i in range(0, self.__size): [print(" ", end="") for j in range(0, self.__position[0])] [print("#", end="") for k in range(0, self.__size)] print("") def __str__(self): """Define the print() representation of a Square.""" if self.__size != 0: [print("") for i in range(0, self.__position[1])] for i in range(0, self.__size): [print(" ", end="") for j in range(0, self.__position[0])] [print("#", end="") for k in range(0, self.__size)] if i != self.__size - 1: print("") return ("")
true
84059ceca8bf9da2d3a7b82f62501c53c99e215d
laurennpollock/comp110-21f-workspace
/exercises/ex01/numeric_operators.py
940
4.1875
4
"""Practicing numberic operators.""" __author__ = "730392344" left_hand_side: str = input("Left-hand side: ") right_hand_side: str = input("Right-hand side: ") int(str(left_hand_side)) int(str(left_hand_side)) exponentiation = int(left_hand_side) ** int(right_hand_side) division = int(left_hand_side) / int(right_hand_side) integer_division = int(left_hand_side) // int(right_hand_side) remainder = int(left_hand_side) % int(right_hand_side) left_hand_side = str(left_hand_side) right_hand_side = str(right_hand_side) exponentiation = str(exponentiation) division = str(division) integer_division = str(integer_division) remainder = str(remainder) print(left_hand_side + " ** " + right_hand_side + " is " + exponentiation) print(left_hand_side + " / " + right_hand_side + " is " + division) print(left_hand_side + " // " + right_hand_side + " is " + integer_division) print(left_hand_side + " % " + right_hand_side + " is " + remainder)
false
9835ccfe8458dbffd844eedc273984aed6025e9c
Knorra416/daily_coding_challenge
/July_2019/20190722.py
856
4.375
4
# There exists a staircase with N steps, # and you can climb up either 1 or 2 steps at a time. # Given N, write a function that returns the number of unique ways you can climb the staircase. # The order of the steps matters. # For example, if N is 4, then there are 5 unique ways: # 1, 1, 1, 1 # 2, 1, 1 # 1, 2, 1 # 1, 1, 2 # 2, 2 # What if, instead of being able to climb 1 or 2 steps at a time, # you could climb any number from a set of positive integers X? For example, # if X = {1, 3, 5}, you could climb 1, 3, or 5 steps at a time. # help from online. Recursion is always important! def findstep(n): if n == 1 or n == 0: return 1 elif n == 2: return 2 else: return findstep(n - 1) + findstep(n - 2) # Solution def staircase(n): if n <= 1: return 1 return staircase(n - 1) + staircase(n - 2)
true
6718a6008d1870df1b20f67a1dd3b948375c6885
king-Daniyal/assignment-1-py
/do.py
550
4.15625
4
#(print) this is the feature which prints the word given ahead of it print("hi, i am a text") # this is the function the word inside of the "" will come as output # lets try numbers print(2020, "was bad") # this works with numbers and text but the "" shall not be included with the number because it is of no use print("text 3 \n") # the special thing here is that the "\n" is actually creating a new sentence ### For the next one we need a clean work space first we create a few "terms" like a = 5 - 3 print("my answer is \n" "a = ", a)
true
73db52476f91e787f5441b81ac790ea4fe0916d0
NickCorneau/PythonAlgorithms
/deep_reverse.py
693
4.375
4
# Procedure, deep_reverse, that takes as input a list, # and returns a new list that is the deep reverse of the input list. # This means it reverses all the elements in the list, and if any # of those elements are lists themselves, reverses all the elements # in the inner list, all the way down. # Note: The procedure must not change the input list. # The procedure is_list below is from Homework 6. It returns True if # p is a list and False if it is not. def is_list(p): return isinstance(p, list) def deep_reverse(l): l.reverse() for i in l: if is_list(i): deep_reverse(i) return l p = [1, [2, 3, [4, [5, 6]]]] #>>> [[[[6, 5], 4], 3, 2], 1]
true
7cf8abf975c0d5317999a2daec0bb0fa4e6cbb8d
AhsanVirani/python_basics
/Basic/Classes/classes_instances_1.py
1,042
4.15625
4
# -*- coding: utf-8 -*- """ Created on Fri May 8 06:57:49 2020 @author: asan """ # Creating and instanciating classes # Tut 1 class Employee: def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@company.com' def fullname(self): return '{} {}'.format(self.first, self.last) ''' # Instances of a class emp_1 = Employee() emp_2 = Employee() print(emp_1) print(emp_2) emp_1.first = 'Ahsan' emp_1.last = 'Virani' emp_1.email = 'ahsan.virani08@gmail.com' emp_1.pay = 100000 emp_2.first = 'Test' emp_2.last = 'User' emp_2.email = 'Test.user@gmail.com' emp_2.pay = 60000 print(emp_1.last) print(emp_2.last) ''' # Using the Class object to do the same thing as above emp_1 = Employee('Ahsan', 'Virani', 100000) emp_2 = Employee('Test', 'User', 60000) # Making method of redundant work print(emp_1.email) print(emp_2.email) # print('{} {}'.format(emp_1.first, emp_1.last)) print(emp_1.fullname()) print(emp_2.fullname())
true
70d8e31b35c73a792f4c6c8160db16f8019bdb7f
kirtanlab/pure_mess
/MODULE15/15.3/main.py
1,754
4.125
4
#Program 1 print("\n**\n ** \nProgram No: 0 : Program to find sum of square of first n natural numbers\n **\n**") def squaresum(n) : sm = 0 for i in range(1, n+1) : sm = sm + (i * i) return sm n = int(input("\nEnter the Input: ")) print(squaresum(n)) #Program 2 print("\n**\n ** \nProgram No: 1 : program to split a string and join it using different delimiter\n **\n**\n") def split_string(string): list_string = string.split(' ') print("\nSplit string: ") return list_string def join_string(list_string): print("\nconcatenated String: ") string = '_'.join(list_string) return string if __name__ == '__main__': string = 'prajapati kirtan 0804' print("Given String is: " + string) list_string = split_string(string) print(list_string) new_string = join_string(list_string) print(new_string) #Program 3 print("\n**\n ** \nProgram No: 2 : demonstrate working of Replace duplicate Occurrence in String Using split() + enumerate() + loop\n **\n**") test_str = 'We resolve to be brave. We resolve to be good. We resolve to uphold the law according to our oath. ' print("\nThe original string is : " + str(test_str)) repl_dict = {'resolve' : 'never resolve', 'to' : 'new_to' } test_list = test_str.split(' ') res = set() for idx, ele in enumerate(test_list): if ele in repl_dict: if ele in res: test_list[idx] = repl_dict[ele] else: res.add(ele) res = ' '.join(test_list) print("\nThe string after replacing : " + str(res)) #Program 3 print("\n**\n ** \ndemonstrate printing pattern of alphabets\n **\n**") def contalpha(n): num = 65 for i in range(0, n): for j in range(0, i+1): ch = chr(num) print(ch, end=" ") num = num +1 print("\r") n = 5 contalpha(n)
true
5abae9ce6ec3065280f6799fd1cab57c79a2d629
nickruta/DataStructuresAlgorithmsPython
/selection_sort.py
1,638
4.21875
4
""" Using the PEP 8 Style Guide for Python Code: https://www.python.org/dev/peps/pep-0008/ and python linters """ def selection_sort(a_list): """The selection sort improves on the bubble sort by making only one exchange for every pass through the list. In order to do this, a selection sort looks for the largest value as it makes a pass and, after completing the pass, places it in the proper location. As with a bubble sort, after the first pass, the largest item is in the correct place. After the second pass, the next largest is in place. This process continues and requires 𝑛 − 1 passes to sort 𝑛 items, since the final item must be in place after the (𝑛 − 1)st pass. Args: a_list (list(int)) : the unordered list to be sorted Big-O Complexity: You may see that the selection sort makes the same number of comparisons as the bubble sort and is therefore also 𝑂(𝑛2). However, due to the reduction in the number of exchanges, the selection sort typically executes faster in benchmark studies. In fact, for our list, the bubble sort makes 20 exchanges, while the selection sort makes only 8. """ for fill_slot in range(len(a_list) - 1, 0, -1): pos_of_max = 0 for location in range(1, fill_slot + 1): if a_list[location] > a_list[pos_of_max]: pos_of_max = location temp = a_list[fill_slot] a_list[fill_slot] = a_list[pos_of_max] a_list[pos_of_max] = temp a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] selection_sort(a_list) print(a_list)
true
8d715b5244502b202be141f5190a8b8032aef202
Leonardo-Alejandro-Juarez-Montes/CLUB_PRO_2020
/EjercicioPOO_21_03_20.py
658
4.15625
4
print("EJERCICIO NUMERO 1") n= 1 + int(input("Introduce el numero de filas weon: ")) for y in range(n): print("* "*y) print(" ") print ("EJERCICIO NUMERO 2") l=int(input("Introduce el numero de filas pd:te quiero :3: ")) for y in range (l,0,-1): print("* "*y) print(" ") print("EJERCICIO NUMERO 3") m= 1 + int(input("Introduce el numero de filas rufian: ")) for z in range(m): print("* "*z) for w in range (m,0,-1): print("* "*w) print(" ") print("EJERCICIO NUMERO 4") r= 1 + int(input("Introduce el numero de filas :3 : ")) h= int(input("Introduce el numero de columnas papito: ")) for cont in range(1,r): print("* "*h) print(" ")
false
a3620b4b22b61a4e05386afedb3e42ebab83fc65
TimTomApplesauce/CIS1415
/PigLatin.py
389
4.1875
4
def to_pig_latin(usr_str): split_str = usr_str.split(' ') for word in split_str: first_letter = word[0] word = word[1:] print(word + first_letter + 'ay', end =' ') print() return user_string = input("Please enter a sentance to convert to Pig Latin:\n") print("English:", user_string) pig_latin = to_pig_latin(user_string)
false
abe3713a43c57d6564c638ceacbab2c2ce308a0a
meermm/test
/композиция.py
908
4.1875
4
''' По композиции один из классов состоит из одного или нескольких экземпляров других классов. Другими словами, один класс является контейнером, а другой класс - содержимым, и если вы удалите объект-контейнер, все его объекты содержимого также будут удалены. ''' class Salary: def __init__(self, pay): self.pay = pay def get_total(self): return (self.pay*12) class Human: def __init__(self, pay, bonus): self.pay = pay self.bonus = bonus self.obj_salary = Salary(self.pay) def annual_salary(self): return "Total: " + str(self.obj_salary.get_total() + self.bonus) obj_emp = Human(680, 500) print(obj_emp.annual_salary())
false
3ac1299605142a62c6c7c9e4df09020fccb95c75
nidhi2802/18IT033_IT374_PythonProgramming_Practical_Tasks
/Week_4/Assignment2/4.py
731
4.15625
4
from collections import Counter list1 = [1, 2, 3, 2, 2, 2, 5, 6] counter = 0 num = list1[0] for i in list1: current = list1.count(i) if(current>counter): counter=current num=i print("Most common element in list: ",num) print("Count of element in list: ", counter) tuples = ("apple", 2, 3,"apple","apple", "apple", 5, 6) counter_t = 0 num_t = tuples[0] for j in tuples: current_t = tuples.count(j) if(current_t>counter_t): counter_t=current_t num_t=j print("Most common element in tuple: ",num_t) print("Count of element in tuple: ", counter_t) dict1={ "one": 1,"two": 2, "two2": 2, "two3": 2, "three": 4, "three3": 4 } res = Counter(dict1.values()) print("The frequency dictionary : " + str(dict(res)))
false
59e4a6bab2feb777b3bec0b1ece5c6bccf1c2433
nidhi2802/18IT033_IT374_PythonProgramming_Practical_Tasks
/Week_1/Practical7.py
501
4.21875
4
choice = int(input("To covert rupees to dollar- enter 1 and to convert dollar to rupees - enter 2 ")) if(choice==1): amt_rupees = float(input("Enter amount in rupees: ")) cnv_dollar = amt_rupees/70 print(amt_rupees, "rupees is equal to ", cnv_dollar, "dollar/s") elif(choice==2): amt_dollar = float(input("Enter amount in dollar: ")) cnv_rupees = amt_dollar*70 print(amt_dollar, "dollar/s is equal to ", cnv_rupees, "rupees") else: print("You have entered invalid choice")
true
1ca2340361d2623294f76a41dc5181d62b5d17c9
melandres8/holbertonschool-higher_level_programming
/0x06-python-classes/3-square.py
733
4.375
4
#!/usr/bin/python3 """Square class""" class Square(): """Validating if size is an instance and if is greater and equal to 0 Attributes: attr1 (int): size is a main attr of a square """ def __init__(self, size=0): """isinstance function checks if the object is an instance or subclass of the second argument Args: size (int): size of my square """ if not isinstance(size, int): raise TypeError("size must be an integer") if size < 0: raise ValueError("size must be >= 0") self.__size = size """Returning the Area of a square""" def area(self): return int(self.__size) * int(self.__size)
true
9a956a51c89fe66441040b2db5ab0b5dd3bf53fe
melandres8/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/5-text_indentation.py
758
4.1875
4
#!/usr/bin/python3 """ Handling new lines, some special characters and tabs function. """ def text_indentation(text): """ Print a text with two new line at the end after each of these characters '.'':''?' Args: text: (string) Given text Raises: TypeError: "text must be a string" """ if (not isinstance(text, str)): raise TypeError("text must be a string") string = "" for i in text: if i == '\n': pass else: string += i if i in '.:?': string = string.strip(" ") print(string, end="") print("\n") string = "" string = string.strip(" ") print(string, end="")
true
9923d3414c6e87199ffca081c646b80967cac9d8
melandres8/holbertonschool-higher_level_programming
/0x0A-python-inheritance/10-square.py
445
4.1875
4
#!/usr/bin/python3 """ Applying inheritance and super() method """ Rectangle = __import__('9-rectangle').Rectangle class Square(Rectangle): """ Defining constructor """ def __init__(self, size): """Constructor method Args: size: square size """ self.integer_validator("size", size) super().__init__(size, size) # call init of rectangle class self.__size = size
true
e89d2a1bb8619dd97424585534da78618f6c4bf7
ml-nic/Algorithms
/src/typical_string_processing_functions.py
1,007
4.125
4
def is_palindrome(string: str) -> bool: """ Is the string a palindrome? :param string: :return: """ length = len(string) for i in range(int(length / 2)): if string[i] != string[-i - 1]: return False return True assert is_palindrome("HelloolleH") is True assert is_palindrome("Hello") is False assert is_palindrome("") is True def extract_filename_and_extension(string: str) -> tuple: """ Extracts filename and extension of given string. :param string: :return: """ dot = string.index(".") base = string[0:dot] extension = string[dot+1:] return base, extension assert ("test", "txt") == extract_filename_and_extension("test.txt") def is_list_of_strings_sorted(list : list) -> bool: for i in range(1,len(list)): if list[i-1] > list[i]: return False return True assert is_list_of_strings_sorted(["hello", "world"]) is True assert is_list_of_strings_sorted(["world", "hello"]) is False
true
422c8cd0e2bcc3bce513c2a4b412d775b328e138
massivetarget/mtar_a
/capping.py
201
4.1875
4
# this is python file for capitalisation of give string nm = str(input("please Enter word to capitilise it: ")) print(nm.capitalize()) # this will do the real work print("adding 23 to 34", 23 + 34)
true
776570db6172e6379b4dc91afd491c5b05871515
jsourabh1/Striver-s_sheet_Solution
/Day-13_Stack/question3_queue_using_stack.py
562
4.125
4
def Push(x,stack1,stack2): ''' x: value to push stack1: list stack2: list ''' #code here stack1.append(x) #Function to pop an element from queue by using 2 stacks. def Pop(stack1,stack2): ''' stack1: list stack2: list ''' #code here if stack1: stack2=[] while stack1: temp=stack1.pop() stack2.append(temp) temp=stack2.pop() while stack2: stack1.append(stack2.pop()) return temp return -1
true
1ba233bf6d91df731ef3347bfe864e6b353f2be8
elinaavintisa/Python_2variants
/2uzdevums.py
900
4.1875
4
""" Funkcija akrs akceptē trīs argumentus - skaiļus viens, divi un trīs, aprēķina to kvadrātu starpību un atgriež to. Pārbaudiet funkcijas darbību ar dažādiem argumentiem, parādot skaitli ar četriem simboliem aiz komata. Argumenti: viens {int vai float} -- pirmais skaitlis divi {int vai float} -- otrais skaitlis tris {int vai float} -- trešais skaitlis Atgriež: int vai float -- argumentu summa """ """ import math import decimal def akrs(a, b, c): kvadrats=float(pow(a,2)+pow(b,2)+pow(c,2)) return kvadrats print('%.2f'% akrs(2, 3, 4)) """ """Kļudu labojums:""" import math import decimal def akrs(a, b, c): kvadrats=float(pow(a,2)+pow(b,2)+pow(c,2)) return kvadrats print("%.4f" % akrs(2, 3, 4)) """ 2f vietā ieliku 4f, jo uzdevumā tiek prasīti 4 cipari aiz komata."""
false
f5d59978eb41fa768c32f83a8270359687f00c85
green-fox-academy/ZaitzeV16
/python_solutions/week-02/day-2/data_structures/telephone_book.py
1,155
4.53125
5
""" # Telephone book We are going to represent our contacts in a map where the keys are going to be strings and the values are going to be strings as well. - Create a map with the following key-value pairs. | Name (key) | Phone number (value) | | :------------------ | :------------------- | | William A. Lathan | 405-709-1865 | | John K. Miller | 402-247-8568 | | Hortensia E. Foster | 606-481-6467 | | Amanda D. Newland | 319-243-5613 | | Brooke P. Askew | 307-687-2982 | - Create an application which solves the following problems. - What is John K. Miller's phone number? - Whose phone number is 307-687-2982? - Do we know Chris E. Myers' phone number? """ phone_book = { "William A. Lathan": "405-709-1865", "John K. Miller": "402-247-8568", "Hortensia E. Foster": "606-481-6467", "Amanda D. Newland": "319-243-5613", "Brooke P. Askew": "307-687-2982" } print("What is John K. Miller's phone number?") print(phone_book.get("John K. Miller")) print("Whose phone number is 307-687-2982?") for k, v in phone_book.items(): if v == "307-687-2982": print(k) print("Do we know Chris E. Myers' phone number?") print("yes :)" if phone_book.__contains__("Chris E. Myers") else "nope, sorry")
false
394529d04bd7be33bf77db2a9c9eb43d0152dea3
green-fox-academy/ZaitzeV16
/python_solutions/week-01/day-4/average_of_input.py
340
4.15625
4
# Write a program that asks for 5 integers in a row, # then it should print the sum and the average of these numbers like: # # Sum: 22, Average: 4.4 _sum = 0 number_of_inputs = 5 for i in range(number_of_inputs): _sum += int(input("number {}: ".format(i + 1))) print("sum: {}, average: {:.1f}".format(_sum, _sum / number_of_inputs))
true
6cef60c67ed6680f4649a9aa9223ad38793d6f72
green-fox-academy/ZaitzeV16
/python_solutions/week-02/day-1/functions/greet.py
356
4.28125
4
# - Create a string variable named `al` and assign the value `Green Fox` to it # - Create a function called `greet` that greets it's input parameter # - Greeting is printing e.g. `Greetings dear, Green Fox` # - Greet `al` al = "Green Fox" def greet(name: str): print("Greetings dear, {}".format(name)) if __name__ == '__main__': greet(al)
true
d591cbf39e6a63369d5c674941a8994c8d87ffd3
vincentt117/coding_challenge
/lc_merge_sorted_array.py
1,577
4.125
4
# Merge Sorted Array # https://leetcode.com/explore/interview/card/microsoft/47/sorting-and-searching/258/ # Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. # Note: # The number of elements initialized in nums1 and nums2 are m and n respectively. # You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. # Example: # Input: # nums1 = [1,2,3,0,0,0], m = 3 # nums2 = [2,5,6], n = 3 # Output: [1,2,2,3,5,6] def merge(nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead. """ # Doesn't run in compiler # Duplicate nums1 and keep only initialized components for nums2 dups1 = nums1[:m] nums2 = nums2[:n] nums1 = [] while dups1 and nums2: print(nums1) if dups1[0] < nums2[0]: nums1.append(dups1.pop(0)) else: nums1.append(nums2.pop(0)) # Add rest of remaining list to nums1 nums1 = nums1 + dups1 + nums2 return nums1 # Solution found in discussion # def merge(self, nums1, m, nums2, n): # while m > 0 and n > 0: # if nums1[m-1] >= nums2[n-1]: # nums1[m+n-1] = nums1[m-1] # m -= 1 # else: # nums1[m+n-1] = nums2[n-1] # n -= 1 # if n > 0: # nums1[:n] = nums2[:n] print(merge([1,2,3,0,0,0], 3, [2,5,6], 3))
true
2d8988baedd00b46718268d1b13aaa05a908dd44
vincentt117/coding_challenge
/lc_power_of_three.py
659
4.1875
4
# 326. Power of Three # https://leetcode.com/problems/power-of-three/description/ # Given an integer, write a function to determine if it is a power of three. # Example 1: # Input: 27 # Output: true # Example 2: # Input: 0 # Output: false # Example 3: # Input: 9 # Output: true # Example 4: # Input: 45 # Output: false # Follow up: # Could you do it without using any loop / recursion? # Base conversion or log arithmetics def isPowerOfThree(self, n): """ :type n: int :rtype: bool """ while n > 1: if n % 3 != 0: return False n = n / 3 return not(n <= 0) # Solution faster than 88% of submissions
true
e4216a7f86a3d561a1d68240942799919fcb3e5b
MarketaR0/up_ii_calculator
/src/Calculator.py
2,774
4.15625
4
from src.FunctionManager import FunctionManager from src.BasicFunctions import add, subtract, multiply, divide # Runs the calculator. def calculate(): func_manager = FunctionManager() # Allows user to choose operation. func_manager.show_functions() user_choice = int_input(len(func_manager.functions)) # Calculates number of needed arguments. num_of_args = func_manager.calc_num_of_args(user_choice) # Asks user to enter number of inputs needed for chosen operation. nums = get_function_args(num_of_args) # This actually calculates result and prints it. print('''The result is {}'''.format( func_manager.use_function(user_choice, *nums) )) # Asks users if they want to do more calculations. again() # def get_function_args(num_of_args): print("The function is accepting {} numbers".format(num_of_args if num_of_args != 0 else "infinite")) # Asks user to enter number of inputs needed for chosen operation. nums = [] for i in range(num_of_args): nums.append(float_input()) # In case that we have function with not defined number of arguments. if len(nums) == 0: print("Stop giving numbers by entering \"stop\"") user_input = input("Enter a number:") while user_input != "stop": nums.append(float_input()) user_input = input("Enter a number: ") return nums # Catches exceptions if user is dumb enough to enter nonsense def int_input(num_of_funcs): while True: try: user_input = float(input("Enter a number: ")) except ValueError: print("Wrong input, try it again.") else: if user_input in range(num_of_funcs): return user_input else: print("Wrong input, try it again.") continue # Catches exceptions if user is dumb enough to enter nonsense def float_input(): while True: try: user_input = float(input("Enter a number: ")) except ValueError: print("Wrong input, try it again.") else: return user_input # Asks users if they want to use the calculator again def again(): # Take input from user calc_again = input(''' Do you want to calculate again? Please type Y for YES or N for NO. ''') # If user types Y, run the calculate() function if calc_again.upper() == 'Y': calculate() # If user types N, say good-bye to the user and end the program elif calc_again.upper() == 'N': print('See you later.') # If user types something else, run the function again else: print('Wrong input. Try it one more time.\n') again() if __name__ == "__main__": calculate()
true
000f23ea08180197ae4e666159a3100d689b1e9e
NicolaBenigni/PythonExam
/Simulation.py
2,517
4.125
4
# Import necessary libraries from matplotlib import pyplot as plt from random import randint # Import the file "Roulette" where roulette and craps games are defined import Roulette ### This file tests whether roulette and craps game works. Moreover, it simulates awards and profit distribution ### for 1000 crap games # First 2 simulations of roulette games (numbers slightly different than in the powerpoint) bets1 = [14, 14, 36, 0, 11, 14] amounts1 = [10, 100, 120, 65, 150, 122] table1 = Roulette.Roulette(100) print(table1.simulate_game(bets1, amounts1)) print(table1.simulate_game(bets1, amounts1)) # First 2 simulations of craps games bets2 = [8, 8, 10, 2, 3, 8] amounts2 = [10, 120, 100, 65, 100, 100] table2 = Roulette.Craps(100) print(table2.simulate_game(bets2, amounts2)) print(table2.simulate_game(bets2, amounts2)) # Create a list that takes the values of 1000 throws of dice pairs (set at only 10 simulation) list_of_values = [] for i in range(10): list_of_values.append(table2.dices()) # Print figures # (they are commented out because the code does not work on my pc) # plt.hist(list_of_values) # plt.show() print(list_of_values) # This is here to see the value that should enter the graph # Simulate the craps game 1000 times and create a list of customers' and casino's results # to show allocation of betted amounts chosen between 100 to 500 (set at only 10 simulation) list_of_profit = [] list_of_awards = [] profit_over_betted_amounts = [] for i in range(10): bets3 = [randint(2, 12) for k in range(10)] amounts3 = [randint(100, 500) for j in range(10)] result = table2.simulate_game(bets3, amounts3) list_of_profit.append(result[0]) list_of_awards.append(result[1]) profit_over_betted_amounts.append(result[0]/sum(amounts3)) # Print figures # plt.hist([item for sublist in list_of_awards for item in sublist]) # plt.hist(profit_over_betted_amounts) # plt.show() print([item for sublist in list_of_awards for item in sublist]) # This is here to see the value that should enter the graph print(profit_over_betted_amounts) # This is here to see the value that should enter the graph # Print the average share of profit over the betted amounts that the casino cashes in. The result is close to 0.10, # which shows the correct programming of the prize factor casino_avg_share = round(sum(profit_over_betted_amounts)/len(profit_over_betted_amounts),2) print("The average share of profit over betted amounts that the casino cashes in is %s" % casino_avg_share)
true
325628121e6010bcf26bb007217b2d9d953b4b4f
jonathadd27/AritmatikaSederhanaPert1
/AritmatikaSederhana.py
963
4.1875
4
#Program Hello World !! print("Hello World") print("Saya sedang belajar bahasa pemrograman Python") print("") print("") print("Berikut program latihan Aritmatika sederhana dengan inline variable Python") print("") print("") #Program Aritmatika Dasar bil1 = 25 bil2 = 50 penjumlahan = bil1 + bil2 pengurangan = bil2 - bil1 perkalian = bil1 * bil2 pembagian = bil2 / bil1 print("Diketahui") print("==============================") print("Bilangan Pertama =", bil1) print("Bilangan Kedua =", bil2) print("") print("") print("Penghitungan :") print("==============================") print("Hasil Penjumlahan dari", bil1, "+", bil2, "adalah", penjumlahan) print("Hasil Pengurangan dari", bil2, "-", bil1, "adalah", pengurangan) print("Hasil Perkalian dari", bil1, "*", bil2, "adalah", perkalian) print("Hasil Pembagian dari", bil2, "/", bil1, "adalah", pembagian) print("") print("==============================") print("")
false
a3258932dc63aba4e3991745592c933e53fd444e
sc1f/algos
/sorting.py
615
4.1875
4
def mergesort(nums): if len(nums) <= 1: # already sorted return # split into 2 mid = len(nums) // 2 left = nums[:mid] right = nums[mid:] # recursively split mergesort(left) mergesort(right) # start merging merge(left, right, nums) return nums def merge(left, right, nums): index = 0 while left and right: # sort if right[0] < left[0]: nums[index] = right.pop(0) else: nums[index] = left.pop(0) index += 1 # clear lists that are left while left: nums[index] = left.pop(0) index += 1 while right: nums[index] = right.pop(0) index += 1 print(mergesort([1,44,5,2,1,3]))
true
d388be010509b5f4afb69817d29edc9cb94f62ad
csulva/Rock_Paper_Scissors_Game
/rock_paper_scissors_game.py
2,174
4.25
4
import random # take in a number 0-2 from the user that represents their hand user_hand = input('\nRock = 0\nPaper = 1\nScissors = 2\nChoose a number from 0-2: \n') def get_hand(number): if number == 0: return 'rock' elif number == 1: return 'paper' elif number == 2: return 'scissors' else: print('Number must be between 0-2...') def determine_winner(user, computer): if user == 'rock' and computer == 'paper': print(f'You chose {user} and the computer chose {computer}... the computer wins!') elif user == 'rock' and computer == 'scissors': print(f'You chose {user} and the computer chose {computer}... You win!') elif user == 'paper' and computer == 'scissors': print(f'You chose {user} and the computer chose {computer}... the computer wins!') elif user == 'paper' and computer == 'rock': print(f'You chose {user} and the computer chose {computer}... You win!') elif user == 'scissors' and computer == 'rock': print(f'You chose {user} and the computer chose {computer}... the computer wins!') elif user == 'scissors' and computer == 'paper': print(f'You chose {user} and the computer chose {computer}... You win!') elif user == computer: print(f'You chose {user} and the computer chose {computer}... It\'s a draw! Try again') # call the function get_hand to get the string representation of the user's hand user_choice = get_hand(int(user_hand)) # generate a random number 0-2 to use for the computer's hand computer_hand = random.randint(0, 2) # call the function get_hand to get the string representation of the computer's hand computer_choice = get_hand(int(computer_hand)) # call the function determine_winner to figure out who won # print out the player hand and computer hand # print out the winner determine_winner(user_choice, computer_choice) while user_hand != 'exit'.lower(): user_hand = input('Choose a number from 0-2: ') user_choice = get_hand(int(user_hand)) computer_hand = random.randint(0, 2) computer_choice = get_hand(int(computer_hand)) determine_winner(user_choice, computer_choice)
true
a0d5e506fda1eb6516c6427d0a246bf8256c75d9
Skelmis/Traffic-Management-Simulator
/cars.py
1,094
4.3125
4
# A class which stores information about a specific car class Car: name = None # Which road did the car enter from enter = None # Which direction would the car like to go in direction = None def __init__(self, name, enter, direction): self.name = name self.enter = enter self.direction = direction def getEnter(self): return self.enter def getDirection(self): return self.direction def getName(self): return self.name """ A function which displays the direction of the car in the simulation. """ def displayDirection(self): if self.direction == "LEFT": return "<" elif self.direction == "RIGHT": return ">" else: return "^" def __str__(self): return ( self.name + ": " + self.direction ) # It looks nicer on the eyes #displayDirection() def __repr__(self): return ( self.name + ": " + self.direction ) # It looks nicer on the eyes #displayDirection()
true
92439e7c1286c56a4a7335f42c496b5e97a49653
efuen0077/Election_Analysis
/Python_prac.py
2,450
4.21875
4
#counties = ["Arapahoe","Denver","Jefferson"] #if counties[1] == 'Denver': #print(counties[1]) #temperature = int(input("What is the temperature outside? ")) #if temperature > 80: # print("Turn on the AC.") #else: # print("Open the windows.") #What is the score? #score = int(input("What is your test score? ")) # Determine the grade. #if score >= 90: # print('Your grade is an A.') #elif score >= 80: #print('Your grade is a B.') #elif score >= 70: #print('Your grade is a C.') #elif score >= 60: #print('Your grade is a D.') #else: #print('Your grade is an F.') #if "El Paso" in counties: # print("El Paso is in the list of counties.") #else: #print("El Paso is not the list of counties.") #candidate_votes = int(input("How many votes did the candidate get in the election? ")) #total_votes = int(input("What is the total number of votes in the election? ")) #message_to_candidate = ( # f"You received {candidate_votes} number of votes. " # f"The total number of votes in the election was {total_votes}. " # f"You received {candidate_votes / total_votes * 100}% of the total votes.") #print(message_to_candidate) #message_to_candidate = ( # f"You received {candidate_votes:,} number of votes. " # f"The total number of votes in the election was {total_votes:,}. " # f"You received {candidate_votes / total_votes * 100:.2f}% of the total votes.") #Below is how I would find the path to a file #Resources/election_analysis.csv # WORKING WITH DEPENDENCIES #Import the datetime class from the datetime module #import datetime as dt #Use the now() attribute on the datetime class to get the current time #now = dt.datetime.now() #Print the present time. #print("The time right now is, ", now) # NOW, LET'S LOOK AT HOW TO USE THE CSV MODULE #import datetime (this is a module) #print(dir(datetime)) #import csv #print (dir(csv)) #IMPORTANT DATA TYPES AND STRUCTURES #INT, FLOAT, BOOL, LIST, TUPLE, DICT, DATETIME # IMPORTANT MODULES #CSV, RANDOM, NUMPY file_to_load = 'Resources/election_results.csv' # Open the election results and READ the file. #election_data = open(file_to_load, 'r') # To do: perform analysis. # Close the file. #election_data.close() #if I want a more efficient set of code, I can use a "with" statement # Open the election results and read the file with open(file_to_load) as election_data: # To do: perform analysis. print(election_data)
true
54e250c7c93908773fd293b84468594d9706eb5d
incesubaris/Numerical
/secant.py
1,330
4.1875
4
import matplotlib.pyplot as plt import numpy as np ## Defining Function def f(x): return x**3 - 5*x - 8 ##Secant Method Algorithm def secant(x0, x1, error, xson, yson): x2 = x0 - (x0-x1) * f(x0) / (f(x0)-f(x1)) print('\n--- SECANT METHOD ---\n') iteration = 1 while abs(f(x2)) > error: if f(x0) == f(x1): print('ERROR : Divide by zero!') break x2 = x0 - (x1 - x0) * f(x0) / (f(x1) - f(x0)) xson.append(x2) yson.append(f(x2)) print('Iteration-%d, x2 = %0.8f and f(x2) = %0.6f' % (iteration, x2, abs(f(x2)))) x0 = x1 x1 = x2 iteration = iteration + 1 print('\nReach the Root Iteration-%d the root is: %0.8f' % (iteration, x2)) ## Input print("\nEnter the Initial Values and Tolerable Error\n") x0 = float(input('Enter Initial Value (x0): ')) x1 = float(input('Enter Initial Value (x1): ')) error = float(input('Tolerable Error: ')) ## Graph Elemnt Lists xson = [] yson = [] ## Implementing Secant Method secant(x0, x1, error, xson, yson) ##Graph of Bisection Method for Visualizing x = np.arange(x0, x1, 0.001) y = (f(x)) plt.title("Secant Method on f(x)") plt.plot(x, y, label="f(x)") plt.plot(xson, yson , '-o', label="Secant Iterations") plt.xlabel('x') plt.ylabel('y') plt.grid() plt.legend() plt.show()
true
4cfefb42c88250aa58e56356cd9489a9eca915f6
ppicavez/PythonMLBootcampD00
/ex09/plot.py
1,399
4.15625
4
import matplotlib.pyplot as plt import numpy as np def cost_(y, y_hat): """Computes the mean squared error of two non-empty numpy.ndarray, without any for loop. The two arrays must have the same dimensions. Args: y: has to be an numpy.ndarray, a vector. y_hat: has to be an numpy.ndarray, a vector. Returns: The mean squared error of the two vectors as a float. None if y or y_hat are empty numpy.ndarray. None if y and y_hat does not share the same dimensions. Raises: This function should not raise any Exceptions. """ if y.shape != y_hat.shape: return None return np.sum(np.power(y_hat - y, 2) / (2 * y.shape[0])) def plot_with_cost(x, y, theta): """Plot the data and prediction line from three non-empty numpy.ndarray. Args: x: has to be an numpy.ndarray, a vector of dimension m * 1. y: has to be an numpy.ndarray, a vector of dimension m * 1. theta: has to be an numpy.ndarray, a vector of dimension 2 * 1. Returns: Nothing. Raises: This function should not raise any Exception. """ y_hat = np.dot(np.c_[np.ones((len(x), 1)), x], theta) cost = cost_(y, y_hat) * 2 plt.plot(x, y, 'o') plt.plot(x, y_hat) i = 0 while i < len(x): plt.plot([x[i], x[i]], [y[i], y_hat[i]], 'r--') i = i + 1 plt.title("Cost : {}".format(cost)) plt.show()
true
7a278079bd6b7ebd4dbb79011fc0f3bb1a77dfe5
vinagrace-sadia/python-mini-projects
/Hangman/hangman.py
1,330
4.125
4
import time import random def main(): player = input('What\'s your name? ') print('Hello,', player + '.', 'Time to play Hangman!') time.sleep(1) print('Start guessing . . .') time.sleep(0.5) # Lists of possible words to guess words = [ 'bacon', 'grass', 'flowers', 'chair', 'fruit', 'morning', 'games', 'queen', 'secret', 'funny' ] word = words[random.randint(0, len(words) - 1)] turns = 10 guesses = '' while turns > 0: # The number of letters or characters to find char_to_find = 0 for char in word: if char in guesses: print(char) else: char_to_find += 1 print('_') # When all the characters of the word are found if char_to_find == 0: print('Congratulations! You won!') print('The word we\'re looking for is: ', word + '.') break guess = input('Guess the letter: ') guesses += guess if guess not in word: turns -= 1 print('Wrong!') if turns == 0: print('Game Over. You Loose.') else: print('You have', turns, 'turn(s) left. More guesses.') main()
true
2c602e7c8e6f9862eda00e14c9959c2cb9d59336
FelipeDreissig/Prog-em-Py---CursoEmVideo
/Mundo 1/Ex006 - operacoes.py
216
4.125
4
num = int(input('Digite um número inteiro: ')) dobro = num*2 triplo = num*3 raiz = num**(1/2) print('O dobro do número é {}, o triplo do número é {} e a raiz do número é {:.2f};'.format(dobro, triplo, raiz))
false
fe74281880b4219344591d6f7e8b1dc974969565
mattthewong/cs_5_green
/hw10/Ant.py
2,671
4.6875
5
from Vector import * import random import turtle class Ant: def __init__(self, position): '''This is the "constructor" for the class. The user specifies a position of the ant which is a Vector. The ant keeps that vector as its position. In addition, the ant chooses a random color for its footstep. A color is a tuple with three numbers between 0 and 1, representing the amount of red, green, and blue in the color mixture. For example, the tuple (0.5, 0.8, 0.1) is a combination of some red, quite a bit of green, and just a touch of blue. You can get a random number between 0 and 1 using the random package using random.uniform(0, 1).''' self.position = position self.color = (random.uniform(0,1), random.uniform(0,1), random.uniform(0,1)) def __repr__(self): '''This function returns a string which represents the ant. This string can simply display the ant's x- and y- coordinates.''' return str(self.position) def moveTowards(self, otherAnt): '''This function takes as input a reference to another ant. Then, our ant "moves" towards the other ant by a step of length 1. That is, we first compute a vector from ourself (self) to the other ant, normalize it to have length 1, and then update our ant's position by adding this vector to its current position. This method doesn't display anything, it simply updates the ant's own position vector!''' distancetomove = otherAnt.position - self.position distancetomove.normalize() self.position = self.position + distancetomove def footstep(self): '''This function draws a dot in the ant's chosen color (remember, we established that color in the constructor when the ant was first "manufactured") at the ant's current location. To do this, you'll need to pickup the turtle (using turtle.penup()), move the turtle to the ant's current location (using turtle.setpos(x, y) where x and y are the desired x- and y- coordinates - which you'll need to extract from the vector that stores the ant's position), put the pen down so that the turtle can draw (using turtle.pendown()), set the turtle's drawing color (using turtle.color(c) where c represents the 3-tuple that contain's this ant's chosen drawing color), and draw a dot for the footstep (using turtle.dot()).''' turtle.penup() turtle.setpos(self.position.x,self.position.y) turtle.pendown() turtle.color(self.color) turtle.dot()
true
0f6ba572e53dc34067241b53aa7d65c72f4e1462
Mauricio1xtra/python
/basic_revisions2.py
2,903
4.125
4
""" Formatando valores com modificadores - AUlA 5 :s - Texto (strings) :d - Inteiro (int) :f - Números de ponto flutuante (float) :.(NÚMERO)f - Quantidade de casas decimais (float) :CARACTERE) (> ou < ou ^) (QUANTIDADE) (TIPO - s, d ou f) > - Esquerda < - Direita ^ - Centro """ """ num_1 = 1 print(f"{num_1:0>10}") num_2 = 2 print(f"{num_2:0^10}") print(f"{num_2:0>10.2f}") nome = "Mauricio" sobrenome = "Ferreira" print(f'{nome:#^50}') #Add cerquinha print((50-len(nome)) / 2) #subtrai 50 - qtde de caracteres da função nome e divide por 2 #Na primeira situação estamos passando o indice do sobrenome(1) nome_formatado = "{1:+^50}".format(nome, sobrenome) #{:*^50}".format(nome) ou "{n:0>20}".format(n=nome) print(nome_formatado) """ #MINIPULANDO STRINGS - AULA 6 """ *String indices *Fatiamento de strings [inicio:fim:passo] *Funções Built-in len, abs, type, print, etc... Essas funções podem ser usadas diretamente em cada tipo. """ #Positivos [012345678] texto = "Python s2" #Negativos -[987654321] nova_string = texto[2:6] #[0::2] pega o caractere do inicio ao fim, pulando 2 casas print(nova_string) """ While em Python = AULA 7 Utilizando para realizar ações enquanto uma condição for verdadeira requisitos: Entender condições e operadores """ """ x = 0 while x < 10: if x == 3: x = x + 1 continue #ou break para o loop quando a condição é verdadeira print(x) x = x + 1 print("Acabou!") """ """ x = 0 while x < 10: y = 0 print(f"({x}, { while y < 5: print(f"({x},{y})") y += 1 x += 1 # x = x + 1 print("Acabou!") """ #Calculadora while True: print() num_1 = input("Digite um número: ") num_2 = input("Digite outro número: ") operador = input("Digite um operador: ") sair = input("Deseja sair? [s]im ou [n]ão: ") if sair == "s": break if not num_1.isnumeric() or not num_2.isnumeric(): print("Você precisa digitar um número.") continue num_1 = int(num_1) num_2 = int(num_2) # + - / * if operador == "+": print(num_1 + num_2) elif operador == "-": print(num_1 - num_2) elif operador == "/": print(num_1 / num_2) elif operador == "*": print(num_1 * num_2) else: print("Operador invalido!") """WHILE / ELSE - AULA 8 Contadores Acumuladores """ #!CONTADOR contador = 0 #pode começar a partir de qualquer número, ex: contador = 50 # while contador <= 100: # print(contador) # contador += 1 #!ACUMULADOR contador_1 = 1 acumulador = 1 while contador_1 <= 10: print(contador_1, acumulador) if contador_1 > 5: break #TODO: quando colocamos o BREAK o ELSE não será executado, ele sai do bloco de código acumulador = acumulador + contador_1 contador_1 += 1 else: print("Cheguei no else.") print("Isso será executado!")
false
f74423128c8fcacbf42426d5a6d8061ad747d706
lyubomirShoylev/pythonBook
/Chapter04/ex08_herosInventory2.py
1,292
4.1875
4
# Hero's Inventory 2.0 # Demonstrates tuples # create a tuple with some items and display with a for loop inventory = ("sword", "armor", "shield", "healing potion") print("\nYour items:") for item in inventory: print(item) input("\nPress the enter key to exit.") # get the length of a tuple print(f"You have {len(inventory)} items in your possesion.") input("\nPress the enter key to exit.") # test for membership with in if "healing potion" in inventory: print("You will live another day.") input("\nPress the enter key to exit.") # display one item through an index index = int(input("\nEnter the index number for an item in inventory: ")) print(f"At index {index} is {inventory[index]}") # display a slice start = int(input("\nEnter the index number to begin a slice: ")) finish = int(input("\nEnter the index number to end a slice: ")) print(f"inventory[{start}:{finish}] is", end=" ") print(inventory[start:finish]) input("\nPress the enter key to exit.") # concatenate two tuples chest = ("gold", "gems") print("You find a chest. It contains: ") print(chest) print("You add the contents of the chest to your inventory.") inventory += chest print("Your inventory is now:") print(inventory) input("\nPress the enter key to exit.")
true
9eaf4fbd375f2f10554b93b64cddd7f6f0e8d334
lyubomirShoylev/pythonBook
/Chapter06/ch02_guessMyNumberModified.py
1,848
4.21875
4
# Guess My Number # **MODIFIED** # # The computer picks a random number between 1 and 100 # The player tries to guess it and the computer lets # the player know if the guess is too high, too low # or right on the money. In this version of the game # the player has limited amount of turns. # # MODIFICATION: # Reusing the function askNumber from Chapter06 in order to exercise # function usage and reusability import random # ask the user for a number in a certain range def askNumber(question, low, high, step = 1): """ askNumber(question, low, high[, step])\n Ask for a number within a range. Optional step is available, and the default value is 1. """ counter = 0 response = None while response not in range(low, high, step): counter += 1 response = int(input(question)) if response > theNumber: print("Lower...") elif response < theNumber: print("Higher...") return response, counter # main print("\tWelcome to 'Guess My Number'!") print("\nI'm thinking of a number between 1 and 100.") print("Try to guess it in under fifteen attempts if possible.\n") # set the inital values theNumber = random.randint(1,100) # guess = int(input("Take a guess: ")) guess = None tries = 0 # guessing loop while guess != theNumber and tries < 15: # if guess > theNumber: # print("Lower...") # else: # print("Higher...") guess, counter = askNumber("Take a guess: ", 1, 101) # guess = int(input("Take a guess: ")) tries += counter if guess == theNumber: print(f"\nYou guessed it! The number was {theNumber}") print(f"And it only took you {tries} tries!\n") else: print(f"\nYou failed! You know there is an actual strategy?") print("Anyway, better luck next time!") input("\n\nPress the enter key to exit.")
true
e550fd073b917dafc66ff71ee3455053617cd920
lyubomirShoylev/pythonBook
/Chapter04/ex05_noVowels.py
445
4.53125
5
# No Vowels # Demonstrates creating new strings with a for loop message = input("Enter a message: ") newMessage = "" VOWELS = "aeiou" print() for letter in message: # letter.lower() assures it could be from VOWELS if letter.lower() not in VOWELS: newMessage += letter print("A new string has been created:", newMessage) print("\n Your message without vowels is:", newMessage) input("\n\nPress the enter key to exit.")
true
bcb1b9acfea3e0eb1714788eee2c42d9ddb9d694
LeeroyC710/pj
/Desktop/py/YuyoITGradingSystem2.py
2,203
4.1875
4
def grading(num): #Grades the grades if num >=99: return "U. No way you could have gotten that without cheating. (A****)" elif num >=94: return "S-Class Hero ranking. All might would be proud." elif num >= 87: return "A**. Either a prodigy or a cheater." elif num >= 79: return "A*. Hard work pays off!" elif num >= 70: return "A. First class grade." elif num >= 58: return "B. You payed enough attention in class. Well done!" elif num >= 42: return "C. You have passed and can still apply to the same jobs as everyone else smarter than you!" elif num >= 28: return "D." elif num >= 17: return "E." elif num >= 11: return "F. At least you can still put it on your CV." else: return "U, which is a fail. How on Earth did you manage to do that? It's only 11% to pass!" def gradecalc(test1, test2, test3, maxgrade1, maxgrade2, maxgrade3): valid = True while valid: try: Home_Grade = float(input(test1)) Assess_Grade = float(input(test2)) Exam_Grade = float(input(test3)) if Home_Grade > maxgrade1 or Assess_Grade > maxgrade2 or Exam_Grade > maxgrade3: print("One (or more) of your grades is higher than the maximum mark") elif Home_Grade < 0 or Assess_Grade < 0 or Exam_Grade < 0: print("You can't have negative marks") else: valid = False except ValueError: print("That is not a (valid) number.") #return [Home_Grade, Assess_Grade, Exam_Grade] return { "home": Home_Grade, "assess": Assess_Grade, "exam": Exam_Grade } def thecode(): print ("Virtual report card.") first = input("First Name:") last = input("Last Name:") grades = gradecalc("Homework grade out of 25: ","Assessment grade out of 50: ","Final exam grade out of 100: ",25,50,100) score = round((grades["home"]*4*0.25 + grades["assess"]*2*0.35 + grades["exam"]*0.45), 2) grade = grading(score) print(first, last, "got a score of: " + str(score) + ", This is a grade of: " + grade) thecode()
true
124cee9a7367047f0fed2037b3997df4cfaf9399
Kamil-Ru/Functions_and_Methods_Homework
/Homework_7.py
1,384
4.46875
4
# Hard: # Write a Python function to check whether a string is pangram or not. (Assume the string passed in does not have any punctuation) # Note : Pangrams are words or sentences containing every letter of the alphabet at least once. # For example : "The quick brown fox jumps over the lazy dog" # Hint: You may want to use .replace() method to get rid of spaces. # Hint: Look at the string module # Hint: In case you want to use set comparisons ##### My Notes ''' import string alphabet=string.ascii_lowercase str1 = "The quick brown fox jumps over the lazy" str2 = str1.replace(' ','') str2 = str2.lower() str2 = set(str2) alphabet=set(string.ascii_lowercase) if alphabet.issubset(str2): print('OK') else: print('nop') ''' import string def ispangram(str1, alphabet=set(string.ascii_lowercase)): # remove any space from string, lowercase, convert too set and grab all uniques letters str2 = set(str1.replace(' ','').lower()) if alphabet.issubset(str2): print('"{}" is a pangram.'.format(str1)) else: print('"{}" is not a pangram.'.format(str1)) ## TEST ispangram("The quick brown fox jumps over the lazy dog") ispangram("The quick brown fox jumps over the lazy DOG") ispangram("The quick brown fox jumps over the lazy") ispangram("Jackdaws love my big sphinx of quartz") ispangram("Pack my box with five dozen liquor jugs")
true
95b5d44432371958fb85efcb606729590797041d
anuradhaschougale18/PythonFiles
/21st day-BinarySearchTreee.py
1,346
4.28125
4
''' Task The height of a binary search tree is the number of edges between the tree's root and its furthest leaf. You are given a pointer, root, pointing to the root of a binary search tree. Complete the getHeight function provided in your editor so that it returns the height of the binary search tree. ''' class Node: def __init__(self,data): self.right=self.left=None self.data = data class Solution: def insert(self,root,data): if root==None: return Node(data) else: if data<=root.data: cur=self.insert(root.left,data) root.left=cur else: cur=self.insert(root.right,data) root.right=cur return root def getHeight(self,root): #Write your code here if root: leftDepth = self.getHeight(root.left) rightDepth = self.getHeight(root.right) if leftDepth > rightDepth: return leftDepth + 1 else: return rightDepth + 1 else: return -1 T=int(input()) myTree=Solution() root=None for i in range(T): data=int(input()) root=myTree.insert(root,data) height=myTree.getHeight(root) print(height)
true
7ce0712c715ebc1a5eadac7d45520f3bd87bd947
jalani2727/HackerRank
/Counting_Valleys.py
770
4.1875
4
#!/bin/python3 import math import os import random import re import sys # Complete the countingValleys function below. # reverse engineer # Every time you return to sea level (n) after n has decreased, one valley has been travelled through def countingValleys(n, s): valley_counter=0 compare_to = n for letter in s: if letter == "U": compare_to += 1 if compare_to == n: valley_counter +=1 else: compare_to -= 1 return valley_counter if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) s = input() result = countingValleys(n, s) fptr.write(str(result) + '\n') fptr.close()
true
4abdbbab21357a288a4cd7f92d09393e9b15f08e
zdravkob98/Python-Advanced-September-2020
/Functions Advanced - Exercise/04. Negative vs Positive.py
421
4.21875
4
def find_biggest(numbers): positive = sum(filter(lambda x: x >= 0, numbers)) negative = sum(filter(lambda x: x <= 0, numbers)) print(negative) print(positive) if abs(positive) > abs(negative): print("The positives are stronger than the negatives") else: print("The negatives are stronger than the positives") numbers = [int(x) for x in input().split()] find_biggest(numbers)
true
01165803a5ece1682e91f49d604a47f39bdba27a
jerryeml/Python_Class
/Class_List01.py
769
4.125
4
a_tuple = (12,3,5,15,6) b_tuple = 2,4,6,7,8 a_list =[12,3,67,7,82] a_list.append(0) #添加 a_list.insert(2,11) #添加在指定位置 a_list.remove(12) #只會刪除碰到第一個12 for i in range(len(a_list)): #依照list長度分別輸出第幾個元素的value print(i,a_list[i]) print('Last element:',a_list[-1])#從最後一個開始數 #print(a_list) print('first to three element:',a_list[0:3]) print('After No.3 element:',a_list[3:]) print('Before No.3 element:',a_list[:3]) print('back:',a_list[0:-2]) print('Find index 67:',a_list.index(67)) #找67的索引 print('Count numbers:',a_list.count(0)) #計算個數 print('reverse:',a_list[::-1]) print('normal:',a_list[::1]) #排序 a_list.sort() print(a_list) a_list.sort(reverse = True) print(a_list)
false
56ed53478852a695eaab1d6b41d5c867fa48909e
LoyalSkm/Home_work_2_base
/hw2_task_3.py
1,866
4.25
4
print(''' 3. "Нарисовать" в консоли прямоугольный треугольник из символов "*", пользователь задаёт высоту и ширину(в количестве элементов). ''') print('''Задавай какую хочешь высоту, но триугольник будит пропорциональным только если высота<ширины в 2 раза ''') import numpy #позволит мне сделать список из е целых чисел while True: try: n = int(input("Высота: ")) d = float(input("Ширина: ")) break except ValueError: print("Введите Целое число") s = [n, d] bl = max(s)/min(s) #коефициент для случая когда высота больше ширины bh = min(s)/max(s) #когда ширина больше высоты max = max(s) if max%2 == 0: #условие для того чтобы сцентрировать триугольник относительно максимального значения r = int(max) else: r = int(max+1) list_L = [X for X in numpy.arange(1, d+1, bl)] #список для случая высоты больше ширины list_H = [Y for Y in numpy.arange(1, d+1, bh)] #навпакы) # print(list_L) # print(list_H) if n<=d: #Тут я делаю 1 переменную которая меняется от случая n<d и n>=d koef = list_L elif n>d: koef = list_H poz = -1 #переменная старта звёздочек for i in range(1, n+1): poz += 1 kol = int(round(koef[poz])) #типо позиция в списках list_L или list_LL print("*" * kol)
false
4e070270f812ddd28e7a7d7453cd10397b16631c
Janarbek11/ifElse
/ifelse.py
832
4.34375
4
# Написать программу которая проверит число на несколько критериев: # Чётное ли число? # Делится ли число на 3 без остатка? # Если возвести его в квадрат, больше ли оно 1000? с = int(input("Введите число: ")) if с % 2 == 0: print ("Четное число!") else: print("Нечетное число!") o = int(input("Введите число: ")) g = o % 3 if g != 0: print("Число делится на 3 с остатком = ", g) else: print("Число делится на 3 без остатка") d = int(input("Возведенеие в 2\nВведите число: ")) e = d ** 2 if e > 1000: print(e, "bolshe 1000") else: print(e, "menshe 1000")
false
9e47611cfa3d80554715e98da0f9f1c08b8331ff
tboydv1/project_python
/Python_book_exercises/chapter6/exercise_11/online_purchase.py
1,288
4.25
4
"""Suppose you are purchasing something online on the Internet. At the website, you get a 10% discount if you are a member. Additionally, you are also getting a discount of 5% on the item because its Father’s Day. Write a function that takes as input the cost of the item that you are purchasing and a Boolean variable indicating whether you are a member (or not), applies the discounts appropriately, and returns the final discounted value of the item.""" def apply_discount(): try: is_member = False item_cost_str = input("Input cost of item purchased: ") membership = input("Are you a member? [y/n]") membership = membership.lower() if membership == "y": is_member = True item_cost_float = float(item_cost_str) except ValueError as a: print(a) if is_member == False: percent = 5 / 100 * item_cost_float dicount_value = item_cost_float - percent return dicount_value elif is_member == True: percent = (15 / 100 * item_cost_float) dicount_value = item_cost_float - percent return dicount_value def main(): discount = apply_discount() print("Discounted value of item is: {}".format(discount)) if __name__ == '__main__': main()
true