blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
90ce5be2b14021e4a40e2682612c6c7fffceea5b
maryakinyi/trialgauss
/hon.py
974
4.1875
4
import math def calculate_area_of_circle(radius): area=math.pi*(radius*radius) print("%.2f" % area) calculate_area_of_circle(6) def area_of_cylinder(radius,height): area=math.pi*(radius*radius)*height print("%.2f" %area) area_of_cylinder(23,34) player_name = input("Hello, What's your name?") number_of_guesses = 0 print('Okay! ' + player_name + ' I am Guessing a number between 1 and 100') for number in range(1, 10): while number == 10: number_of_guesses = int(input()) number += 1 if number_of_guesses > number: print('Your guess is too low') elif number_of_guesses > number: print('Your guess is too high') elif number_of_guesses >= number: print("your guess is with the range") break elif number_of_guesses >= number: print('You guessed the number in ' + str(number_of_guesses) + ' tries!') else: print('You did not guess the number, The number was ' + str(number))
true
12beda910c4fcbb13e1b9094142c8140a2b47675
marwanforreal/SimpleCeaserModular
/code.py
860
4.125
4
# this is just a fun project you can use it for whatever import string import re #List Of Upper Case Letters For Cipher A = list(string.ascii_uppercase) Cipher = [] #To Decrypt Or Encrypt Flag = input("To Encrypt Enter 1 to Decrypt Enter 0: ") while(True): Key = int(input("Please Enter a Key Between 1 and 25: ")) #Verfication Of Key if(Key < 26): break #If we want to decrypt we'll need the Kbar which satisfies K + KBAR = 26 if(Flag == '0'): Key = 26 - Key S = input("Please Enter Plaintext: ") #remove spaces and special characters using regular expression CleanString = re.sub('\W+','',S) for x in range(0,len(CleanString)): temp = 0 Position = A.index(CleanString[x].upper()) Ceaser = (Position+Key) % 26 Cipher.append(A[Ceaser]) #To Decrypt You can use K-bar instead of Key and print print(''.join(Cipher))
true
d0e47a40d7dc896f2646c85ba6b70ddfc413af57
AkibSamir/FSWD_Python_Django
/third_class.py
765
4.21875
4
# Set # declaration data_set = set() print(type(data_set)) data_set2 = {1, 2, 3, 4, 5} print(data_set2, type(data_set2)) # access item # print(data_set2[1]) # Python set does not maintain indexing that's why we can't able to access any item # update item # data_set2.update(9) # typeerror: int object is not iterable # print(data_set2) data_set3 = {"apple", "mango", "orange"} print(data_set3) data_set3.add("pineapple") # it takes only one item otherwise it gives an typeerror message that set.add() takes exactly one argument (2 given) print(data_set3) data_set3.update("guava", "ginger") print(data_set3) data_set3.remove("v") print(data_set3) data_set3.discard("r") print(data_set3) data_set3.pop() print(data_set3) data_set3.clear() print(data_set3)
true
4c4beb3e71d405a3c427d55aee8c130e5f4fa851
emilybisaga1/emilybisaga2.github.io
/Hws/wordcloud.py
1,024
4.3125
4
def generate_wordcloud(text): ''' You can earn up to 10 points of extra credit by implementing this function, but you are not required to implement this function if you do not want the extra credit. To get the extra credit, this function should take as input a string and save a file to your computer called `wordcloud.png`. The word cloud should be generated using python's wordcloud library from the text input. You can find instructions on how to install and use wordcloud online at https://github.com/amueller/word_cloud ''' import os from os import path from wordcloud import WordCloud d = path.dirname(__file__) if "__file__" in locals() else os.getcwd() info = open(path.join(d, text)).read() wordcloud = WordCloud().generate(info) import matplotlib.pyplot as plt plt.imshow(wordcloud, interpolation='bilinear') plt.axis("off") wordcloud = WordCloud(max_font_size=40).generate(text) plt.figure() plt.imshow(wordcloud, interpolation="bilinear") plt.axis("off") plt.show()
true
3e44c4ef971a823812c72bf4a08a9a25b6dfbb56
ore21/PRG105
/average rainfall.py
662
4.1875
4
years = int(input("Please enter the number of years: ")) grand_total = 0 for year in range(0, years): year_total = 0 print("Year " + str(year + 1)) for months in ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec "): rainfall_inch = float(input("Enter the inches of rainfall for " + months + ": ")) year_total += rainfall_inch grand_total += rainfall_inch print("average rainfall per month is: ", format(year_total / 12)) print(" The total inches of rainfall is:", grand_total) print(" The average rainfall per month for the entire period is:", format(grand_total / (years * 12), ".2f"))
true
34d3a22fc681d55be6c4d0358f960e943dfdcf0d
ore21/PRG105
/calories by macronutrient.py
1,026
4.1875
4
"""Calories by Macronutrient""" fat_grams = float(input("enter a number of fat grams:")) carbohydrate_grams = float(input("enter a number of carbohydrate grams:")) protein_grams = float(input("enter a number of protein grams:")) def calories_from_fat(fat_grams): total = fat_grams * 9 print("calories from fat is:") print(total) calories_from_fat(fat_grams) def calories_from_carbs(carbohydrate_grams): total = carbohydrate_grams * 4 print("calories from carbohydrates is:") print(total) calories_from_carbs(carbohydrate_grams) def calories_from_proteins(protein_grams): total = protein_grams * 4 print("calories from proteins is:") print(total) calories_from_proteins(protein_grams) def calories_for_day(calories_from_fat, calories_from_carbs, calories_from_proteins): total = calories_from_fat + calories_from_carbs + calories_from_proteins print("your total calories for the day is:") print(total)
true
d4473972a201e825f635bf891f8763f128c48695
kirankumar-7/python-mini-projects
/hangman.py
496
4.125
4
import random print("Welcome to the hangman game ") word_list=["python","java","programming","coding","interview","dsa","javascript","html","css","computer"] chosen_word=random.choice(word_list) #creating a empty list display=[] word_len=len(chosen_word) for _ in range(word_len): display += "_" print(display) guess=input("Guess a letter: ").lower() for letter in chosen_word: if letter==guess: print("Right") else: print("false")
true
cbc1ae8e2cf208c50c6ea112b4b9802d1a4e2b8c
kirankumar-7/python-mini-projects
/lovecalculator.py
1,172
4.125
4
print("welcome to the love calculator! ") name1=input("What is your name? ").lower() name2=input("What is their name? ").lower() combined_name=name1+name2 t=combined_name.count("t") r=combined_name.count("r") u=combined_name.count("u") e=combined_name.count("e") true =t+r+u+e #this stores integer value l=combined_name.count("l") o=combined_name.count("o") v=combined_name.count("v") e=combined_name.count("e") love =l+o+v+e #this stores integer value '''concatenating int and int so change to string for example we get true 5 times and love 6times to get 56 we need strings here this will be a string we can't compare it it the if that is str<int gives error so wrap the string around integer ''' love_score =int(str(true)+str(love)) if (love_score<10) or(love_score>90): print(f"Your score is {love_score},you get together like coke and mentos") elif(love_score>=40) and (love_score<=50): print(f"Your score is {love_score},you are alright together ") else: print(f"Your score is{love_score}")
true
f931a44604fa5cb283be4c7c904a7795aa38a03e
Gyanesh-Mahto/Practice-Python
/string/index_rindex.py
1,716
4.53125
5
# index() method is also used to find substring from main string from left to right(begin to end). # It returs as follows: # If substring is found then index() method returns index of first occurance of substring # But if substring is not found in main string then index() will generate ValueError instead of -1 as compared to find(). print("============="*5) print("Example - 1") s='ABCBA' print(s) print(s.index('B')) #1 #print(s.index('F')) #ValueError # rindex() method is also used to find substring from main string from right to left(end to begin). # It returs as follows: # If substring is found then index() method returns index of first occurance of substring from right to left. # But if substring is not found in main string then index() will generate ValueError instead of -1 as compared to find(). print("============="*5) print("Example - 2") s='ABCBA' print(s) print(s.rindex('B')) #3 #print(s.rindex('F')) #ValueError print("============="*5) print("Example - 3: Mail ID example") mail=input("Please enter valid mail id: ") try: i=mail.index('@') print("You have entered valid mail id.") except ValueError: print("You have entered invalid mail id. Please use '@' for mail id") # If we want to search substring in given boundary index, then we can use index() methods as follows: # index(substring, begin, end) # substring is our given substring for searching # This method will search from begin index to end-1 index print("============="*5) print("Example - 4") s='ABCDEFGHIJBM' print(s) #print(s.index('B',3,8)) #ValueError print(s.index('B',1,8)) #1 print(s.rindex('B',3,11)) #10 #print(s.rindex('B',3,8)) #ValueError print(s.index('BCD',1,8)) #1 print(s.index('BCD',1,1000)) #1
true
0b3776767151ffba5e60fcb171a332e586dcef53
Gyanesh-Mahto/Practice-Python
/control_flow/if_elif_else.py
327
4.28125
4
''' if-elif-else syntax: if condition-1: Action-1 elif condition-2: Action-2 elif condition-3: Action-3 - - - else: default action ''' num=int(input("Please enter any number: ")) if num>0 and num%2==0: print("Even") elif num>0 and num%2!=0: print("Odd") else: print('Number is negative or zero')
false
a85a63008d812d2ed0cc260ec38a209493227b60
Gyanesh-Mahto/Practice-Python
/control_flow/biggest_smallest_num_3_input.py
448
4.4375
4
#WAP to find biggest of 3 given numbers num1=int(input('Please enter your first number: ')) num2=int(input('Please enter your second number: ')) num3=int(input('Please enter your third number: ')) if num1>num2 and num1>num3: print('{} is greater'.format(num1)) elif num2>num1 and num2>num3: print('{} is greater'.format(num2)) elif num3>num1 and num3>num2: print('{} is greater'.format(num3)) else: print('All numbers are equal')
true
4717626688d17378fba8cb068262cc886b126904
greenca/checkio
/three-points-circle.py
1,529
4.4375
4
# You should find the circle for three given points, such that the # circle lies through these point and return the result as a string with # the equation of the circle. In a Cartesian coordinate system (with an # X and Y axis), the circle with central coordinates of (x0,y0) and # radius of r can be described with the following equation: # "(x-x0)^2+(y-y0)^2=r^2" # where x0,y0,r are decimal numbers rounded to two decimal # points. Remove extraneous zeros and all decimal points, they are not # necessary. For rounding, use the standard mathematical rules. # Input: Coordinates as a string.. # Output: The equation of the circle as a string. # Precondition: All three given points do not lie on one line. # 0 < xi, yi, r < 10 import math def checkio(data): x1, y1, x2, y2, x3, y3 = map(float, data.replace('(','').replace(')','').split(',')) if y1 == y3: x3, x2 = x2, x3 y3, y2 = y2, y3 c1 = (x1**2 - x3**2 + y1**2 - y3**2)/(2*(y1 - y3)) c2 = (x3 - x1)/(y1 - y3) x0 = (y2**2 - y1**2 + x2**2 - x1**2 + 2*(y1 - y2)*c1)/(2*(x2 - x1) + 2*(y2 - y1)*c2) y0 = c1 + c2*x0 r = math.sqrt((x1 - x0)**2 + (y1 - y0)**2) x0 = round(x0, 2) y0 = round(y0, 2) r = round(r, 2) return "(x-%g)^2+(y-%g)^2=%g^2" % (x0, y0, r) #These "asserts" using only for self-checking and not necessary for auto-testing if __name__ == '__main__': assert checkio(u"(2,2),(6,2),(2,6)") == "(x-4)^2+(y-4)^2=2.83^2" assert checkio(u"(3,7),(6,9),(9,7)") == "(x-6)^2+(y-5.75)^2=3.25^2"
true
e2b49d23784a27bb16540c7b7665694dbc0f406b
greenca/checkio
/most-wanted-letter.py
1,671
4.1875
4
# You are given a text, which contains different english letters and # punctuation symbols. You should find the most frequent letter in the # text. The letter returned must be in lower case. # While checking for the most wanted letter, casing does not matter, so # for the purpose of your search, "A" == "a". Make sure you do not count # punctuation symbols, digits and whitespaces, only letters. # If you have two or more letters with the same frequency, then return # the letter which comes first in the latin alphabet. For example -- # "one" contains "o", "n", "e" only once for each, thus we choose "e". # Input: A text for analysis as a string (unicode for py2.7). # Output: The most frequent letter in lower case as a string. # Precondition: # A text contains only ASCII symbols. # 0 < len(text) ≤ 105 def checkio(text): letters = 'abcdefghijklmnopqrstuvwxyz' letter_counts = [] for letter in letters: letter_counts.append(text.lower().count(letter)) max_count = max(letter_counts) return letters[letter_counts.index(max_count)] if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing assert checkio(u"Hello World!") == "l", "Hello test" assert checkio(u"How do you do?") == "o", "O is most wanted" assert checkio(u"One") == "e", "All letter only once." assert checkio(u"Oops!") == "o", "Don't forget about lower case." assert checkio(u"AAaooo!!!!") == "a", "Only letters." assert checkio(u"abe") == "a", "The First." print("Start the long test") assert checkio(u"a" * 9000 + u"b" * 1000) == "a", "Long." print("The local tests are done.")
true
17f9605c4bbde3c512d322f9fc0f52ac05b47b30
angrajlatake/codeacademyprojects
/Scrabble dictonary project.py
2,817
4.1875
4
'''In this project, you will process some data from a group of friends playing scrabble. You will use dictionaries to organize players, words, and points. There are many ways you can extend this project on your own if you finish and want to get more practice!''' letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] points = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 4, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10] #We have provided you with two lists, letters and points. We would like to combine these two into a dictionary that would map a letter to its point value. #Using a list comprehension and zip, create a dictionary called letter_to_points that has the elements of letters as the keys and the elements of points as the values. lettrs_to_points = {key:value for key, value in zip(letters,points)} #Our letters list did not take into account blank tiles. Add an element to the letter_to_points dictionary that has a key of " " and a point value of 0. lettrs_to_points[" "] = 0 #We want to create a function that will take in a word and return how many points that word is worth. #Define a function called score_word that takes in a parameter word. #Inside score_word, create a variable called point_total and set it to 0. def score_word(word): points_total = 0 for char in word: points_total += lettrs_to_points.get(char, 0) return points_total #Create a dictionary called player_to_words that maps players to a list of the words they have played. This table represents the data to transcribe into your dictionary: player_to_word = {"player1" : ["BLUE, TENNIS, EXIT"], "wordNerd" : ["EARTH", "EYES", "MACHINE"], "Lexi Con" : ["ERASER", "BELLY", "HUSKY"], "Prof Reader" : ["ZAP", "COMA", "PERIOD"]} #Create an empty dictionary called player_to_points. player_to_point = {} #player_to_points should now contain the mapping of players to how many points they’ve scored. Print this out to see the current standings for this game! #If you’ve calculated correctly, wordNerd should be winning by 1 point. def update_total_score() : for player, words in player_to_word.items(): player_points = 0 for word in words: player_points += score_word(word) player_to_point[player] = player_points update_total_score() print(player_to_point) # give option to enter the words and add it to the directory. Once the word is added update the score. #every player will get 2 chances count = 0 while count != 2 : for player, word in player_to_word.items(): word =input(player +" Please enter your word :") player_to_word[player].append(word.upper()) update_total_score() print(player_to_point) count+=1 print(player_to_word)
true
f9fd421e081da8c9617af08604ce70228a8318fa
aj112358/python_practice
/(1)_The_Python_Workbook/DICTIONARIES/unique_characters.py
821
4.5625
5
# This program determines the number of unique characters in a string. # Created By: AJ Singh # Date: Jan 8, 2021 from pprint import pprint # Places characters of string into a dictionary to count them. # @param string: String to count characters for. # @return: Dictionary of character counts. def check_unique(string: str) -> dict: """Determine unique characters.""" characters = {} for char in string: if char in characters: characters[char] += 1 else: characters[char] = 1 return characters def main(): user_string = input("Enter a string to analyze: ") result = check_unique(user_string) print("Here are the unique characters in your string, along with their frequency:") pprint(result, width=1) if __name__ == '__main__': main()
true
f7116009a799a92e16f1434c4c5d7f30c26f8737
aj112358/python_practice
/(1)_The_Python_Workbook/LISTS/infix_to_postfix.py
1,751
4.25
4
# This program converts a list of tokens representing a mathematical expression, and # converts it from infix form to postfix form. # Created By: AJ Singh # Date: Jan 7, 2021 from tokenizing_strings import tokenize, identify_unary from string_is_integer import is_integer from operator_precedence import precedence OPERATORS = list("+-*/^") + ['u+', 'u-'] # Converts tokens of a math expression from infix form to postfix form. # @param infix: List of tokens for a math expression. # @return: List of tokens in postfix form. def to_postfix(infix: list) -> list: """Convert a list of mathematical tokens to postfix form.""" operators = [] postfix = [] for token in infix: if is_integer(token): postfix.append(token) if token in OPERATORS: while len(operators) > 0 and \ operators[-1] != "(" and \ precedence(token) < precedence(operators[-1]): item = operators.pop() postfix.append(item) operators.append(token) if token == "(": operators.append(token) if token == ")": while operators[-1] != "(": item = operators.pop() postfix.append(item) operators.pop() while len(operators) > 0: item = operators.pop() postfix.append(item) return postfix def main(): math_exp = input("Enter a basic mathematical expression:\n") tokens = tokenize(math_exp) tokens = identify_unary(tokens) print("\nThe tokens are:") print(tokens) tokens_postfix = to_postfix(tokens) print("\nThe tokens in postfix form are:") print(tokens_postfix) if __name__ == '__main__': main()
true
4a304cfabcd09a9e64f518ebe06c97de188c2321
aj112358/python_practice
/(1)_The_Python_Workbook/FILES_EXCEPTIONS/letter_frequency.py
948
4.3125
4
# Exercise 154: Letter Frequency Analysis. from string import ascii_uppercase from string import punctuation from string import digits import sys if len(sys.argv[1]) < 2: print("Input file needed.") quit() def open_file(): try: file = open(sys.argv[1], mode="r") return file except FileNotFoundError: print("Unable to open file.") # Determine frequency of letters. def letter_frequency(words): freq = {} for word in words: for char in word: if char in list(punctuation) or char in list(digits): continue if char.upper() in freq: freq[char.upper()] += 1 else: freq[char.upper()] = 1 return freq def main(): file_obj = open_file() words = file_obj.read().split() file_obj.close() freq = letter_frequency(words) for k, v in freq.items(): print(f"{k}:{v}") main()
true
d150af4735c935c4007f9ed797656fd39b26650f
aj112358/python_practice
/(1)_The_Python_Workbook/FUNCTIONS/string_is_integer.py
683
4.5
4
# This program determines if a string is an integer, and takes the sign into account. # Created By: AJ Singh # Date: Jan 7, 2021 # Check if a string represents a valid integer # @param num: String to check. # @return: Boolean value. def is_integer(num: str) -> bool: """Determine if a string represents a valid positive or negative integer.""" num = num.strip() if len(num) == 0: return False if num.isdigit(): return True if num[0] in ('+', '-'): return num[1:].isdigit() return False def main(): n = input("Enter a string to check if it's a valid integer: ") print(is_integer(n)) if __name__ == '__main__': main()
true
6f112b3d3d079773fea42c67408b770b8b239cbc
aj112358/python_practice
/(1)_The_Python_Workbook/LISTS/proper_divisors.py
739
4.625
5
### This program compute the list of proper divisors of an integer # Created By: AJ Singh # Date: Jan 6, 2021 from math import sqrt, floor # This function computes the divisors of an integer # @param n: Input to factor. # @return: List of divisors. def divisors(n: int) -> list: """Compute all the (positive) divisors of an integer.""" factors = [] for i in range(1, floor(sqrt(n))+1): if n % i == 0: factors.append(i) if i**2 != n: factors.append(int(n/i)) factors.sort() return factors def main(): n = int(input("What integer do you want to factor? ")) factors = divisors(n) print("The factors are: ", factors) if __name__ == '__main__': main()
true
ff2b2ad084e8ce4f0ffe6484ce87094f68b9db12
aj112358/python_practice
/(1)_The_Python_Workbook/LISTS/evaluate_postfix_expr.py
1,503
4.4375
4
# This programs evaluates a basic mathematical expression, given via tokens in postfix form. # Created By: AJ Singh # Date: Jan 7, 2021 from tokenizing_strings import tokenize, identify_unary from infix_to_postfix import to_postfix OPERATORS = list("+-*/^") # Evaluates a postfix expression, given the tokens. # @param tokens: List of tokens representing math expression. # @return: Answer to original math expression. def evaluate_postfix(postfix: list) -> float: """Evaluates tokens in a postfix mathematical expression.""" values = [] for token in postfix: if token.isdigit(): values.append(int(token)) elif token == "u-": item = values.pop() values.append(-int(item)) elif token in OPERATORS: right = values.pop() left = values.pop() if token == "^": token = "**" math = str(left) + token + str(right) value = eval(math) values.append(value) return values[0] def main(): math_exp = input("Enter a basic mathematical expression you wish to evaluate:\n") tokens = tokenize(math_exp) tokens = identify_unary(tokens) # print("\nThe tokens are:") # print(tokens) tokens_postfix = to_postfix(tokens) # print("\nThe tokens in postfix form are:") # print(tokens_postfix) answer = evaluate_postfix(tokens_postfix) print("\nThe answer is:", answer) if __name__ == '__main__': main()
true
01c9bb23ef18c66e2eb631571534669e073ae0c8
oddduckden/lesson3
/task1.py
1,242
4.15625
4
# 1. Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление. Числа запрашивать у # пользователя, предусмотреть обработку ситуации деления на ноль. def division_func(): ''' Функция деления двух введенных чисел первое на второе :return: None ''' while True: try: num = input('Введите два числа через запятую: ').replace(' ', '').split(',') print(f'Результат деления первого на второе: {float(num[0]) / float(num[1])}') except ZeroDivisionError: print('Извините, деление на ноль недопустимо') except ValueError: print('Нужно было вводить числа') except IndexError: print('Нужно было ввести два числа') else: if input('Повторим?(Y/N): ') == 'N': break finally: print('\n') return division_func()
false
02974eec581d9a28f995a6b187f13bfd7a272664
ricaenriquez/intro_to_ds
/project_3/other_linear_regressions/advanced_linear_regressions.py
2,740
4.59375
5
import numpy as np import pandas as pd import statsmodels.api as sm """ In this optional exercise, you should complete the function called predictions(turnstile_weather). This function takes in our pandas turnstile weather dataframe, and returns a set of predicted ridership values, based on the other information in the dataframe. You should attempt to implement another type of linear regression, that you may have read about, such as ordinary least squares regression: http://en.wikipedia.org/wiki/Ordinary_least_squares This is your playground. Go wild! How does your choice of linear regression compare to linear regression with gradient descent? You can look at the information contained in the turnstile_weather dataframe below: https://www.dropbox.com/s/meyki2wl9xfa7yk/turnstile_data_master_with_weather.csv Note: due to the memory and CPU limitation of our amazon EC2 instance, we will give you a random subset (~15%) of the data contained in turnstile_data_master_with_weather.csv If you receive a "server has encountered an error" message, that means you are hitting the 30 second limit that's placed on running your program. See if you can optimize your code so it runs faster. """ def normalize_features(array): """ Normalize the features in our data set. """ array_normalized = (array-array.mean())/array.std() mu = array.mean() sigma = array.std() return array_normalized, mu, sigma def predictions(weather_turnstile): # # Your implementation goes here. Feel free to write additional # helper functions # dummy_units = pd.get_dummies(weather_turnstile['UNIT'], prefix='unit') features = weather_turnstile[['rain', 'precipi', 'Hour', 'meantempi']].join(dummy_units) values = weather_turnstile[['ENTRIESn_hourly']] m = len(values) features, mu, sigma = normalize_features(features) features['ones'] = np.ones(m) features_array = np.array(features) values_array = np.array(values).flatten() # Fit a OLS model with intercept on TV and Radio features_array = sm.add_constant(features_array) olsres = sm.OLS(values_array, features_array).fit() prediction = olsres.predict(features_array) return prediction def compute_r_squared(data, predictions): SST = ((data-np.mean(data))**2).sum() SSReg = ((predictions-np.mean(data))**2).sum() r_squared = SSReg / SST return r_squared if __name__ == "__main__": input_filename = "turnstile_data_master_with_weather.csv" turnstile_master = pd.read_csv(input_filename) predicted_values = predictions(turnstile_master) r_squared = compute_r_squared(turnstile_master['ENTRIESn_hourly'], predicted_values) print predicted_values print r_squared
true
45362e23912a3f3fae4021f27f5983875cf64aaf
DonNinja/111-PROG-Assignment-5
/max_int.py
610
4.59375
5
num_int = int(input("Input a number: ")) # Do not change this line # Fill in the missing code max_int = 0 while num_int > 0: if num_int > max_int: max_int = num_int num_int = int(input("Input a number: ")) print("The maximum is", max_int) # Do not change this line # First we have to take in number # Then it runs until a negative number is written into the input # If it sees that the number the user inputs is bigger than the current max_int then it sets max_int as the inputted number # When the user inputs a negative number then it prints out the largest number that was inputted
true
92fb6e42ffea61173e20c30d7541d68501156ef7
cyber-holmes/temperature_conversion_python
/temp.py
333
4.5
4
#Goal:Convert the given temperature from Celsius to Farenheit. #Step1:Take the user-input on temperature the user wish to convert. cel= input("Enter your temperature in Celsius ") #Step2:Calculate the conversion using formula (celsius*1.8)+32 far = (cel*1.8)+32 #Step3:Print the output. print ("It is {} Farenheit".format(far))
true
8f6ca9ea53f6cfad80afb24783e381e78e0c595d
Youngjun-Kim-02/ICS3U-Unit6-03-python
/smallest_number.py
852
4.21875
4
#!/usr/bin/env python3 # Created by: Youngjun Kim # Created on: June 2021 # This program uses a list as a parameter import random def find_smallest_number(random_numbers): Smallest_number = random_numbers[0] for counter in random_numbers: if Smallest_number > counter: Smallest_number = counter return Smallest_number def main(): # this function uses a list random_numbers = [] # input for loop_counter in range(1, 11): a_number = random.randint(1, 100) random_numbers.append(a_number) print("The random number {0} is: {1} ".format(loop_counter, a_number)) print("") # call the function Smallest_number = find_smallest_number(random_numbers) # output print("The smallest number is: {0} ".format(Smallest_number)) if __name__ == "__main__": main()
true
92beb7b2e2a8e8819ff0d48605a174b899a37b18
paulthomas2107/TKinterStuff
/entry.py
388
4.21875
4
from tkinter import * root = Tk() e = Entry(root, width=50, bg="blue", fg="white", borderwidth=5) e.pack() e.insert(0, "Enter your name: ") def myClick(): hello = "Hello " + e.get() my_label = Label(root, text=hello) my_label.pack() myButton = Button(root, text="Enter name", padx=50, pady=50, command=myClick, fg="green", bg="#eeeeee") myButton.pack() root.mainloop()
true
5b3e1e1e415cddbc0eccf6358731a28a31025bc9
darren11992/think-Python-homework
/Chapter 9/Exercise9-3.py
924
4.125
4
"""Write a function named avoids that takes a word and a string of forbidden letters and returns True if the word doesn't use any of the forbidden letters. Modify the program to prompt the user to enter a string of forbidden letters and then print the number of words that don't contain any of them. Can you find a combination of five forbidden letters that excludes the smallest number of words?""" def avoids(word, letters): # letters are characters that are to be avoided for letter in letters: if letter in word: return False return True def avoided_words(): fin = open('words.txt') forbidden_input = input("Enter the letters you want to be forbidden:") forbidden_letters = forbidden_input.replace(" ", "") total = 0 for line in fin: if avoids(line, forbidden_letters): total += 1 print(total) avoided_words()
true
1e015d5e59880d86ebf92721884242b31393bf0e
darren11992/think-Python-homework
/Chapter 7/exercise7-1.py
1,058
4.21875
4
"""Copy the loop from "Square roots" on page 79 and encapsulate it in a function called mysqrt that takes a as a parameter, chooses a reasonable value of x, and returns an estimate of the square root of a. To test it, write a function named "test_square_root that prints a table like this: First column: a number, a. Second column: a's square root, computed with my_sqrt. Third column: a's square root, computed with math.sqrt. Fourth column: the difference between the two square roots. """ import math def mysqrt(a): x = a - .05 while True: y = (x + a/x) / 2 #print(abs(y-x)) if abs(y-x)< 0.0000001: break x = y return y def test_square_root(): print("a mysqrt(a) math.sqrt() diff") print("- --------- ----------- ----") a = 1 while a < 10: print(a, mysqrt(a),math.sqrt(a), max(mysqrt(a), math.sqrt(a)) - min(mysqrt(a), math.sqrt(a))) a += 1 #Note: This produces a shit table. test_square_root()
true
2d5540b41a118e786295696f6914076900f3d2d8
darren11992/think-Python-homework
/Chapter 10/Exercise 10-3.py
406
4.125
4
"""Write a function called middle that takes a list and returns a new list that contains all but the first and last elements. For example: >>> t = [1, 2, 3, 4] >>> middle(t) >>> [2, 3]""" def middle(t): new_t = t[:] # new_t = t will use the same reference for both lists del new_t[0] del new_t[len(new_t)-1] return new_t print(middle([1, 2, 3, 4, 5, 6]))
true
4b6588e9bfbadac7f21f380fa94f1a7de79ad444
darren11992/think-Python-homework
/Chapter 9/Exercise9-9.py
2,279
4.15625
4
"""Here's another car talk Puzzler you can solve with a search; "Recently I had a visit with my mum and we realised that the two digits that make up my age reversed resulted in her age. For example, if she's 73, I'm 37. We wondered how often this has happened over the years but we got sidetracted with other topics and we never came up with the answer. When I got home I figured out that the digits of our ages have been reversible six times so far. I also figured out that if we're lucky it would happen again in a few years, and if we're really lucky it would happen one more time after that. In other words, it would happen 8 times overall. So the question is, how old am I now?" Write a python program that searches fir solutions to this puzzler. Hint: you might find the string method zfill useful""" def is_opposite(first, second): """checks if a number reversed is the other number""" no1 = str(first) no2 = str(second) if no1[:] == no2[2::-1]: return True else: return False def main(): elder_ages = list(range(18, 100)) younger_ages = list(range(0, 100)) possible_ages = [] for young_age in younger_ages: print(young_age, ":") for old_age in elder_ages: original_young_age = young_age original_old_age = old_age total = 0 while old_age < 100: if is_opposite(old_age, young_age): total += 1 old_age += 1 young_age += 1 if total > 0: print(total, original_young_age, original_old_age) #if total == 8: #possible_ages.append(original_age) return possible_ages """possible_ages = [] for age in elder_ages: younger_age = age - 18 #if younger_age < 0: #pass #else: total = 0 while age < 100: original_age = younger_age if is_opposite(age, younger_age): total += 1 age += 1 younger_age += 1 if total == 8: possible_ages.append(original_age) return possible_ages """ print(main())
true
0b6a86223916b8161c66054f5eb03afcbf301b4e
darren11992/think-Python-homework
/Chapter 8/notes8.py
1,379
4.25
4
""" - Strings are sequences of characters. - The bracket operator allows you to select individual characters in a string: eg: fruit = 'banana' letter = fruit[2] --> 'n' Note: string indexs begin at 0. -The len() function returns the length of a string. The final index of a string is always its length -1. - A traversal is going over each character in a loop iteratively, usually done with a while loop. - The bracket operator also allow you to 'splice' strings; Eg: fruit[:3]---> 'ban' fruit[3:]---> 'ana' In general: string[n:m]--> produce a string from the nth to the character before the mth term. - Strings are immutable, meaning an existing string cannot be changed. Eg: string = "Hello, World" string[0] = 'h' ---> will produce a TypeError. The best you can do is create a new string thats a varient. new_string = 'J' + string[1:] print(new_string)----> 'Jello, World' - Strings have several methods like .upper() or .find(). They use dot notation, with the strings name going behind the dot. Eg: fruit.upper()----> 'BANANA' fruit.find('a')---- returns '1' (index of first 'a') - The in operator returns a boolean value if the string to the left of it is a substring of the one to its right. Eg: 'a' in 'banana'---> True 'c' in 'banana' --> False """
true
b6876e179285f7578c42538e73a0f5587fa46960
chenxi-zhao/various_tools
/python_tools/_basic/dictionary.py
1,208
4.125
4
# coding=utf-8 __author__ = 'TracyZro' # Python 字典(Dictionary) # 访问字典里的值 mydict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} print("dict['Name']: ", mydict['Name']) print("dict['Age']: ", mydict['Age']) # 修改字典 mydict['Age'] = 8 # update existing entry mydict['School'] = "DPS School" # Add new entry print('mydic:', mydict) # 删除字典元素 # 字典值可以没有限制地取任何python对象,既可以是标准的对象,也可以是用户定义的,但键不行 del mydict['Name'] # 删除键是'Name'的条目 mydict.clear() # 清空词典所有条目 # 字典内置函数&方法 # http://www.runoob.com/python/python-dictionary.html dict1 = {'Name': 'Zara', 'Age': 7} dict2 = {'Name': 'Mahnaz', 'Age': 27} print(len(dict1)) # 计算字典元素个数,即键的总数。 print(str(dict2)) # 输出字典可打印的字符串表示 print(type(dict1)) # 返回输入的变量类型,如果变量是字典就返回字典类型。 dict3 = dict1.copy() # 返回一个字典的浅复制 dict1.clear() # 删除所有元素 print(dict3.get('Name', 'defalut = None')) # 返回指定键的值,如果值不在字典中返回default值 print(dict3.keys())
false
53d4055fd07e0b4477fad07281d3c8af223e90d3
yura702007/algorithms
/quick_sort.py
453
4.15625
4
def quick_sort(arr): if len(arr) < 2: return arr pivot = arr[0] left_arr, middle_arr, right_arr = [], [], [] for i in arr: if i < pivot: left_arr.append(i) elif i == pivot: middle_arr.append(i) else: right_arr.append(i) return quick_sort(left_arr) + middle_arr + quick_sort(right_arr) if __name__ == '__main__': array = [5, 2, 9] print(quick_sort(array))
false
018e5b31a3717d11a37460be83c42d97ff4b673b
Jagadeshwaran-D/Python_pattern_programs
/simple_reverse_pyramid.py
291
4.25
4
""" python program for simple reverse pyramid * * * * * * * * * * * * * * * """ ### get input from the user row=int(input("enter the row")) ##logic for print the pattern for i in range(row+1,0,-1): for j in range(0,i-1): print("* " ,end="") print()
true
f639317fbaab1d84ef7bbc939185c52ddeabd531
AbilashC13/module1-practice-problems-infytq
/problem05.py
715
4.15625
4
#PF-Prac-5 ''' Write a python function which accepts a sentence and finds the number of letters and digits in the sentence. It should return a list in which the first value should be letter count and second value should be digit count. Ignore the spaces or any other special character in the sentence. ''' def count_digits_letters(sentence): #start writing your code here c1=0 c2=0 result_list=[] for i in sentence: if((i>="a" and i<="z") or (i>="A" and i<="Z")): c1+=1 if(i>="0" and i<="9"): c2+=1 result_list.append(c1) result_list.append(c2) return result_list sentence="Infosys Mysore 570027" print(count_digits_letters(sentence))
true
75115dbfa45590ecebc885a7fcc2f6637ea5e281
Midhun10/LuminarPython
/Luminar_Python/exceptionHandling/except.py
451
4.21875
4
num1=int(input("Enter num1")) num2=int(input("Enter num2")) # res=num1/num2#exception can be raised in this code. # print(res) try: res=num1/num2 print(res) except Exception as e:#Exception is a class in the # print("exception occured") print("Error:",e.args) finally: print("Printing finally") # if(age<18): # raise Exception("invalid Age") used for raiseing custom exception or userdefined # else: # print("U can vote")
true
ae0c5498a64706c510bdad26b28d32c3b1ee121c
drewgoodman/Python-Exercises
/birthday_lookup.py
1,305
4.53125
5
# keep track of when our friend’s birthdays are, and be able to find that information based on their name. Create a dictionary (in your file) of names and birthdays. When you run your program it should ask the user to enter a name, and return the birthday of that person back to them. The interaction should look something like this: # Welcome to the birthday dictionary. We know the birthdays of: # Albert Einstein # Benjamin Franklin # Ada Lovelace # >> Who's birthday do you want to look up? # Benjamin Franklin # >> Benjamin Franklin's birthday is 01/17/1706. import sys birthday_data = { 'Albert Einstein' : (3, 14, 1879), 'Benjamin Franklin' : (1, 17, 1706), 'Ada Lovelace' : (12, 10, 1815) } print("Welcome to the birthday dictionary. We know the birthdays of:") names_list = sorted(list(birthday_data.keys())) for j in names_list: print(j) query = input("\n >> Whose birthday do you want to look up?: ").strip().title() while query not in birthday_data: if query == "": print("\nGoodbye!") sys.exit() else: query = input("\n >> Not available. Try another name?: ").strip().title() else: month, day, year = birthday_data[query] if month < 10: month = "0" + str(month) if day < 10: day = "0" + str(day) input(f"\t >> {query}'s birthday is {month}/{day}/{year}. Press ENTER to exit: ")
true
92faf865a1991fb85273660d92adfc06048808a3
willgood1986/myweb
/pydir/listgen.py
282
4.25
4
# -*- coding: utf-8 -*- print("List generate: [x for x in 'abc']") print([ x + "&" + y for x in 'ABC' for y in '123']) print("list-generator operates on list") datas = {'a':1, 'b':2, 'c':3} print("Get data[key, val] from dict use dict.items") print([y+2 for x, y in datas.items()])
false
f941240d58c731e5307c76b1a36c01174a70fa62
guilhermebaos/Other-Programs
/Modules/my_inputs/__init__.py
2,256
4.28125
4
# Manter Ordem Alfabética def inputfloat(string='Escreva um número: ', error='ERRO! Escreva um número válido!\n', show_error=False, change_commas=True, default=0): """ :param string: Input text :param error: Error message for non-float input :param show_error: Show what caused the error :param change_commas: Change commas in numbers to dots :param default: Default value for input :return: The float entered by the user """ while True: n = input(string).strip() if change_commas: n = n.replace(',', '.') try: n = float(n) return n except ValueError as erro: if n == '' and default != 0: return default else: if show_error: erro = str(erro).capitalize() print(f'{error}{erro}\n') else: print(f'{error}\n') def inputint(string='Escreva um número inteiro: ', error='ERRO! Escreva um número inteiro válido!\n', show_error=False, default=0) -> int: """ :param string: Input text :param error: Error message for non-interger input :param show_error: Show what caused the error :param default: Default value for input :return: The interger entered by the user """ while True: n = input(string).strip() try: n = int(n) return n except ValueError as erro: if n == '': return default else: if show_error: erro = str(erro).capitalize() print(f'{error}{erro}\n') else: print(f'{erro}\n') def inputthis(question='-> ', expected_tuple=('Y', 'N'), error='ERRO! Resposta inesperada!'): """ :param question: Input text :param expected_tuple: Tuple containing all the options from wich the user should choose from :param error: Error message for when the input isn't cointained in the tuple :return: The user's answer """ while True: x = str(input(question)).strip() if x in expected_tuple: return x else: print(error, '\n')
false
cd379021d642213e5d3879485d53610283277e09
robbyorsag/pands-problem-set
/solution-9.py
360
4.3125
4
# Solution to problem 9 # Open the file moby-dick.txt for reading and mark as "f" with open('moby-dick.txt', 'r') as f: count = 0 # set counter to zero for line in f: # for every line in the file count+=1 # count +1 if count % 2 == 0: # if the remainder is 0 print(line) # print line where the remainder is 0
true
89279b55447199014c2fb78fce1f538f09095cc0
taisonmachado/Python
/Lista de Exercicios - Wiki_python/Estrutura de Decisao/18.py
358
4.25
4
#Faça um Programa que peça uma data no formato dd/mm/aaaa e determine se a mesma é uma data válida.) data = input("Digite uma data no formato dd/mm/aaaa: ") data = data.split('/') dia = int(data[0]) mes = int(data[1]) ano = int(data[2]) if(dia>0 and dia<=31 and mes>0 and mes<=12 and ano>0): print("Data válida") else: print("Data inválida")
false
39de0b3527cff7a7638b6b0381781f92a63e1015
taisonmachado/Python
/Lista de Exercicios - Wiki_python/Estrutura Sequencial/06.py
242
4.15625
4
# Faça um Programa que peça o raio de um círculo, calcule e mostre sua área. import math raio = int(input("Digite o raio do círculo: ")) area = math.pow(raio, 2) * math.pi print("Area: ", area) input("Pressione Enter para continuar")
false
bfc4b237e97584616ff6ff0f25ba95fdb38852d2
taisonmachado/Python
/Lista de Exercicios - Wiki_python/Estrutura de Repetição/10.py
293
4.1875
4
#Faça um programa que receba dois números inteiros e gere os números inteiros que estão no #intervalo compreendido por eles. print("Informe dois números: ") num1 = int(input()) num2 = int(input()) print("\nIntervalo entre os dois números: ") for i in range(num1+1, num2): print(i)
false
e35ad11469ddc5af286489ccb6724ee80113cac7
311210666/Taller-de-Herramientas-Computacionales
/Clases/Programas/Práctica/problema6.py
302
4.15625
4
#!usr/bin/python2.7 # -*- coding: utf-8 -*- '''Implemente una función recursiva que calcule n! = n * (n-1) * (n-2) * …* 2 * 1''' def Factorial (n): if n == 1: return 1 else: if n == 2: return n * (n-1) else: return n * Factorial (n-1)
false
959982a60351e59343506654ebd3853590f9d82a
devsetgo/devsetgo_lib
/examples/cal_example.py
681
4.15625
4
# -*- coding: utf-8 -*- from dsg_lib.calendar_functions import get_month, get_month_number month_list: list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] month_names: list = [ "january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december", "bob", ] def calendar_check_number(): for i in month_list: month = get_month(month=i) print(month) def calendar_check_name(): for i in month_names: month = get_month_number(month_name=i) print(month) if __name__ == "__main__": calendar_check_number() calendar_check_name()
false
e67a95bace31db0b3aed7329da33e8bccd2457e4
evidawei/Hacktoberfest2021-2
/Python/Queue using Stacks.py
604
4.3125
4
# Python3 program to implement Queue using # two stacks with costly enQueue() class Queue: def __init__(self): self.s1 = [] self.s2 = [] def enQueue(self, x): while len(self.s1) != 0: self.s2.append(self.s1[-1]) self.s1.pop() self.s1.append(x) while len(self.s2) != 0: self.s1.append(self.s2[-1]) self.s2.pop() def deQueue(self): if len(self.s1) == 0: print("Q is Empty") x = self.s1[-1] self.s1.pop() return x if __name__ == '__main__': q = Queue() q.enQueue(1) q.enQueue(2) q.enQueue(3) print(q.deQueue()) print(q.deQueue()) print(q.deQueue())
false
f343e54fdbb35885b1e610287d556abcc5f70f5c
tsar0720/HW_python
/HW11.py
1,218
4.34375
4
""" Напишите функцию letters_range, которая ведет себя похожим на range образом, однако в качестве start и stop принимает не числа, а буквы латинского алфавита (в качестве step принимает целое число) и возращает не перечисление чисел, а список букв, начиная с указанной в качестве start, до указанной в качестве stop с шагом step (по умолчанию равным 1). """ def letters_range(start, stop, step=1): start = ord(start) # получаю символ в числовом представлении stop = ord(stop) # получаю символ в числовом представлении mas = list() for i in range(start, stop, step): mas.append(chr(i)) # получаю символ из числового представления и добавляю в список return mas print(letters_range('b', 'w', 2)) print(letters_range('a', 'g')) print(letters_range('g', 'p')) print(letters_range('p', 'g', -2)) print(letters_range('a','a'))
false
821a532855aac783305a4ef5147c85c0a94546aa
DobleRodriguez/Inteligencia-de-Negocio
/S01 - E01.py
1,918
4.15625
4
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% [markdown] # # Ejercicios del Seminario 1 (Introducción a Python) # # En este notebook se pide realizar un par de ejercicios sencillos para ir practicando Python. # %% [markdown] # ## Ejercicio 1 # # # Escriba una función _califica_ que reciba un vector con los valores de los # estudiantes, y devuelva "MH" si la nota se encuentra en 10, "SOB" si la nota media # se encuentra entre 9 y 10, "NOT" si se encuentra entre 7 y 9, "BIEN" si se encuentra # entre 6 y 7, "APRO" si tiene entre 5 y 6, y "SUS" si es menor que cinco. # # %% def califica(vector): result = [] cad = "" for valor in vector: if valor == 10: cad = "MH" elif valor >= 9 and valor < 10: cad = "SOB" elif valor >= 7 and valor < 9: cad="NOT" elif valor >= 6 and valor < 7: cad="BIEN" elif valor >= 5 and valor < 6: cad="APRO" elif valor < 5: cad="SUS" result.append(cad) return result def main(): result = califica([2.3, 5.6, 8, 10, 9, 4.2]) print(result) assert result == ["SUS", "APRO", "NOT", "MH", "SOB", "SUS"] main() # %% [markdown] # ## Ejercicio 2 # # Escribir las funciones _potencia_ y _factorial_. # %% def potencia(a, b): result = 1 for i in range(b): result = result*a return result def factorial(n): result = 1 for i in range(n): result = result*(i+1) return result def test_potencia(): assert potencia(2, 2)==4 assert potencia(2, 3)==8 assert potencia(2, 1)==2 assert potencia(1, 10)==1 def test_factorial(): assert factorial(0) == 1 assert factorial(1) == 1 assert factorial(2) == 2 assert factorial(3) == 6 assert factorial(5) == 120 test_potencia() test_factorial()
false
f8024b9b4a567f1d38a0db933953e6273a305bb0
britneh/Intro-Python-I
/src/03_modules.py
961
4.25
4
""" In this exercise, you'll be playing around with the sys module, which allows you to access many system specific variables and methods, and the os module, which gives you access to lower- level operating system functionality. """ import sys # See docs for the sys module: https://docs.python.org/3.7/library/sys.html #Print out the command line arguments in sys.argv, one per line: for i in range(len(sys.argv)): #for i in sys.argv if i == 0: print("Function name: %s" % sys.argv[0]) else: print("%d.argument: %s" % (i, sys.argv[i])) # Print out the OS platform you're using: print(sys.platform) # Print out the version of Python you're using: print(sys.version) import os # See the docs for the OS module: https://docs.python.org/3.7/library/os.html # Print the current process ID print(os.getppid()) # Print the current working directory (cwd): print(os.getcwd()) # Print out your machine's login name print(os.getlogin())
true
f7a7dbafab4f54888a363b34f2bf7e60b64056de
aishuse/luminarprojects
/two/inpulseOperator.py
1,223
4.34375
4
# list1 = [10,11,23,45] # list2 = list1 # # # print("2nd list : ",list2) # # list1 += [1, 2, 3, 4] # # print(list2) # # print(list1) # print("next") # list1=list1+[1,2,3,4] # # print(list1) # print(list2) # Python code to demonstrate difference between # Inplace and Normal operators in Immutable Targets # importing operator to handle operator operations import operator # Initializing values x = 5 y = 6 a = 5 b = 6 # using add() to add the arguments passed z = operator.add(a,b) # using iadd() to add the arguments passed p = operator.iadd(x,y) # printing the modified value print ("Value after adding using normal operator : ",end="") print (z) # printing the modified value print ("Value after adding using Inplace operator : ",end="") print (p) # printing value of first argument # value is unchanged print ("Value of first argument using normal operator : ",end="") print (a) # printing value of first argument # value is unchanged print ("Value of first argument using Inplace operator : ",end="") print (x) ######################### alist=[1,2,3,4,5] z=operator.add(alist,[7,8,9]) print("z is ",z) print("alist is ",alist) iad=operator.iadd(alist,[7,8,9]) print("iad is ",iad) print("alist is ",alist)
true
c42869a5b6d2d2052c01b7305b35f59a03b2064a
YunJ1e/LearnPython
/DataStructure/Probability.py
1,457
4.21875
4
""" Updated: 2020/08/16 Author: Yunjie Wang """ # Use of certain library to achieve some probabilistic methods import random def shuffle(input_list): """ The function gives one of the permutations of the list randomly As we know, the perfect shuffle algorithm will give one specific permutation with the probability of 1/(# of element)! :param input_list: The list we need to shuffle :return: The shuffled list """ length = len(input_list) for i in range(length - 1, -1, -1): random_num = random.randint(0, i) input_list[random_num], input_list[i] = input_list[i], input_list[random_num] print(input_list) def reservoir_sample(sample, n, value): """ The function implements the reservoir sampling algorithm - reading part :param sample: The original sample :param n: Indicates the "value" is the n-th in the data stream :param value: Actual value in the data stream :return: tuple of the new sample and the "n" as a counter """ r = random.randint(0, n - 1) if r == 0: sample = value return sample, n + 1 def new_random(m, n): """ The function generate 0 ~ n-1 integers using randint(0, m-1) :param m: The random function m we have :param n: The random function n we need to build :return: randint(0,n-1) """ digit = 0 cur = n while cur > 0: cur = cur // m digit += 1 while True: sum = 0 for i in range(digit): sum = sum * m + random.randint(0, m - 1) if sum < n: return sum print(new_random(2, 1000))
true
24c9c43afea201cba04dc20b1cd6bef2ec32f71d
frclasso/python_examples_one
/name.py
292
4.28125
4
#!/usr/bin/env python3 import readline def name(): """Input first and last name, combine to one string and print""" fname = input("Enter your first name: ") lname = input("Enter your last name: ") fullname = fname + " " + lname print("You name is ", fullname) name()
true
5cf568d7b5301a8c37b94ebb8665448af21dbcc9
RodrigoMSCruz/CursoEmVideo.com-Python
/Desafios/desafio060.py
454
4.125
4
# Programa que calcula o fatorial de um número inserido pelo usuário. n = int(input('Digite o valor a ser calculado o fatorial: ')) i = n fat = 1 while i != 0: fat = fat * i i = i - 1 # end-while print('Resultado do fatorial de {} com while: {}.'.format(n, fat)) # Mesmo exercício, apenas usando a estrutura FOR. fat = 1 for i in range(n, 0, -1): fat = fat * i # end-for print('Resultado do fatorial de {} com for: {}.'.format(n, fat))
false
bc14c555b482300307a75b579782b09007e21bd0
RodrigoMSCruz/CursoEmVideo.com-Python
/Desafios/desafio083.py
520
4.25
4
# Programa onde o usuário digite uma expressão qualquer que use parênteses. A aplicação deve # analisar se a expressão passada está com os parênteses abertos e fechados na ordem correta. abre = fecha = 0 expressao = str(input('Digite a expressão a ser analisada: ')) for c in expressao: if c == '(': abre = abre = 1 elif c == ')': fecha = fecha + 1 # end-if-elif # end-for if abre == fecha: print('A expressão está OK!') else: print('A expressão está errada!') # end-if
false
4ff2e11f7cf8cd04dd5d98e70ccb7565dd219a1b
RodrigoMSCruz/CursoEmVideo.com-Python
/Desafios/desafio086.py
426
4.5
4
# Programa que declara uma matriz de dimensão 3×3 e preencha com valores lidos pelo teclado. No final, mostra # a matriz na tela, com a formatação correta. matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] for y in range(0, 3): for x in range(0, 3): n = int(input(f'Digite o valor para a posição [{y , x}]: ')) matriz[y][x] = n # end-for # end-for for y in range(0, 3): print(matriz[y]) # end-for
false
38540039331f7afd2f28b8b80a5bb2a33dca4c13
RodrigoMSCruz/CursoEmVideo.com-Python
/Desafios/desafio018.py
466
4.25
4
#Programa que Lê um ângulo e exibe o seno, cosseno e tangente desse ângulo. from math import sin, cos, tan, radians angulo = float(input('Digite um ângulo: º')) rad = radians(angulo) #Necessário converter para radianos, pois as funções sin(), cos() e tan() funcionam com radianos. print('O ângulo {}, em radianos é {} e tem os seguintes valores:'.format(angulo, rad)) print('Seno: {:.2f}, Cos: {:.2f} e Tg: {:.2f}.'.format(sin(rad), cos(rad), tan(rad)))
false
eec120862b6318eeb401286f08c3b958207355d2
RodrigoMSCruz/CursoEmVideo.com-Python
/Desafios/desafio033.py
529
4.125
4
# Pede para o usuário entrar com 3 valores e o programa informa qual é o menor e o maior deles. n1 = int(input('Digite um valor inteiro para o primeiro número: ')) n2 = int(input('Digite um valor inteiro para o segundo número: ')) n3 = int(input('Digite um valor inteiro para o terceiro número: ')) seq = [n1, n2, n3] # Cria uma lista com os valores digitados pelo usuário. seq.sort() # Ordena a lista. print('O menor número é {} e o maior é {}.'.format(seq[0], seq[2])) # Array de 3: 0-2. A posição começa de 0.
false
3352a7824e6e62b969d5507b9e6cb791b15216fc
JaygJr/Pie
/Bmi/Test/testlong.py
2,081
4.28125
4
#!/usr/bin/env python3 """This script will calculate BMI via height/weight input""" import string from time import sleep from gpiozero import LED # ToDo accept input for positive integers ONLY, and make it a function # DONE INTERNALLY ONLY - ToDo change bmi height/weight calculations to a func # ToDo change code for RGB LED tesing def calc_meters(height): return height * .0254 def calc_kilograms(weight): return weight / 2.2046 def calc_bmi(kilograms, meters): return kilograms / meters**2 # red = 17 yellow =27 green =22 red_led = LED(17) # under weight and obese yellow_led = LED(27) # overweight green_led = LED(22) # normal weight # Welcome to JAYY BMI Calculator calculator print("Welcome to JAYS BMI Calculator") print() # Get height from user, # Code for get inches initially.Then later, change to ft/in. # Then convert back to inches # Get height from user height = int(input("Please enter your height in inches: ")) # Convert from inches to meters # inches * 0.0254 meters = calc_meters(height) print("your height in meters is: " + str(meters)) # Convert from meters to centimeters # multiply meters X 100 centimeters = meters * 100 print("your height in centimeters is: " + str(centimeters)) # Get weight from user weight = int(input("Please enter your weight in pounds: ")) print() #convert from pounds to kilograms #kg = lb / 2.2046 kilograms = calc_kilograms(weight) print("your weight in kg is: " + str(kilograms)) #compute BMI # BMI = kilograms / meters squared #Display answer to user BMI = calc_bmi(kilograms, meters) print("Your BMI is: " + str(BMI)) # If BMI < 18.5 print 'underweight' if BMI < 18.5: print("underweight") red_led.on() sleep(5) # if bmi >= 18.5 and < 25 print 'normal' elif BMI >= 18.5 and BMI < 25: print("normal") green_led.on() sleep(5) # If bmi >= 25 and bmi < 30 print 'overweight' elif BMI >= 25 and BMI < 30: print("overweight") yellow_led.on() sleep(5) # If bmi >= 30 print 'obese' elif BMI >= 30: print("obese") red_led.on() sleep(5)
true
5170c66b0a7fda701e0052543100577362e72f3a
BaerSenac/Curso_em_Video_Modulo
/Curso_em_video_Modulo2/condicoes_alinhadas/Exercicios/triangulos+.py
297
4.125
4
r1 = float(input("Digite um lado: ")) r2 = float(input("Digite um segundo lado: ")) r3 = float(input("Digite um terceiro lado: ")) if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2: print("Os segmentos acima PODEM FORMAR UM TRIANGULO!") else: print("Os acima não PODEM FORMAR UM TRIANGULO!")
false
eb5d06d370df3491e5144320bf670797bc56fc46
SalihGezgin/meinarbeitsbereich
/python/coding-challenges/cc-005-create-phonebook/app.py
1,717
4.1875
4
def print_menu(): print("Welcome to the phonebook application.") print('1. Find phone number.') print('2. Insert a phone number.') print('3. Delete a person from the phonebook.') print('4. Terminate!') print() def find(name): if name in phonebook: print(phonebook[name]) else: print("Kayit bulunamadi!") def delet(name): if name in phonebook: del phonebook[name] print("Kayit silindi!") else: print("Kayit bulunamadi!") phonebook = { 'Qay' : '1234', 'Wsx' : '2347', 'Zgv' : '4324', 'Wsx' : '3333', 'Tgb' : '5432', 'Zhb' : '9876', 'Esy' : '1111', 'Edc' : '9876' } menu_choice = 0 print_menu() while menu_choice <= 4: menu_choice = int(input("Type in a number (1-4): ")) if menu_choice == 1: print("Find phone number.") name = input("Name: ").title() find(name) elif menu_choice == 2: print("Insert a phone number.") name = input("Name: ").title() phone = input("Number: ") phonebook.update({name:phone}) phonebook[name] = phone elif menu_choice == 3: print('Insert a name to delete own phone number.') name = input("Name: ").title() delet(name) elif menu_choice == 4: print('Terminate!') break else: print("Welcome to the phonebook application.Please insert 1..4") Welcome to the phonebook application. 1. Find phone number. 2. Insert a phone number. 3. Delete a person from the phonebook. 4. Terminate! Find phone number. 1234 Terminate! In [20]: print(phonebook) {'Wsx': '3333', 'Zgv': '4324', 'Tgb': '5432', 'Zhb': '9876', 'Esy': '1111', 'Edc': '9876'} In [ ]:
false
64eb2ebc38fc4c2b5201dae4b75e61e97eda4fc2
MouChakraborty/JISAssasins
/Question15.py
277
4.25
4
#!/usr/bin/env python # coding: utf-8 # In[2]: #Program to find the value of x^(y+z) By Moumita Chakraborty import math x=int(input("Enter the value of x")) y=int(input("Enter the value of y")) z=int(input("Enter the value of z")) a=y+z b=pow(x,a) print("The value is",b) # In[ ]:
true
320e3160f26f2b52fe22825a9e676719bb31ac15
MouChakraborty/JISAssasins
/Question16.py
404
4.5625
5
#!/usr/bin/env python # coding: utf-8 # In[1]: #Question 16 ##Write a Program to Accept character and display its # Ascii value and its Next and Previous Character. #chr() for ascii to char By Moumita Chakraborty x= input("Enter the input :") n= ord(x) prev= n - 1 next= n + 1 a=chr(prev) b=chr(next) print(" ASCII value is : ",n) print("The previous value is : ",a) print("The next value is : ",b) # In[ ]:
true
b1ae07b29c5e5e39adb58970b8fdbc3a4508957e
atulzh7/IW-Academy-Python-Assignment
/python assignment ii/question_no_6.py
244
4.21875
4
"""Searching name using for loop """ sample_list = ["Kushal", "John", "Bikash", "Paras", "Pradeep", "Diwash"] print(sample_list) for name in sample_list: if name == 'John': print("Found...") else: print("Not found...")
false
24ed34ca93e72f8f56a0ec16e8e2e5733c40e768
rchen00/Algorithms-in-Python
/string reverse recursive.py
801
4.15625
4
# -*- coding: utf-8 -*- """ Created on Sat Jan 16 21:12:26 2021 @author: robert """ def string_reverse1(s): if len(s) == 0: return s else: return string_reverse1(s[1:]) + s[0] s = "Robert" print ("The original string is: ",end="") print (s) print ("The reversed string(using recursion) is: " , end="") print (string_reverse1(s)) """ String is passed as the argument to a recursive function to reverse a string. The base case is that the length of the string equal to 0, the string is returned. If the length of the string is not 0, the reverse string function is recursively called to slice the part of the string except the first character and move the first character to the endof the sliced string. """
true
b022fcf0e10ca9d637ccafa31a018a2523770c30
optionalg/python-programming-lessons
/rock_paper_scissors.py
2,520
4.1875
4
# pylint: disable=C0103 # 2 players # 3 possibles answers: rock, paper, scissors # rock > scissors > paper > rock ... # ask the players their name # ------- loop start ------- # ask their choice # check their choice (needs to be valid) # find a way to hide the choice???? https://stackoverflow.com/questions/2084508/clear-terminal-in-python # compare the choices # announce the winner # ------- loop end --------- # loop to play several times # have a way to exit the program # scores # high scores (in a file) # extend the game: add more choices (lizard, spock...) more complex rules, # a list will not work http://www.samkass.com/theories/RPSSL.html import os # order is important, the next element beasts the current one choices = ["rock", "paper", "scissors"] player1 = input('Name of player 1: ') player2 = input('Name of player 2: ') def check(question, solutions): """ ask a question to the user, and check that their answer is in the solutions """ while True: answer = input(question) if answer in solutions: return answer else: print("Please try again!") def compare(first, second): """ returns 2 if second beats first, 1 if first beats seconds, 0 if they are equal """ if first not in choices or second not in choices: print("Error: invalid arguments for compare") return None # check if first equals second, if so return 0 if first == second: return 0 index1 = choices.index(first) # 2 index2 = choices.index(second) # 0 # check if second beats first if index2 == (index1 + 1) % 3: return 2 # otherwise, first beasts second, return 1 else: return 1 continuePlaying = True while continuePlaying: choice1 = check(player1 + ": enter your choice (rock, paper or scissors) ", choices) os.system("cls||clear") choice2 = check(player2 + ": enter your choice (rock, paper or scissors) ", choices) print(player1 + " choice is " + choice1) print(player2 + " choice is " + choice2) if compare(choice1, choice2) == 0: print("It's a tie!") elif compare(choice1, choice2) == 1: print(player1 + " wins") elif compare(choice1, choice2) == 2: print(player2 + " wins") else: print("ERROR: invalid result for compare") quitAnswer = input('Write quit or press enter to continue: ') if quitAnswer == 'quit': continuePlaying = False
true
fcc875501cf71d3fe510e1bcbb20ca9e3b8e2774
optionalg/python-programming-lessons
/Students/temperature_wendy2.py
776
4.125
4
# Temperature conversion def menu(): print("\nl. Celcius to Fahrenheit") print("2. Fahrenheit to Celcius") print("3. Exit") return int(input("Enter a choice: ")) def toCelsius(f): return int((f-32) / 1.8) def toFahrenheit(c): return int(c * 1.8 +32) def main(): choice = menu() while choice != 3: if choice == 1: # convert C to F c = eval(input("Enter degrees Celsius: ")) print(str(c) + "C = " + str(toFahrenheit(c)) + "F") elif choice == 2: # convert F to C f = eval(input("Enter degrees Fahrenheit:")) print(str(f) + "F = " +str(toCelsius(f)) + "C") else: print("invalid entry") choice = menu() main()
false
7be942bc1eed5186e5867bbb05d684dedecc67ba
ENAIKA/PasswordLocker
/user_test.py
2,726
4.15625
4
import unittest # Importing the unittest module from user import User # Importing the user class class TestUser(unittest.TestCase): ''' Test class that defines test cases for the user class behaviours. ''' def setUp(self): ''' Set up method runs before each test cases. ''' self.new_user = User("Naika","Nakish254") # create user object def tearDown(self): ''' tearDown method that does clean up after each test case has run. ''' User.users_list = [] def test_init(self): ''' test_init test case to test if the object is initialized properly ''' self.assertEqual(self.new_user.firstname,"Naika") self.assertEqual(self.new_user.password,"Nakish254") def test_save_user(self): ''' test_save_user test case to test if the user object is saved into the users list ''' self.new_user.save_user() # saving the new user self.assertEqual(len(User.users_list),1) def test_save_multiple_user(self): ''' test_save_multiple_user to check if we can save multiple users users_list ''' self.new_user.save_user() test_user = User("Test","user123") # new user test_user.save_user() self.assertEqual(len(User.users_list),2) def test_delete_user(self): ''' test_delete_user to test if a user can be removed from users list ''' self.new_user.save_user() test_user = User("Test","user123") # new user test_user.save_user() self.new_user.delete_user()# Deleting user object self.assertEqual(len(User.users_list),1) def test_find_user(self): ''' test to check users by firstname and display information ''' self.new_user.save_user() test_user = User("Test","user123") # new user test_user.save_user() found_user = User.find_user("Test") self.assertEqual(found_user.firstname,test_user.firstname) def test_user_exists(self): ''' test to check if we can return a Boolean if we cannot find the user. ''' self.new_user.save_user() test_user = User("Test","user123") # new user test_user.save_user() user_exists = User.user_exist("Test") self.assertTrue(user_exists) def test_display_users(self): ''' method that returns a list of all users saved ''' self.assertEqual(User.display_users(),User.users_list) if __name__ == '__main__': unittest.main()
true
244edeb9206d06f0b27d2dcc761bd43fadeb3748
SoniaAmezcua/python_class
/ejercicio_01.py
2,889
4.15625
4
''' Ejercicio 1 Construir un Script que permita generar una fila de 'Sudoku', es decir, una fila de 9 valores con numeros del 1 al 9 y que ninguno de los valores se repitan y mostrar la fila. Para comprobar que la fila esta bien construida, deberan calcular la sumatoria de la fila y debe dar como resultado 45 Al igual que en Sudoku, la fila se segmenta en 3 partes, por lo que es necesario calcular la sumatoria de cada bloque , mostrarlos e indicar que bloque es el mayor (A, B o C). en el caso de que existen bloque con igual valor, debera mostrar cuales son los bloques mayores. Y si todos son iguales, indicar el siguiente mensaje 'Todos los bloques son iguales'. * Este script se puede resolver con las funciones y metodos vistas en clase, no es necesario implementar algo fuera de la misma y en el caso de realizarlo, debera escribir un comentario de la justificacion. * El objetivo de este ejercicio es evaluar los conocimientos adquiridos, como a su vez las buenas practicas y la optimizacion de la solucion, por lo que todos estos factores seran considerados para su evaluacion. ''' import random #import numpy as np lista_sudoku = [] contador = 1 while contador < 10: valor = random.randint(1,9) if valor not in (lista_sudoku): lista_sudoku.append(valor) contador += 1 print('Lista Sudoku: {}'.format(lista_sudoku)) # #Me apoye de la libreria numpy para hacer el split en 3 secciones y poder manejarlos de manera independiente # lista_sudoku_split= np.array_split(lista_sudoku, 3) # print(lista_sudoku_split[0]) # print(lista_sudoku_split[1]) # print(lista_sudoku_split[2]) # sum_bloque_a = sum(lista_sudoku_split[0]) # sum_bloque_b = sum(lista_sudoku_split[1]) # sum_bloque_c = sum(lista_sudoku_split[2]) #Con lo aprendido en clase hoy print(lista_sudoku[:3]) print(lista_sudoku[3:6]) print(lista_sudoku[-3::]) sum_bloque_a = sum(lista_sudoku[::3]) sum_bloque_b = sum(lista_sudoku[3:6]) sum_bloque_c = sum(lista_sudoku[-3::]) print('Sumatoria: {}'.format(sum(lista_sudoku))) print('Sumatoria de A: {}'.format(sum_bloque_a)) print('Sumatoria de B: {}'.format(sum_bloque_b)) print('Sumatoria de C: {}'.format(sum_bloque_c)) if sum_bloque_a > sum_bloque_b and sum_bloque_a > sum_bloque_c: print("Bloque A es mayor") elif sum_bloque_b > sum_bloque_a and sum_bloque_b > sum_bloque_c: print("Bloque B es mayor") elif sum_bloque_c > sum_bloque_a and sum_bloque_c > sum_bloque_b: print("Bloque C es mayor") elif sum_bloque_a == sum_bloque_b and sum_bloque_a > sum_bloque_c: print("Bloque A y B son mayores") elif sum_bloque_a == sum_bloque_c and sum_bloque_a > sum_bloque_b: print("Bloque A y C son mayores") elif sum_bloque_b == sum_bloque_c and sum_bloque_b > sum_bloque_a: print("Bloque B y C son mayores") else: print("Todos los bloques son iguales")
false
b429f034f7810ef4e4331ae80cb648710e8ff4ac
charliealpha094/Python_Crash_Course_2nd_edition
/Chapter_8/try_8.8.py
961
4.53125
5
#Done by Carlos Amaral in 29/06/2020 """ Start with your program from Exercise 8-7. Write a while loop that allows users to enter an album’s artist and title. Once you have that information, call make_album() with the user’s input and print the dictionary that’s created. Be sure to include a quit value in the while loop. """ #User Albums def make_album(artist_name, album_title): """Returns the name of the album and it's title.""" album_discription = f"{artist_name}, {album_title}" return album_discription.title() while True: print("Please, enter the name of an artist and album") print("(Enter 'q' at any time to quit)") artist_name = input("Artist name: ") if artist_name == 'q': break album_name = input("Album name: ") if album_name == 'q': break music = make_album(artist_name, album_name) print(f"\nArtist: {artist_name}, Album: {album_name} ") print("Thanks for using our program!")
true
40f000710dba311de1cfb53c3740df002537de25
charliealpha094/Python_Crash_Course_2nd_edition
/Chapter_8/try_8.3.py
728
4.34375
4
#Done by Carlos Amaral in 28/06/2020 """ Write a function called make_shirt() that accepts a size and the text of a message that should be printed on the shirt. The function should print a sentence summarizing the size of the shirt and the message printed on it. Call the function once using positional arguments to make a shirt. Call the function a second time using keyword arguments. """ #T-shirt def make_shirt(size_shirt, message): """Displays information about size and text of a message.""" print(f"I want a {size_shirt}.") print(f"I want to see '{message}' written on my {size_shirt.title()}. ") make_shirt('small shirt', 'Im loving python') make_shirt(size_shirt = 'small shirt', message = 'Im loving python')
true
03741ecd81689dce53ca5f31115f635db5b2b3ee
charliealpha094/Python_Crash_Course_2nd_edition
/Chapter_3/try_3.10.py
341
4.3125
4
cities = ['Porto', 'Lisboa', 'Viseu', 'Vigo', 'Wien'] print(cities) print(len(cities)) #Reverse alphabetical order cities.sort(reverse=True) print(cities) #Sorting a list temporarily with the sorted() function print("\nHere is the sorted list:") print(sorted(cities)) #Printing a list in Reverse Order print(cities) cities.reverse()
true
a330687c3ff041d17b9530c05c074555b284a919
charliealpha094/Python_Crash_Course_2nd_edition
/Chapter_5/try_5.2.py
1,259
4.1875
4
#Done by Carlos Amaral in 17/06/2020 """ 5-2. More Conditional Tests: You don’t have to limit the number of tests you create to ten. If you want to try more comparisons, write more tests and add them to conditional_tests.py. Have at least one True and one False result for each of the following: • Tests for equality and inequality with strings • Tests using the lower() method • Numerical tests involving equality and inequality, greater than and less than, greater than or equal to, and less than or equal to • Tests using the and keyword and the or keyword • Test whether an item is in a list • Test whether an item is not in a list """ #Some tests. wrist_watches=['casio', 'seiko', 'rolex', 'citizen'] for wrist_watch in wrist_watches: if wrist_watch == 'casio': print(wrist_watch.lower()) else: print(wrist_watch.title()) print("\n") #Inequality requested_watch = 'seiko' if requested_watch != 'casio': print("Sorry, not in our stock.") print("\n") #Numerical comparisions answer = 50 if answer != 30: print("Your answer is incorrect. Try again, please!") #More numercial tests age = 16 if age < 6: price = 5 elif age < 18: price = 10 else: price = 15 print(f"\nYour price is {price}!")
true
6f35e52ecc19b49821a12684fcc4bc77d2ad0257
charliealpha094/Python_Crash_Course_2nd_edition
/Chapter_10/try_10.2/learn_C.py
656
4.375
4
#Done by Carlos Amaral in 11/07/2020 """You can use the replace() method to replace any word in a string with a different word. Here’s a quick example showing how to replace 'dog' with 'cat' in a sentence: >>> message = "I really like dogs." >>> message.replace('dog', 'cat') 'I really like cats.' Read in each line from the file you just created, learning_python.txt, and replace the word Python with the name of another language, such as C. Print each modified line to the screen. """ filename = 'learning_python.txt' with open (filename) as x: lines = x.readlines() for line in lines: line = line.rstrip() print(line.replace('Python', 'C'))
true
d16f147994679c01cebbcab39ec9d80969a1f30a
charliealpha094/Python_Crash_Course_2nd_edition
/Chapter_6/try_6.2.py
953
4.3125
4
#Done by Carlos Amaral in 21/06/2020 """ Use a dictionary to store people’s favorite numbers. Think of five names, and use them as keys in your dictionary. Think of a favorite number for each person, and store each as a value in your dictionary. Print each person’s name and their favorite number. For even more fun, poll a few friends and get some actual data for your program. """ #Favourite numbers favourite_numbers = { 'Carlos': '17', 'Patricia': '12', 'Rita': '23', 'Sofia': '2', 'Eva': '15' } number = favourite_numbers['Carlos'] print(f"Carlos' favourite number is {number}.") number = favourite_numbers['Patricia'] print(f"Patricia's favourite number is {number}.") number = favourite_numbers['Rita'] print(f"Rita's favourite number is {number}.") number = favourite_numbers['Sofia'] print(f"Sofia's favourite number is {number}.") number = favourite_numbers['Eva'] print(f"Eva's favourite number is {number}.")
true
894bd27767bb90b0c1e66344b4e38ec462681c13
charliealpha094/Python_Crash_Course_2nd_edition
/Chapter_5/try_5.3.py
708
4.1875
4
#Done by Carlos Amaral in 18/06/2020 """ Imagine an alien was just shot down in a game. Create a variable called alien_color and assign it a value of 'green' , 'yellow' , or 'red' . • Write an if statement to test whether the alien’s color is green. If it is, print a message that the player just earned 5 points. • Write one version of this program that passes the if test and another that fails. (The version that fails will have no output.) """ #Alien Colors 1 alien_color = 'green' if alien_color == 'green': print("Congratulations. You've just earned 5 points!") print("\n") #Fail version alien_color = 'yellow' if alien_color == 'green': print("Congratulations. You've just earned 5 points!")
true
f9493f994afa60ee4ea4e5177eb87f2deb60d39a
charliealpha094/Python_Crash_Course_2nd_edition
/Chapter_11/try_11.1/city_functions.py
812
4.25
4
#Done by Carlos Amaral in 16/07/2020 """ Write a function that accepts two parameters: a city name and a country name. The function should return a single string of the form City, Country , such as Santiago, Chile . Store the function in a module called city _functions.py. Create a file called test_cities.py that tests the function you just wrote (remember that you need to import unittest and the function you want to test). Write a method called test_city_country() to verify that calling your function with values such as 'santiago' and 'chile' results in the correct string. Run test_cities.py, and make sure test_city_country() passes. """ #City, country def get_formatted_place(city, country): """Generate the name of a place, neatly formatted.""" place = f"{city} {country}" return place.title()
true
4fac06b757d902fbf633efd826c9854b429373d5
premanshum/pythonWorks
/aFolder/miscDemo01.py
639
4.125
4
''' This program prints the histogram for the list provided We will solve this using list comprehension List Comprehension => [expr(item) for item in iterable] ''' def histogram ( items) : [print(item,' : ', '* ' * item) for item in items] #histogram ([3, 5, 2, 6, 9]) import socket print([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2]]) print([l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0])
false
c2e0671c986eaeb5cbdad8c2b193a2f21617dc4c
rajeevbkn/fsdHub-mathDefs
/factorialNum.py
371
4.40625
4
# This snippet is to find factorial of a positive integer number. n = int(input('Enter a positive integer number: ')) factorial = 1 if n < 0: print('Factorial of a negative number is not possible.') elif n == 0: print('Factorial of 0 is 1.') else: for i in range(1, n+1): factorial = factorial * i print('The factorial of ', n, ' is ', factorial)
true
bd1fddbe81544186001b12fd84faf35b17f688bb
MariusArhaug/bicycleLocation
/highestProduct.py
948
4.40625
4
def highestProduct(listA): length = len(listA) if length < 3: return "List is not big enough to find biggest product of 3 integers!" listA.sort() #ascending order #Check if a list only contains negative numbers count = 0 for integer in listA: if integer < 0: count += 1 if (count == length): return "Cannot find biggest triplet in a list with only negative numbers!" #find triplet with two biggest negative numbers = positive * biggest positive number biggestNegative = listA[0] * listA[1] * listA[length-1] #find triplet with three biggest positive numbers biggestPositive = listA[length-1] * listA[length-2] * listA[length-3] finalProduct = max(biggestNegative, biggestPositive) return finalProduct listA = [1,10,2,5,6,3] print(highestProduct(listA)) listB = [-50,-20,-1,-25,-25,-25] print(highestProduct(listB)) #print(highestProduct(listB,3))
true
724078ce3c84dca14dada8889fc0c4828a63670a
RyanMullin13/Euler
/problem1.py
400
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 5 13:58:41 2021 @author: ryan """ """ If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ ans = 0 for i in range(1,1000): if(i % 3 == 0 or i % 5 == 0): ans += i print(ans)
true
7014468d396a9f3b4a8eb43a8f4f71d0d3e8004f
meenakshikathiresan3/sorting_algorithms
/insertion_sort/insertion_sort.py
2,442
4.4375
4
""" Python insertion sort implementation 20210920 ProjectFullStack """ import random def insertion_sort(the_list): # outer loop, we start at index 1 because we always assume the # FIRST element in the_list is sorted. That is the basis of how # insertion sort works for i in range(1, len(the_list)): # "pull out" or store the value we are trying to insert insert_value = the_list[i] # inner WHILE loop, start at the last sorted index ( which is at i - 1) # and count DOWN check each value we find at j against the # value we are trying to insert j = i - 1 while j >= 0 and the_list[j] > insert_value: # "move" the value we find a j to the right, which is the index # j + 1 the_list[j + 1] = the_list[j] # decrement J, otherwise we will never break out of while loop! j -= 1 # finally, when we get here j should be the first card that is # less than the insert value, so insert value needs to go # one to the right of j, or at index j + 1 the_list[j+1] = insert_value # return the sorted list return the_list # Test Case 1, list of 6 elements unsorted = [17, 12, 37, 19, 20] python_sorted = list(unsorted) python_sorted.sort() our_sorted = insertion_sort(list(unsorted)) print(f"Passed: {python_sorted == our_sorted} : {unsorted} -> {our_sorted}") # Test Case 2, list of 5 elements with duplicate values unsorted = [17, 12, 12, 19, 20] python_sorted = list(unsorted) python_sorted.sort() our_sorted = insertion_sort(list(unsorted)) print(f"Passed: {python_sorted == our_sorted} : {unsorted} -> {our_sorted}") # Test Case 3, list of 5 elements, include negative numbers unsorted = [-5, -100, 3245, 10, 2532] python_sorted = list(unsorted) python_sorted.sort() our_sorted = insertion_sort(list(unsorted)) print(f"Passed: {python_sorted == our_sorted} : {unsorted} -> {our_sorted}") # Test Case 4, list of 0 elements unsorted = [] python_sorted = list(unsorted) python_sorted.sort() our_sorted = insertion_sort(list(unsorted)) print(f"Passed: {python_sorted == our_sorted} : {unsorted} -> {our_sorted}") # Test Case 5, random list of 20 elements unsorted = random.sample(range(0, 100), 20) python_sorted = list(unsorted) python_sorted.sort() our_sorted = insertion_sort(list(unsorted)) print(f"Passed: {python_sorted == our_sorted} : {unsorted} -> {our_sorted}")
true
39302fda8f50d1fd6f9af28b537bca7396d8b20a
juanhuancapaza/PythonFinal
/Modulo 1/Problema1.py
205
4.15625
4
# Ingresar el nombre de Emma name = input('What is your name?') print('Hello, {}'.format(name)) # Ingresar el nombre de Rodrigo name = input('What is your name?') print('Hello, {}'.format(name))
false
f965af6dd3aed580e083dd2040e2ea63fb6d5707
GuilhermeZorzon/Project-Euler
/Problem6.py
558
4.15625
4
def sqr_sum_difference(num = 100): ''' (int/ ) -> int Given num, finds the diference between the sum of all the squares of the numbers lower than num and the square of the sum of these same numbers. Num is set to 100 if no value is passed To use: >>> sqr_sum_difference(2) 4 >>> sqr_sum_difference() 25164150 ''' sum_sqr = 0 sqr_sum = 0 for i in range(1, num + 1): sum_sqr += (i * i) for j in range(1, num + 1): sqr_sum += j sqr_sum *= sqr_sum return sqr_sum - sum_sqr
true
fe4f040f406b291c774ed2d9d7aaeb559e29bdb3
Dheeraj809/dheeraj-b2
/rev of string.py
217
4.34375
4
def reverse(s): if len(s)==0: return s else: return reverse(s[1:])+s[0] s= input('enter the string') print("The original string is:") print(s) print("The reversed string is:") print(reverse(s))
true
5b0b9b23d2be5485525cddee396049237b17c1e4
f034d21a/leetcode
/344.reverse_string.py
753
4.25
4
#! /usr/bin/python # -*- coding: utf-8 -*- """ 344. Reverse String Write a function that takes a string as input and returns the string reversed. Example: Given s = "hello", return "olleh". """ class Solution(object): def reverseString(self, s, method='a'): _method = getattr(self, method) if not _method: raise Exception('Method `{}` not found.'.format(method)) return _method(s=s) @staticmethod def a(s): """ :param s: str :return: str """ return s[::-1] if __name__ == '__main__': solution = Solution() _input = 'hello' _output = solution.reverseString(s='hello') print(_input, '==>', _output)
true
ae8ee04522609dd86fb35bb7c38dacdb6d5c3ff9
bethanyuo/DSA
/inputs.py
401
4.40625
4
# user_input = input("What's the meaning of life? ") TypeError: '<' not supported between instances of 'str' and 'int' user_input = int(input("What's the meaning of life? ")) # ==> Converts any input into an interger if user_input == 42: print("Correct answer!") elif user_input < 42: print("Sorry, but you entered a small answer") else: print("Sorry, but you entered a big answer")
true
6e671ccc023ecbcd163aecc57633d93a78d106e7
chidoski/Python-Projects
/ex32.py
1,040
4.625
5
the_count = [1, 2, 3, 4, 5] fruits = ['apples', 'oranges', 'pears', 'apriocts'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] #the first kind of for-loop goes through a list for number in the_count: print "This is count %d" % number #same as above for fruit in fruits: print "These are the fruit %s" % fruit #Going through mixed lists #notice we have to use %r since we dont know what's in this list for i in change: print "I got %r" % i #lists can also be built, start with an empty one elements = [] #then use the range funtion to do 0 to 5 counts for i in range(0,6): print "Adding %d to the list." % i #append is a function that lists understand elements.append(i) #now we will print them out for i in elements: print "Elements was: %d" % i my_list = ['one', 'two', 'three', 'four'] my_list_len = len(my_list) for i in range(0, my_list_len): print "Element is: %s" % i #in order to print the elements use the list plus the elements print (my_list[i]) multi_dim = [1 ,2, 3, 4, 5],[6, 7, 8, 9, 10] print multi_dim
true
bcf489c63c2c3e3ee5af3c0ff9bfba06f1df49e3
baliaga31/Python
/codecademy_exercices/Anti_vowels.py
231
4.21875
4
#!/usr/bin/python def anti_vowel(text): vowel_list = ["a","e","i","o","u","A","E","I","O","U"] for n in text: for n in vowel_list: text = text.replace(n,"") return text print anti_vowel("Hey you")
false
64902aa98e5a99ae3401b8cd647936eb77f0202e
tsvielHuji/Intro2CSE-ex10
/ship.py
2,050
4.21875
4
# Relevant Constants SHIP_RADIUS = 1 SHIP_LIFE = 3 TURN_LEFT = "l" TURN_RIGHT = "R" VALID_MOVE_KEY = {TURN_RIGHT, TURN_LEFT} class Ship: """Handles the methods and characteristics of a single Ship""" def __init__(self, location, velocity, heading): self.__location_x = location[0] # Location in X direction self.__velocity_x = velocity[0] # Velocity in X direction self.__location_y = location[1] # Location in Y direction self.__velocity_y = velocity[1] # Velocity in Y direction self.__heading = heading # The angle of the head of the ship self.__life = SHIP_LIFE def get_velocity(self): """ :return: return the current velocity of the ship """ return self.__velocity_x, self.__velocity_y def get_location(self): """ :return: return the current location of the ship """ return self.__location_x, self.__location_y def get_heading(self): """ :return: return the angle of the head of the ship in Radians """ return float(self.__heading) def get_radius(self): """ :return: The radius of the ship based on the declared constant """ return SHIP_RADIUS def reduce_life(self): """ The function reduce the life of the ship :return: True upon success and False upon failing """ if self.__life <= 0: return False self.__life -= 1 return True def update_location(self, location): """Updates the location of the ship""" self.__location_x = location[0] self.__location_y = location[1] def update_heading(self, heading): """Updates the heading of the ship""" self.__heading = heading def update_velocity(self, velocity): """Updates the velocity of the ship""" self.__velocity_x = velocity[0] self.__velocity_y = velocity[1]
true
0a9dd5c965612b6907fb7c4acb2a2bd09a34a2ca
JiWenE/pycode
/函数部分/ex10.py
739
4.25
4
def break_words(stuff): """This function will break up words for us.""" words = stuff.split(' ') # 以空格为分隔符将其转换为列表 return words def sort_words(words): """Sorts the words.""" return sorted(words) # 排序 def print_first_word(words): """Prints the first word after popping it off.""" word = words.pop(0) # 移除当前位置的元素 print(word) def print_last_word(words): """Prints the last word after popping it off.""" word = words.pop(-1) print(word) sentence = "All good things come to those who wait." print(break_words(sentence)) print(sort_words(break_words(sentence))) print_first_word(break_words(sentence)) print_last_word(break_words(sentence))
true
04c3436776290503c57409b445a8681e302a7bbc
shreyanse081/Some-Algorithms-coded-in-Python
/QuickSort.py
1,137
4.15625
4
""" QuickSort procedure for sorting an array. Amir Zabet @ 05/04/2014 """ import random def Partition(a,p): """ Usage: (left,right) = Partition(array, pivot) Partitions an array around a pivot such that the left elements <= and the right elements >= the pivot value. """ pivot = a[p] ## the pivot value right = [] ## the right partition left = [] ## the left partition for i in range(len(a)): if not i == p: if a[i] > pivot: right.append(a[i]) else: left.append(a[i]) left.append(pivot) return(left, right) def QuickSort(a): """ Usage: sorted_array = QuickSort(array) Sorts an array using the Randomized QuickSort algorithm. """ if len(a) <= 1: return(a) if len(a) == 2: if a[0] > a[1]: a[0], a[1] = a[1], a[0] return(a) k = random.randint(1, len(a)-1) (left,right) = Partition(a,k) return QuickSort(left)+QuickSort(right) def main(): a = [6,8,1,9,5,4] print('Input array: ', a) b = QuickSort(a) print('Sorted array: ', b) # This is the standard boilerplate that calls the main() function. if __name__ == '__main__': main()
true
853c3a462260bc1e20f624ff80b784701ab4ba01
ernestas-poskus/codeacademy
/Python/io_buffering.py
820
4.125
4
# PSA: Buffering Data # We keep telling you that you always need to close your files after you're done writing to them. Here's why! # During the I/O process, data are buffered: this means that they're held in a temporary location before being written to the file. # Python doesn't flush the buffer—that is, write data to the file—until it's sure you're done writing, and one way to do this is to close the file. # If you write to a file without closing, the data won't make it to the target file. # Open the file for reading read_file = open("text.txt", "r") # Use a second file handler to open the file for writing write_file = open("text.txt", "w") # Write to the file write_file.write("Not closing files is VERY BAD.") write_file.close() # Try to read from the file print read_file.read() read_file.close()
true
c5987e266f3beb69d15ac78d21b0eada3f09527c
ernestas-poskus/codeacademy
/Python/int.py
631
4.28125
4
# int()'s Second Parameter # Python has an int() function that you've seen a bit of already. It can turn non-integer input into an integer, like this: # int("42") ==> 42 # What you might not know is that the int function actually has an optional second parameter. # If given a string containing a number and the base that number is in, the function will return the value of that number in base ten. # So running int("1010", 2) will return 10 because 0b1010 is the base 2 equivalent of 10. print int("1",2) print int("10",2) print int("111",2) print int("0b100",2) print int(bin(5),2) print int('11001001',2)
true
8ad6c8bd609d664314df0a35cf3b81ded0b32250
BeefAlmighty/CrackingCode
/ArraysStrings/Problem6.py
989
4.15625
4
# String compression: Compress a string on basis of character counts # SO, e.g. aaabccaaaa --> a3b1c2a4. If the compressed string is not smaller # than the original string, then the method should return the original string. def compress(string): letter_list = [] count_list = [] idx = 0 compressed = [] while idx < len(string): letter = string[idx] count = 1 idx += 1 while idx < len(string) and string[idx] == letter: count += 1 idx += 1 compressed.append(letter + str(count)) compressed = "".join(compressed) return compressed if len(compressed) < len(string) else string def main(): assert compress("aabccca") == "aabccca" assert compress("aaabccaaaa") == "a3b1c2a4" assert compress("b") == "b" assert compress("abc") == "abc" assert compress("abcc") == "abcc" assert compress("abccc") == "abccc" if __name__ == "__main__": main() print("Problem 6")
true
09d52ea26960f115db480abec979775cee4b7c99
Redlinefox/Games_and_Challenges
/Guessing_Game/Guessing_Game_v2.py
2,106
4.28125
4
# Write a program that picks a random integer from 1 to 100, and has players guess the number. # The rules are: # If a player's guess is less than 1 or greater than 100, say "OUT OF BOUNDS" # On a player's first turn, if their guess is within 10 of the number, return "WARM!" # further than 10 away from the number, return "COLD!" # On all subsequent turns, if a guess is # closer to the number than the previous guess return "WARMER!" # farther from the number than the previous guess, return "COLDER!" # When the player's guess equals the number, tell them they've guessed correctly and # how many guesses it took! import random goal = random.randint(1, 101) stored_answers = [0] guess = 0 print("WELCOME TO GUESS THE NUMBER!") print("I'm thinking of a number between 1 and 100") print("If your guess is more than 10 away from my number, I'll tell you you're COLD") print("If your guess is within 10 of my number, I'll tell you you're WARM") print("If your guess is farther than your most recent guess, I'll say you're getting COLDER") print("If your guess is closer than your most recent guess, I'll say you're getting WARMER") print("LET'S PLAY!") while True: valid = False while valid == False: try: guess = int(input('Make a guess between 1 - 100: ')) except ValueError: print('Found string input - Make a numerical guess between 1 - 100') else: if guess <= 0 or guess > 100: print('OUT OF BOUNDS - Make a numerical guess between 1 - 100') else: valid = True if guess == goal: stored_answers.append(guess) stored_answers.pop(0) print('You win! It took you {} tries.'.format(str(len(stored_answers)))) print(stored_answers) break stored_answers.append(guess) if stored_answers[-2]: if abs(goal-guess) < abs(goal - stored_answers[-2]): print('WARMER!') else: print('COLDER!') else: if abs(guess - goal) < 10: print('WARM!') else: print('COLD!')
true
70342d4a95cfe0e7fcf26a480f166601865e75c2
RubenTadeia/IASD
/2_Project/classes.py
2,336
4.125
4
class Tree(): """ Defines tree class """ def __init__(self, root): if isinstance(root, tuple): if len(root) == 2: self.data = root[0] self.left = Tree(root[1]) self.right = None elif len(root) == 3: self.data = root[0] self.left = Tree(root[1]) self.right = Tree(root[2]) elif len(root) > 3: print("Illegal sentence") exit() elif isinstance(root, str): self.data = root self.left = None self.right = None elif isinstance(root, Tree): self.data = root.data self.left = root.left self.right = root.right def insert_left(self, new_node): """ Inserts """ if self.left is None: self.left = Tree(new_node) else: aux_tree = Tree(new_node) aux_tree.left = self.left self.left = aux_tree def insert_right(self, new_node): """ Inserts """ if self.right is None: self.right = Tree(new_node) else: aux_tree = Tree(new_node) aux_tree.left = self.right self.right = aux_tree def change_root_data(self, obj): """ Changes the valu of the root """ self.data = obj def get_root_data(self): """ Returns the value of the data """ return self.data def get_root_left(self): """ Returns the left tree """ return self.left def get_root_right(self): """ Returns the right tree """ return self.right def print_tree(self, level): """ Prints the whole tree """ print("Level: ", level) print("Root is: ", self.data) if isinstance(self.left, Tree): print("Left child is: ", self.left.get_root_data()) else: print("Left child is: ", self.left) if isinstance(self.right, Tree): print("Right child is: ", self.right.get_root_data()) else: print("Right child is: ", self.right) if isinstance(self.left, Tree): self.left.print_tree(level+1) if isinstance(self.right, Tree): self.right.print_tree(level+1)
false
6264b6239d29e1aee3a9b7139ffe1c93d549d980
alialavia/python-workshop-1
/sixth.py
1,671
4.375
4
""" To evaluate the good or bad score of a tweet, we count the number of good and bad words in it. if a word is good, increase the value of good_words by one else if a word is bad, increase the value of bad_words by one if good_words > bad_words then it's a good tweet otherwise it's a bad tweet """ import json import nltk from nltk.stem.porter import * stemmer = PorterStemmer() # Break down a string into words def get_words(str): return nltk.word_tokenize(str) # Calculate the average value of words in list_of_words def get_average_word_weight(list_of_words, word_weights): number_of_words = len(list_of_words) sum_of_word_weights = 0.0 if number_of_words == 0: return 0.0 # Iterate through the words in the tweet string for w in list_of_words: stemmed_word = stemmer.stem(w) if stemmed_word in word_weights: sum_of_word_weights += word_weights[stemmed_word] #else: #print ('"' + stemmed_word + '": 0.0,') return sum_of_word_weights / number_of_words def anaylse_tweet(tweet_string, word_weights): words = get_words(tweet_string) avg_tweet_weight = get_average_word_weight(words, word_weights) print ("The weight of the tweet is " + str(avg_tweet_weight)) if avg_tweet_weight > 0: print ("It's a good tweet") else: print ("It's a bad tweet") # Read tweets from an outside source def read_from_files(json_file, tweet_file): word_weights = {} with open(json_file) as f: s = f.read() word_weights = json.loads(s) with open(tweet_file) as f: for tweet in f: print(tweet) anaylse_tweet(tweet, word_weights) print("----------------------") read_from_files("word_weights.json", "tweets.txt")
true
cc7ef88686c8d373fd39688118340cda0064312d
brlala/Educative-Grokking-Coding-Exercise
/03. Pattern Two Pointer/7 Dutch National Flag Problem (medium).py
932
4.3125
4
# Problem Statement # Given an array containing 0s, 1s and 2s, sort the array in-place. You should treat numbers of the array as objects, # hence, we can’t count 0s, 1s, and 2s to recreate the array. # # The flag of the Netherlands consists of three colors: red, white and blue; and since our input array also consists # of three different numbers that is why it is called Dutch National Flag problem. def dutch_flag_sort(arr): """ Time: Space: """ n = len(arr) left, right = 0, n - 1 i = 0 while i <= right: if arr[i] == 0: arr[i], arr[left] = arr[left], arr[i] left += 1 if arr[i] == 2: arr[i], arr[right] = arr[right], arr[i] right -= 1 else: i += 1 print(arr) return arr print(dutch_flag_sort([1, 0, 2, 1, 0]) == [0, 0, 1, 1, 2]) print(dutch_flag_sort([2, 2, 0, 1, 2, 0]) == [0, 0, 1, 2, 2, 2])
true
8a9475e083e978b40b6e164e6ff65af999ce569e
brlala/Educative-Grokking-Coding-Exercise
/11. Pattern Subsets/3. Permutations (medium).py
862
4.1875
4
# Problem Statement # Given a set of distinct numbers, find all of its permutations. def find_permutations(nums): """ Time: Space: """ result = [] find_permutations_recursive(nums, 0, [], result) return result def find_permutations_recursive(nums, index, current_permutation, result): """ Time: Space: """ if index == len(nums): result.append(current_permutation) else: # create a new permutation by adding the current number at every position for i in range(len(current_permutation) + 1): new_permutation = list(current_permutation) new_permutation.insert(i, nums[index]) find_permutations_recursive(nums, index + 1, new_permutation, result) def main(): print("Here are all the permutations: " + str(find_permutations([1, 3, 5]))) main()
true
a6dbf81217f5306e17a270d2863d00168d42f31e
brlala/Educative-Grokking-Coding-Exercise
/04. Fast Slow pointers/2 Start of LinkedList Cycle (medium).py
1,784
4.15625
4
# Problem Statement # Given the head of a Singly LinkedList, write a function to determine if the LinkedList has a cycle in it or not. from __future__ import annotations class Node: def __init__(self, value, next: Node=None): self.value = value self.next = next def has_cycle(head: Node): """ Time: O(N) Space: O(1) """ slow, fast = head, head while fast is not None and fast.next is not None: fast = fast.next.next slow = slow.next if slow == fast: slow = head while slow != fast: # why this works explanation https://stackoverflow.com/a/10886319/10262825 # Floyd's cycle algorithm # https://cs.stackexchange.com/questions/10360/floyds-cycle-detection-algorithm-determining-the-starting-point-of-cycle # https://www.youtube.com/watch?v=9YTjXqqJEFE slow = slow.next fast = fast.next return slow.value return 0 def find_cycle_length(slow): current = slow cycle_length = 0 while True: current = current.next cycle_length += 1 if current == slow: break return cycle_length if __name__ == '__main__': head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) head.next.next.next.next = Node(5) head.next.next.next.next.next = Node(6) head.next.next.next.next.next.next = head.next.next print(f"LinkedList cycle start: {has_cycle(head)}") head.next.next.next.next.next.next = head.next.next.next print(f"LinkedList cycle start: {has_cycle(head)}") head.next.next.next.next.next.next = head print(f"LinkedList cycle start: {has_cycle(head)}")
true