blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
19669fa3f5182bcb05bc6dfaa74f26e6bc072231
DawnBee/01-Learning-Python-PY-Basics
/PY Practice problems/List Ends.py
636
4.34375
4
# LIST ENDS ''' Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25]) and makes a new list of only the first and last elements of the given list. For practice, write this code inside a function. ''' a = [5, 10, 15, 20, 25] b = [12,34,53,73,85,2,44,7,3] def list_ends(giv_list): new_list = [giv_list[0]] new_list.insert(1,giv_list[-1]) return new_list print(list_ends(a)) print(list_ends(b)) ''' # SOLUTION 2: def result(giv_list): new_list = [] for n in giv_list: if n == giv_list[-1] or n == giv_list[0]: new_list.append(n) return new_list print(result(a)) print(result(b)) '''
true
9e83da0e096858b004afda42349683e7030e0976
dimasun9707/project
/Lesson 5/dz3.py
802
4.125
4
# 3. Создать текстовый файл (не программно), построчно записать фамилии сотрудников и величину их окладов. # Определить, кто из сотрудников имеет оклад менее 20 тыс., вывести фамилии этих сотрудников. # Выполнить подсчет средней величины дохода сотрудников. # прочитать файл # сравнить вторые переменные - либо перевести их в другой формат # вывести минимальную переменную # name,salary with open('002.txt', 'r') as file: data = file.read().splitlines() for i in data: a = (i.split()) print(a)
false
ae1780b7ca503a7902fe3232a5106043e9acf006
yanayang01/python-playground
/students.py
2,179
4.25
4
# simple data entry program to practice manipulating data structures # track the english and math grades of n students # prints the average grade of the class def calculate_average(marks): average = sum(marks) / len(marks) * 1.0 return average def grades(): n = int(input("Enter the number of students: ")) data = {} # dictionary to store the data subjects = ('English', 'Math') # subjects that we're going to track # nested for loops to get the marks for the students for i in range(0, n): name = input(f"Enter name of student {i+1}: ") marks = [] # list of marks for j in subjects: s = int(input(f"Enter student {i+1}'s mark in {j}: ")) marks.append(s) data[name] = marks # for loop to calculate each student's average for i, j in data.items(): student_average = calculate_average(j) print(f"{i}'s grade average is {student_average:.1f}") # ilija updates def grades_better(): n = int(input("Enter the number of students: ")) data = {} # dictionary to store the data subjects = ('English', 'Math') # subjects that we're going to track # nested for loops to get the marks for the students for i in range(1, n+1): name = input(f"Enter name of student {i}: ") marks = {} # dictionary of marks for j in subjects: s = int(input(f"Enter student {i}'s mark in {j}: ")) marks[j] = s data[name] = marks # for loop to calculate each student's average for name, student in data.items(): marks = [] for sub in subjects: marks.append(student[sub]) student_average = calculate_average(marks) print(f"{name}'s grade average is {student_average:.1f}") # Calculate class average for sub in subjects: grades = [] for student in data.values(): grades.append(student[sub]) average = calculate_average(grades) print(f"class average for {sub} is {average:.1f}") # grades() grades_better() # print(calculate_average(4, [90, 100, 90, 95]))
true
6774ef2b95926ccced627dd00942bb1590b93d7d
yanayang01/python-playground
/loops.py
1,511
4.1875
4
# file to practice some (canta)loop(e)s! # while loop to output the fibonacci series def while_fib(limit=100): a, b = 0, 1 while b < limit: # print function has default end = \n # this will put everything on the same line, delimited by # a comma (and space)! print(b, end=', ') a, b = b, a + b # now a is b, and b is old b plus a! # creating a multiplication table using a while loop def while_multiple(): i = 1 print("-" * 50) # a line of dashes! while i < 11: n = 1 while n <= 10: print(f"{i*n:4d}", end=' ') n += 1 print() i += 1 print("-" * 50) # a line of dashes! # a while loop to print asterisks def while_print(): r = int(input("Enter the number of rows: ")) if r <= 10: while r >= 0: x = "*" * r print(x) r -= 1 else: print("That's too many rows!") # lists: comma seperated between square brackets a = [1, 2, 3, 4, 'Yana', 'Nico'] # access items in a list using square brackets and item position print(a[0]) print(a[5]) # access items in a list in reverse using negative positions print(a[-1]) print(a[-2]) # access a portion of the list using : or :: to indicate range print(a[1:4]) print(a[3:-1]) print(a[1::2]) # s[i:j:k] means slice s from i to j with step k # check if certain elements are in a list print('Yana' in a) print('Home' in a) # while_fib(limit=1000) # while_multiple() # while_print()
true
89f856fdc9157caa30158de4f69ce41518a5d896
paolo12/first_gift
/empireofcode/golf3.py
2,384
4.6875
5
def golf(numbers): return 0 print(golf((5, -3, -1, 2))) """ Stair Steps In emergencies, robots will always use staircases instead elevators. Sometimes we drill them in emergency scenarios, but often times it's a boring affair. So we've added little fun to the mix. There is a staircase with N steps and two platforms; one at the beginning of the stairs and the other at the end. On each step a number is written (ranging from -100 to 100 with the exception of 0.) Zeros are written on both platforms. You start going up the stairs from the first platform, to reach the top on the second one. You can move either to the next step or to the next step plus one. You must find the best path to maximize the sum of numbers on the stairs on your way up and return the final sum. __ __ / | ______ / | | _____ / | | _____| 0 __ / _____| 2 / || _____| -1 | _____| -3 ____| 5 0 Input: Numbers on stairs as a tuple of integers. Output: The final sum for the best path as an integer. Example: golf((5, -3, -1, 2)) == 6 golf((5, 6, -10, -7, 4)) == 8 golf((-11, 69, 77, -51, 23, 67, 35, 27, -25, 95)) == 393 golf((-21, -23, -69, -67, 1, 41, 97, 49, 27)) == 125 Precondition: 0 < |steps| ≤ 10 ∀ x ∈ steps: -100 < x < 100 Scoring: In this mission the main goal to make your code as short as possible. The shorter your code, the more points you earn. Your score for this mission is dynamic and directly related to the length of your code. Scoring in this mission is based on the number of characters used in your code (comment lines are not counted). Rank1: Any code length. Rank2: Your code should be shorter than 250 characters. Rank3: Your code should be shorter than 150 characters. How it is used: This is a classical example of an optimization problem. It can show you the difference between the various methods of programming; such as dynamic programming and recursion. """ # if __name__ == '__main__': # # These "asserts" using only for self-checking and not necessary for auto-testing # assert golf((5, -3, -1, 2)) == 6 # assert golf((5, 6, -10, -7, 4)) == 8 # assert golf((-11, 69, 77, -51, 23, 67, 35, 27, -25, 95)) == 393 # assert golf((-21, -23, -69, -67, 1, 41, 97, 49, 27)) == 125 # print("Use 'Check' to earn sweet rewards!")
true
c409a12cc580589fb8d5ee78331600f8705559a4
HarshCasper/Dataquest-Tracks
/Calculus for Machine Learning/Understanding Linear and Nonlinear Functions-157.py
851
4.28125
4
## 1. Why Learn Calculus? ## import numpy as np import matplotlib.pyplot as plt x = np.linspace(0,3,100) y = -(x ** 2) + 3 * x - 1 plt.plot(x,y) plt.show() ## 4. Math Behind Slope ## def slope(x1, x2, y1, y2): s = (y2 - y1) / (x2 - x1) return s slope_one = slope(0,4,1,13) slope_two = slope(5,-1,16,-2) print(slope_one) print(slope_two) ## 6. Secant Lines ## import seaborn seaborn.set(style='darkgrid') def draw_secant(x_values): x = np.linspace(-20,30,100) y = -1*(x**2) + x*3 - 1 plt.plot(x,y, c = 'blue') y_0 = -1*(x_values[0] ** 2) + x_values[0] * 3 - 1 y_1 = -1*(x_values[1] ** 2) + x_values[1] * 3 - 1 m = (y_1 - y_0) / (x_values[1] - x_values[0]) b = y_1 - m * x_values[1] y_s = x * m + b plt.plot(x, y_s, c = 'red') plt.show() draw_secant([3,5]) draw_secant([3,10]) draw_secant([3,15])
false
cdaf812821b59e87484ecd3e5bf864884ad1022a
syed-ayman-quadri/Quiz_With_Scoring_For_Class_8
/Quiz_With_Score.py
2,787
4.28125
4
print("Welcome to Class 8 General Science Quiz") print() wanna_play = (input("Do you want to play? ").lower()) print() if wanna_play != "yes": print("The game has ended. See you soon! :)") quit() print("Ok then, Let's Play!") print() score = 0 print("READ THE INSTRUCTIONS CAREFULLY") print() ins = """Instructions: 1. There are 10 questions in this Quiz. 2. After typing the answer press Enter. 3. Don't write the answers in sentences, instead write in words. 4. Make sure you write the correct spelling otherwise your answer may be wrong. 5. Write the answers which have numbers in digits instead of words.""" print(ins) print() ans = input("1. ________ is called force per unit area. ") if ans.lower() == "pressure": print("Correct!") score += 1 else: print("Wrong!") print('Pressure') print() ans = input("2. Due to which force does an apple fall from a tree? ") if ans.lower() == "gravitational force": print("Correct!") score += 1 else: print("Wrong!") print('Gravitational Force') print() ans = input("3. Is electrostatic force a contact force? ") if ans.lower() == "no": print("Correct!") score += 1 else: print("Wrong!") print("It is a non-contact force.") print() ans = int(input("4. How many zones are there in a flame? ")) if ans == 3: print("Correct!") score += 1 else: print("Wrong!") print("3") print() ans = input("5. What is the Full Form of LPG? (MIND YOUR SPELLING) ") if ans.lower() == "liquefied petroleum gas": print("Correct!") score += 1 else: print("Wrong!") print("Liquefied Petroleum Gas") print() ans = input("6. The lowest temperature at which a substance catches fire is called? ") if ans.lower() == "ignition temperature": print("Correct!") score += 1 else: print("Wrong!") print("Ignition Temperature") print() ans = input("7. Is water a lubricant? ") if ans.lower() == "no": print("Correct!") score += 1 else: print("Wrong!") print("No, it is not.") print() ans = input("8. The Frictional Force exerted by fluids is called? ") if ans.lower() == "drag": print("Correct!") score += 1 else: print("Wrong!") print("Drag") print() ans = input("9. Is Paramecium a multicellular organism? ") if ans.lower() == "no": print("Correct!") score += 1 else: print("Wrong!") print("It is unicellular and has a single cell.") print() ans = int(input("10. White light consists of how many colours? ")) if ans == 7: print("Correct!") score += 1 else: print("Wrong!") print("7") print() input("Press Enter To View Your Score") print() print("You got " + str(score) + " answer correct!!" ) print("Your Percentage Of Correct Answers is : " + str((score/10)*100) + "%" ) print()
true
10ebefcfa9eb5aba2bae86f80f8e2409a3be8bd2
listenviolet/python
/2-4-judge.py
359
4.25
4
#is elif else age = 20 if age >= 6: print('teenager') elif age >=18: print('adult') else: print('kid') #exercise height = 1.75 weight = 80.5 bmi = weight/(height*height) print(bmi) if bmi < 18.5: print('1') elif bmi >=18.5 and bmi <25: print('2') elif bmi >=25 and bmi <28: print('3') elif bmi >=28 and bmi <=32: print('4') elif bmi > 32: print('5')
false
9d3095015ed772e5b0dd2d6698c1e859abda10c3
christacaggiano/sorting-functions
/sorting/quick_sort.py
1,682
4.375
4
# quick sort and bubble sort implementation hw # jan 2018 # author <christa.caggiano@ucsf.edu> import random conditional = 0 assignments = 0 def quick_sort(l): """ :param l: unsorted list :return: sorted list pick a random pivot. Put all the items in the list that are less than the pivot in a 'less than list' or greater than in a 'greater than' list. Recursively call quick_sort on these two lists so that a new pivot is chosen each time, sorting smaller and smaller lists until the sorted list is returned. """ global conditional global assignments conditional += 1 if len(l) == 0 or len(l) == 1: # base case, where list is empty or 1 item return l assignments += 3 pivot = random.randint(0, len(l)-1) # pick random pivot # initialize lists for sorting less_than = [] greater_than = [] # for each index in l, if the index isn't the pivot, # add to appropriate list for index, item in enumerate(l): assignments += 1 conditional += 1 if not index == pivot: conditional += 1 assignments += 1 if item < l[pivot]: less_than.append(item) else: greater_than.append(item) # recursively call the sorting function until a sorted list is returned return quick_sort(less_than) + [l[pivot]] + quick_sort(greater_than) def quicksort_count(l): """ :param l: unsorted list :return: number of conditionals and number of assignments """ global conditional global assignments conditional = 0 assignments = 0 quick_sort(l) return conditional, assignments
true
cb990e4db7924928afa27bc794635b021bf72036
Pavan9676/Python-Codes
/BasicProgramOfArrays/PrintArrayWithRange.py
1,024
4.34375
4
from array import * arr = array('i', []) n = int(input("Enter size of array: ")) for i in range(n): x = int(input("Enter next element: ")) arr.append(x) print("1 = smallest value \n2 = second smallest value\n3 = third smallest value\n4 = fourth smallest value\n" "5 = fifth smallest value") n1 = int(input("Enter your choice: ")) for j in range(n1): """if n1==1: this is normal logic print(arr[0]) break elif n1==2: print(arr[1]) break elif n1==3: print(arr[2]) break elif n1==4: print(arr[3]) break elif n1==5: print(arr[4]) break :""" print(arr[n1-1]) break # 18) print the range of heights which you want arr = array('i', []) n = int(input("Enter size of array: ")) for i in range(n): x = int(input("Enter next element: ")) arr.append(x) print(arr) num = sorted(arr) print("The sorted array: ", num) y = int(input("enter the nth height of array: ")) print(num[y-1])
false
f58834544e77f2e6e8e43d285f53d6bc046bc807
PuzzleDude98/pythoncode
/MachineLearning.py
1,711
4.1875
4
""" Machine_Learning Description: Use basic machine learning to make a comprehensible sentence """ import random #word_list2=["the","small","cute","rubber","duckies","will","go","to","war","soon"] """ pos1=random.choice(word_list) pos2=random.choice(word_list) pos3=random.choice(word_list) pos4=random.choice(word_list) pos5=random.choice(word_list) pos6=random.choice(word_list) pos7=random.choice(word_list) pos8=random.choice(word_list) pos9=random.choice(word_list) pos10=random.choice(word_list) """ """ while True: word=random.choice(word_list) print(word) cute=input("Cute? ") if cute=="y": word_list.append(word) elif cute=="stop": break """ print("Welcome to the machine learning program!") print("Say if each word is a boys word!(y/n)") tr=input("Enter the amount of training data to automate") nos=[] word_list=["cute","adorable","baby","kitten","love","war","rage","guns","tanks","explosions"] print("AUTOMATED TRAINING DATA") print("~~~~~~~~~~~~~~~~~~~~~~~") print() for x in range(tr): num=random.randint(0,(len(word_list)-1)) word=word_list[num] print(word) if word=="cute" or word=="adorable" or word=="baby" or word=="kitten" or word=="love": cute="y" else: cute="n" print("Cute?",cute) if cute=="y": word_list.append(word) elif cute=="n": nos.append(word) if nos.count(word)>=10: nos.remove(word) word_list.remove(word) print() print() print() print("HUMAN TRAINING DATA:") print() while True: print() word=random.choice(word_list) print(word) cute=input("Cute? ") if cute=="y": word_list.append(word) elif cute=="stop": break
true
81f9b01ec420acead633b49af03305543780f18f
schatto1/weekly-python-exercises
/A1 01 - ISBN Checker/solution.py
839
4.21875
4
#!/usr/bin/env python3 # Get the ISBN from the user user_isbn = input("Enter an ISBN-13: ").strip() isbn = '' # Only capture digits from the user's input for one_digit in user_isbn: if one_digit.isdigit(): isbn += one_digit check_digit = isbn[-1] print(f"Checking '{isbn}', check digit {check_digit}") is_valid = False # Calculate the checksum if len(isbn) == 13: total = 0 for index, digit in enumerate(isbn[:12]): if index % 2: # odd index? 3*digit total += 3 * int(digit) else: total += int(digit) user_check_digit = 10 - (total % 10) if user_check_digit == 10: user_check_digit = 0 if user_check_digit == int(check_digit): is_valid = True if is_valid: print("Your ISBN is valid") else: print("Your ISBN is invalid")
true
a581c3a1ff965b040c11140330ce7c47a39c389c
gustavodomenico/Python-Exercises
/WarmUp/003_sum_doubles.py
337
4.1875
4
# Given two int values, return their sum. Unless the two values are the same, then return double their sum. # sum_double(1, 2) = 3 # sum_double(3, 2) = 5 # sum_double(2, 2) = 8 def sum_double(a, b): sum = a + b return sum if a != b else sum * 2 assert sum_double(1, 2) is 3 assert sum_double(3, 2) is 5 assert sum_double(2, 2) is 8
true
a93863ab595691a9de6e67657b918ca374395e77
gustavodomenico/Python-Exercises
/Strings/005_extra_end.py
302
4.125
4
# Given a string, return a new string made of 3 copies of the last 2 chars of the original # string. The string length will be at least 2. def extra_end(str): sub = str[-2:] return sub * 3 assert extra_end('Hello') == 'lololo' assert extra_end('ab') == 'ababab' assert extra_end('Hi') == 'HiHiHi'
true
b013a85e681cfc8fc9b383e022f1721853b22c8b
angiereyes99/coding-interview-practice
/easy-problems/ShuffleArray.py
1,370
4.15625
4
# PROBLEM: # Given the array nums consisting of 2n elements # in the form [x1,x2,...,xn,y1,y2,...,yn]. # Return the array in the form [x1,y1,x2,y2,...,xn,yn]. # EXAMPLE: # Input: nums = [2,5,1,3,4,7], n = 3 # Output: [2,3,5,4,1,7] # Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7]. from typing import List class Solution: # APPROACH: SPLIT ARRAYS IN HALF # - We just split the given arr in half # and add elements from the other halfs every # other space in our output array. In this method, # we assume that the arrays will always be even. # And in this method, you can notice I do not use # n at all. All test cases passed. # # Runtime 52 ms # Memory: 14 MB # Faster than 99.02% of Python3 submissions. # Less than 100% of Python3 submissions memory usage. def approach(self, arr: List[int], n: int) -> List[int]: result = [] # EX: nums = [2,5,1,3,4,7] a_half = arr[:len(arr)//2] # [2,5,1] b_half = arr[len(arr)//2:] # [3,4,7] for i in range(len(a_half)): result.append(a_half[i]) result.append(b_half[i]) # result = [a_half, b_half, ...,] return result if __name__ == '__main__': solution = Solution() arr = [2,5,1,3,4,7] n = 3 print(solution.approach(arr, n))
true
36a0d3f254a5e2199419a2dc38fe87efe1719ee4
smbrannen1/Python
/test_average_scores.py
455
4.125
4
""" Program: test_average_scores.py Author: Suzanne Brannen Last Date Modified: 09/13/2020 """ import unittest class average_scores(unittest.TestCase): def average(): score1, score2, score3 = eval(input("Enter 3 scores separated by a comma: ")) #get input from user average = (score1 + score2 + score3)/3 #calculation to add the 3 scores and /3 to generate average score if __name__ == '__main__': unittest.main()
true
4c14a1959f38739537d6e3de9c9f4449ce2bf581
Nikola-Putnik/Projet2_Groupe_B_2-Partie-2-Web
/0-divers/idée.py
1,067
4.21875
4
""" Ce code affiche les moyennes de chaque cours et la moyenne générale """ import sqlite3 # Accès à la base de données conn = sqlite3.connect('inginious.sqlite') # Le curseur permettra l'envoi des commandes SQL cursor = conn.cursor() données = {} l1=[] moyenne = 0 for row in cursor.execute("SELECT course, avg(grade)from user_tasks GROUP BY course"): # Je choisis la moyenne pour chaque cours l1.append(row) #j'insère le tuple( cours,moyenne) dans une liste. chaque element est un tuple for i in l1: x,y = i #je parcours ma liste et j'assigne x au cours et y a sa moyenne données[x] =y # chaque element de ma liste transormé est ajouté dans mon dictionnaire données for row in cursor.execute("SELECT avg(grade) from user_tasks"): # je calcule la moyenne générale moyenne = row for key,value in données.items(): print("le cours {} à une moyenne de {} ´%".format(key,value)) print("{} ´% ceci est la moyenne générale".format(moyenne)) # Toujours fermer la connexion quand elle n'est plus utile conn.close()
false
3348188c8b3ac3bdc6c0151b1483b587383b5907
moshun8/IS211_Assignment1
/assignment1_part1.py
873
4.125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """Part 1""" def listDivide(numbers, divide=2): ''' Returns number of items in a list divisible by the divide parameter ''' counter = 0 for num in numbers: if num % divide == 0: counter += 1 return counter class ListDivideException(Exception): pass def testListDivide(): ''' Tests function listDivide ''' try: assert listDivide([1, 2, 3, 4, 5]) == 2, '1st' assert listDivide([2, 4, 6, 8, 10]) == 5, '2nd' assert listDivide([30, 54, 63, 98, 10], divide=10) == 2, '3rd' assert listDivide([]) == 0, '4th' assert listDivide([1, 2, 3, 4, 5], divide=1) == 5, '5th' # assert listDivide([1, 2, 3, 4, 5],0) == 2, 'test' except: raise ListDivideException if __name__ == "__main__": testListDivide()
false
30342f391afb66983d6a02f447198799116e237d
katas-meltem/katas
/feature3.py
1,254
4.46875
4
#Source : https://agilekatas.co.uk/katas/FizzBuzz-Kata #Feature 3 : Creating Fizz Buzz Variations input = int(input("Please enter a number : ")) #---------------------------------------------------------------------- #Using a Custom Substitution """As a player I want to be able to choose my own substitutions So that I can tailor the game to my preferences Given I have substituted multiples of two for 'fuzz' When I enter $number Then $result is returned """ def hav_hav(input): if input % 2 == 0: return "hav hav" else: return input #print("{} → {}".format(input, hav_hav(input))) #---------------------------------------------------------------------- #Linking Custom Substitutions Together """As a player I want my substitutions to work the same way as Fizz Buzz So that the essence of the game remains the same Given I have substituted multiples of two for 'fuzz' And I have substituted multiples of three for 'bizz' When I enter $number Then $result is returned """ def hav_vız(input): if input % 2 == 0 and input % 3 == 0: return "hav hav vız vız" elif input % 2 == 0: return "hav hav" elif input % 3 == 0: return "vız vız" else: return input print("{} → {}".format(input, hav_vız(input)))
true
4967fed6c262d287059b93aa646b88470e56e83e
vekkev/ProgrammingConcepts
/Python/Übungen/Assignment2/Assignmentpy02.py
2,825
4.4375
4
#!/usr/bin/env python3 # Requirement for Python Upload 02 about lists and lambda and for each and ...: # # a) Comments required: Add your Name # remove this comments or other unused lines of code # b) Return the longest word of a list in four different ways: # b1) longestWord_with_loop # loop through the list and.... # b2) longestWord_with_recursion # # call a function again and again until ... # b3) longestWord_with_reduce # import functools # check out the reduce function: help(functools.reduce) # b4) longestWord_with_max # what is this optional 'key' parameter good for? # c) for each solution add a comment about # c1) (+) advantage # c2) (-) disadvantage # Kevin Gruber def longestWord_with_loop(w): result = None longest_size = 0 for word in w: if len(word) > longest_size: longest_size = len(word) longest_word = word result = longest_word # c1: (+) advantage: after "max" this is my favourite method of getting the longest_word from a list return result def longestWord_with_recursion(wrds): result = None if len(wrds) == 1: result = wrds[0] return result elif len(wrds[0]) < len(wrds[1]): wrds.pop(0) return longestWord_with_recursion(words) elif len(wrds[0]) >= len(wrds[1]): wrds.pop(1) return longestWord_with_recursion(words) # c1: (+) advantage: simpole to read # c2: (-) disadvantage: longest method of solving return result def longestWord_with_reduce(w): result = None import functools result = functools.reduce(lambda w, longest_word: w if len(w) > len(longest_word) else longest_word, w) # c2: (-) disadvantage: very nested method of solving and you have to import a library return result def longestWord_with_max(w): result = None result = max(w, key=len) return result # My personal impression of this way to solve the problem # c1: (+) advantage: shortest way to get the longest word # Just for testing the implemented functions: # we create demo data quotes = """The Scandal of education is that every time you teach something, you deprive a student of the pleasure and benefit of discovery. (Seymour Papert, born February 29, 1928 died July 31 2016) If debugging is the process of removing bugs, then programming must be the process of putting them in. (Edsger W. Dijkstra) """ import re # \W to substitute non-word-chars quotes = re.sub(r'\W', ' ', quotes) words = quotes.split() # we test the functions with demo data print(longestWord_with_loop(words)) # should print: .... print(longestWord_with_recursion(words)) # should print: .... print(longestWord_with_reduce(words)) # should print: .... print(longestWord_with_max(words)) # should print: ....
true
83b8823099b7a8a05018f8cd9e25ecb68cd9c7fe
RRCHcc/python_base
/python_base/day10/作业/day10作业.py
1,831
4.125
4
""" 1. 使用面向对象思想,写出下列场景: 玩家(攻击力)攻击敌人,敌人受伤(血量)后掉血,还可能死亡(播放动画). 敌人(攻击力)攻击力攻击玩家,玩家(血量)受伤后碎屏,还可能死亡(游戏结束). 程序调试,画出内存图. """ class Play: def __init__(self, atk=0, hp=0): self.atk = atk self.hp = hp @property def atk(self): return self.__atk @atk.setter def atk(self,value): self.__atk = value @property def hp(self): return self.__hp @hp.setter def hp(self, value): self.__hp = value def attker_enemy(self, enemy): # enemy.enemy_hp -= self.atk print("打死你") # 调用敌人受伤方法 enemy.enemy_hurt(self.atk) def play_hurt(self,value): self.hp -= value if self.hp <= 0: self.__death() def __death(self): print("玩家死亡") class Enemy: def __init__(self, atk=0, hp=0): self.enemy_atk= atk self.enemy_hp= hp @property def enemy_atk(self): return self.__enemy_atk @enemy_atk.setter def enemy_atk(self,value): self.__enemy_atk = value @property def enemy_hp(self): return self.__enemy_hp @enemy_hp.setter def enemy_hp(self, value): self.__enemy_hp = value def attker_play(self, play): print("打死你") play.paly_hurt(self.enemy_atk) def enemy_hurt(self,value): self.enemy_hp -= value if self.enemy_hp <= 0: self.__death() def __death(self): print("死啦,播放动画") p01 = Play(100,10000) e01 = Enemy(10,2000) # while e01.enemy_hp > 0 or p01.hp > 0: # p01.attker_enemy(e01) # e01.attker_play(p01) p01.attker_enemy(e01)
false
ca9290d9f15ff2e833f80811492ab6166d965f5a
RRCHcc/python_base
/python_base/day02/算数运算符.py
235
4.15625
4
""" 算数运算符(针对数值进行) 比较运算符 """ num01=5 num02=2 print(num01//num02) # 取 %作用: 判断一个数能否被另外的数整除 print(num01%5 ==0) # %作用2: 获取个位 print(67 % 10)
false
bf90e64c8250e4c8f85f3365b2e4ae7d84ac7e8f
RRCHcc/python_base
/python_base/day12/exercise03.py
1,033
4.46875
4
""" 练习: 实现向量类与整数做减法 乘法运算 """ class Vector: """ 向量 """ def __init__(self,x): self.x = x def __str__(self): return "向量的x变量是:%s"%self.x def __sub__(self, other): return Vector(self.x - other) def __mul__(self, other): return Vector(self.x * other) def __add__(self, other): return Vector(self.x+other) def __radd__(self, other): return Vector(self.x + other) def __rmul__(self, other): return Vector(self.x * other) def __isub__(self, other): self.x -= other return self def __imul__(self, other): self.x *= other return self v01 = Vector(10) v001 =Vector(2) v02 = v01 -3 v03 = v01 * 3 print(v02) print(v03) """ 实现整数与向量做 减法/乘法 向量与向量 """ v04 = 4+ v01 print(v04) v05 = 4* v01 print(v05) v06 = v04 + v05 print(v06.x) #实现向量类与整数 做累计减法/乘法 v01 -=1 print(v01) v01 *= 2 print(v01)
false
95311a2ec1fb1a4b98218f74cae5f9b223866cfe
RRCHcc/python_base
/python_base/day16/exercise02.py
318
4.375
4
""" 练习: 使用列表推导式,与生成器表达式,获取list02中大于三的数据 """ list02 = [2, 3, 4, 6] result = [item for item in list02 if item > 3] print(result) result = (item for item in list02 if item > 3) for item in result:#循环一次,计算一次,返回一次 print(item)
false
d322849e81c7e2d3a525b5dc84038df45c799d96
sol83/python-code_in_place-section3
/running_total.py
795
4.15625
4
""" Running Total Write a program that asks a user to continuously enter numbers and print out the running total, the sum of all the numbers so far. Once you get the program working, see if you can modify it so that the program stops when the user enters a 0. Enter a value: 7 Running total is 7 Enter a value: 3 Running total is 10 Enter a value: 5 Running total is 15 Enter a value: 12 Running total is 27 Enter a value: 0 """ def main(): total = 0 while True: value = int(input("Enter a value: ")) if value == 0: # end the loop if the user types 0 break # otherwise, calculate the new running total total += value print("Running total is " + str(total)) print() if __name__ == '__main__': main()
true
16bf6a351313261e04e694637494e6d58231d516
ajinra020307/pythontutorial
/12.tuples.py
335
4.4375
4
#tuples are similar to arrays but cannot br changed thistuple = ("apple", "banana", "cherry") thistuple2=(2,3,4) print(thistuple) print(thistuple[2]) print(thistuple[-2]) print(thistuple[0:2]) print('apple' in thistuple) print(len(thistuple)) #returns a new tuple print(thistuple+thistuple2) for value in thistuple: print(value)
true
d1879d75f906f6408c1f9ad035f0a2b7eaeee2ed
bg588/PythonCourse
/src/Dictionaries.py
1,688
4.1875
4
# Dictionary is like a HashMap in Java, Key Value pairs. Data structures basically lists and maps, in any language # Order isnt guaranteed in dictionaries. Think of it as a tiny database. All keys must be unique. Can repeat values # as many times as you'd like. # Create an empty dictionary emptydict = dict() # Instantiate treasurechest = {'gold coins': 5, 'silver coins': 10} print(treasurechest) print("We have", treasurechest.get('gold coins'), "XAU coins") numberofcoins = treasurechest.get('gold coins') print("Add one coin") numberofcoins += 1 # assign a value to the key treasurechest['gold coins'] = numberofcoins print("We now have", treasurechest.get('gold coins'), "XAU coins") # Also an easier way to increment/update the current value treasurechest['gold coins'] = treasurechest['gold coins'] + 2 print("We now have", treasurechest.get('gold coins'), "XAU coins") # Natch can throw errors if you try to get someth that isnt there, so you can get around that with this hack # this is handy to initialise in a loop x = treasurechest.get('bronze coins', 0) print("We have", x, "bronze coins") # loop through keys for key in treasurechest: print("We have", treasurechest[key], key) print("Keys are ", treasurechest.keys()) print("Values are", treasurechest.values()) # a list of key value pairs : print("Items are", treasurechest.items()) # easy way to see keys and values in dictionary, can iterate on two things at same time which is quite unique for k, v in treasurechest.items(): print(k, v) string = "this is a line" print(string.split()[1]) # Sorting a dictionary using sorted() d = {'a': 10, 'c': 22, 'b': 1} print(d.items()) print(sorted(d.items()))
true
676530b87cfa3432821cd981683e6f0eb1f6a5e8
1ceRocks/PLD-Assignment-2
/amountandprice.py
827
4.21875
4
#Rendered a welcoming greet to a user after the initialization of the program. print("\nWelcome to Villariza Foods! Our available product for today is apple. \n") money = float(input("How much cash do you possess right now? \n> PHP: ")) apple = float(input("\nWhat is the cost of an apple per item? \n> PHP: ")) #Displayed an aditional feature (updated: comma) and response when a user does not have enough money to buy a single quantity of Apple. if money >= apple: exchange = money % apple apple_maxQuantity = int(money // apple) print(f"\nYou can buy {apple_maxQuantity: ,} apples and your change is {exchange:.2f} PHP.") else: moneyShortage = float(apple - money) print(f"\nSorry, but you do not have enough money to buy an apple. You need {moneyShortage:.2f} PHP in order to purchase a single apple.")
true
9f924095ca0a39298e6712adfa2f3d06af82ecb4
gtechzilla/OpenCV_course
/basics/drawing_images.py
2,154
4.34375
4
import cv2 import numpy as np #creating a black square image #we use numpy zeros function #dimensions are 512 by 512,the 3 is for the color dimension image = np.zeros((512,512,3),np.uint8) #for a black and white images #for a black and white image we remove the color dimension img_bw = np.zeros((512,512),np.uint8) cv2.imshow("Black rectange(colored)",image) cv2.imshow("Black rectange(black&white)",img_bw) #Drawing a line over our black square #we use opencv's line function #the arguments are as follows '''we start with the image,start co-ordinate of the line, end co-ordinate,color of the line(g,g,r),thickness of the line''' cv2.line(image,(0,0),(200,512),(240,230,0),5) cv2.imshow('our_line',image) #drawing a rectangle #we use the rectangle cv2 function #arguments are the same as with the line function #we drew it on our black and white image cv2.rectangle(img_bw,(0,0),(100,100),(128,240,0),5) cv2.imshow('Our green rectange',img_bw) #what about circles #we use cv2 circle function img_circle=np.zeros((300,300,3),np.uint8) img_circle2=np.zeros((300,300,3),np.uint8) '''its arguments are (image,center co-ordinate,radius,color,fill)''' cv2.circle(img_circle,(150,150),90,(0,0,255),1) cv2.imshow('image with circle',img_circle) #filled circle cv2.circle(img_circle2,(150,150),90,(0,0,255),-1) cv2.imshow('image with circle filled',img_circle2) #lets draw a polygon img_polygon=np.zeros((400,600,3),np.uint8) #now we define four points points=np.array([[10,50],[300,50],[80,200],[60,400]],np.int32) #reshaping the points into the form required by polylines points=points.reshape(-1,1,2) cv2.polylines(img_polygon,[points],True,(0,255,0),3) cv2.imshow('polygon',img_polygon) #we can add text to our images #we use opencv putText function '''arguments are in the following order (image,text to display,bottom left starting point,font,font size,color,thickness) ''' #please check the documentation to know the various fonts opencv supports image_text=np.zeros((512,512),np.uint8) cv2.putText(image_text,'hey ppl',(75,290),cv2.FONT_HERSHEY_COMPLEX,2,(100,170,0),3) cv2.imshow('image_text',image_text) cv2.waitKey(0) cv2.destroyAllWindows()
true
4b3cd50f7c7d8496d40ea96cd051463860de2d47
brunocamps/python3thehardway
/exercise3/numbersAndMath.py
629
4.34375
4
print(2 % 10) print("I will now count my chickens: ") print("Hens", 25 + 30 / 6) print("Roosters", 100 - 25 * 3 % 4) print("Now I will count the eggs:") print(3+2+1-5+4%2-1/4+6) print("Is it true that 3 + 2 < 5- 7?") print("What is 3 + 2? ", 3+2) print("What is 5 - 7? ", 5 - 7) print("Oh, that's why it's false!") print("How about some more.") print("Is it greater?", 5 >= -2) #Compares is 5 is more than or equal to -2 #and then returns boolean value True or False print("Is it greater or equal?", 5 >= -2) print("Is it less or equal?", 5 <= -2) # % character: modulus. print(10 % 9) #Rest of division. Remaining value
true
34737eff65e4f754bf136f09a0136873238bc1e4
trojrobert/algorithm_and_data_structure
/data_structures/stacks_and_queues/queue_with_linked_list.py
1,243
4.125
4
class Node(): def __init__(self, value): self.value = value self.next = None class Queue: def __init__(self): self.first = None self.last = None self.length = 0 def __str__(self): return str(self.__dict__) def peek(self): return self.first.value def enqueue(self, value): new_node = Node(value) if self.length == 0: self.first = new_node self.last = new_node else: self.last.next = new_node self.last = new_node self.length += 1 def dequeue(self): if self.length == 0: return None temp = self.first self.first = self.first.next self.length -= 1 def printl(self): temp = self.first while temp != None: print(f"{temp.value} ", end = " -> ") temp = temp.next print() if __name__ == "__main__": my_queue = Queue() my_queue.enqueue('google') my_queue.enqueue('microsoft') my_queue.enqueue('facebook') my_queue.enqueue('apple') my_queue.printl() my_queue.dequeue() my_queue.printl() x = my_queue.peek() print(x)
false
2e5a229d01e477b1a669f61db66e662cbc871917
trojrobert/algorithm_and_data_structure
/algorithms/sorting/bubble_sort.py
418
4.28125
4
def bubble_sort(array): length_array = len(array) for i in range(length_array -1): for j in range(length_array -1): if (array[j] > array[j+1]): #Swap number temp = array[j] array[j] = array[j+1] array[j+1]= temp return array if __name__ == "__main__": numbers = [4, 7, 2, 1, 6, 3] print(bubble_sort(numbers))
false
d03c60967cff05de2dc98242091c203944099131
Biaku/introduccion-python
/5-listas.py
386
4.34375
4
# Listas # https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions numeros = [10, 15, 20] print(numeros) # agregar elemento al final de lista numeros.append(25) print(numeros) # agregar elemento en X posicion numeros.insert(0, 5) print(numeros) # eliminar elemento numeros.remove(25) print(numeros) # eliminar elemento por indice numeros.pop(0) print(numeros)
false
1f652d6b545dcd84783322acb70002c5dd83b629
JordanHolmes/cp1404practicals
/prac_04/Extension & Practice work/repeated_strings.py
380
4.15625
4
inputed_strings = [] repeated_strings = [] user_string = input("Enter a string: ") while user_string != "": if user_string in inputed_strings: repeated_strings.append(user_string) inputed_strings.append(user_string) user_string = input("Enter a string: ") print("Repeated strings: {}".format(repeated_strings)) # TODO: format repeated words in string format
true
7205901d13d3200dcf04c1645037b92d5c78b3ab
reynardasis/code-sample
/vowels.py
236
4.21875
4
text = raw_input("Enter the string: ").replace(" ","") #get string then replace spaces with '' or removing spaces vowels = 'aeiou' print [a for a in text if a not in vowels] print "".join(letter for letter in text if letter in vowels)
true
be6525659c999e5d7bc40597782bc4549caba9cb
SergeiChaban/GRAF
/HW-easy-2.py
318
4.21875
4
# Задача-2: # Даны два произвольные списка. # Удалите из первого списка элементы, присутствующие во втором списке. x = [45,34,23,56,67,78,90] y = [5,34,23,89,32] i = 0 result = [x[i] for x[i] in x if x[i] not in y] print(result)
false
c8d6ae24bc5e883f1560de4f27928429a586be48
avadai/hello-world
/Chapter3Project6.py
302
4.21875
4
import math iterations = int(input("How many iterations would you like to calculate? ")) while iterations > 48: print("The number you entered is too large!") iterations = int(input("How many iterations would you like to calculate? ")) else: print('%.*f' % (iterations, math.pi))
true
9a739c2d7bebcfb6d8220c8d8cf652f61631ac53
avadai/hello-world
/Week4Page67.py
603
4.125
4
Python 3.8.4 (tags/v3.8.4:dfa645a, Jul 13 2020, 16:30:28) [MSC v.1926 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> product = 1 >>> for count in range(1, 5): product = product * count >>> product 24 >>> for count in range(1, 3 + 1): print(count * 3) 3 6 9 >>> lower = int(input("Enter the lower bount: ")) Enter the lower bount: 1 >>> upper = int(input("Enter the upper bound: ")) Enter the upper bound: 10 >>> theSum = 0 >>> for number in range(lower, upper + 1): theSum = theSum + number >>> theSum 55 >>>
true
2a872769cf9cf8f39c708066ca61a76362cea0a9
avadai/hello-world
/Week9Project9.py
418
4.25
4
import functools # Asks the user for a file, opens it and reads it. f = input("Enter a filename: ") file = open(f, 'r') file = file.read() # The contents of the file are put into a list file = file.split() # Turns the contents of the list into integer values file = list(map(int, file)) # The lambda function is used to find the average. print(functools.reduce(lambda x, y: x+y / len(file), file, 0))
true
354f80cf7e3b80751c6eb60a3b20414401380b6e
kaestro/algorithm-study
/QuestionBox/jan 29th.py
1,407
4.15625
4
#https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/583/week-5-january-29th-january-31st/3621/ from typing import List from collections import defaultdict # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def __init__(self): self.trav = defaultdict(list) def verticalTraversal(self, root: TreeNode) -> List[List[int]]: self.visit(0,0,root) res, prev_x, cur = [], None, [] for key, value in sorted(self.trav.items(), key=lambda x:(x[0][0], -x[0][1])): value.sort() if prev_x is None or prev_x != key[0]: res.append(cur) cur = value prev_x = key[0] else: cur += value res.append(cur) res.pop(0) return res def visit(self, x:int, y:int, node:TreeNode): if node is None: return self.trav[x, y].append(node.val) self.visit(x-1, y-1, node.left) self.visit(x+1, y-1, node.right) if __name__ == "__main__": root = TreeNode(3) root.left = TreeNode(9) node = TreeNode(20) node.left = TreeNode(15) node.right = TreeNode(7) root.right = node sol = Solution() sol.verticalTraversal(root)
true
fd488f27c50c6325c5c61e1a3128cbd8e4ef4462
Javaz89/Python
/controlflujo.py
537
4.25
4
# condicional if: condiciona una ejecucion con determinada condicion o evaluacion # comparadores: <, >, ==, !=, <=, >=, if 2 > 5: print("primera") elif 3 > 5: # si la primera condicion ya fue verdadera elif no se evalua print("segunda") elif 4 > 5: print("tercera") else: # si ninguna de todas las condiciones fue verdadera se ejecuta else print("cuarta") # if ternario if y else en una sola linea print('if verdadero') if 5 > 2 else print('else') # operadores logicos and, or if 3 > 2 and 1 > 0: print("verdad")
false
302e867c9994877ab064fd674f0e43cbaa055bc1
anujarora1/Projects
/Numbers/change.py
1,142
4.125
4
# Change Return Program - The user enters a cost and # then the amount of money given. The program will figure # out the change and the number of quarters, dimes, nickels, # pennies needed for the change. import math def change(cost, given, denominations): #check if cost and given are floats #check if given is less than or equal to cost #returns a list of tuples where first value is denomiations and second qty retval = [] remainder = given - cost for key in sorted(denominations.keys(), reverse=True): required_qty = remainder // key right_qty = min(required_qty, denominations[key]) if right_qty > 0: retval.append((key, right_qty)) remainder = remainder - (right_qty * key) if remainder == 0: break return retval, remainder cost = float("{:.2f}".format(float(raw_input("enter the cost: ")))) given = float("{:.2f}".format(float(raw_input("enter the given: ")))) denominations = {20 : 10, 10 : 10, 5 : 10, 1 : 10, .25 : 100, .05 : 100, .01 : 100} print change(cost, given, denominations)
true
268df222de2dc1bbd2ec51fcc9c37f0d762cfc6e
saisurajpydi/Recursion-problems
/Fibonacci.py
269
4.21875
4
""" fibonacci - 0,1,1,2,3,5,8,13,21..... """ def fibonacci(n): if(n <= 1): return n else: return (fibonacci(n-1) + fibonacci(n-2)) n = int(input("enter the N value to print N fibonacci :" )) for i in range(n): print(fibonacci(i), end = " ")
false
9494feece2844fa07126369520a259735eb76945
svwatson13/Python_basics_exercises
/Fizz_Buzz.py
1,373
4.3125
4
# Write a bizz and fizz game ##project # Without loop # Asks user for number num = int(input('Whats your number? ')) #Run through game function def fizz_buzz(num): # If remainder of number after being divided by 3 and 5 is 0 then return Bizzuu if num%3 == 0 and num%5 == 0: return 'Bizzuu' # If remainder of number after being divided by 3 then return Bizz if num%3 == 0: return 'Bizz' # If remainder of number after being divided by 5 then return Fizz if num%5 == 0: return 'Fizz' else: return 'Loser' # In loop while True: num = int(input('Whats your number? ')) if num == 0: break if num % 3 == 0 and num % 5 == 0: print('Bizzizz') # If remainder of number after being divided by 3 then return Bizz elif num % 3 == 0: print('Bizz') elif num % 5 == 0: print('Fizz') else: print(num) # print user input number and the function output #print(num, (fizz_buzz(num))) ## separating parts of a computer program into modules that deal with a single feature or behavior # Definition of done for the project: # This should be it's own project # it should have a read me # it should outline the project # it should have simple instructions on how to run the project # it should have git and git history # it should be on git hub
true
6aaf36f96cc13b011334db8a6e157cb0cb2c26dc
xulongqiu/lxflearn
/170402/basic/listtuple.py
1,024
4.15625
4
#!/usr/bin/python3.5 #list print('LIST *******') classmates = ['Eric', 'Alex', 'Jhon', 'Frank'] print('%d students:' %len(classmates), classmates) print('classmates[0]=', classmates[0]) print('classmates[-1]=', classmates[-1]) classmates.append('Fly') print('%d students:' %len(classmates), classmates) classmates.insert(1, 'Adam') print('%d students:' %len(classmates), classmates) classmates.pop() print('%d students:' %len(classmates), classmates) #different type of data in list L = ['iPhone', 'Huawei', 3, 4, True] print(L) #list in list S = ['C', 'C++', ['PHP', 'Python']] print('%d elements:' %len(S), S) #tuple, its content is constant once define print('\nTUPLE *******') teachers = ('Michael', 'Bob', 'Tracy') print('%d teachers:' %len(teachers), teachers) print('teachers[-1]=', teachers[-1]) t = (1, 2) print('t(1, 2)=', t) t=() print('t()=', t) t = (1) print('t(1)=', t) t = (1,) print('t(1,)=', t) #list in tuple t = (1, 2, ['x', 'Y']) print(t) t[2][0] = 'A' t[2][1] = 'B' t[2].append('C') print(t)
false
9a580ea205c1f6eb1eb9c1bc71349c3817ba06b0
sudeep0901/python
/src/18.generatorexpression.py
654
4.25
4
# generator expression is an object that carries out the same computation as a list comprehension, # but which iteratively produces the result. values = [1, 2, 3, 4] genexp = (n * n for n in values) print(genexp) next(genexp) next(genexp) next(genexp) next(genexp) next(genexp) next(genexp) genlist = list(genexp) print(genlist) # Read a file f = open("data.txt") # Open a file lines = (t.strip() for t in f) # Read lines, strip # trailing/leading whitespace comments = (t for t in lines if t[0] == '#') # All comments for c in comments: print(c) # a generator funciton can be converted into list using list function # clist = list(comments)
true
bd1cb73ada0741a5415689d76ec373ea61ba2dc8
sudeep0901/python
/src/asyncio/1.coroutine.py
1,035
4.15625
4
def print_name(prefix): print("Searching for prefix:{}".format(prefix)) while True: name = (yield) if prefix in name: print(name) # Execution of coroutine is similar to the generator. # When we call coroutine nothing happens, # it runs only in response to the next() and send() method. # This can be seen clearly in above example, as only after calling __next__() method, # out coroutine starts executing. After this call, execution advances to the first yield expression, # now execution pauses and wait for value to be sent to corou object. When first value is sent to it, # it checks for prefix and print name if prefix present. After printing name it goes through loop # until it encounters name = (yield) expression again. corou = print_name("dear") corou.__next__() corou.send("Sudeep") corou.send("dear Sudeep") corou.close() def add_values(val): while True: value1 = (yield) print(val + value1) av = add_values(100) av.__next__() av.send(1000) av.send(1001)
true
fa3be2abeea9643798757a73edcf75b64f98dc93
sudeep0901/python
/src/35.closures.py
709
4.125
4
def outer(mst): def inner(): print("i am closure inner function") print(mst) return inner another = outer("hello") print(outer.__closure__) # another # del outer # another() def make_multiplier_of(n): def multiplier(x): return x * n return multiplier times3 = make_multiplier_of(3) times3.__closure__ # print(make_multiplier_of.__closure__[0]) def print_msg(msg): # This is the outer enclosing function def printer(): # This is the nested function print(msg) printer() # We execute the function # Output: Hello print_msg("Hello") print(print_msg.__closure__) def foo(): def fii(): pass return fii f = foo() f.func_closure
false
5619504ec4b1465ef2498b9665310ba7874de445
Elijah-M/Module7
/fun_with_collections/basic_list_exception.py
1,222
4.34375
4
""" Author: Elijah Morishita elmorishita@dmacc.edu 10/5/2020 This program gathers numeric input from a user, and places it into a list as a string """ def get_input(): """ This function gathers numeric user input and converts it to a string, then returns it :return: user_input """ end_loop = True # Used to stop the loop for user input while end_loop: try: user_input = str(float(input("Please enter a number: "))) if user_input < 0: # added for the test_make_list_below_range() Test assert ValueError if user_input > 50: # added for the test_make_list_above_range() Test assert ValueError end_loop = False # The loop breaks once the user has entered valid input except(ValueError): # added a ValueError print("Invalid input, please try again.") return user_input def make_list(): """ This function places the return of get_input() into a list, then returns the list :return: user_input """ user_input = [0, 0, 0] # initialized a list for x in range(0, 3): user_input[x] = get_input() return user_input if __name__ == '__main__': print(make_list())
true
99a10c6486b8c9962b9ed0d7319a157da59f1a17
collegemenu/week2-hello-world
/helloworld.py
1,123
4.5
4
# Joel Mclemore # write a program that: # 1. greets the user in English # 2. asks the user to choose from 1 of 3 spoken languages (pick your favorite languages!) # 3. displays the greeting in the chosen language # 4. exits # make sure that your code contains comments explaining your logic! while True: #While loop to prompt the user andd keep operations contained print('Hello! To continue, type "1" for EN, "2" for DE, "3" for RU. Type "4" to exit') #3 language types to choose from lang = input() if lang == '1, 2, 3,': continue #continue with the loop if lang == "1": #statement for english users print('Please type your name') name = input() print('Hello,',name ) #To be honest prof. Alfaro, I remember C# having a similar functionality and got lucky this time. break if lang == "2": print('Bitte dein namen schreiben') name = input() print('Hallo,',name ) #c/p from line 9-11, auf Deutsch break if lang == "3": print('Пожалуйста писать ваше имя') name = input() print('Привет,',name ) #c/p from 9-11, Pyccknñ break if lang == "4": break exit
true
83e592ed6c2c32f326cff14676ae0b50583258d1
Ahmed-Camara/Python
/Strings/Exercise 03/password_validation.py
1,069
4.28125
4
""" (Check password) Some Web sites impose certain rules for passwords. Write a function that checks whether a string is a valid password. Suppose the password rules are as follows: ■ A password must have at least eight characters. ■ A password must consist of only letters and digits. ■ A password must contain at least two digits. Write a program that prompts the user to enter a password and displays valid password if the rules are followed or invalid password otherwise. """ def validate_password(password): digits = 0 chars = 0 # iterate through the password string for ch in password: if ch.isalpha(): chars += 1 elif ch.isdigit(): chars += 1 digits += 1 if chars >= 8: if digits >= 2: return True return False if __name__ == '__main__': password = input("Enter a password : ") if validate_password(password): print("{} is a valide password".format(password)) else: print("{} is not a valide password".format(password))
true
ef72bf9cae4309eaa2c9c7323e33a0840730713c
Ahmed-Camara/Python
/Strings/palindrome.py
424
4.15625
4
def isPalindrome(string): low = 0 high = len(string) - 1 while low < high: if string[low] != string[high]: return False low += 1 high -= 1 return True if __name__ == "__main__": string = input("Enter a string : ") if isPalindrome(string): print("{} is a palindrome.".format(string)) else: print("{} is not a palindrome.".format(string))
true
b6e14da4c1048f674adf71daf606281576d01fce
mukund7296/Python-Programs-10-sept
/Average of Numbers in a Given List.py
755
4.21875
4
"""Problem Solution 1. Take the number of elements to be stored in the list as input. 2. Use a for loop to input elements into the list. 3. Calculate the total sum of elements in the list. 4. Divide the sum by total number of elements in the list. 5. Exit. n=int(input("Enter the number of elements to be inserted: ")) a=[] for i in range(0,n): elem=int(input("Element element ")) a.append(elem) avg = sum(a) / n print("Average of elements in the list", round(avg, 2)) """ user=int(input("How many elemnts you want to enter :-")) box=[] for i in range(0,user): user1=int(input("Enter your elemnts to add in list :- ")) box.append(user1) avg=sum(box)/user print("Avg of these numbers are",round(avg,2))
true
934891083e4777efe6ad2cb0b7a6a0966db48300
Spandanachereddy/Cognizance-
/Task 1/Question-1/minmaxavg.py
531
4.1875
4
l=[] file=input("Enter the path of the filename with extension: ") with open(file,'r') as file1: # reading each line for line in file1: # reading each word for word in line.split(): l.append(float(word)) print("The file is: ") with open(file,'r') as f: print(f.read()) avg=sum(l)/len(l) print("Maximum number in the file is: " + str(max(l))) print("Minimum number in the file is: " + str(min(l))) print("The average of the numbers in the file is: "+ str(avg))
true
c13224a001835ccff59227f1938bc2d4d8c77cfa
janemacrae/Advanced-Programming-Fall
/shape.py
1,819
4.15625
4
class Circle(): def __init__(self, r): self.r = r def area(self): return (self.r**2)*3.14 def perimeter(self): return 2*self.r*3.14 def __str__(self): return "Circle has a radius of %.2f, an area of %.2f, and a perimeter of %.2f" % (self.r, self.area(), self.perimeter()) class Rectangle(): def __init__(self, x, y): self.x = x self.y = y def area(self): return self.x*self.y def perimeter(self): return (2* self.x) + (2 * self.y) def __str__(self): return "Rectangle has a dimensions of x = %.2f and y = %.2f, an area of %.2f, and a perimeter of %.2f" % (self.x, self.y, self.area(), self.perimeter()) class Square(Rectangle): def __init__(self, x): self.x = x self.y = x class Triangle(): def __init__(self, x, y): self.x=x self.y=y def area(self): return self.x*self.y*0.5 def perimeter(self): hypotenuse=((self.x**2)+(self.y**2))**0.5 return hypotenuse+self.x+self.y def __str__(self): return "Triangle has dimensions of x= %.2f and y= %.2f, and area of %.2f, and a perimeter of %.2f" % (self.x, self.y, self.area(), self.perimeter()) class Iscoceles(Triangle): def __init__(self, x): self.x = x self.y = x class Depth(): def __init__(self, z): self.z=z def volume(self): return self.area()*self.z def surfacearea(self): return 2*self.area()+(self.z*self.perimeter()) class Box(Rectangle, Depth): def __init__(self, x, y, z): self.x=x self.y=y self.z=z class Cylinder(Circle, Depth): def __init__(self, r): self.r=r z=Box(3,4,5) print z.surfacearea() cyl=Cylinder(5) print cyl.surfacearea() #x = Rectangle(3,4) #print x #y = Square(5) #print y
false
c609646f41fd754683060aa646bdc2eae67a0190
cmusic22/capstone-lab-1
/hello.py
343
4.34375
4
name = input('What is your name?') month = input ('What month were you born in?') #count number of letters in name nameLength = len(name) print('Hello ' + name) print('There are ' + str(nameLength) + ' in your name') if month == 'January': print('It is your birthday month!') elif month != 'January': print('Your birthday is in ' + month)
true
286c5083c89e557db59260183f7859d24cb564cf
mrcmillington/Python-From-Scratch-Teacher-
/24 Ex. 2.py
212
4.21875
4
# Task # Write a program to print out # the 8 times table from 1-12 # # 1 x 8 = 8 # 2 x 8 = 16 # 3 x ..... print(" ------- Task -------") for x in range(1,13): print(x," x 8 = ", x * 8)
false
3571b4859f1450f8abf8fb21d805f6396b8b8182
torikk/html-me-something
/initials/initials.py
404
4.125
4
def get_initials(fullname): """ Given a person's name, returns the person's initials (uppercase) """ # TODO your code here names = fullname.split() initial = "" for name in names: initial = initial + name[0] return initial.upper() def main(): username = input("What is your full name?") get_initials(fullname) if __name__ == '__main__': main()
true
1abd740487d6a4655b4ea7194a11bb9f7e2f556e
milesvp/pokerbot
/TreeVQ/Vector.py
2,137
4.125
4
class Vector(object): """A class to implement the Vector type to be used in VMUs""" def __init__(self, Vect): """Create the vector, initialised from the list 'Vect'""" if isinstance(Vect, list): if isinstance(Vect[0], (int, float, long, complex)): self.Value = Vect return res = [] for i in Vect: if isinstance(i, (int, float, long, complex)): res.append(i) else: res.append(Vector(i)) self.Value = res def __repr__(self): return "Vector(%s)" % repr(self.Value) def __add__(self, V2): res = [] for i in xrange(0, len(self.Value)): res.append(self.Value[i]+V2.Value[i]) return Vector(res) def __sub__(self, V2): res = [] for i in xrange(0, len(self.Value)): res.append(self.Value[i]-V2.Value[i]) return Vector(res) def __mul__(self, V2): """Dot product for vectors, magnitude multiply for scalars""" if isinstance(V2, Vector): res = 0 for i in xrange(0, len(self.Value)): res += self.Value[i]*V2.Value[i] return res else: res = [] for i in xrange(0, len(self.Value)): res.append(self.Value[i]*V2) return Vector(res) __rmul__ = __mul__ def __div__(self, V2): res = [] for i in xrange(0, len(self.Value)): res.append(self.Value[i]/float(V2)) return Vector(res) def __magnitude(self): res = 0 for i in xrange(0, len(self.Value)): res += self.Value[i]*self.Value[i] return pow(res, 0.5) mag = property(__magnitude) def __eq__(self, other): Equal = True for i in xrange(0, len(self.Value)): Equal = Equal and (self.Value[i] == other.Value[i]) return Equal def __ne__(self, other): return not self.__eq__(other) def __nonzero__(self): Zero = True for i in xrange(0, len(self.Value)): Zero = Zero and (self.Value[i] == 0) return not Zero def __getitem__(self, index): return self.Value[index] def __setitem__(self, index, item): self.Value[index] = item
false
679d8828eabf51d7a33baceebfa656e2e7406f49
jonnywilliams162/pythonpractice
/rockpaperscissors.py
1,441
4.15625
4
from random import randint import time #create a list of play options t = ["Rock", "Paper", "Scissors"] #assign a random play to the computer computer = t[randint(0,2)] #set player to False player = False rounds = int(input("how many games would you like to play? ")) time.sleep(1) no_rounds= (range(rounds)) for round in no_rounds: time.sleep(1) print("Round {}".format(round)) while player == False: #set player to True player = input("Rock, Paper, Scissors? ") if player == computer: print("Tie!") elif player.lower() == "rock": if computer.lower() == "paper": print("You lose!", computer, "covers", player) else: print("You win!", player, "smashes", computer) elif player.lower() == "paper": if computer.lower() == "scissors": print("You lose!", computer, "cut", player) else: print("You win!", player, "covers", computer) elif player.lower() == "scissors": if computer.lower() == "rock": print("You lose...", computer, "smashes", player) else: print("You win!", player, "cut", computer) else: print("That's not a valid play. Check your spelling!") #player was set to True, but we want it to be False so the loop continues player = False computer = t[randint(0,2)]
true
a0d5ff7dc50a482b9a19cca4bebeae2b38cbcd1a
Chalfantscott/digital-crafts-lessons
/projects/shape_chooser.py
774
4.15625
4
def drawTriangle(height): base = height * 2 - 1 for row in range(1, height + 1): spaces = height - row print " " * spaces + "*" * (row * 2 - 1) def drawBox(width, height): for row in range(height): if row == 0: print "*" * width elif row == height - 1: print "*" * width else: spaces = width - 2 print "*" + " " * spaces + "*" shapeToPrint = raw_input("Pick a shape to print: triangle, box, or square. ") if shapeToPrint == "triangle": height = int(raw_input("What is the height? ")) drawTriangle(height) if shapeToPrint == "box": height = int(raw_input("What is the height? ")) width = int(raw_input("What is the width? ")) drawBox(width, height)
true
deea46e972a8de5eebe079739f2218ed8cd91077
polavskiran/pythoncodes
/Sample3.py
728
4.1875
4
##country_list1 = ['India','France','Russia','Israel'] ##country_list2 = ['UK','US','China','Brazil'] ##country_list = country_list1 + country_list2 ## ##print('Country List is: {}'.format(country_list)) ## ##index = 0 ##print("List of countries are:") ##while index < len(country_list): ## print(country_list[index]) ## index +=1 ## ##print('Countries in Sorted order is: {}'.format(sorted(country_list))) ## #To print the numbers in range ##for number in range(10): ## print(number) #To print the numbers from start to end. for number in range(5,14): print(number) print("###############################") #To print the numbers from start to end in interval(step) for number in range(5,55,5): print(number)
true
399bc86025ebef1e36b6eb7c29c7a7c29eba92a1
primowalker/Python_Training
/Linux_Academy/sets_examples.py
749
4.28125
4
#!/usr/bin/python # The sets_example.py gives several examples of how to use python sets # Creat two sets of names set1 = set(["James","Kyle","Brad","Sid","Nancy","Marvin","Zaphod"]) set2 = set(["James","Brad","Zaphod","Lewis","Mervin","Sherlock"]) print "These are the people in set 1: %s " % (set1) print "These are the people in set 2: %s " % (set2) # Find the common members of both sets both_courses = set1 & set2 print "These people are in both sets: %s " % (both_courses) # Find members who are in set2, but not set1 not_in_set1 = set2 - set1 print "These people are not in set 1: %s " % (not_in_set1) # Find members who are in set1, but not in set2 not_in_set_2 = set1 - set2 print "These people are not in set 2: %s " % (not_in_set_2)
true
f5c3343ad367642d1c37e5a65411ba02a1c07871
yddong/Py3L
/src/Week4/test4.py
353
4.3125
4
#!/usr/bin/env python3 mytext = "Hello world" mycharacters = list(mytext) mycharacters[1] = "a" # merge list of strings back to a string print( "-".join(mycharacters) ) print( mytext[2] ) mytext = "Hallo Welt!" print(mytext) # we cannot change characters in a string this way! #mytext[1] = "e" print( mytext + " " + mytext ) print( (mytext + " ") * 3 )
false
155781ddb251aec2507e07c054a3d7985d9d312e
yddong/Py3L
/src/Week2/s2-test-1.py
252
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- mylist = [ "a", 2, 4.5 ] myotherlist = mylist[ : ] mylist[1] = "hello" print(myotherlist) mytext = "Hello world" myothertext = mytext mytext = "Hallo Welt!" #print(myothertext) print(mylist[ : ])
false
fc377b90527b2e5936e1a348d8eff882ee7a27e3
shivkumarnagre/Python
/CompareTwoNumbers.py
669
4.15625
4
'''Get two integers x and y from the user and write a python program to relate 2 integers as equal to, less than or greater than. Input format: Input consist of 2 integers The first input corresponds to the first number(x) The second input corresponds to the second number(y) Output format: If the first number is equal to the second number, print "x and y are equal". Otherwise, print "x greater than y" or "x less than y" Sample Input: 17 12 Sample Output: 17 greater than 12''' x=int(input()) y=int(input()) if x==y: print("{} equal to {}".format(x,y)) elif x>y: print("{} greater than {}".format(x,y)) else: print("{} less than {}".format(x,y))
true
7faa69fe881b9bdeb3360cf7ef3960b305150045
felipenatividade/curso-python
/aula03/estrutura_de_controle.py
404
4.1875
4
var = input('Digite um número: ') #if 10 > int(var): # print('condição verdadeiro' + var + ' é menor que 10') #else: # print('condição falso') numero = int(var) #if 10 > numero: # print(numero + ' é menor que 10') #elif 10 == numero: # print(numero + ' é igual a 10') #else: # print(numero + ' é maior que 10') while numero >= 3: print(numero) if numero == 3: break numero -= 1
false
de6ea1200e905fa3d43ef826f3b283a3bc2ab02a
FrankCasanova/Python
/Funciones/313.py
272
4.21875
4
# give a function that, given a list of numbers, # returns another list that only includes their odd numbers def odd_numbers(list1): return [i for i in list1 if i % 2 != 0] list_a = [3, 4, 5, 45, 2, 34, 2, 1, 53, 4, 643, 45, 23, 2, 4, ] print(odd_numbers(list_a))
true
6d9e547afbb3d49bd530545f59dd4ff04c40a860
FrankCasanova/Python
/Funciones/309.py
1,856
4.15625
4
# desins a procedure that shows on the # screen the total capital paid to the bank for a mortage # of h euros at i% annual interest for 10, 15, 20 and 25 years. # (if it suits your, substract how the functions you designed as # a solution to the previous exercices) # calculate r def r(interest): return interest/(100*12) def quote(mortgage, interest): """ calculate the quote. the forumula appear on the book/ """ re = r(interest) quote = round(mortgage*re/(1-(1+re)**(-12*15)), 2) return quote def finalPay(quote): """ calculate the final pay """ return quote*12*(15) def totalInterest(mortgag): """ calculate how much interest we have paid """ return finalPay(quote(mortgage, interest)) - mortgag def totalPercentage(mortgage): """ calculate the total percentage you have paid """ return (totalInterest(mortgage) * 100) / mortgage def variousYears(interest, mortgage): """ calculate the total quote to pay for a mortgage for a capital of H euros at i% annual interest for 10, 15, 20 and 25 years. """ listYears = [10, 15, 20, 25] for year in listYears: print(f'para {year} años la cuota es de : ', round( mortgage*r(interest)/(1-(1+r(interest))**(-12*year)), 2)) def differentFinalPays(mortgage, interest): """ shows the total capital paid in differents range of years """ listYears = [10, 15, 20, 25] for year in listYears: print(f'para {year} años habrás pagado: ', quote(mortgage, interest)*12*year) # dates mortgage = 150_000 interest = 4.75 print(quote(mortgage, interest)) print(finalPay(quote(mortgage, interest))) print(totalInterest(mortgage)) print(totalPercentage(mortgage)) variousYears(interest, mortgage) differentFinalPays(mortgage, interest)
true
be0990dd41cb43a298cea64f74ca226b9d88dd7b
FrankCasanova/Python
/Tipos estructurados De Secuencias/5.4.4-OperacionesConMatrices.py
859
4.15625
4
# Pedimos la dimensión de las matrices. m = int(input('Dime el número de filas:\n')) n = int(input('Dime el número de columnas:\n')) # Creamos 2 matrices nulas... a = [[0]*n for i in range(m)] b = [[0]*n for i in range(m)] # ... y leemos sus contenidos de teclado. print('Lectura de la matriz a.') for i in range(m): for j in range(n): a[i][j] = float(input(f'Componente {i}, {j}:\n ')) print('Lectura de la matriz b.') for i in range(m): for j in range(n): b[i][j] = float(input(f'Componente {i}, {j}:\n ')) # Construimos la matriz en la que queremos albergar el resultado. c = [[0]*n for i in range(m)] for i in range(m): for j in range(n): c[i][j] = a[i][j] + b[i][j] # Mostramos el resultado por pantalla print('Suma: ') for i in range(m): for j in range(n): print(c[i][j], end=' ') print()
false
87b169314ff08529a7b91ad6ee7c2e8afcb060ee
NelinVitaliy/Chapter_2__Task_8
/Task_8.py
220
4.15625
4
print('Type an integer number 1: ') a = int(input()) print('Type an integer number 2: ') b = int(input()) for a in range(a, b+1): print(a, end=" ") # a = int(input()) # b = int(input()) # print(list(range(a, b+1)))
false
995b1d90972cb7ec63928bea8e63573fed7e8589
Jy411/Dailies
/#228 - Letters in Alphabetical Order [Easy].py
773
4.25
4
# https://www.reddit.com/r/dailyprogrammer/comments/3h9pde/20150817_challenge_228_easy_letters_in/ def letterSort(letter): unorderedLetter = list(()) for char in letter: unorderedLetter.append(char) orderedLetter = unorderedLetter.copy() orderedLetter.sort() reversedLetter = unorderedLetter.copy() reversedLetter.sort(reverse=True) if unorderedLetter == orderedLetter: print(letter + " IN ORDER") elif unorderedLetter == reversedLetter: print(letter + " IN REVERSE ORDER") else: print(letter + " NOT IN ORDER") wordList = ["billowy", "biopsy", "chinos", "defaced", "chintz", "sponged", "bijoux", "abhors", "fiddle", "begins", "chimps", "wronged"] for word in wordList: letterSort(word)
true
a818241a901867044f6a29c05c86a83f7aeb6038
pablocalderon9408/computational_thinking_python
/aproximate_to_solution_algorithm.py
448
4.40625
4
def aproximate_to_solution(): number = int(input("Please enter a number to calculate its square root: " + "\n" + "\n")) ERROR = 0.01 result = 0 step = ERROR ** 3 while abs(result**2-number) >= ERROR and result<number: print(result**2-number, result) result += step print("The square root of {number} is {result}".format(number=number, result=result)) if __name__=="__main__": aproximate_to_solution()
true
a5bc6efed6f636076c84505bebee24a5d158f570
darkraven92/D0009E
/Laborationer/Lab 3- Str-ngar- listor och -dictionaries/Program2.py
1,088
4.28125
4
#Ordlista tupler def menu(): wordtuple = () desctuple = () while True: print("""" 1. Insert 2. Lookup 3. Exit """) ch = input("> ") if ch == "1": addWord = input("Insert word: ") if addWord not in wordtuple: wordlist = list(wordtuple) wordlist.append(addWord) print(wordlist) addDesc = input("Description: ") desclist = list(desctuple) desclist.append(addDesc) print(addDesc) print(addWord,":", addDesc,"have been added to the list") else: print("Word is in list") elif ch == "2": lookupword = input("Word to lookup: ") if lookupword in wordlist: print("Description of", lookupword,":",desclist[wordlist.index(lookupword)]) else: print("Word not found") elif ch == "3": print("Exiting program") break else: print("Not a vaild input") menu()
false
dc695125cd08d4b48255c65ead850d4daa592c74
alexplahotnik/homework
/homework/homework1/task3.py
433
4.21875
4
from typing import Tuple def find_maximum_and_minimum(file_name: str) -> Tuple[int, int]: """Finding max and min values in file""" with open(file_name) as f: lines = f.readlines() maximum, minimum = int(lines[0]), int(lines[0]) for line in lines: if int(line) > maximum: maximum = int(line) elif int(line) < minimum: minimum = int(line) return (minimum, maximum)
true
09af1a718e6472034096855fc5ca56f867a12f3e
InCodeLearning/InCodeLearning-Python3
/func_prog/iterator_generator.py
1,929
4.3125
4
""" https://docs.python.org/3/howto/functional.html?highlight=iterator#generators Iterator is an object representing a stream of data, each time returns one element of the data. It must support next() or__next__() (special) method, and raise StopIteration exception when no more element in the stream. Generator is a special class of functions simplify the task of writing iterators. Regular function computes a value and returns it, but generator returns an iterator that returns a stream of data. It must have yield in definition block. It can improve program performance by reducing running time and memory usage. It is general opinion that generator is always an iterator (not vice versa), but there is also counterview. """ import sys import time s = "python" for w in s: print(w) d = iter(s) for i in range(len(s)): # if range length is longer than len(s), # raise StopIteration exception print(next(d)) # iterate s print((next(iter(s)))) # every time print p, reason? def even_num(l): even_l = [] for i in l: if i % 2 == 0: even_l.append(i) return even_l a = [1, 2, 3, 4, 5, 6, 7, 8, 9] print(even_num(a)) # generator def even_num_gen(l): for i in l: if i % 2 == 0: yield i b = [1, 2, 3, 4, 5, 6, 7, 8, 9] c = even_num_gen(b) print(even_num_gen(b)) # yield even number print(next(c)) # 2 print(next(c)) # 4 print(next(c)) # 6 print(next(c)) # 8 # print(next(c)) raise StopIteration exception e = [x for x in range(1000000)] b_time_list = time.clock() e_list = even_num(e) e_time_list = time.clock() print(sys.getsizeof(e_list)) print('Time costs {} seconds.'.format(e_time_list - b_time_list)) b_time_gen = time.clock() e_gen = even_num_gen(e) e_time_gen = time.clock() print(sys.getsizeof(e_gen)) print('Time costs {} seconds.'.format(e_time_gen - b_time_gen)) # sys.getsizeof() return the size of an object in bytes.
true
4af82d63805c9a67847bdedbd815d6f6d3e11ca1
Abarna13/HackerRank-Challenge
/Python/If-else.py
615
4.25
4
''' Given an integer, , perform the following conditional actions: If is odd, print Weird If is even and in the inclusive range of to , print Not Weird If is even and in the inclusive range of to , print Weird If is even and greater than , print Not Weird ''' import math import os import random import re import sys if __name__ == '__main__': n = int(input().strip()) if n%2==1: print("Weird") elif n%2==0 and (n>= 2 and n<6): print("Not Weird") elif n%2==0 and (n>6 and n<21): print("Weird") else: print("Not Weird")
false
7f7a9022e3d10e7b2844bc6a13aa91470bd3d030
Vi-r-us/Python-Projects
/14 Fibonacci Calculator.py
728
4.3125
4
print("Welcome to the Fibonacci Calculator App.") num = int(input("\nHow many digits of the Fibonacci Sequence you like to compute: ")) fib = [1, 1] if num > 0: if num > 2: for i in range(num-2): new_sum = fib[i] + fib[i+1] fib.append(new_sum) print(f"\nThe first {num} numbers of theFibonacci Sequence are:") for ele in fib: print(ele) golden = [] for i in range(len(fib)-1): ratio = fib[i+1]/fib[i] golden.append(ratio) print("\nThe corresponding Golden Ratio values are: ") for ele in golden: print(ele) print("\nThe Ratio of the consecutive Fibonacci terms approaches Phi; 1,618....") else: print("\nWrong Choice")
false
e31565fec0a9ab62ea3afaa488259b1d6a887cef
Vi-r-us/Python-Projects
/17 Coin Toss.py
941
4.1875
4
import random print("Welcome to the Coin Toss App.") print("\nI will flip a coin a set number of times.") n = int(input("How many times would you like me to flip the coin: ")) c = input("Would you like to see the results: (y/n) ") Heads = 0 Tails = 0 if c == 'y' or c == 'Y': print("\nFLIPPING!!\n") for flips in range(n): if (Heads == Tails) and (Heads != 0 and Tails != 0): print(f"At {flips} flips, the number of head and tails are equal at {Heads} each.") toss = random.randint(0, 1) if toss == 1: Heads = Heads + 1 print("HEAD") elif toss == 0: Tails = Tails + 1 print("TAIL") print(f"\nResult of flipping a coin {n} Times:") print(f"\nSide \t\tCount \t\tPercentage" f"\nHeads\t\t{Heads}/{n}\t\t{Heads*100/n}%" f"\nTails\t\t{Tails}/{n}\t\t{Tails*100/n}%") else: print("\nHere take your coin then.")
true
daca39e6e75a0c4a59b1a687fe7ef1fd0fd1ff81
Vi-r-us/Python-Projects
/23 Yes No Polling.py
1,435
4.28125
4
print("Welcome to the Yes or No Issue Polling App.") votes = {} issue = input("\nWhat is the yes or no issue you will be voting on today: ").capitalize().strip() no_of_votes = int(input("What are the number of voters you will allow on the issue: ")) yes = 0 no = 0 for i in range(no_of_votes): name = input("\nEnter your full name: ").title().strip() if name not in votes.keys(): print(f"Here's the issue: {issue}") vote = input("What do you think?....yes or no: ").lower() if vote == 'yes': yes += 1 elif vote == 'no': no += 1 else: print("That is not a yes or no answer, but okay...") print(f"Thank you {name}! Your vote of {vote} has been recorded.") votes[name] = vote else: print("Sorry, it seems that you someone with that name has already voted.") print(f"\nThe following {len(votes)} people voted:") for key in votes.keys(): print(key) print(f"\nOn the following issue: {issue.lower()}") if yes > no: print(f"Yes Wins! {yes} votes to {no}.") elif no > yes: print(f"No Wins! {no} votes to {yes}.") else: print(f"It was a tie! {yes} votes to {no}.") ch = input("\nDo you want to see the voting results (yes/no): ").lower().strip() if ch == 'yes': for key, value in votes.items(): print(f"Voter: {key}\t\t\t\tVote: {value}") print("Thank You for using Yes or No Issue Polling App.")
true
cbfc664d62492d956c90cdb5f64814054cd8e703
ngkhang/py4e
/Chapter06/ch06_03.py
565
4.3125
4
''' Exercise 3: Encapsulate this code in a function named count, and generalize\ it so that it accepts the string and the letter as arguments. ----Example: word = 'banana' count = 0 for letter in word: if letter == 'a': count = count + 1 print(count) ''' def count(str_1, str_sub): count_num = 0 for letter in str_1: if letter == str_sub: count_num = count_num + 1 print(count_num) word = input('Input a word: ') letter = input('Input a letter: ') count(word, letter)
true
c813b9cca73a2df2636ac95265b8450130c2a752
ngkhang/py4e
/Chapter03/ch03_ex03.py
880
4.15625
4
''' Exercise 3: Write a program to prompt for a score between 0.0 and 1.0.\ If the score is out of range, print an error message. If the score is between 0.0 and 1.0, print a grade using the following table: Score Grade >= 0.9 A >= 0.8 B >= 0.7 C >= 0.6 D < 0.6 F ----Example: Enter score: 0.95 A Enter score: perfect Bad score Enter score: 10.0 Bad score ''' try: score = float(input('Enter score: ')) except: print('Bad score') quit() if(score > 1 or score < 0): print('Bad score') elif (score >= 0.9): print('A') elif (score >= 0.8): print('B') elif (score >= 0.7): print('C') elif (score >= 0.6): print('D') else: print('F')
true
910814ebbc322bff5c105381946300835861af23
ngkhang/py4e
/Chapter03/ch03_ex02.py
683
4.21875
4
''' Exercise 2: Rewrite your pay program using try and except so that your\ program handles non-numeric input gracefully by printing a message and exiting the program. The following shows two executions of the program: ----Example: Enter Hours: 20 Enter Rate: nine Error, please enter numeric input Enter Hours: forty Error, please enter numeric input ''' try: hours = int(input('Enter Hours: ')) rate = float(input('Enter Rate: ')) except: print('Error, please enter numeric input') quit() if(hours>40): pay = (40 + (hours-40) * 1.5) * rate else: pay = 40 * rate print('Pay:', pay)
true
0130d67055bd79f0a6b6996f9cdbc0c9b4c60305
ngkhang/py4e
/Chapter09/ch09_03.py
883
4.15625
4
''' Exercise 3: Write a program to read through a mail log, build a histogram using a\ dictionary to count how many messages have come from each email address, and print the dictionary. Sample Line: From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 ----Example: Enter file name: mbox-short.txt {'gopal.ramasammycook@gmail.com': 1, 'louis@media.berkeley.edu': 3, 'cwen@iupui.edu': 5, 'antranig@caret.cam.ac.uk': 1, 'rjlowe@iupui.edu': 2, 'gsilver@umich.edu': 3, 'david.horwitz@uct.ac.za': 4, 'wagnermr@iupui.edu': 1, 'zqian@umich.edu': 4, 'stephen.marquard@uct.ac.za': 2, 'ray@media.berkeley.edu': 1} ''' dict_mail = dict() file_name = input('Enter file name: ') try: file = open(file_name) except: print('File cannot be opened:', file_name) exit() for line in file: if(line.startswith("From ")): raw_email = line.split(' ') email = raw_email[1] dict_mail[email] = dict_mail.get(email,0) + 1 print(dict_mail)
false
007b4caf81d88c2d3d1a08517ef6ab69850b96c7
lytl890/DailyQuestion
/question_4/Fourth.py
486
4.125
4
# _*_ coding:utf-8 _*_ ''' 用Python实现斐波那契数列(Fibonacci sequence) 除第一个和第二个数外,任意一个数都可由前两个数相加得到: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ... ''' def fib(max): #n=0, a=0, b=1 n, a, b = 0, 0, 1 #条件满足 n < max 就循环,n > max 就停止 while n < max: print(b) #不等于a=b, b=a + b a, b = b, a + b n = n + 1 return 'done' #调用函数 f= fib(9) print(f)
false
158961d607ae5774db37f4b8a52b5bb05c3240a6
BilalAhmedali/Python_BootCamp
/Assignment_1.py
1,074
4.21875
4
while True: print("1- Addition") print("2- Subtraction") print("3- Multiplication") print("4- Division") operation = input("Please choice one of math operation above to calculate ") numOne = int(input("Enter first number: ")) numTwo = int(input("Enter second number: ")) if operation.title == "Addition" or operation == "1": Addition = lambda x,y:x+y print(Addition(numOne,numTwo)) elif operation.title() == "Subtraction" or operation == '2': Subtraction = lambda x,y : x-y print(Subtraction(numOne,numTwo)) elif operation.title() == "Multiplication" or operation == "3": Multiplication = lambda x,y:x*y print(Multiplication(numOne,numTwo)) elif operation.title() == "Division" or operation == '4': Division = lambda x,y:x/y print(Division(numOne,numTwo)) else: print("Sorry operation not in a list") calculation = input("Do you wish to calculation agian or quite (yes or no)") if calculation.lower() == "no": break
true
44e38db81f871b57fdddfa38f0ed2c6336262fdb
RafaFT/checkio
/elementary/between_markers/between_markers.py
1,779
4.34375
4
""" You are given a string and two markers (the initial and final). You have to find a substring enclosed between these two markers. But there are a few important conditions: The initial and final markers are always different. If there is no initial marker then the beginning should be considered as the beginning of a string. If there is no final marker then the ending should be considered as the ending of a string. If the initial and final markers are missing then simply return the whole string. If the final marker is standing in front of the initial one then return an empty string. Input: Three arguments. All of them are strings. The second and third arguments are the initial and final markers. Output: A string. """ def between_markers(text, begin, end): """ (str, str, str) -> str Returns the substring of text between two given markers (begin and end). If begin isn't found, and end is, returns text[:end], if begin is found and end isn't, return [begin:], if begin and end are not found, return the whole text and finally, if begin index > end index, return empty string. >>> between_markers('What is >apple<', '>', '<') 'apple' >>> between_markers("<head><title>My new site</title></head>", "<title>", "</title>") 'My new site' >>> between_markers('No[/b] hi', '[b]', '[/b]') 'No' >>> between_markers('No [b]hi', '[b]', '[/b]') 'hi' >>> between_markers('No hi', '[b]', '[/b]') 'No hi' >>> between_markers('No <hi>', '>', '<') '' """ index_begin = text.find(begin) + len(begin) if begin in text else None index_end = text.find(end) if end in text else None return text[index_begin: index_end] if __name__ == '__main__': import doctest doctest.testmod()
true
bf5f1f57713c6bcc51f0a0728fa41eea166700ca
RafaFT/checkio
/elementary/easy_unpack/easy_unpack.py
728
4.3125
4
""" Your mission here is to create a function that gets an tuple and returns a tuple with 3 elements - first, third and second to the last for the given array. Input: A tuple, at least 3 elements long. Output: A tuple. """ def easy_unpack(elements): """ (tuple of int) -> tuple of int Pre-condition: len(elements) >= 3 Returns a tuple with 3 elements - first, third and second to the last of elements. >>> easy_unpack((1, 2, 3, 4, 5, 6, 7, 9)) (1, 3, 7) >>> easy_unpack((1, 1, 1, 1)) (1, 1, 1) >>> easy_unpack((6, 3, 7)) (6, 7, 3) """ return (elements[0],) + (elements[2],) + (elements[-2],) if __name__ == '__main__': import doctest doctest.testmod()
true
9afa36f574e726df904b5d43da9c29192f3ec133
RafaFT/checkio
/elementary/first_word/first_word.py
976
4.4375
4
""" You are given a string where you have to find its first word. When solving a task pay attention to the following points: There can be dots and commas in a string. A string can start with a letter or, for example, a dot or space. A word can contain an apostrophe and it's a part of a word. The whole text can be represented with one word and that's it. Input: A string. Output: A string. """ import re def first_word(text): """ (str) -> str Returns the first word in a given text or empty string if there's no word in it. >>> first_word("Hello world") 'Hello' >>> first_word(" a word ") 'a' >>> first_word("don't touch it") "don't" >>> first_word("... and so on ...") 'and' >>> first_word("Hello.World") 'Hello' >>> first_word(".") '' """ word = re.search(r"[a-zA-Z-']+", text) return word.group(0) if word else '' if __name__ == '__main__': import doctest doctest.testmod()
true
eb8ea47262b716ccd11884f74cec3b0a4ee44862
kannankandasamy/GeneralPrograms
/LinkedList.py
802
4.15625
4
""" Create linked list and add operations like push, reverse, get elements from linked list """ class Node(object): def __init__(self,val): self.value = val self.next = None class LinkedList(object): def __init__(self): self.head = None def push(self,val): new_node = Node(val) new_node.next = self.head self.head = new_node def printList(self): tmp = self.head while tmp: print(tmp.value) tmp = tmp.next def reverse(self): prev, nxt = None, None current = self.head while current: nxt = current.next current.next = prev prev = current current = nxt self.head = prev
true
c3860a73c527a86876c93756c81a1bc92a9e7d7d
christopherkalfas/python_master_ticket_application
/masterticket.py
1,429
4.15625
4
TICKET_PRICE = 10 SERVICE_CHARGE = 2 tickets_ramaining = 100 def calculate_price(number_of_tickets): return (number_of_tickets * TICKET_PRICE) + SERVICE_CHARGE while tickets_ramaining >= 1: print("Number of remaining tickets: {}".format(tickets_ramaining)) user_name = input("What is your name: ") number_of_tickets = input("Hello, {}! How many tickets would you like? (Price per ticket: ${}.00) ".format(user_name, TICKET_PRICE)) try: number_of_tickets = int(number_of_tickets) if number_of_tickets > tickets_ramaining: raise ValueError("There are only {} tickets remaining".format(tickets_ramaining)) except ValueError as err: print("Oh no! That is not a valid value. {}. Try again.".format(err)) else: total = calculate_price(number_of_tickets) print("Total: ${}.00 for {} tickets ".format(total, number_of_tickets)) confirmation = input("Are you sure you want to proceed with purchase of {} tickets for a total of ${}.00 USD? Y/N ".format(number_of_tickets, total )) if confirmation.upper() == "Y": #3 TODO gather cc info and process print("SOLD!") tickets_ramaining -= number_of_tickets else: print("Thanks for wasting my time, {}".format(user_name)) print("The show is sold out. Sorry")
true
d0480c8316efcb8bf9f7bce0634675f781259bb2
hhigorb/exercicios_python_brasil
/2_EstruturaDeDecisao/11.py
1,683
4.375
4
""" 11. As Organizações Tabajara resolveram dar um aumento de salário aos seus colaboradores e lhe contraram para desenvolver o programa que calculará os reajustes. Faça um programa que recebe o salário de um colaborador e o reajuste segundo o seguinte critério, baseado no salário atual: salários até R$ 280,00 (incluindo) : aumento de 20% salários entre R$ 280,00 e R$ 700,00 : aumento de 15% salários entre R$ 700,00 e R$ 1500,00 : aumento de 10% salários de R$ 1500,00 em diante : aumento de 5% Após o aumento ser realizado, informe na tela: o salário antes do reajuste; o percentual de aumento aplicado; o valor do aumento; o novo salário, após o aumento. """ salario = float(input('Qual o seu salário? ')) if salario < 280: novo_salario = salario + salario * 0.20 print(f'Seu antigo salário era: {salario}\n' f'O aumento salarial foi de 20%: {salario * 0.20}\n' f'Seu novo salário é: {novo_salario}') elif 280 <= salario < 700: novo_salario = salario + salario * 0.15 print(f'Seu antigo salário era: {salario}\n' f'O aumento salarial foi de 15%: {salario * 0.15}\n' f'Seu novo salário é: {novo_salario}') elif 700 <= salario < 1500: novo_salario = salario + salario * 0.10 print(f'Seu antigo salário era: {salario}\n' f'O aumento salarial foi de 10%: {salario * 0.10}\n' f'Seu novo salário é: {novo_salario}') else: novo_salario = salario + salario * 0.05 print(f'Seu antigo salário era: {salario}\n' f'O aumento salarial foi de 5%: {salario * 0.05}\n' f'Seu novo salário é: {novo_salario}')
false
13a7ce7d5b39fa1f9c7d91959a8f95881c125d39
hhigorb/exercicios_python_brasil
/3_EstruturaDeRepeticao/7.py
245
4.15625
4
"""7. Faça um programa que leia 5 números e informe o maior número.""" maior = 0 for _ in range(5): numero = int(input('Digite um número: ')) if numero > maior: maior = numero print(f'O maior número é: {maior}')
false
f04a9e69bbbfcc23613fd95436f9d751669866e8
hhigorb/exercicios_python_brasil
/3_EstruturaDeRepeticao/18.py
518
4.15625
4
"""18. Faça um programa que, dado um conjunto de N números, determine o menor valor, o maior valor e a soma dos valores.""" quantidade = int(input('Quantos valores você deseja digitar? ')) menor = 1 maior = 0 soma = 0 for valor in range(quantidade): numero = int(input('Digite um número: ')) if numero > maior: maior = numero else: menor = numero soma += numero print(f'O menor número é: {menor}, o maior é: {maior} e a soma de todos os valores é de: {soma}')
false
038e3737339ed31b1487b4a68efec1e161d2631f
hhigorb/exercicios_python_brasil
/2_EstruturaDeDecisao/25.py
1,347
4.34375
4
""" 25. Faça um programa que faça 5 perguntas para uma pessoa sobre um crime. As perguntas são: "Telefonou para a vítima?" "Esteve no local do crime?" "Mora perto da vítima?" "Devia para a vítima?" "Já trabalhou com a vítima?" O programa deve no final emitir uma classificação sobre a participação da pessoa no crime. Se a pessoa responder positivamente a 2 questões ela deve ser classificada como "Suspeita", entre 3 e 4 como "Cúmplice" e 5 como "Assassino". Caso contrário, ele será classificado como "Inocente". """ print("RESPONDA AS PERGUNTAS COM 'SIM' OU 'NÃO'!") p1 = input('Telefonou para a vítima? ').lower() p2 = input('Esteve no local do crime? ').lower() p3 = input('Mora perto da vítima? ').lower() p4 = input('Devia para a vítima? ').lower() p5 = input('Já trabalhou com a vítima? ').lower() somatoria = 0 if p1 == 'sim': somatoria = somatoria + 1 if p2 == 'sim': somatoria = somatoria + 1 if p3 == 'sim': somatoria = somatoria + 1 if p4 == 'sim': somatoria = somatoria + 1 if p5 == 'sim': somatoria = somatoria + 1 if somatoria == 2: print('Classificação: Suspeita!') elif 3 <= somatoria <= 4: print('Classificação: Cúmplice!') elif somatoria == 5: print('Classificação: Assassino!') else: print('Classificação: Inocente!')
false
a12e053e20200f88d229e31bc85f83ca9cfdd219
hhigorb/exercicios_python_brasil
/3_EstruturaDeRepeticao/1.py
359
4.3125
4
"""1. Faça um programa que peça uma nota, entre zero e dez. Mostre uma mensagem caso o valor seja inválido e continue pedindo até que o usuário informe um valor válido.""" nota = int(input('Digite uma nota: ')) while nota < 0 or nota > 10: print('Valor inválido. Entre com um valor entre 0 e 10') nota = int(input('Digite uma nota: '))
false
24fcdba02975ca99e1d413c118b622af4edf8122
hhigorb/exercicios_python_brasil
/2_EstruturaDeDecisao/23.py
280
4.1875
4
""" 23. Faça um Programa que peça um número e informe se o número é inteiro ou decimal. Dica: utilize uma função de arredondamento. """ n = float(input('Digite um número: ')) if n == round(n): print('É um número inteiro!') else: print('É um decimal!')
false
01e240c8e6740e103331b402bba84b061dd714d0
veerabhadrareddy143/python
/list.py
828
4.15625
4
l1=[1,2,3] l2=[3,4,5] l3=l1+l2 print(l3) print(l1==l2) l4=[[5,6],[7,8],[12,45]] #nested list print(l4[1][1]) #printing specific element in list l4.append('veera') print(l4) l4.extend(['raja']) print(l4) l3.remove(1) print(l3) l3.insert(3,15) print(l3) l3.pop(2) print('pop',l3) print(l3.count(5)) # we have sort() ,reverse(), copy() lst=['big', 'small', 'medium', 'large'] lst.sort() print(lst) lst.reverse() print(lst) tup=tuple(lst) #converting a list into tuple print(tup) l5=l3[1:5:2] #syntax: listname[start:stop:step] print(l5) data=enumerate(lst) # this enumerate keyword is used for data handle print(list(data)) edata=enumerate(lst,20) #syntax:enumerate(list name,counting no. strt) print(list(edata))
false
868817c35d65f123c6cf7595e2e50bc63f9d6adf
GuilhermeSilvaCarpi/exercicios-programacao
/treinamento progrmação/Python/w3schools/6. lists/4.Add list itens.py
802
4.375
4
print('Adicionando itens em listas') lista = ['a', 'e', 'i', 'o', 'u'] print(lista) print('-'*40) print('''Método [append()]. Adiciona um item no final da lista.''') lista.append('ão') print(lista) print('-'*40) print('''Método [insert()]. Insere um item em uma posição específica da lista.''') lista.insert(2, 3) print(lista) print('-'*40) print('''Método [extend()]. Acrescenta uma lista no final de outra.''') lista = ['a', 'e'] lista2 = ['i', 'o', 'u'] print('lista:', lista) print('lista2:', lista2) lista.extend(lista2) print(lista) print() print('''O método [extend()] pode adicionar qualquer tipo de iterável a uma lista.''') lista = ['a', 'b', 'c'] tuple = ('d', 'e', 'f') print('lista:', lista) print('tuple:', tuple) lista.extend(tuple) print('''lista | V''') print(lista)
false
f5f54e8eb925013a40e0dad124715704682b4ff1
GuilhermeSilvaCarpi/exercicios-programacao
/treinamento progrmação/Python/w3schools/10. Condirionals, loops & iterations/3. For loops.py
1,285
4.375
4
variável = 'banana' print(variável) # Percorrendo um item iterável. for x in variável: print(x, end='-*') print() # Percorrendo outro item iterável. for x in ['um', 'dois', 'três', 'quatro']: print(x) # Percorrendo um item iterável e usando break, que interrompe o loop. for x in variável: print(x,end='-') if x == 'n': break print() # Usando continue, que pula para o próximo passo do loop. for x in variável: if x == 'a': continue print(x,end='') print() # Usando range com um parâmetro. for x in range(11): print(x, end=' ') print() # Usando range com 3 parametros: inicio, final, "pulo" (dois parâmetros declaram somente: inicio e final). for x in range(10,30,2): print(x, end=', ') print() # Usando "else" em loop for. O bloco do "else" é executado depois que o loop for termina. for x in range(8): print(x, end=', ') else: # O bloco de código do "else" não será executado se o loop for terminar com um "break". print('fim') print() # Loops aninhados, são nada menos que loops dentro de loops. for x in ['computador', 'carro', 'caderno']: for y in ['grande', 'bonito', 'útil']: print(x,y) # Declaração "pass", usada para métodos vazios não terem erros. for x in range(4): pass
false