blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
72385e51495ed17597e19bd13f49992ef96df332
karlmanalo/cs-module-project-recursive-sorting
/src/searching/searching.py
1,243
4.5
4
# TO-DO: Implement a recursive implementation of binary search def binary_search(arr, target, start, end): # Handling empty arrays if len(arr) == 0: return -1 # Setting midpoint midpoint = (start + end) // 2 if target == arr[midpoint]: return midpoint # Recursion if target is not found at midpoint # If target is less than the midpoint, search from the beginning # of the array to one element before the midpoint (subtract 1 from # the index because we've already compared the target to the midpoint's # value in the beginning of this if statement) elif target < arr[midpoint]: return binary_search(arr, target, start, midpoint - 1) # If target is greater than the midpoint, search from the midpoint # (plus one) to the end of the array else: return binary_search(arr, target, midpoint + 1, end) # STRETCH: implement an order-agnostic binary search # This version of binary search should correctly find # the target regardless of whether the input array is # sorted in ascending order or in descending order # You can implement this function either recursively # or iteratively # def agnostic_binary_search(arr, target): # Your code here
true
fbb99279410300d18b04e4206e9c9b043a4c0866
egbea123/Math
/Test_REMOTE_389.py
281
4.1875
4
#!/usr/bin/env python def main (): num1 = 10.5 num2 = 6.3 # Subtract two numbers sum = float(num1) - float(num2) # Display the result print('The sum of {0} and {1} is {2}',num1, num2, sum ) #division of two numbers result = 10.5 / 6.3 print ("Result :",result)
true
e0334e857bed3460736a05791dcd7469ac2fdeab
jakelorah/highschoolprojects
/Senior(2018-2019)/Python/Chapter 2/P2.8.py
781
4.25
4
#Name: Jake Lorah #Date: 09/14/2018 #Program Number: P2.8 #Program Description: This program finds the area and perimeter of the rectangle, and the length of the diagonal #Declaring the sides of a rectangle Side1 = 24 Side2 = 13 Side3 = 24 Side4 = 13 print("The 4 sides of the rectangle are 24 inches, 13 inches, 24 inches, and 13 inches.") print() #Finding the area Area = Side1 * Side2 print("The area of the rectangle is", Area, "inches squared.") print() #Finding the perimeter Perimeter = Side1 + Side2 + Side3 + Side4 print("The perimeter of the rectangle is", Perimeter, "inches.") print() #Finding the length of the diagonal Diagonal = ((Side1 * Side3) + (Side2 * Side4))**(1/2) print("The length of the diagonal is", Diagonal, "inches.")
true
cdf0b54074aa96db6c30c21d0aaf9026ca250317
jakelorah/highschoolprojects
/Senior(2018-2019)/Python/Tkinter GUI/3by3grid _ Window Project/7.Button_Event_handler.py
815
4.125
4
#Name: Jake Lorah #Date: 11/26/2018 #Program Number: 7.Button_Event_handler #Program Description: This program adds a button event handler. from tkinter import * window = Tk() window.title("Welcome To Computer Science 4") window.geometry('1100x500') addtext= Label(window, text="Hello How are you today", font=("Arial Bold", 70)) addtext.grid(column=0, row=0) count = 0 def clicked(): global count old = '1000x500' addtext.configure(text="Button was Clicked!!") window.geometry(old) count = count + 1 if count % 2 == 0: window.geometry('1100x500') addtext.configure(text = "Hello How are you today") addbutton = Button(window, text="Click me", bg="black", fg="red", command=clicked) addbutton.grid(column=0, row=2) window.mainloop()
true
afec42e00509bc8ae26cf9f73bde35d5b47d2ee7
jakelorah/highschoolprojects
/Senior(2018-2019)/Python/Chapter 4/average.py
317
4.15625
4
#Find the average total = 0.0 count = 0 inputStr = input("Enter value: ") while inputStr != "" : value = float(inputStr) total = total + value count = count + 1 inputStr = input("Enter value: ") if count > 0 : average = total / count else : average = 0.0 print (average)
true
939412528610843959ee52b2b4fbd620083c5cb9
T-D-Wasowski/Small-Projects
/Turtle Artist/Prototype.py
473
4.15625
4
import random import turtle turtle.stamp() moveAmount = int(input("Enter the amount of moves \ you would like your Turtle Artist to make: ")) for i in range(moveAmount): turtle.right(random.randint(1,51)) #<-- For circles. turtle.forward(random.randint(1,101)) turtle.stamp() #Do you collect stamps? input("Press any button to exit.") #Turtle bounce off the edge mechanic. #Input preference, square, circle, etc. #Print/Save image.
true
bd940f09734b661d4902b0f304f1d38d1530fa44
MichaelAlonso/MyCSSI2019Lab
/WeLearn/M3-Python/L1-Python_Intro/hello.py
1,107
4.21875
4
print("Hello world!") print("Bye world!") num1 = int(raw_input("Enter number #1: ")) num2 = int(raw_input("Enter number #2: ")) total = num1 + num2 print("The sum is " + str(total)) num = int(raw_input("Enter a number: ")) if num > 0: print("That's a positive number!") print("Do cherries come from cherry blossom trees!") elif num < 0: print("That's a negative number!") print("Hello I am able to read this message again in my mind!") else: print("Zero is neither positive nor negative") string = "hello there" for letter in string: print(letter.upper()) for i in range(5): print(i) x = 1 while x <= 5: print(x) x = x + 1 my_name = "Bob" friend1 = "Alice" friend2 = "John" friend3 = "Mallory" print( "My name is %s and my friends are %s, %s, and %s" % (my_name, friend1, friend2, friend3) ) def greetAgent(): print("Bond. James Bond.") def greetAgent(first_name, last_name): print("%s. %s %s." % (last_name, first_name, last_name)) def createAgentGreeting(first_name, last_name): return "%s. %s %s." % (last_name, first_name, last_name)
true
ab631a8f16be070bb556ed662c1af5931cd9cbe7
vishalagg/Using_pandas
/bar_plot.py
1,829
4.625
5
import matplotlib.pyplot as plt ''' In line charts, we simply pass the the x_values,y_values to plt.plot() and rest of wprk is done by the function itself. In case of bar graph, we have to take care of three things: 1.position of bars(ie. starting position of each bar) 2.position of axis labels. 3.width of the bars. ''' ''' We can generate a vertical bar plot using either pyplot.bar() or Axes.bar(). prefebly, use Axes.bar() so we can extensively customize the bar plot more easily. We can use pyplot.subplots() to first generate a single subplot and return both the Figure and Axes object. eg:****** fig, ax = plt.subplots() ^above eqn is equivalent to: fig = plt.figure(1,1,1) ax = fig.add_subplot() ''' ''' To pass all three parameters mentioned in 1st paragraph, we can pass like: ax.bar(bar_positions, bar_heights, width) here: bar_positions(left) and bar_heights = Both are lists. width = specifys the width of each bar,generally float o int. ''' ''' Ticks,labels,rotation: By default, matplotlib sets the x-axis tick labels to the integer values the bars spanned on the x-axis (from 0 to 6). We only need tick labels on the x-axis where the bars are positioned. We can use Axes.set_xticks() to change the positions of the ticks to [1, 2, 3, 4, 5]: tick_positions = range(1,6) ax.set_xticks(tick_positions) Then, we can use Axes.set_xticklabels() to specify the tick labels: col = ['bar1','bar2','bar3','bar4','bar5'] ax.set_xticklabels(num_cols,rotation=90) ''' ''' ***similarly we can create HORIZONTAL BAR using: ax.barh(bar_positions(bottom), bar_widths,width) instead of ax.bar() We use Axes.set_yticks() to set the y-axis tick positions to [1, 2, 3, 4, 5] and Axes.set_yticklabels() to set the tick labels to the column names '''
true
3cb86970951a4c592edf191fb44af65aca41e321
rachelprisock/python_hard_way
/ex3.py
1,014
4.21875
4
from __future__ import division print "I will now count my chickens:" # PEMDAS so 30 / 6 = 5 and 25 + 5 = 30 print "Hens", 25 + 30 / 6 # 25 * 3 = 75, 75 % 4 = 3, so 100 - 3 = 97 print "Roosters", 100 - 25 * 3 % 4 print "Now I will count the eggs:" # 4 % 2 = 0, 1 / 4 (no floats with /) = 0 # so 3 + 2 + 1 - 5 + 0 - 0 + 6 = 7 print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 print "Is it true that 3 + 2 < 5 - 7?" # 5 < -2 False. print 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 is greater?", 5 > -2 print "Is it greater or equal?", 5 >= -2 print "Is it less or equal?", 5 <= -2 # NOTE: this difference in division between Python 2 and 3. # If I ran this file using Python 3 I would get floating # point integers instead of only whole numbers # In python 2 it's best to import division from the future version # otherwise you can use float() or just multiply the number with a float, ex: # 1/(2 * 1.0) = 0.5
true
34a8d045b8b194670396993143d998ff0ffc8605
Kyle-Everett10/cp_1404_pracs
/practical_3/oddName.py
562
4.125
4
"""Kyle""" def main(): name = input("Enter your name here: ") while name == "": print("Not a valid name") name = input("Enter your name here: ") frequency = int(input("How frequent do you want the names to be taken?: ")) print(extract_characters(name, frequency)) def extract_characters(name, frequency): characters = [] for character in range(0, len(name), frequency): characters.append(name[character]) extracted_characters = " ".join(characters) return extracted_characters main() print("Done")
true
5536d5bf0689156156e257522381bc2122351be7
thinpyai/python-assignments
/python_small_exercises/sum_matix_crosses.py
745
4.28125
4
def sum_all_cross(matrix): """ Sum all cross direction of matrix. matrix: input integer value in list. """ sum = sum_cross(matrix) reversed_matrix = list(reversed(matrix)) sum += sum_cross(reversed_matrix) return sum def sum_cross(matrix): """ Sum matrix in one cross direction. matrix: input integer value in list. """ target_index = 0 sum = 0 for row in matrix: sum += row[target_index] target_index +=1 return sum if __name__=='__main__': """ Calculate two cross direction of matrix. e.g. (1+5+9) + (3+5+7) """ matrix = [ [1,2,3], [4,5,6], [7,8,9] ] result = sum_all_cross(matrix) print(result)
true
de9325d80d1942fec3c7298d01dedc2bd4b864d5
thinpyai/python-assignments
/python_small_exercises/flatten.py
1,566
4.375
4
# Approximate 1 ~ 1.5h # For this exercise you will create a global flatten method. The method takes in any number of arguments and flattens them into a single array. If any of the arguments passed in are an array then the individual objects within the array will be flattened so that they exist at the same level as the other arguments. Any nested arrays, no matter how deep, should be flattened into the single array result. # The following are examples of how this function would be used and what the expected results would be: # flatten(1, [2, 3], 4, 5, [6, [7]]) # returns [1, 2, 3, 4, 5, 6, 7] # flatten('a', ['b', 2], 3, None, [[4], ['c']]) # returns ['a', 'b', 2, 3, None, 4, 'c'] def flatten(*argv, flatten_list = None): if flatten_list is None: flatten_list = [] for var in argv: if isinstance(var, list): flatten(*var, flatten_list = flatten_list) continue flatten_list.append(var) return flatten_list def flatten_2(*a): r = [] for x in a: if isinstance(x, list): r.extend(flatten(*x)) else: r.append(x) return r def flatten_3(*args): return [x for a in args for x in (flatten(*a) if isinstance(a, list) else [a])] def main(): print(flatten()) # [] print(flatten(1,2,3)) # [1,2,3] print(flatten([1,2],[3,4,5],[6,[7],[[8]]])) # [1,2,3,4,5,6,7,8] print(flatten(1,2,['9',[],[]],None)) # [1,2,'9',None] print(flatten(['hello',2,['text',[4,5]]],[[]],'[list]')) # ['hello',2,'text',4,5,'[list]'] if __name__ == "__main__": main()
true
f4291c2cc1fb648f6cb11ceb8dd5de3fb8d078ed
CarlosArro2001/Little-Book-of-Programming-Problems-Python-Edition
/cards.py
1,100
4.375
4
#... #Aim : Write a program that will generate a random playing cards , when the return return is pressed. # Rather than generate a random number from 1 to 52 . Create two random numbers - one for the suit and one for the card. #Author : Carlos Raniel Ariate Arro #Date : 09-09-2019 #... #imports import random #Array for the suits suits = ["Hearts","Spades","Clubs","Diamonds"] #Array for the numbers numbers = ["Ace","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","King","Queen","Jack"] #press enter to output a random card input() #two variables for storing the randomly generated , one for the suit and one for the numbers randSuit = random.choice(suits) randNum = random.choice(numbers) cardName = randSuit + " of " + randNum if cardName != randSuit + " of " + "King" or cardName != randSuit + " of " + "Queen" or cardName != randSuit + " of " + "Jack" : print(cardName) else: randSuit = random.choice(Suits) randNum = random.choice(numbers) cardName = randSuit + " of " + randNum #Extension - put it into a loop.
true
266b63afbc2a3739423616db5fc2dd395c6977f5
shiyuan1118/Leetcode-in-Python
/Leetcode in Python/double index/merge sorted array(88).py
585
4.21875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri May 8 13:09:50 2020 @author: baoshiyuan """ #Merge Sorted Array class Solution: def merge(nums1, m, nums2, n): while m>0 and n>0: if nums2[n-1]>nums1[m-1]: nums1[m+n-1]=nums2[n-1] n=n-1 else: nums1[m-1],nums1[m+n-1]=nums2[n-1],nums1[m-1] m=m-1 if m==0 and n>0: nums1[:n]=nums2[:n]##if the length of nums2 is greater than nums1,then put the rest of nums2 in the front of merger
true
86686597a2fd83e42237aa24e038a360d9227d8c
Faithlmy/Python_base
/P_base/faith_class/class_inherite.py
926
4.15625
4
#!/usr/bin/env python # # -*- coding:utf-8 -*- # fileName : class_inherite.py """ python的单继承 """ class book(object): __author = '' __name = '' __page = '' def __check(self, item): if item == '': return 0 else: return 1 def show(self): if self.__check(self.__author): print(self.__author) else: print('No value') if self.__check(self.__name): print(self.__name) else: print('No value') def setname(self, name): self.__name = name def __init__(self, author, name): self.author = author self.name = name class student(book):#继承book类 __class = '' __sname = '' __grade = '' def showinfo(self):#使用show 方法 self.show() if __name__ == '__main__': b = student('jack', 'faith') b.show() b.showinfo()
false
67de285c1a6768c8a3b004bfb5364cdf88acdfc6
ianevangelista/Python3
/Ranges.py
336
4.1875
4
for n in range(3, 10, 2): # går fra 3-9 med hopp på 2 print(n) burgere = ['cheese', 'big mac', 'double cheese', 'chicken salsa'] for n in range(len(burgere)): #lengden på lista print(n, burgere[n]) for n in range(len(burgere) -1, -1, -1): # starte på siste, avslutte på første og hopp baklengs print(n, burgere[n])
false
cb4846cfca090647945f8966ff89163050e15e31
akhi1212/pythonpracticse
/StringTask_2_only_first_three_character_of_string.py
525
4.1875
4
## Compare only first three character of string def comparisonFirstThreeChars(s1_inp,s2_inp): a = len(s1_inp) b = len(s2_inp) c_newa = s1_inp[0:3] print(c_newa) d_newb = s2_inp[0:3] print(d_newb) if c_newa == d_newb: print("first three chars matched enjoy your are become code in coding") else: print("Chage your logic First three char is not matched") input3 = input("PLease enter your string more then 3 ") input4 = input("PLease enter your second string more then 3 ") comparisonFirstThreeChars(input3,input4)
false
786fb08e27d3c8a4e79b3525b6169200b081be7a
oceanpad/python-tutorial
/code/basic/if/if.py
242
4.15625
4
age = input('please input your age(int):') try: age = int(age) if age > 18 : print("adult") elif age < 6 : print("children") else : print("teenage") except ValueError: print("'" + age + "' is not an int!")
false
65e075c9b4d051a8308b590626a0828cdbc9c695
StefanDimitrovDimitrov/Python_Basic
/01. First-Steps in Codding Lab+Exr/07.time_to_complete_projects.py
1,071
4.1875
4
""" Напишете програма, която изчислява колко часове ще са необходими на един архитект, за да изготви проектите на няколко строителни обекта. Изготвянето на един проект отнема три часа. Вход От конзолата се четат 2 реда: 1. Името на архитекта - текст; 2. Брой на проектите - цяло число. Изход На конзолата се отпечатва: • "The architect {името на архитекта} will need {необходими часове} hours to complete {брой на проектите} project/s." """ def needed_time_for_the_projects(architect_name, projects_count, time): print(f"The architect {architect_name} will need {projects_count*time} hours to complete {projects_count} project/s.") architect_name = input() projects_count = int(input()) time = 3 needed_time_for_the_projects(architect_name, projects_count, time)
false
53ab52140f9e10ff5670353d9a2296034046a01c
StefanDimitrovDimitrov/Python_Basic
/01. First-Steps in Codding Lab+Exr/08.zoo_food_math_challenge.py
1,045
4.125
4
""" Напишете програма, която пресмята нужните разходи за закупуването на храна за кучета и други животни. Една опаковка храна за кучета е на цена 2.50лв., а всяка останала, която не е за тях струва 4лв. Вход От конзолата се четат 2 реда: 1. Броят на кучетата - цяло число; 2. Броят на останалите животни - цяло число. Изход На конзолата се отпечатва: """ def food_expenses(num_dogs, num_others, food_price_dog, food_price_others): total = float(num_dogs*food_price_dog + num_others*food_price_others) print(f'{total} lv.') num_dogs = int(input()) num_others = int(input()) dog_food_price = 2.5 others_food_price = 4 food_expenses(num_dogs, num_others,dog_food_price, others_food_price) # dog - 5 others - 4 result 28.5 lv # dog - 13 others - 9 result 68.5 lv
false
cf35a1461dde6e392ef6318378bbe892819e1e20
StefanDimitrovDimitrov/Python_Basic
/01. First-Steps in Codding Lab+Exr/12.deposits.py
756
4.34375
4
""" Напишете програма, която изчислява каква сума ще получите в края на депозитния период при определен лихвен процент. Използвайте следната формула: сума = депозирана сума + срок на депозита * ((депозирана сума * годишен лихвен процент ) / 12) Вход Изход 200 3 5.7 202.85 Вход Изход 2350 6 7 2432.25 """ def deposits(deposit, period, annual_rate): annual_rate = annual_rate/100 total = deposit + period * ((deposit*annual_rate)/12) print(total) d = float(input()) p = int(input()) a_r = float(input()) # % deposits(d,p,a_r)
false
c7a9f186a03d699cfb4c205e0d4012f637d9963b
carden-code/python
/stepik/third_digit.py
356
4.15625
4
# A natural number n is given, (n> 99). Write a program that determines its third (from the beginning) digit. # # Input data format # The input to the program is one natural number, consisting of at least three digits. # # Output data format # The program should display its third (from the beginning) digit. num = input() digit = int(num[2]) print(digit)
true
74446a287ad4ff8721c0a882051cd13971e88ba4
carden-code/python
/stepik/removing_a_fragment.py
504
4.1875
4
# The input to the program is a line of text in which the letter "h" occurs at least twice. # Write a program that removes the first and # last occurrences of the letter "h" from this string, as well as any characters in between. # # Input data format # The input to the program is a line of text. # # Output data format # The program should display the text in accordance with the condition of the problem. string = input() elem = 'h' print(string[:string.find(elem)] + string[string.rfind(elem) + 1:])
true
69b16d9c547d2c153d686af7d849138a64ca1bd1
carden-code/python
/stepik/simple_cipher.py
424
4.3125
4
# The input to the program is a line of text. # Write a program that translates each of its characters into their corresponding code # from the Unicode character table. # # Input data format # The input to the program is a line of text. # # Output data format # The program should output the code values of the string characters separated by one space character. string = input() for c in string: print(ord(c), end=' ')
true
69fd35f3faed85dd3ccc5a9a5c1fd5943b52623f
carden-code/python
/stepik/replace_me_completely.py
360
4.21875
4
# The input to the program is a line of text. # Write a program that replaces all occurrences of the number 1 with the word "one". # # Input data format # The input to the program is a line of text. # # Output data format # The program should display the text in accordance with the condition of the problem. string = input() print(string.replace('1', 'one'))
true
e0268220615c83737c7a823fd3195ed76188ab85
carden-code/python
/stepik/word_count.py
468
4.40625
4
# The input to the program is a line of text consisting of words separated by exactly one space. # Write a program that counts the number of words in it. # # Input data format # The input to the program is a line of text. # # Output data format # The program should output the word count. # # Note 1. A line of text does not contain leading or trailing spaces. # # Note 2. Use the count method to solve the problem. string = input() s = ' ' print(string.count(s) + 1)
true
6be2286fe9476c8ee964976e14b3de72d4228609
carden-code/python
/stepik/fractional_part.py
342
4.375
4
# A positive real number is given. Output its fractional part. # # Input data format # The input to the program is a positive real number. # # Output data format # The program should output the fractional part of the number in accordance with the condition of the problem. num = float(input()) fractional = num - (int(num)) print(fractional)
true
10ccf77bd405de979d859da5f0d2489cecfb845e
carden-code/python
/stepik/prime_numbers.py
583
4.1875
4
# The input to the program is two natural numbers a and b (a < b). # Write a program that finds all prime numbers from a to b, inclusive. # # Input data format # The program receives two numbers as input, each on a separate line. # # Output data format # The program should print all prime numbers from a to b inclusive, each on a separate line. a = int(input()) b = int(input()) total = 0 for i in range(a, b + 1): for j in range(1, b + 1): if i % j == 0: total += 1 if total < 3 and i > 1: print(i) total = 0 else: total = 0
true
98c21ee3a49b5420d1f74200a2b2c097c5c49a7a
carden-code/python
/stepik/same_numbers.py
483
4.15625
4
# A natural number is given. Write a program that determines if a specified number consists of the same digits. # # Input data format # One natural number is fed into the program. # # Output data format # The program should print "YES" if the number consists of the same digits and "NO" otherwise. num = int(input()) last_num = num % 10 flag = True while num != 0: if last_num != num % 10: flag = False num = num // 10 if flag: print('YES') else: print('NO')
true
bd2ee920b3b63169a741adedb5fc6c37fad8931f
carden-code/python
/stepik/diagram.py
469
4.21875
4
# The input to the program is a string of text containing integers. # Write a program that plots a bar chart for given numbers. # # Input data format # The input to the program is a text string containing integers separated by a space character. # # Output data format # The program should output a bar chart. # Sample Input 1: # # 1 2 3 4 5 # Sample Output 1: # # + # ++ # +++ # ++++ # +++++ string = input() sym = '+' for i in string.split(): print(sym * int(i))
true
d74b3a0f209a35e82e1061370ea268d36cb3f1b4
carden-code/python
/stepik/reverse_number.py
558
4.53125
5
# Write a program that reads one number from the keyboard and prints the inverse of it. # If at the same time the number entered from the keyboard is zero, # then output "The reverse number does not exist" (without quotes). # # Input data format # The input to the program is one real number. # # Output data format # The program should output a real number opposite to the given one, # or the text in accordance with the condition of the problem. num = float(input()) if num == 0: print('The reverse number does not exist') else: print(num**-1 / 1)
true
8c678c8d77d22a603a84c0434d459197f6eadf6f
carden-code/python
/stepik/number_of_members.py
630
4.375
4
# The program receives a sequence of words as input, each word on a separate line. # The end of the sequence is one of three words: "stop", "enough", "sufficiently" (in small letters, no quotes). # Write a program that prints the total number of members in a given sequence. # # Input data format # The program receives a sequence of words as input, each word on a separate line. # # Output data format # The program should output the total number of members in the given sequence. counter = 0 text = input() while text != 'stop' and text != 'enough' and text != 'sufficiently': counter += 1 text = input() print(counter)
true
b06660bcc21e0142f6cdb78adb357b8df1953fb5
carden-code/python
/stepik/characters_in_range.py
500
4.3125
4
# The input to the program is two numbers a and b. # Write a program that, for each code value in the range a through b (inclusive), # outputs its corresponding character from the Unicode character table. # # Input data format # The input to the program is two natural numbers, each on a separate line. # # Output data format # The program should display the text in accordance with the condition of the problem. a = int(input()) b = int(input()) for i in range(a, b + 1): print(chr(i), end=' ')
true
84342c5f534b935c231e13a9836c4af83e840fe2
carden-code/python
/stepik/sum_of_digits.py
218
4.125
4
# Write a function print_digit_sum () that takes a single integer num and prints the sum of its digits. def print_digit_sum(_num): print(sum([int(i) for i in str(_num)])) num = int(input()) print_digit_sum(num)
true
0291ba0bf851212409f7ac5f928153ba0fda249f
carden-code/python
/stepik/line_by_line_output.py
347
4.4375
4
# The input to the program is a line of text. Write a program that displays the words of the entered line in a column. # # Input data format # The input to the program is a line of text. # # Output data format # The program should display the text in accordance with the condition of the problem. string = input() print(*string.split(), sep='\n')
true
f3e5e2a96224b5ad2133b5683b8803a654141797
carden-code/python
/stepik/sum_num_while.py
497
4.28125
4
# The program is fed a sequence of integers, each number on a separate line. # The end of the sequence is any negative number. # Write a program that outputs the sum of all the members of a given sequence. # # Input data format # The program is fed with a sequence of numbers, each number on a separate line. # # Output data format # The program should display the sum of the members of the given sequence. total = 0 i = int(input()) while i >= 0: total += i i = int(input()) print(total)
true
ce3399dcdfc212a588de430f21cb81735264b258
Mario-D93/habit_tracker
/t_backend.py
1,885
4.21875
4
import sqlite3 class Database(): ''' The Database object contains functions to handle operations such as adding, viewing, searching, updating, & deleting values from the sqlite3 database The object takes one argument: name of sqlite3 database Class is imported to the frontend script (t_fronted.py) ''' def __init__(self,db): ''' Database Class Constractor to initialize the object and connect to the database if exists. IF not, new database will be created and will contain columns: id, work, wake_up, training, bedtime, sleep ''' self.conn=sqlite3.connect(db) self.curs=self.conn.cursor() self.curs.execute("CREATE TABLE IF NOT EXISTS trackerdata(id INTEGER PRIMARY KEY, dt TEXT, work INTEGER, wake_up INTEGER,\ training TEXT, bedtime INTEGER, sleep INTEGER)") self.conn.commit() def insert(self,dt,work,wake_up,training,bedtime,sleep): self.curs.execute("INSERT INTO trackerdata VALUES(NULL,?,?,?,?,?,?)",(dt,work,wake_up,training,bedtime,sleep)) self.conn.commit() def view_all(self): self.curs.execute("SELECT * FROM trackerdata") view_all=self.curs.fetchall() return view_all def search(self,dt="",work="",wake_up="",training="",bedtime="",sleep=""): self.curs.execute("SELECT * FROM trackerdata WHERE dt=? OR work=? OR wake_up=? OR training=? OR bedtime=? OR sleep=?",\ (dt,work,wake_up,training,bedtime,sleep)) view_all=self.curs.fetchall() return view_all def delete(self,id): self.curs.execute("DELETE FROM trackerdata WHERE id=?",(id,)) self.conn.commit() def update(self,id,dt,work,wake_up,training,bedtime,sleep): self.curs.execute("UPDATE trackerdata SET dt=?,work=?,wake_up=?,\ training=?,bedtime=?,sleep=? WHERE id=?",(dt,work,wake_up,\ training,bedtime,sleep,id)) self.conn.commit() def __del__(self): #function closes the connection with the sqlite3 database self.conn.close()
true
c93ea29aafd03ee6e05efb2a460b9f93fa017107
dfkigs/helloworld
/python/basic/generator/generator.py
1,114
4.1875
4
#!/usr/bin/python # keyword : yield def flatten(nested): for sublist in nested: for element in sublist: yield element def flatten_recursion(nested): try: try: nested + '' except TypeError: pass else: raise TypeError for sublist in nested: for element in flatten_recursion(sublist): yield element except TypeError: yield nested nested = [[1,2],[3,4],[5]] nested2 = [[1,2],[3,4],5] nested3 = [[1,2],[3,4],[5,6,[7,8]]] nested4 = [[1,2],[3,4],[5,6,[7,8]],'test'] print "nested" for n in flatten(nested): print n print list(flatten(nested)) print "nested2" for n in flatten_recursion(nested2): print n print list(flatten_recursion(nested2)) print "nested3" for n in flatten_recursion(nested3): print n print list(flatten_recursion(nested3)) print "nested4" for n in flatten_recursion(nested4): print n print list(flatten_recursion(nested4)) # fib def fib(max): n,a,b = 0,0,1 while n < max: yield b a,b=b,a+b n += 1 print fib(5) # run steps def odd(): print 'step 1' yield 1 print 'step 2' yield 2 print 'step 3' yield 3 o = odd() print o.next() #
false
89fafeb66a04184fb1f8fe490ecde074c68ae4bc
0n1udra/Learning
/Python/Python_Problems/Rosalind-master/Algorithmic_009_BFS.py
1,705
4.21875
4
#!/usr/bin/env python ''' A solution to a ROSALIND problem from the Algorithmic Heights problem area. Algorithmic Heights focuses on teaching algorithms and data structures commonly used in computer science. Problem Title: Breadth-First Search Rosalind ID: BFS Algorithmic Heights #: 012 URL: http://rosalind.info/problems/bfs/ ''' from collections import defaultdict def minimum_dist_bfs(n, edges): '''Performs a BFS to get the minimum distance to all nodes starting at node 1.''' # Build the graph. graph = defaultdict(list) for n1, n2 in edges: graph[n1].append(n2) # BFS to find the minimum distance to each node from node 1. min_dist = [0] + [-1]*(n-1) remaining = set(xrange(2, n+1)) queue = [1] while queue: current = queue.pop(0) for node in graph[current]: if node in remaining: queue.append(node) remaining.discard(node) # Rosalind starts indices at 1 instead of 0. min_dist[node-1] = min_dist[current-1] + 1 return min_dist def main(): '''Main call. Reads, runs, and saves problem specific data.''' # Read the input data. with open('data/algorithmic/rosalind_bfs.txt') as input_data: n = map(int, input_data.readline().strip().split())[0] edges = [map(int, line.strip().split()) for line in input_data] # Get the minimum distances. min_dist = map(str, minimum_dist_bfs(n, edges)) # Print and save the answer. print ' '.join(min_dist) with open('output/algorithmic/Algorithmic_009_BFS.txt', 'w') as output_data: output_data.write(' '.join(min_dist)) if __name__ == '__main__': main()
true
7bc496f3183da034730fad98d0b6bc26b27573c2
0n1udra/Learning
/Python/Python_Problems/Rosalind-master/001_DNA.py
934
4.1875
4
#!/usr/bin/env python ''' A solution to a ROSALIND bioinformatics problem. Problem Title: Counting DNA Nucleotides Rosalind ID: DNA Rosalind #: 001 URL: http://rosalind.info/problems/dna/ ''' from collections import Counter def base_count_dna(dna): '''Returns the count of each base appearing in the given DNA sequence.''' base_count = Counter(dna) return [base_count[base] for base in 'ACGT'] def main(): '''Main call. Parses, runs, and saves problem specific data.''' # Read the input data. with open('data/rosalind_dna.txt') as input_data: dna = input_data.read().strip() # Get the count of each base appearing in the DNA sequence. base_count = map(str, base_count_dna(dna)) # Print and save the answer. print ' '.join(base_count) with open('output/001_DNA.txt', 'w') as output_data: output_data.write(' '.join(base_count)) if __name__ == '__main__': main()
true
c8508b6bba66b1052ca57cc2b9b31af313f805da
0n1udra/Learning
/Python/Python_Problems/Interview_Problems-master/python/logarithm.py
732
4.1875
4
''' Compute Logarithm x: a positive integer b: a positive integer; b >= 2 returns: log_b(x), or, the logarithm of x relative to a base b. Assumes: It should only return integer value and solution is recursive. ''' def myLog(x, b): if x < b: return 0 else: return myLog(x/b, b) + 1 if __name__ == '__main__': # Test section implementations = [myLog] for impl in implementations: print "trying %s" % impl print " f(1, 2) == 0: %s" % (impl(1,2) == 0) print " f(2, 2) == 1: %s" % (impl(2,2) == 1) print " f(16, 2) == 4: %s" % (impl(16,2) == 4) print " f(15, 3) == 2: %s" % (impl(15,3) == 2) print " f(15, 4) == 1: %s" % (impl(15,4) == 1)
true
6fb3874538b010fa6367cfd1ef6ed6fd392e91c3
TheJoeCollier/cpsc128
/code/python2/tmpcnvrt.py
1,242
4.5
4
########################################################### ## tmpcnvrt.py -- allows the user to convert a temperature ## in Fahrenheit to Celsius or vice versa. ## ## CPSC 128 Example program: a simple usage of 'if' statement ## ## S. Bulut Spring 2018-19 ## Tim Topper, Winter 2013 ########################################################### print "This program converts temperatures from Fahrenheit to Celsius," print "or from Celsius to Fahrenheit." print "Choose" print "1 to convert Fahrenheit to Celsius" print "2 to convert Celsius to Fahrenheit" choice = input( "Your choice? " ) if choice == 1: print "This program converts temperatures from Fahrenheit to Celsius." temp_in_f = input( "Enter a temperature in Fahrenheit (e.g. 10) and press Enter: " ) temp_in_c = (temp_in_f - 32) * 5 / 9 print temp_in_f, " degrees Fahrenheit = ", temp_in_c, " degrees Celsius." elif choice == 2: print "This program converts temperatures from Celsius to Fahrenheit ." temp_in_c= input( "Enter a temperature in Celsius (e.g. 10) and press Enter: " ) temp_in_f = temp_in_c * 9 / 5 + 32 print temp_in_c, " degrees Celsius = ", temp_in_f, " degrees Fahrenheit." else: print "Error: Your choice not recognized!"
true
0048afa92e4b1d09b35e2d7ae5c1dbe074f0b60e
shraddhaagrawal563/learning_python
/numpy_itemsize.py
705
4.28125
4
# -*- coding: utf-8 -*- #https://www.tutorialspoint.com/numpy/numpy_array_attributes.htm import numpy as np x = np.array([1,2,3,4,5]) print ("item size" , x.itemsize) #prints size of an individual element x = np.array([1,2,3,4,5,4.2,3.6]) print ("item size" , x.itemsize) #converts every element to the largest of size x = np.array([1,2,3,4,5,3.3,"str"]) print ("item size" , x.itemsize) x = np.array(["a","b", 4.5]) #adding size of each type print ("item size" , x.itemsize) ''' only similar datatypes element can be put inside an numpy array.. the above thing is not practised''' print("\nnumpy flags") x = np.array([1,2,3,4,5]) print ("item size" , x.flags) #gives the complete state of array
true
1e0b7b0aed95cfb2db8b1f382bd898fef6c5e595
hyetigran/Sorting
/src/recursive_sorting/recursive_sorting.py
1,465
4.125
4
# TO-DO: complete the helpe function below to merge 2 sorted arrays def merge(arr, arrA, arrB): # TO-DO left_counter = 0 right_counter = 0 sorted_counter = 0 while left_counter < len(arrA) and right_counter < len(arrB): if arrA[left_counter] < arrB[right_counter]: arr[sorted_counter] = arrA[left_counter] left_counter += 1 else: arr[sorted_counter] = arrB[right_counter] right_counter += 1 sorted_counter += 1 while left_counter < len(arrA): arr[sorted_counter] = arrA[left_counter] left_counter += 1 sorted_counter += 1 while right_counter < len(arrB): arr[sorted_counter] = arrB[right_counter] right_counter += 1 sorted_counter += 1 return arr # TO-DO: implement the Merge Sort function below USING RECURSION def merge_sort(arr): if len(arr) > 1: left_arr = arr[:len(arr)//2] right_arr = arr[len(arr)//2:] merge_sort(left_arr) merge_sort(right_arr) merge(arr, left_arr, right_arr) return arr # STRETCH: implement an in-place merge sort algorithm def merge_in_place(arr, start, mid, end): # TO-DO return arr def merge_sort_in_place(arr, l, r): # TO-DO return arr # STRETCH: implement the Timsort function below # hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt def timsort(arr): return arr
true
5b4b1cea5e01a539d288bde1bbc1ae264434f962
farooqbutt548/Python-Path-Repo
/strings.py
1,303
4.34375
4
# Strings # Simple String '''string1 = ' this is 1st string, ' string2 = "this is 2nd string" print(type(string1)) connect_string = string1+ " "+string2 print(connect_string) # print("errer"+3) erreor print('this is not error'+' ' + str(3)) print('this will print 3 times'*3 )''' # f-string, string-formatting '''f_name = 'farooq' l_name = 'butt' print(f'hello {f_name} {l_name} how are you.') # string input via split method() name, age,degree = input('enter your name, age & degree comma separated : ').split(',') print(f'hello {name} your age is {age} & degree is {degree}.') # string indexing name_index = 'farooq butt' print(name_index[1]) #2nd number char will print from left print(name_index[-1]) #last char will print print(name_index[2:6:1]) # string slicing [start:ending:step] print(name_index[ : :-1]) # reverse string''' # string exercice # name in reversed order '''name = input('enter your naem : ') ; print(name[::-1])''' # string methods '''word = 'abCdefgHijKlmnOpqRsTuvwXyz' print(len(word)) # leangth of word print(word.lower()) # for lower letters print(word.upper()) # for upper letters print(word.count('b')) # for count a letter in word print(word.title()) # for first letter capital print(word.center(80)) # for aligning text '''
true
8b8f9374e4084d763f3b4195f5be59c95deeea50
Khepanha/Python_Bootcamp
/week01/ex/e07_calcul.py
287
4.125
4
total = 0 while True: number = input("Enter a number: \n>> ") if number == "exit": break else: try: number = int(number) total += number print("TOTAL: ",total) except: print("TOTAL: ",total)
true
faa5907d95f8ab25764f7dd6b0a05ef44f5e7f9b
rp764/untitled4
/Python Object Orientation /OrientationCode.py
1,348
4.40625
4
# OBJECT ORIENTED PROGRAMMING # INHERITANCE EXAMPLE CODE class Polygon: width_ = None height_ = None def set_values(self, width, height): self.width_ = width self.height_ = height class Rectangle(Polygon): def area(self): return self.width_ * self.height_ class Triangle(Polygon): def area(self): return self.width_ * self.height_ / 2 # ENCAPSULATION EXAMPLE CODE class Car: def __init__(self, speed, color): self.__speed = speed self.__color = color def set_speed(self, value): self.__speed = value def get_speed(self): return self.__speed def get_color(self): return self.__color def set_color(self, value): self.__color = value audi = Car(200, 'red') honda = Car(250, 'white') audi.set_speed(400) # ABSTRACT EXAMPLE CODE from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): pass @abstractmethod def perimeter(self): pass class Square(Shape, ABC): def __init__(self, side): self.__side = side def area(self): return self.__side * self.__side def perimeter(self): return 4 * self.__side # POLYMORPHISM EXAMPLE CODE OVERWRITING VARIABLE class Parent: name = "Bob" class Child(Parent): pass obj = Child()
true
1a057628c822895bf6e506846fb5fc7de0e10184
giovannyortegon/holbertonschool-machine_learning
/supervised_learning/0x07-cnn/1-pool_forward.py
1,717
4.125
4
#!/usr/bin/env python3 """ Pooling """ import numpy as np def pool_forward(A_prev, kernel_shape, stride=(1, 1), mode='max'): """ pool - performs pooling on images Args: A_prev is a numpy.ndarray of shape (m, h_prev, w_prev, c_prev) containing the output of the previous layer. m is the number of examples h_prev is the height of the previous layer w_prev is the width of the previous layer c_prev is the number of channels in the previous layer kernel_shape is a tuple of (kh, kw) containing the size of the kernel for the pooling. kh is the kernel height kw is the kernel width stride is a tuple of (sh, sw) containing the strides for the pooling sh is the stride for the height. sw is the stride for the width. mode is a string containing either max or avg, indicating whether to perform maximum or average pooling, respectively. Returns: the output of the pooling layer. """ m, h_prev, w_prev, c_prev = A_prev.shape kh, kw = kernel_shape sh, sw = stride pool_h = int((h_prev - kh) / sh) + 1 pool_w = int((w_prev - kw) / sw) + 1 pool = np.zeros((m, pool_h, pool_w, c_prev)) for i in range(pool_h): for j in range(pool_w): slide_img = A_prev[:, i * sh:i * sh + kh, j * sw:j * sw + kw] if mode == 'max': pool[:, i, j] = np.max(np.max(slide_img, axis=1), axis=1) elif mode == 'avg': pool[:, i, j] = np.mean(np.mean(slide_img, axis=1), axis=1) return pool
true
e97603a1bf321aaede95c36998fe3c780b94ef84
giovannyortegon/holbertonschool-machine_learning
/math/0x00-linear_algebra/3-flip_me_over.py
551
4.25
4
#!/usr/bin/env python3 """ the transpose of a 2D matrix """ matrix_shape = __import__("2-size_me_please").matrix_shape def matrix_transpose(matrix): """ matrix_transpose - the transpose of a 2D matrix mat1: Input first matrix mat2: Input second matrix Return: New matrix """ m_length = matrix_shape(matrix) new_matrix = [[0 for i in range(m_length[0])] for j in range(m_length[1])] for i in range(m_length[0]): for j in range(0, m_length[1]): new_matrix[j][i] = matrix[i][j] return new_matrix
true
9c0a6af5710db5a8921f02a6420006081eb802fd
santoshr1016/WeekendMasala
/itsybitsy/MyDP_Quest/stair_case_to_heaven_with_fee.py
843
4.125
4
""" You can take at max 2 steps if _ ways 1, you are already there 1 _1 if _| ways needed from Ground 1, G->1 _2 _| if _| ways needed from Ground 2, G->1, 1->1 G->2 _3 _|2 _|1 if _| steps needed from Ground will be Ways to reach from second last step to 3 which is FROM 2 + 1 step OR 1 + 2 leap step ways are 2+1 """ def stair_case(nth, fee): min_fee = [None]*(nth+1) min_fee[0] = 0 min_fee[1] = fee[0] min_fee[2] = fee[0] for i in range(3,nth+1): min_fee[i] = min(min_fee[i-1] + fee[i-1], min_fee[i-2] + fee[i-2], min_fee[i-3] + fee[i-3]) print(min_fee) return min_fee[nth] step_to_climb = 5 fee = [2, 1, 3, 1, 2] print(stair_case(step_to_climb, fee))
false
7d19eb3f453acd08dc5ac3a415c51f6e3a01afdc
santoshr1016/WeekendMasala
/itsybitsy/collections_DS/most_occuring_items.py
657
4.4375
4
words = [ 'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the', 'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into', 'my', 'eyes', "you're", 'under' ] from collections import Counter word_counts = Counter(words) print(word_counts) top_3 = word_counts.most_common(3) print(top_3) morewords = ['why','are','you','not','looking','in','my','eyes'] for word in morewords: word_counts[word] += 1 print(word_counts) # word_counts.update(morewords) print("using count") s = "This is the word, which is the most repeated" print(s.count("is"))
false
192d8c2fa81b0f8469deb319622e8962d4e1273a
EachenKuang/LeetCode
/code/202#Happy Number.py
2,457
4.125
4
# First of all, it is easy to argue that starting from a number I, if some value - say a - appears again during the process after k steps, the initial number I cannot be a happy number. Because a will continuously become a after every k steps. # Therefore, as long as we can show that there is a loop after running the process continuously, the number is not a happy number. # There is another detail not clarified yet: For any non-happy number, will it definitely end up with a loop during the process? This is important, because it is possible for a non-happy number to follow the process endlessly while having no loop. # To show that a non-happy number will definitely generate a loop, we only need to show that for any non-happy number, all outcomes during the process are bounded by some large but finite integer N. If all outcomes can only be in a finite set (2,N], and since there are infinitely many outcomes for a non-happy number, there has to be at least one duplicate, meaning a loop! # Suppose after a couple of processes, we end up with a large outcome O1 with D digits where D is kind of large, say D>=4, i.e., O1 > 999 (If we cannot even reach such a large outcome, it means all outcomes are bounded by 999 ==> loop exists). We can easily see that after processing O1, the new outcome O2 can be at most 9^2*D < 100D, meaning that O2 can have at most 2+d(D) digits, where d(D) is the number of digits D have. It is obvious that 2+d(D) < D. We can further argue that O1 is the maximum (or boundary) of all outcomes afterwards. This can be shown by contradictory: Suppose after some steps, we reach another large number O3 > O1. This means we process on some number W <= 999 that yields O3. However, this cannot happen because the outcome of W can be at most 9^2*3 < 300 < O1. # https://leetcode.com/problems/happy-number/description/ class Solution(object): def isHappy(self, n): """ :type n: int :rtype: bool """ def calculateSum(n): sum = 0 while(n): tmp = n % 10 sum += tmp * tmp n //= 10 return sum; slow = fast = n; while True: slow = calculateSum(slow); fast = calculateSum(fast); fast = calculateSum(fast); if slow==fast: break if slow == 1: return True else: return False;
true
4c599c9f902ed403eb88fa39b61657003917751d
Billoncho/EncoderDecoder
/EncoderDecoder.py
1,469
4.5625
5
# EncoderDecoder.py # Billy Ridgeway # Encode or decode your messages by shifting the ASCII characters. message = input("Enter a message to encode or decode: ") # Prompt the user for a message to encode/decode. message = message.upper() # Convert the string of letters to upper case. output = "" # Sets output to an empty string. for letter in message: # A loop to convert each letter in the message. if letter.isupper(): # Checks to see if the letter is already in upper case. value = ord(letter) + 13 # Converts the letter to it's corresponding ASCII number. letter = chr(value) # Converts an ASCII number to a letter. if not letter.isupper(): # This loop runs to ensure that the ASCII number hasn't shifted too far and gone past 'Z'. value -= 26 # This subtracts 26 from the number to ensure it's in the range from 'A' to 'Z'. letter = chr(value) # Converts the ASCII value to a letter. output += letter # Add the letter to the output string. print("Output message: ", output) # Prints the encoded/decoded message to the screen.
true
66ca9d86e2fc88d1402c31fbc1078c4cf9b262b3
Sophon96/2021-software-general-homework
/lesson_2_1.py
1,443
4.21875
4
# A student has taken 3 tests in a class, and wants to know their current grade # (which is only calculated by these tests). # Ask the user to input all three of the test scores for the student, one by one. # The program should then calculate the average test score (average is adding all three # test scores together then dividing by 3), and then print the student's letter grade # (as well as the average score as a number). if __name__ == '__main__': import decimal import sys import statistics endings = ['st', 'nd', 'rd'] scores = [] for i in range(3): try: scores.append(decimal.Decimal(input(f"Please input your {i+1}{endings[i]} score: "))) except decimal.InvalidOperation: print("The score must be a valid Decimal!", file=sys.stderr) exit(1) avg = statistics.mean(scores) lgs = {decimal.Decimal(65): 'F', decimal.Decimal(66): 'D', decimal.Decimal(69): 'D+', decimal.Decimal(72): 'C-', decimal.Decimal(76): 'C', decimal.Decimal(79): 'C+', decimal.Decimal(82): 'B-', decimal.Decimal(86): 'B', decimal.Decimal(89): 'B+', decimal.Decimal(92): 'A-', decimal.Decimal(96): 'A', decimal.Decimal(100): 'A+'} for k in lgs: if avg < k: break print(f"Your average score is {avg}, which is a {lgs[k]}")
true
a2a18544685a691a7b072d14b04f7b2f1e6ddca7
SebastianoFazzino/Python-for-Everybody-Specialization-by-University-of-Michigan
/Word_coutnter_using_dictionaries.py
461
4.125
4
#how to find the most common word in a text: openfile = input("Enter file name: ") file = open(openfile) counts = dict() for line in file: words = line.split() for word in words: counts[word] = counts.get(word,0) + 1 bigcount = None bigword = None for word, count in counts.items(): if bigcount is None or count > bigcount: bigword = word bigcount = count print(bigword,bigcount)
true
5cd45a7e4fee6f5440f4126b64ae8e80730e9ae9
SebastianoFazzino/Python-for-Everybody-Specialization-by-University-of-Michigan
/Conditional Statements.py
907
4.25
4
#Calculating the score score = input("Enter Score: ") try: score = float(score) if score > 0.0 and score < 0.6: print ("F") elif score >= 0.6 and score <= 0.69: print("D") elif score >= 0.7 and score <= 0.79: print ("C") elif score >= 0.8 and score <= 0.89: print("B") elif score >=0.9 and score <=1.0: print("A") else: print("Score value must be between 0.0 and 1.0") except: print("wrong input!") #calculating the pay hrs = input("Enter Hours:") hr_rate = input("Enter Pay Rate:") try: hrs = float(hrs) hr_rate = float(hr_rate) except: print("Please enter numeric input!") quit() extratime = hrs - 40 if hrs > 40: pay = 40 * hr_rate + extratime * 15.75 elif hrs > 1 and hrs <= 40: pay = hrs * hr_rate print(pay)
true
96dd5264ff38d0fd2c97413156397cea4da742d9
JLockleyASC/jaymond_ASC3
/mash.py
1,132
4.15625
4
house =["Mansion", "Apartment", "igloo", "House" ,"tent", "tree house"] spouse =["peewee herman", "Snookie", "Oprah", "kylie jennner"] car =["horse", "bugatti with one wooden wheel", "DeLorean DMC-12", "Scooter"] kids =["0", "1", "2", "5"] print ("Enter the name of three people you could marry: ") name1 = input("Name1:") spouse[0]= "oprah" name2 = input("Name2:") spouse[1]= "snookie" name5 = input("Name3:") spouse[2]= "oprah" print ("Enter the name of one person you wouldn't want to marry:") name4 =raw_input("Name4: ") spouse[3]= "kylie jennner" print ("Enter the name of 3 cars you want: ") car1 =input("car1:") car[0]= "Bugatti with one wooden wheel" car2 = input("car2:") car[1] = "Bugatti with one wooden wheel" car3=input("car3:") car[2]="DeLorean DMC-12" print ("Enter the name of one car you don't want: ") car4 =input("car4:") car[3]="scooter" '''print ("You will live in a: ") for i in range(1): print(house[i]) print ("Married to: ") for i in range(1): print (spouse[i]) print ("While driving your: ") for i in range(1): print (car[i]) print ("With ") for i in range(1): print (kids[i]) print ("kids in it")'''
false
e3e14d6b50222fddaea52f6a1a9012daf1654cdb
NakonechnyiMykhail/PyGameStart
/lesson26/repeat.py
505
4.1875
4
# functions without args without return # 0. import random # library # 1. create a function with name "randomizer" # 2. create a varieble with name "data" = 'your text at 6-10 words' # or "lorem ipsum..." # 3. select var "data" with text and with random method print # with for-loop 20 times only ONE character data = 'Antidisestablishmentarianism' # randint() Returns a random number between the given range # choice() Returns a random element from the given sequence # functions with args
true
e128dc2672cbf6b6b4dee1c1537884ffcc9dc86a
ridhim-art/practice_list2.py
/tuple_set_dictionary/example_contacts.py
707
4.1875
4
#program where user can add contacta for contact book contacts = {'help': 100} print('your temp contact book') while True: name = input("=> enter contact name :") if name: if name in contacts: print('=> contact found') print(f'=> {name} :{contacts[name]}') else: print('=> contact not found') update = input('>> do you want to add the contact(y/n)?') if update.lower() == 'y': number = input(f'>> enter contact number for {name}') contacts[name] = number print(f'=> contact updated for {name}') else: print('closing contact book') break
true
c504e5e4f9433cea90d3a95157a7424ab9a74f25
ridhim-art/practice_list2.py
/prime_number.py
287
4.15625
4
# 7 -> 7/2,7/3,7/4,7/5,7/6 prime # 20 -> 20/2 non prime # program to find if number is prime num = int(input('enter a number : ')) for i in range(2,num): print(num,'%',i,'=',num % i) if num % i ==0: print('non prime') break else: print('prime')
false
ad5fdda33ea752ed77936eba34e371562ed868bc
ridhim-art/practice_list2.py
/condition_1.py
264
4.21875
4
a = 10 if a > 5: print('this is a greater than 5') if a > 15: print ('this is also bigger than 15') if a == 10: print ('thisis equal to 10 ') if a == 5 or a < 15: print ('so this condition is true ') print('any one of them is true')
false
d9e76d1f7a25dfa8d4e160ce4a1f89fcd8eaf704
subbuinti/python_practice
/loopControlSystem/HallowDaimond.py
865
4.25
4
# Python 3 program to print a hallow diamond pattern given N number of rows alphabets = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U','V', 'W', 'X', 'Y', 'Z'] # Diamond array diamond = [] rows = -1 # Prompt user to enter number of rows while rows < 1 or rows > 26: rows = int(input()) for i in range(0, rows): # Add letters to the diamond diamond.append("") for j in range(0, rows - i): diamond[i] += " " diamond[i] += alphabets[i]; if alphabets[i] != 'A': # Put spaces between letters for j in range(0, 2 * i - 1): diamond[i] += " " diamond[i] += alphabets[i] # Print the first part of the diamond print(diamond[i]) # Print the second part of the diamond for i in reversed(range(0, rows - 1)): print(diamond[i])
true
f6ef587277e59d1568fad4072db790627afc6657
jaewHong/myappsample
/jae_week1hw.py
251
4.125
4
#!/usr/bin/env python3 import datetime if __name__ == '__main__': print("user name:",end='') username = input() date = datetime.datetime.now() print("Hello {0}! Today is [{1}/{2}/{3}].".format(username,date.month,date.day,date.year))
false
915ca9bbea032f07b0adc06a94f3409c6d7e3bad
lokeshsharma596/Base_Code
/Pyhton/Lambda_Map_Filter.py
2,346
4.375
4
# Lambda Function # any no of arguments but only one statement # single line ,anoymous,no def,no return # example-1 def sum(a, b, c): return a+b+c print(sum(4, 5, 1)) add=lambda a,b,c: a+b+c print(add(4, 5, 1)) # example-2 cube=lambda n:n**3 print(cube(4)) # Map Function # Atleast Two arguments :function and an iterable # Iterable(list,string,dictionary,set,tuple) # runs the lambda for each value in iterable and return a map object which, # can be converted into any data structure # example-1 nums = [1, 2, 3, 4, 5] def sq(n): return n*n square = list(map(sq, nums)) print(square) # example-2 nums = [1, 2, 3, 4, 5] square = list(map(lambda x: x**x, nums)) print(square) # example-3 people = ["lokesh", "sharma", "python", "developer"] up = list(map(lambda x: x.upper(), people)) print(up) # example-4 names = [ {'first': 'lokesh', 'last': 'sharma'}, {'first': 'ravi', 'last': 'sharma'}, {'first': 'jiu', 'last': 'sharma'} ] first_names = list(map(lambda x: x['first'], names)) print(first_names) # Filter # There is a lambda for each value in iterable # return only values which are true to lambda # example-1 names = ['anthony', 'penny', 'austing', 'boy', 'amio'] a = list(filter(lambda x: x[0] == 'a', names)) print(a) # example-2 #filter inactive users users = [ {"username": 'samuel', "tweets": ["i love cake", "i am good"]}, {"username": 'andy', "tweets": []}, {"username": 'kumal', "tweets": ["India", "Python"]}, {"username": 'sam', "tweets": []}, {"username": 'lokesh', "tweets": ["i am good"]}, ] inactive_users = list(filter(lambda a:not a['tweets'], users)) print(inactive_users) #example-3 #filter inactive users with just username in uppercase inactive_users=list(map(lambda x: x["username"].upper(), filter(lambda a:not a['tweets'], users))) print(inactive_users) #example-4 #return a new list with the string "your name is" + name # but only if length of name is less than five names=['lokesh','lassie','bob','to'] new=list(map(lambda name:f"your name is {name}", filter(lambda x:len(x)>4,names))) print(new) #List Comprehension # for example 2 inactive_users=[user for user in users if not user["tweets"]] print(inactive_users) # for example 3 inactive_users=[user["username"].upper() for user in users if not user["tweets"]] print(inactive_users)
true
7c1c8e21773cf05be04e25f2cc42f9b947929f39
andrezzadede/Curso-de-Python-POO
/decorators.py
743
4.28125
4
''' Decorator = Função que recebe outra função como parametro, gera uma nova função que adiciona algumas funcionalidades à função original e a retorna essa nova funçao ''' ''' def modificar(funcao): def subtrair(a, b): return a - b return subtrair @modificar def soma(a, b): return a + b print(soma(2, 4)) ''' def modificar(funcao): def somar_pares(a, b): if a % 2 == 0 or b % 2 == 0: return a + b return a - b return somar_pares @modificar def soma(a, b): return a + b print(soma(2, 2)) def meu_decorador(funcao): def imprime_algo(): print('Eu não sei somar') return imprime_algo @meu_decorador def imprime(): print('Eu sei somar') imprime()
false
b201d29f539242f9295b7826df8cd4834b173a02
gillc0045/CTI110
/Module3/CTI110_M3HW2_bodyMassIndex_gillc0045.py
502
4.4375
4
# Write a program to calculate a person's body mass index (BMI). # 12 Jun 2017 # CTI 110 - M3HW2 -- Body Mass Index # Calvin Gill weight = float(input("Enter the person's weight (pounds): ")) height = float(input("Enter the person's height (inches): ")) bmi = weight*(703/height**2) print("The person's BMI value is ",bmi) if bmi > 25: print('The person is overweight') elif bmi < 18.5: print('The person is underweight') else: print('The person is at optimal weight')
true
f74f8032c81b88479718b6bd9e861f1bb04c77c1
HussainWaseem/Learning-Python-for-Data-Analysis
/NewtonRaphson.py
1,625
4.1875
4
''' Newton Raphson ''' # Exhaustive Enum = In this we were using guesses but we were going all the way from beginning to end. # And we were only looking for correct or wrong answers. No approximation. # Approximation = It was an improvement over Exhaustive Enum in a way that now we can make more correct guesses # and can give an approximate answers to those which are not representable. # But due to correctness, we have to take a very small epsilon and steps. # No. of guesses we made was in the order of answer/steps, it took a lot of time. # Bisection Search = It was a massive improvement over both of the above in terms of speed. # We were approximating as well as making smart guesses. # We were at each guess looking for the correct search bound by leaving half of the range. # Newton Raphson Method = Well it tells us that if we improve our guesses in each iteration ,we might reach our # goal much earlier, even earlier than bisection search. # we were using Approximation, but our steps were not in the order of epsilon**2. # But we were making guesses which were more smart and calculated. ''' Square root using Newton Paphson Method ''' x = int(input("Give your Integer : ")) answer = x/2 epsilon = 0.01 guess = 0 while abs(answer**2 - x) >= epsilon: answer = answer - ((answer**2)-x)/(2*answer) # this is newton's betterement method of guess for Sq Root. guess += 1 print("Number of guesses made:",guess) print("Approximate Sq root is:",answer) # If I remove this betterment of guess method, and set the answer to increment of epsilon and run this program. # then this program will run too slow!!
true
026139b2e0beed35054a503d4c308c5450e6684b
HussainWaseem/Learning-Python-for-Data-Analysis
/FractionsToBinary.py
1,695
4.3125
4
''' Fractions to Binary ''' # Method ->> Fractions -> decimals using 2**x multiplication -> Then converting decimal to binary. # -> Then dividing the resultant binary by 2**x (Or right shift x times) to get the outcome. num = float(input("Give your fraction : ")) # we have to take a float. x = 0 if num < 0: num = abs(num) isNeg = True elif num > 0: isPos = True if num == 0: isZero = True while (num - int(num) != 0): # Checking if my num is not a whole number keep multiplying it with power of 2. num = num * (2**x) x += 1 print(num) # printing the number too to see what whole number we get at the end of loop. result = 0 mylist = [] # We take an empty list. while num > 0: result = int((num%2)) # we take int, because num was in float. But we want remainders/bits in either 0/1. print(result) # Printing the binaries too. mylist.append(str(result)) # creating a string list (Why?). But all the bits are from back to front order # Since modulo gives bits from back to front. num = num // 2 mylist.reverse() # reversing the list to get correct binary order. result = "".join(mylist) # we had to use join() thats why we took string list. (Answer to Why!) result = int(result) # Now the result was in string taken out from join(). So we convert it into int. result = result * (10**-x) # Now finally right shifting it the number of times we multiplied by pow of 2. if isNeg == True: print("Binary is",-result) elif isPos == True: print("Binary is",result) elif isZero == True: result = 0 print("Binary is",result)
true
346c05201be6379aea4801d2ad28d3b495258b4a
HussainWaseem/Learning-Python-for-Data-Analysis
/Tuples.py
2,673
4.40625
4
''' Tuples ''' # Immutables. # defining tuples = With braces or without braces t = (1,2,'l',True) print(t) g = 1,2,'l',False print(g) # Tuples are Squences (just like Strings and lists) = So they have 6 properties = len(),indexing,slicing, concatenation, # iterable and membership test (in and not in) # Range object is also sequence but it doesnot follow concatenation. print(t[3]) print(t[1:2]) # prints (2,) This comma denotes that it is a tuple and not just an int object. print(t[:]) # Assignment doesnot works for tuples. You can't change tuples t = (1,) h = 1, print(t,h) ''' Iteration over Tuples and Nested Tuples ''' ''' Write a Program that gets data in the form of nested tuples. Each nested tuple has an integer at index 0 and string at index 1. Gather all the numbers in one new tuple and strings in another new tuple. Return maxnumber, minnumber and number of unique words. ''' def getData(t): num = () words = () for i in t: num = num + (i[0],) # num is a tuple. (i[0],) is a singleton tuple. We concatenate. if i[1] not in words: # taking only unique words words = words + (i[1],) min_number = min(num) max_number = max(num) unique_words = len(words) return (min_number,max_number,unique_words) data = ((1,"Hello"),(2,"World"),(15,"Hello")) print(getData(data)) #---------------------------------------------------------------------------------------- x = (1, 2, (3, 'John', 4),'hi') # Whenever you slice something out of a tuple, the resultant is always tuple. # Unlike indexing, where the resultant may be any other type.' y = x[0:-1] z = x[0:1] print(y) print(z) print(type(y),type(z)) # Also you can multi index a string inside a tuple/list and can access its individual Character. print(x[-1][-1]) print(type(x[-1][-1])) #----------------------------------------------------------------------------------- ''' Write a procedure called oddTuples, which takes a tuple as input, and returns a new tuple as output, where every other element of the input tuple is copied, starting with the first one. So if test is the tuple ('I', 'am', 'a', 'test', 'tuple'), then evaluating oddTuples on this input would return the tuple ('I', 'a', 'tuple'). ''' def oddTuples(t): t_new = () count = 0 for i in t: if count % 2 == 0: # Here I do for even because indexing starts from 0. Odd elements are indexed even. t_new = t_new + (t[count],) # concatenation of strings. else: pass count +=1 return t_new test = ('I', 'am', 'a', 'test', 'tuple') print(oddTuples(test))
true
85bdb20c063b623b3ba8b576096318804c70b212
sakar123/Python-Assignments
/Question24.py
261
4.3125
4
"""24. Write a Python program to clone or copy a list.""" def clone_list(given_list): new_list = [] for i in given_list: new_list.append(i) return new_list print(clone_list([1, 2, 3, 4, 5])) print(clone_list([(1, 2), ('hello', 'ji')]))
true
cc02f947a004d1c929d2a1ca6a79808909ed7d02
sakar123/Python-Assignments
/Question37.py
410
4.1875
4
"""37. Write a Python program to multiply all the items in a dictionary.""" def prod_dicts(dict1): list_of_values = dict1.values() product_of_values = 1 for i in list_of_values: product_of_values = i * product_of_values return product_of_values print(prod_dicts({1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225}))
true
69c3484772644518a3245f6a925858232fa066ab
ngongongongo/Python-for-beginners
/Chapter 1 - Python Basics/1.8-Practice.py
2,669
4.4375
4
#1.8 Practice #---------------------------------------- #Question 1 #Prompt the computer to print from 1 to 10 using loop #Ask user if he/she wants to do it again using loop #Question 2 #Write a rock-paper-scissor game #The winning condition is either the player or the computer win 3 times first #Hint: import random #---------------------------------------- #Solution 1 print("Question 1\n") answers = 'y' while answers == 'y': for i in range(1,11): print (i) i += 1 answers = input("Do you want to do it again (y/n): ").lower() #Solution 2 import random loop = 'y' playerScore = computerScore = 0 playerChoice = computerChoice =0 playerDecision = computerDecision = 'INVALID ENTRY' print("\nQuestion 2\n") while loop == 'y': #play multiple games playerScore = computerScore = 0 print ("\nGame Score is now ", playerScore, " Player, ", computerScore, " Computer") #Scores Tracker while playerScore < 3 and computerScore < 3: print("\n1 is ROCK, 2 is PAPER, or 3 is SCISSOR") playerChoice = int(input("PLease choose an option: ")) #Get inputs from the user computerChoice = random.randrange(1,4) #Generate a random decision for the computer while playerDecision == "INVALID ENTRY": if playerChoice == 1: #Convert player's decisions playerDecision = "ROCK" elif playerChoice == 2: playerDecision = "PAPER" elif playerChoice == 3: playerDecision = "SCISSOR" else: playerDecision = "INVALID ENTRY" if computerChoice == 1: #Convert computer's decisions computerDecision = "ROCK" elif computerChoice == 2: computerDecision = "PAPER" else: computerDecision = "SCISSOR" print ("\nPlayer chose ", playerDecision) print ("Computer chose ", computerDecision) if (computerChoice % 3) + 1 == playerChoice: #Win - Lose conditions print("Player wins") playerScore += 1 elif (playerChoice % 3) + 1 == computerChoice: print("Computer wins") computerScore += 1 else: print ("Draw") print ("\nGame Score is now ", playerScore, " Player, ", computerScore, " Computer") #Scores Tracker if playerScore == 3: print("Player wins with 3 scores") else: print("Computer wins with 3 scores") loop = input("\nDo you want to play another game: ").lower()
true
d4caf8442473e71d624651bb9a8ccc67384ef05d
Bua0823/python_clases
/clase_2/imprimir_opcion.py
1,470
4.1875
4
# mensaje =""" # hola # como estas? # elige una de estas opciones por favor # 1 # 2 # 3 # 4""" #print(mensaje) opcion = int(input('ingrese una opcion: ')) #if opcion == 1: #print(f'la opcion que elegiste es {opcion}') #print('adios!') #elif opcion == 2: #print(f'la opcion que elegiste es {opcion}') #print('adios!') #elif opcion == 3: #print(f'la opcion que elegiste es {opcion}') #print('adios!') #elif opcion == 4: #print(f'la opcion que elegiste es {opcion}') #print('adios!') #else: #print('elegiste una opcion incorrecta xd :(') # def mensaje(opcion): # print(f'la opcion que elegiste es {opcion}') # print('adios!') # if opcion == 1: # mensaje(opcion) # elif opcion == 2: # mensaje(opcion) # elif opcion == 3: # mensaje(opcion) # elif opcion == 4: # mensaje(opcion) # else: # print('elegiste una opcion incorrecta xd :(') # def mensaje(opcion): # print('hola!') # print('como estas?') # print(f'la opcion que elegiste es {opcion}') # print('adios!') # if opcion == 1 or opcion == 2 or opcion == 3 or opcion ==4: # mensaje(opcion) # else: # print('elegiste una opcion incorrecta xd :(') def mensaje(opcion): mensajillo = f""" hola! como estas? la opcion que elegiste es {opcion} adios!""" print(mensajillo) if opcion == 1 or opcion == 2 or opcion == 3 or opcion ==4: mensaje(opcion) else: print('elegiste una opcion incorrecta xd :(')
false
0c5c216e024271752c5cf2cebddfa5d2e70d846c
jingyi-stats/-python-
/python_syntax.py
865
4.1875
4
# Python syntax 语法 # print absolute value of an integer a = 100 if a >= 0: print(a) else: print(-a) # print if the input age is adult or not year = input("Please enter your birth year: ") print(2020 - int(year)) a = int(2020 - int(year)) if a >= 18: print("Adult") else: print("underage") # print what to do next condition = input("What can I help you with?") if condition == "hungry": print("Please eat.") elif condition == "tired": print("Get some rest.") elif condition == "sick": print("Go to a doctor.") elif condition == "chill": print("Go to study.") else: print("Sorry, I don\'t understand \"your condition\".") print('I\'m learning\nPython.') print('\\\n\\') print('\\\t\\') print(r'\\\t\\') print('''line1 line2 line3''') # -*- coding: utf-8 -*- print(r'''hello,\n world''') True False 3 > 2 3 > 5
true
b0866402b38328d8070e078a7acef16b8e9fb7eb
Dhiraj-tech/Python-Lab-Exercise
/greater,smallest and odd number among them in list (user input in a list).py
400
4.21875
4
#WAP to take a user input of a list consist of ten numbers and find (1)greater no among the list (2)smaller no among the list (3) list of a odd number list=[] odd=0 for i in range(10): num=int(input("enter a number")) list.append(num) print("minimum no among them:",min(list)) print("maximum no among them:",max(list)) odd=[num for num in list if num%2==1] print("odd no among them is:",odd)
true
b96f2252a44943ccef0b5cd6950479cf67241857
Dhiraj-tech/Python-Lab-Exercise
/(4) define a function and show the multiples of 3 and 5.py
231
4.34375
4
#write a function that returns a sum of multiples of 3 and 5 between 0 and limit(parameter) def function(): for i in range(21): sum=0 if i%3==0 or i%5==0: sum=sum+i print (sum) function()
true
e9eee3acec1e30befcc951b356fb81f2302a4e56
Dhiraj-tech/Python-Lab-Exercise
/calculator by using def.py
709
4.125
4
print("enter a choice") print("1 for addition") print("2 for substraction") print("3 for multiplication") print("4 for division") choice=int(input()) def add(): x=int(input("first number")) y=int(input("second number")) z=x+y print(z) def substraction(): a=int(input("first number")) b=int(input("second number")) c=a-b print(c) def multiplication(): d=int(input("first number")) e=int(input("second number")) f=d*e print(f) def division(): g=int(input("first number")) h=int(input("second number")) i=g/h print(i) if choice==1: add() elif choice==2: substraction() elif choice==3: multiplication() elif choice==4: division()
false
a443b4acf86964757b39b1b912c93259629ca1b4
ButtonWalker/Crash_Course
/4_Exercise2.py
455
4.125
4
for value in range(1, 21): print(value) numbers = [] for value in range(1,1001): numbers = value print(numbers) digits = range(1, 1000001) print(min(digits)) print(max(digits)) print(sum(digits)) # odd numbers for value in range(1,21,2): print(value) for value in range(3, 30, 3): print(value) cubes = [] for value in range(1, 11): cubes.append(value**3) print(cubes) cubes = [value**3 for value in range(1,11)] print(cubes)
true
74bff2e14dc504862c597880f6aeec91e3406fde
abhikot1996/Python-Python-All-In-One-Mastery-From-Beginner-to-AdvanceEasy-Way-
/Python-Python-All-In-One-Mastery-From-Beginner-to-AdvanceEasy-Way-/PracticeWebExersicesProgram.py
965
4.21875
4
# 1) Program to print twinkle twinkle little star poem #print("""Twinkle, twinkle, little star,\n\t #How I wonder what you are!\n #\t\tUp above the world so high,\n #\t\tLike a diamond in the sky.\n #Twinkle, twinkle, little star,\n #\tHow I wonder what you are!) #""") # 2) Program to print version of python installed on system # import sys # print("Python version") # print (sys.version) # print("Version info.") # print (sys.version_info) # 3) Program to print current date and time # import datetime # now = datetime.datetime.now() # print ("Current date and time : ") # print (now.strftime("%Y-%m-%d %H:%M:%S")) # 4) Program to print Area of circle # radius = float(input("Enter radius:")) # print(3.14*radius**2) # 5) Write a Python program which accepts the user's first and last name and # print them in reverse order with a space between them # fname =input("Enter first name: ") # lname = input("Enter last name: ") # print(lname + " " + fname)
true
62f570056a533dd8152b2139b28614486a79b7e1
abhikot1996/Python-Python-All-In-One-Mastery-From-Beginner-to-AdvanceEasy-Way-
/Python-Python-All-In-One-Mastery-From-Beginner-to-AdvanceEasy-Way-/star_args_in_function.py
514
4.28125
4
''' *args in Function * '*args' is used in function when we want to assign argument as many as we want then *args is used in function definition. * '*ola' same as '*args' ''' # E.g , # *args def greet(*args): print("Hello " +args[0]+" how are you") print("Hello " + args[1] + " I don't know you") print("Hello " + args[2] + " I don't know you") greet("Samy","John","Bally","Bob") #o/p # Hello Samy how are you # Hello John I don't know you # Hello Bally I don't know you
false
07c1ed5ed93ba79ecedb4ba9aa85a6f66ed24cee
abhikot1996/Python-Python-All-In-One-Mastery-From-Beginner-to-AdvanceEasy-Way-
/Python-Python-All-In-One-Mastery-From-Beginner-to-AdvanceEasy-Way-/Prime_no.py
304
4.125
4
''' Prime no * Number which can divide only itself ''' num = int(input("Enter no: ")) if num>1: for i in range(2,num): if num%i==0: print(f"{num} is not a prime no") break else: print(f"{num} is prime no") else: print(f"{num} is not prime no")
false
fc243f4ddc5a2da7b2385e7a09a2780f1f964d2a
carmelobuglisi/programming-basics
/projects/m1/005-units-of-time-again/solutions/pietrorosano/solution_005-againUnitsOfTime.py
998
4.40625
4
# In this exercise you will reverse the process described in Exercise 24. Develop a program that begins by reading a number of seconds from the user. Then your program should display the equivalent amount of time in the form D:HH:MM:SS, where D, HH, MM, and SS represent days, hours, minutes and seconds respectively. The hours, minutes and seconds should all be formatted so that they occupy exactly two digits. Use your research skills determine what additional character needs to be included in the format specifier so that leading zeros are used instead of leading spaces when a number is formatted to a particular width. print("\nSTART PROGRAM") print("------------------") print("\nDays") days = int(input()) print("\nHours") hours = int(input()) print("\nMinutes") minutes = int(input()) print("\nSeconds") seconds = int(input()) print("\nTime...") # print(str(days)+":"+str(hours)+":"+str(minutes)+":"+str(seconds)) print("{:02d}:{:02d}:{:02d}:{:02d}".format(days, hours, minutes, seconds))
true
cac250740ee4e25dee623c499b6654bcf234a831
daniocen777/Proyectos-python
/programacion_de_funciones/funciones_recursivas.py
749
4.125
4
def cuenta_atras(num): num -= 1 if num > 0: print(num) cuenta_atras(num) else: print('Boooooooom!') print('Fin de la función', num) cuenta_atras(5) ''' result: 4 3 2 1 Boooooooom! Fin de la función 0 Fin de la función 1 Fin de la función 2 Fin de la función 3 Fin de la función 4''' ''' Factorial de un número ''' def factorial(num): print('valor inicial =>', num) if num > 1: num = num * factorial(num -1) print('valor final =>', num) return num print(factorial(5)) # = 120 ''' result: valor inicial => 5 valor inicial => 4 valor inicial => 3 valor inicial => 2 valor inicial => 1 valor final => 1 valor final => 2 valor final => 6 valor final => 24 valor final => 120 '''
false
363bea7a6b63e651138099e4a455cad66b0eeee3
daniocen777/Proyectos-python
/colecciones_de_datos/pilas_colas_con_listas.py
897
4.21875
4
''' En python, se emulan las pilas con listas ''' # pila => sólo añadir o quitar (LIFO) from collections import deque pila = [3, 4, 5] pila.append(6) pila.append(7) print(pila) # result => [3, 4, 5, 6, 7] # Sacar el último elemento pila.pop() print(pila) # result => [3, 4, 5, 6] ''' Error si se quita el último elemento de una pila vacía ''' ''' Para las colas, se debe impotar => from collections import deque ''' # colas => sólo añadir o quitar (FIFO - 1° entrar 1° en salir) cola = deque() cola = deque(['Hector', 'Juana', 'Miguel']) print(cola) # result => deque(['Hector', 'Juana', 'Miguel']) # Añadiendo cola.append('Maria') cola.append('Armando') # result => deque(['Hector', 'Juana', 'Miguel', 'Maria', 'Armando']) print(cola) # sacar al 1° primero = cola.popleft() print(primero) # result => Hector print(cola) # result => deque(['Juana', 'Miguel', 'Maria', 'Armando'])
false
90f62a8ec5f6cee9e9d88f5bfb8f36599ca33616
a3X3k/Competitive-programing-hacktoberfest-2021
/CodeWars/Calculating with Functions.py
1,540
4.34375
4
''' 5 kyu Calculating with Functions https://www.codewars.com/kata/525f3eda17c7cd9f9e000b39/train/python This time we want to write calculations using functions and get the results. Let's have a look at some examples: seven(times(five())) # must return 35 four(plus(nine())) # must return 13 eight(minus(three())) # must return 5 six(divided_by(two())) # must return 3 Requirements: There must be a function for each number from 0 ("zero") to 9 ("nine") There must be a function for each of the following mathematical operations: plus, minus, times, dividedBy (divided_by in Ruby and Python) Each calculation consist of exactly one operation and two numbers The most outer function represents the left operand, the most inner function represents the right operand Divison should be integer division. For example, this should return 2, not 2.666666...: eight(divided_by(three())) ''' def zero(f = None): return 0 if not f else f(0) def one(f = None): return 1 if not f else f(1) def two(f = None): return 2 if not f else f(2) def three(f = None): return 3 if not f else f(3) def four(f = None): return 4 if not f else f(4) def five(f = None): return 5 if not f else f(5) def six(f = None): return 6 if not f else f(6) def seven(f = None): return 7 if not f else f(7) def eight(f = None): return 8 if not f else f(8) def nine(f = None): return 9 if not f else f(9) def plus(y): return lambda x: x+y def minus(y): return lambda x: x-y def times(y): return lambda x: x*y def divided_by(y): return lambda x: int(x/y)
true
481537d5d715298b4f112158bf257dd23967c5d5
a3X3k/Competitive-programing-hacktoberfest-2021
/CodeWars/Build Tower.py
939
4.125
4
''' 6 kyu Build Tower https://www.codewars.com/kata/576757b1df89ecf5bd00073b/train/python Build Tower Build Tower by the following given argument: number of floors (integer and always greater than 0). Tower block is represented as * Python: return a list; JavaScript: returns an Array; C#: returns a string[]; PHP: returns an array; C++: returns a vector<string>; Haskell: returns a [String]; Ruby: returns an Array; Lua: returns a Table; Have fun! for example, a tower of 3 floors looks like below [ ' * ', ' *** ', '*****' ] and a tower of 6 floors looks like below [ ' * ', ' *** ', ' ***** ', ' ******* ', ' ********* ', '***********' ] Go challenge Build Tower Advanced once you have finished this :) https://www.codewars.com/kata/57675f3dedc6f728ee000256 ''' def tower_builder(n): return [("*" * (i*2-1)).center(n*2-1) for i in range(1, n+1)]
true
cb1a541b30cec2a374ec146c53fcab3b074fbfdd
Jsmalriat/python_projects
/dice_roll_gen/dice_roll.py
2,683
4.25
4
# __author__ = Jonah Malriat # __contact__ = tuf73590@gmail.com # __date__ = 10/11/2019 # __descript__ = This program takes user-input to determine the amount of times two dice are rolled. # The program then adds these two dice rolls for every time they were rolled and outputs how many # times each number 2 - 12 was rolled and the percentage it was rolled. It then compares this percentage # to the probability and finds the difference between the two values. import random def greeting(): print('=> Welcome to the random dice-roll generator!') def num_iterations(): iter = input('=> How many times would you like to roll the dice? ') return iter def first_roll(): first_roll = random.randint(1, 6) return first_roll def second_roll(): second_roll = random.randint(1, 6) return second_roll def roller(iter): roll_list = [] for i in range(0, iter): roll_list.append(first_roll() + second_roll()) return roll_list def num_of_value(roll_list, num): x = 0 for i in roll_list: if i == num: x += 1 return x def perc_of_value(roll_list, num): y = 0 x = num_of_value(roll_list, num) for i in roll_list: y += 1 x /= y x *= 100 return round(x, 2) def expected_prob(num): if num == 2: x = (1 / 36) * 100 elif num == 3: x = (1 / 18) * 100 elif num == 4: x = (1 / 12) * 100 elif num == 5: x = (1 / 9) * 100 elif num == 6: x = (5 / 36) * 100 elif num == 7: x = (1 / 6) * 100 elif num == 8: x = (5 / 36) * 100 elif num == 9: x = (1 / 9) * 100 elif num == 10: x = (1 / 12) * 100 elif num == 11: x = (1 / 18) * 100 elif num == 12: x = (1 / 36) * 100 return round(x, 2) def diff_in_prob(roll_list, x): x = abs(perc_of_value(roll_list, x) - expected_prob(x)) return round(x, 2) def print_iter(iter): print(f"Number of iterations = {iter}") def print_key(a, b, c, d, e): print('{:^14}'.format(a), '{:^14}'.format(b), '{:^14}'.format(c), '{:^14}'.format(d), '{:^14}'.format(e)) def print_table(a, b, c, d, e): print('{:^14}'.format(a), '{:^14}'.format(b), '{:^14}'.format(f"{c}%"), '{:^14}'.format(f"{d}%"), '{:^14}'.format(f"{e}%")) def table_maker(roll_list): x = 1 while x < 12: x += 1 print_table(f"{x}", num_of_value(roll_list, x), perc_of_value(roll_list, x), expected_prob(x), diff_in_prob(roll_list, x)) def main(): greeting() iter = int(num_iterations()) roll_list = roller(iter) print_iter(iter) print_key('Number', 'Times Rolled', 'Percentage', 'Expected', 'Difference') table_maker(roll_list) if __name__ == '__main__': main()
true
d9630b46886066ea9c30426a08e2edb4f4c41bd3
tomekregulski/python-practice
/logic/bouncer.py
276
4.125
4
age = input("How old are you: ") if age: age = int(age) if age >= 21: print("You are good to enter and you can drink!") elif age >= 18: print("You can entger, but you need a wristband!") else: print("Sorry, you can't come in :(") else: print("Please enter an age!")
true
29e7b459ca79807dc28ea3919a14347de30e5a34
vanceb/STEM_Python_Crypto
/Session3/decrypt.py
1,127
4.15625
4
############################## # Caesar Cypher - Decrypt ############################## # Define the alphabet that we are going to encode LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # Define variables to hold our message, the key and the translated message message = 'This is secret' key = 20 translated = '' # Change the key to enable decryption key = len(LETTERS) - key # Convert the message to uppercase message = message.upper() # Repetatively do something for every symbol in the message for symbol in message: # See if the current symbol is in the alphabet we defined earlier if symbol in LETTERS: # if it is then we get a number that represents its position num = LETTERS.find(symbol) # change the number based on the key num = (num + key) % len(LETTERS) # get the letter from the changed number translated = translated + LETTERS[num] else: # the symbol is not in the alphabet so just add it unchanged translated = translated + symbol # we have now been through every letter in the message so we can print the translated version print(translated)
true
dc3ddb3005f68fe2dd862b2cc70cdd2ba5c4fbbc
Stunt-Business/Py-BasicQ_As_Challenges
/Day10_oued.py
1,267
4.21875
4
# --------------------------------------------------- # Author : Erwan Ouedraogo # Community : Stunt Business # Community website : www.stuntbusiness.com # # 30 Days - Q&A Python Basic # Day 10 : 31-05-2020 # Day 10 | IG : https://www.instagram.com/stuntbusiness/ # Subject : Challenges II - Basic Calculator #---------------------------------------------------- # what would be the output of this program ? import random import string print('How many letters do you want?') hml = input() #permettre a l'utilisateur d'entrer le nombre de lettres qu'il veut sous forme de chaine de caractere hml = int (hml) #chaine de caractere transformée en chiffre entier password = "" while(hml > 0) : letter = random.choice(string.ascii_letters) password = password + str(letter) hml = hml - 1 print('How many numbers do you want?') hmn = input () hmn = int (hmn) #chaine de caractere transformée en chiffre entier while(hmn > 0) : number = random.randint(0,9) #random number password = password + str(number) hmn = hmn - 1 print('How many symbols do you want?') hms = input() hms = int (hms) while(hms > 0) : symbol = random.choice(string.punctuation) password = password + str(symbol) hms = hms - 1 print(password)
false
5eb82c0b75ecd9125a10149ac70f7e9facbbf5c8
carlhinderer/python-exercises
/reddit-beginner-exercises/ex03.py
1,357
4.59375
5
# Exercise 3 # # # [PROJECT] Pythagorean Triples Checker # # BACKGROUND INFORMATION # # If you do not know how basic right triangles work, read this article on wikipedia. # # MAIN GOAL # # Create a program that allows the user to input the sides of any triangle, and then return whether the triangle is a Pythagorean # Triple or not. # # SUBGOALS # # If your program requires users to input the sides in a specific order, change the coding so the user can type in the sides # in any order. Remember, the hypotenuse (c) is always the longest side. # # Loop the program so the user can use it more than once without having to restart the program. def triplechecker(): a, b, c = promptforsides() triple = checkfortriple(a, b, c) printresult(triple) def promptforsides(): a = promptforside() b = promptforside() c = promptforside() return (a, b, c) def promptforside(): side = None while type(side) is not int: try: side = input('Enter the length of a side: ') side = int(side) except ValueError: print('The side lengths must be integers.') return side def checkfortriple(a, b, c): if a > c: a, c = c, a if b > c: b, c = c, b return (a ** 2 + b ** 2 == c ** 2) def printresult(triple): if triple: print("Yes, it's a Pythagorean Triple!") else: print("Nope, it's not a Pythagorean Triple.") triplechecker()
true
81b6f41cf4da9ba055fa5b1efd3ba7b6993f04d0
carlhinderer/python-exercises
/daily-coding-problems/problem057.py
729
4.125
4
# Problem 57 # Medium # Asked by Amazon # # Given a string s and an integer k, break up the string into multiple lines such that # each line has a length of k or less. You must break it up so that words don't break across # lines. Each line has to have the maximum possible amount of words. If there's no way to # break the text up, then return null. # # You can assume that there are no spaces at the ends of the string and that there is exactly one # space between each word. # # For example, given the string "the quick brown fox jumps over the lazy dog" and k = 10, you # should return: ["the quick", "brown fox", "jumps over", "the lazy", "dog"]. No string in the # list has a length of more than 10. #
true
e8ec7c1c8e7edd373c1a2dd59a98cb8444317c3a
carlhinderer/python-exercises
/ctci/code/chapter01/src/palindrome_permutation.py
769
4.3125
4
# # 1.4 Palindrome Permutation: # # Given a string, write a function to check if it is a permutation of a palindrome. # A palindrome is a word or phrase that is the same forwards and backwards. A # permutation is a rearrangement of letters. The palindrome does not need to be # limited to just dictionary words. # # EXAMPLE Input: Tact Coa Output: True (permutations: "taco cat". "atco cta". etc.) # from collections import Counter def palindrome_permutation(s): no_whitespace = s.strip().replace(' ', '') counts = Counter(no_whitespace) odd_count = False for pair in counts.items(): if pair[1] % 2 == 1: if odd_count: return False else: odd_count = True return True
true
8bc07815ab7a29e1aa5b472bddaff588fc405cfa
carlhinderer/python-exercises
/zhiwehu/src/ex007.py
1,033
4.21875
4
# Question 7 # Level 2 # # Question: # Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in # the i-th row and j-th column of the array should be i*j. # # Note: i=0,1.., X-1; j=0,1,¡­Y-1. # # Example: # Suppose the following inputs are given to the program: # 3,5 # Then, the output of the program should be: # [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]] # # Hints: # Note: In case of input data being supplied to the question, it should be assumed to be a console input in a # comma-separated form. def print_matrix(): dimensions = get_dimensions() matrix = build_matrix(dimensions[0], dimensions[1]) print(matrix) def get_dimensions(): dimensions = input('Enter the dimensions: ') return list(map(int, dimensions.split(','))) def build_matrix(x, y): matrix = [] for i in range(x): row = [i * j for j in range(y)] matrix.append(row) return matrix if __name__ == '__main__': print_matrix()
true
069c09ec5a3bf11a00480ef3de0207f7161c0263
suprajaarthi/DSA
/19 Day8 CheckPalindRec.py
656
4.3125
4
# Recursive function to check if `str[low…high]` is a palindrome or not def isPalindrome(str, low, high): # base case if low >= high: return True # return false if mismatch happens if str[low] != str[high]: return False # move to the next pair else: return isPalindrome(str, low + 1, high - 1) # isPalindrome("malayalam",0,8) 0!>=8 # isPalindrome("alayala",) 1!>=7 # layal 2 6 # ayal 3 5 # aya 4>=4 return True str = "malayalam" if isPalindrome(str, 0, len(str) - 1): print("Palindrome") else: print("Not Palindrome")
false
322db8f52f43c93c7ee36440e6355b62f1054166
schase15/Sprint-Challenge--Data-Structures-Python
/names/binary_search_tree.py
2,965
4.4375
4
# Utilize the BST from the hw assignment # Only need contains and insert methods class BSTNode: def __init__(self, value): self.value = value self.left = None self.right = None # Insert the given value into the tree # Compare the input value against the node's value # Check if the direction we need to go in has a node # If not, wrap the value in a node and park it # Otherwise, go back to step 1, but with the node in that spot # This doesn't work if there is no root def insert(self, value): # Compare the input value with the value of the Node if value < self.value: # We need to go left # If there is no child node to the left if self.left is None: # Create and park the new node self.left = BSTNode(value) # Otherwise there is already a child else: # Call the insert method to do this loop again, until we reach no child node self.left.insert(value) # If the input value is greater than or equal to we move to the right else: # See if there is no right child if self.right is None: # Wrap the value in BSTNode and park it self.right = BSTNode(value) # Otherwise there is a child node else: # Call the insert method to continue the loop until we find a node without a child self.right.insert(value) # Return True if the tree contains the value # False if it does not def contains(self, target): # If the input value is equal to the node value, return true # Base Case if self.value == target: return True # Recursive cases: How do we move closer to the base case # If the input value is greater than the node value, move to the right -> re-run method on right child node elif self.value < target: # Check if there is a next node to move to to continue the comparison # If there is not then it is the end of the tree and there is no match, return False if self.right is None: return False else: # Call contains method on right child # Eventually we will need to return a value return self.right.contains(target) # If the input value is less than the node value, move to the left -> re-run method on left child node else: # Check to see if there is a node to the left to move to # If not then it is the end of the tree, return False if self.left is None: return False else: # Call contains method on left child # Eventually we will need to return a value return self.left.contains(target)
true
198ce51002296c632ee5522b2ab4f5dec317727d
wangtaodd/LeetCodeSolutions
/069. Sqrt.py
586
4.25
4
""" Implement int sqrt(int x). Compute and return the square root of x. x is guaranteed to be a non-negative integer. Example 1: Input: 4 Output: 2 Example 2: Input: 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated. """ class Solution(object): def mySqrt(self, x): """ :type x: int :rtype: int """ res = 0 for i in range(15,-1,-1): if (res + (1 << i)) * (res + (1 << i)) <= x: res += (1 << i) return res
true
44327cd41d09d206b171781dd89aae73376e2dec
wangtaodd/LeetCodeSolutions
/693. Binary Number with Alternating Bits.py
770
4.25
4
""" Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. Example 1: Input: 5 Output: True Explanation: The binary representation of 5 is: 101 Example 2: Input: 7 Output: False Explanation: The binary representation of 7 is: 111. Example 3: Input: 11 Output: False Explanation: The binary representation of 11 is: 1011. Example 4: Input: 10 Output: True Explanation: The binary representation of 10 is: 1010. """ class Solution: def hasAlternatingBits(self, n): """ :type n: int :rtype: bool """ res = 1 n = n ^ (n >> 1) while n > 1: res = res & (n & 1) n = n >> 1 return True if res == 1 else False
true
42b522c5d47b3f31c12398ee1304a62814dec748
wangtaodd/LeetCodeSolutions
/530. Minimum Absolute Difference in BST.py
902
4.1875
4
""" Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes. Example: Input: 1 \ 3 / 2 Output: 1 Explanation: The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3). Note: There are at least two nodes in this BST. """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def getMinimumDifference(self, root): """ :type root: TreeNode :rtype: int """ def dfs(node, l=[]): if node.left: dfs(node.left, l) l.append(node.val) if node.right: dfs(node.right, l) return l l = dfs(root) return min([abs(a - b) for a, b in zip(l, l[1:])])
true
ea0ce1b541e74ca38790a66990d809be4ce825af
wangtaodd/LeetCodeSolutions
/107. Binary Tree Level Order Traversal II.py
1,190
4.125
4
""" Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its bottom-up level order traversal as: [ [15,7], [9,20], [3] ] """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def levelOrderBottom(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] tree=[root] res=[] dept=0 hasSubTree=True while hasSubTree: temp=[] hasSubTree=False res.append([]) for i in tree: res[-1].append(i.val) if i.left: temp.append(i.left) hasSubTree=True if i.right: temp.append(i.right) hasSubTree=True tree=temp res.reverse() return res
true