blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
580c275bc2bd3394aae13f831d36e0b588bc2024
MariomcgeeArt/CS2.1-sorting_algorithms-
/iterative_sorting2.py
2,069
4.34375
4
#funtion returns weather items are sorted or not boolean #creating the function and passing in items def is_sorted(items): # setting variable copy to equal items copy = items[:] #calling sort method on copy copy.sort() # if copy is equal to items it returns true return copy == items def bubble_sort(items): #set is sorted to true is_sorted = True # set a counter to 0 counter = 0 # while items_is_sorted we want to then change is sorted to false while(is_sorted): #set is sorted to false is_sorted = False # this is the for loop to loop trhough the items for i in range(len(items) - counter - 1): #if the item we are looking at is larger thane the item to its right we want to swap them if items[i] > items[i+1]: # swap the items positioins items[i], items[i+1] = items[i+1], items[i] # is sorted now becomes troue is_sorted = True # incremantation of the counter to move though the array counter += 1 def selection_sort(items): #finding the minimum item and swaping it with the first unsorted item and repeating until all items are in soreted order #for loop to loop throught the items items_length = range(0, len(items)-1) for i in items_length: #set min value to i min_value = i #nested for loop to set j value for j in range(i+1, len(items)): if items[j] < items[min_value]: min_value = j items[min_value], items[i] = items[i], items[min_value] return items def insertion_sort(items): item_length = range(1, len(items)) for i in item_length: #element to be compared unsorted_value = items[i] #comparing the current element with the sorted portion and swapping while items[i-1] > unsorted_value and i > 0: items[i], items[i-1] = items[i-1], items[i] i -= 1 #returning items return items
true
b40a434cf49126560b59272992e223eed3b78d22
ppfenninger/ToolBox-WordFrequency
/frequency.py
1,918
4.21875
4
""" Analyzes the word frequencies in a book downloaded from Project Gutenberg """ import string from pickle import load, dump def getWordList(fileName): """ Takes raw data from project Gutenberg and cuts out the introduction and bottom part It also tranfers the entire text to lowercase and removes punctuation and whitespace Returns a list >>> s = 'A***H ***1234@&().ABCab c***' >>> f = open('text.txt', 'w') >>> dump(s, f) >>> f.close() >>> get_word_list('text.txt') ['abcab', 'c'] """ inputFile = open(fileName, 'r') text = load(inputFile) l = text.split('***') #marker for stop and end of text in gutenberg try: #returns none in case there is something strange with the project gutenberg text mainText = l[2] #main text is the third block of text except: return None mainText = mainText.lower() #changes everything to lowercase mainText = mainText.replace("\r\n", "") mainText = mainText.translate(string.maketrans("",""), string.punctuation) #removes punctuation mainText = mainText.translate(string.maketrans("",""), string.digits) #removes numbers mainList = mainText.split() return mainList def getTopNWords(wordList, n): """ Takes a list of words as input and returns a list of the n most frequently occurring words ordered from most to least frequently occurring. word_list: a list of words (assumed to all be in lower case with no punctuation n: the number of words to return returns: a list of n most frequently occurring words ordered from most frequently to least frequently occurring """ d = {} for word in wordList: d[word] = d.get(word, 0) d[word] += 1 l = [] for i in d: l.append((d[i], i)) l.sort(reverse = True) mostCommon = l[0:(n-1)] words = [x[1] for x in mostCommon] return words if __name__ == "__main__": # import doctest # doctest.testmod() l1 = getWordList('odyssey.txt') l2 = getTopNWords(l1, 100) print l2
true
c127da0e7bf2078aa65dfcbec441b1c6dd6e7328
Habibur-Rahman0927/1_months_Python_Crouse
/Python All Day Work/05-05-2021 Days Work/Task_2_error_exception.py
2,582
4.34375
4
# Python Error and Exception Handling """ try: your code except: message """ # try: # with open('test.txt', mode='r') as open_file: # openFlie = open_file.read() # print(data) # except: # print("File is not found") # print('Hello, its working') """ try: your code except ExceptionName: your message """ # try: # with open('test.txt', mode='r') as my_new_file: # data_file = my_new_files.read() # print(data_file) # except NameError: # print('Name not found') # print('Hello, Its working.') """ try: your code except ExceptionName1: message except ExceptionName2: message """ # try: # with open('test.txt', mode='r') as my_file: # data = my_file.read() # print(data) # except NameError: # print('Name not found') # except FileNotFoundError: # print('Oops!!, File not found.') # print('Hello, Its working.') """ try: your code except (ExceptionName1, ExceptionName2...) message """ # try: # with open('test.txt', mode='r') as my_new_file: # data = my_new_file.read() # print(data) # except (NameError, FileNotFoundError): # print('Errors Found! Please check') # print('Hello, Its working.') """ try: your code except ExceptionName as msg: msg """ # try: # with open('test.txt', mode='r') as my_new_file: # print('Yes') # data = my_new_file.read() # print(data) # except FileNotFoundError as msg: # print(msg) # print('Please ensure that required file is exist') # print('Hello, Its working.') """ try: your code except ExceptionName: message else: message """ # try: # with open('test.txt', mode='r') as my_new_file: # data = my_new_file.read() # print(data) # except FileNotFoundError: # print("File not found.") # else: # print('No errors found :') # print('Hello, Its working.') """ try: your code except ExceptionName: message else: message finally: your code """ # try: # with open('test.txt', mode='r') as my_new_file: # data = my_new_file.read() # print(data) # except FileNotFoundError: # print(" File not found.") # else: # print('No errors found :') # finally: # print('Finally') # print('Hello, Its working.') """ try: raise NameError('Hello, It is user defined error msg.') except NameError as msg: message """ try: raise NameError('Hello, It is user defined error msg.') except NameError as msg: print(msg)
true
ebc54a6955ebe113dad58dd0eed16b3caff2ce89
Habibur-Rahman0927/1_months_Python_Crouse
/HackerRank problem solving/problem_no_6.py
1,101
4.21875
4
def leapYears(years): leap = False if(years%400 == 0): leap = True elif years%4 == 0 and years%100 != 0: leap = True return leap years = int(input()) print(leapYears(years)) """ years = int(input()) if (years%4 == 0): if(years%100 == 0): if(years%400 == 0): print("This years is leap year ") else: print("This years is not leap year") else: print("This years is not leap year") else: print("This years is not leap year") """ """ def leapYears(years): leap = False if (years%4 == 0): if(years%100 == 0): if(years%400 == 0): leap = True else: leap= False else: leap= False else: leap = False return leap years = int(input()) leapYears(years) """ """ def is_leap(year): leap = False if (year%4 == 0): leap = True if(year%100 ==0): leap = False if(year%400 == 0): leap = True return leap is_leap(year) year = int(input()) """
false
c5c77da3e67eacdc6c02fa2f052ae89c508cd743
FalseG0d/PythonGUIDev
/Sample.py
236
4.125
4
from tkinter import * root=Tk() #To create a Window label=Label(root,text="Hello World") #To create text on label and connect it to root label.pack() #to put it on root root.mainloop() #To avoid closing until close button is clicked
true
18c9cc619d5e44504665132e9fad5315a8b44799
pjkellysf/Python-Examples
/backwards.py
960
4.78125
5
#!/usr/local/bin/python3 # Patrick Kelly # September 29, 2015 # Write a program that prints out its own command line arguments, but in reverse order. # Note: The arguments passed in through the CLI (Command Line Interface) are stored in sys.argv. # Assumption: The first item argument in sys.argv is the filename and should NOT be included in the output. # Import the sys module import sys # Subtract one from the length of sys.argv to access the last index and store the result in the variable argumentIndex. argumentIndex = len(sys.argv) - 1 # Iterate through sys.argv starting with the last argument at index argumentIndex. for argument in sys.argv: # Exclude the filename which is the first argument in sys.argv at index 0. if argumentIndex > 0: # Print out the indexed argument from sys.argv print (sys.argv[argumentIndex]) # Decrement argumentIndex to access the previous argument in the next loop argumentIndex -= 1
true
0c0115b670926748b7df837e063d0953a16199b1
Bryanx/exercises
/Python/Fibonacci copy.py
289
4.15625
4
def fibonacci(x): x -= 2 f = [0, 1] if x < 0: return[0] elif x < 1: return f else: for i in range(x): f.append(f[len(f) - 2] + f[len(f) - 1]) return f print(fibonacci(int(input("Enter the amount of Fibonacci numbers:\n"))))
false
d8f1f90bcf7d84a8a52a5055ab3f4850de1d4a77
lykketrolle/Noroff_NIS2016
/TAP 4/TAP04-sets[4].py
2,083
4.75
5
#!/usr/bin/python """ Name: Kjell Chr. Larsen Date: 24.05.2017 Make two different set with fruits, copy the one set in to the other and compare the two sets for equality and difference. """ print("This program will have two sets of fruits. One will then be copied,\n" "into the other, then a comparison of the two sets for difference and equality \n" "is done to show the operators used and the result produced.\n") print("A set is an unordered collection with no duplicate elements. Curly braces or the \n" "set() function can be used to create sets. Note: to create an empty set, we use the \n" "set() and not {} - curly braces, where the latter creates an empty dictionary.\n") print("Here is a demonstration. A set with duplicate elements: ") print(""" "basket = {'Banana', 'Apple', 'Banana', 'Apple', 'Pear', 'Orange'}" Here we see there are duplicate elements, lets see how the printout will be. """) test_basket = {'Banana', 'Apple', 'Banana', 'Apple', 'Pear', 'Orange'} print(test_basket) print("\nAs we can see, the printout only prints out one of the duplicate elements.\n") # Here is the sets related to the assignment. Both sets have different and equal values set1 = {'Grapes', 'Apples', 'Oranges', 'Pear', 'Peaches'} set2 = {'Blueberry', 'Apricot', 'Avocado', 'Apples', 'Bilberry'} print("SET1:", set1, "\nSET2:", set2) print("") """ Now I will copy the content from set2 into set1. I do this by using the | operator. """ # Here I copy set2 into set1 and then print out the result cp_set = set1 | set2 print("Here is the result of copying set2 into set1 using ' | ':\n", cp_set) print("") # Now I will use the ' - ' operator to check the difference between set1 and set2 diff_set = set1 - set2 print("The difference between set1 and set2: ", diff_set) print("Now to test difference between the sets. First I test to see if every\n" "element is in set1 and set2 by using the ' set.difference() 'operator.\n") print(set1.difference(set2)) print("This is the difference in the two sets.")
true
9fb5404d86596e822da14852d181caedd240edf2
georgiedignan/she_codes_python
/Session3/Exercises/while_loops.py
947
4.21875
4
#Exerise 1 # number = input("Please guess any number: ") # while number != "": # number = input("Please guess any number: ") #Exercise 2 number = int(input("Please enter a number: ")) #using a for loop # for num in range(1,number+1): # if num%2!=0: # print(num) #try using a while loop i=1 while (i<=number): if i%2 != 0: print(i) i+=1 # N = int(input("Enter a number: ")) # i = 1 # while(i <= N): # if (i % 2) == 0: # print('EVEN') # else: # print('ODD') # i += 1 #Exercise 3 # number = 43 # guess = int(input("Guess my number: ")) # if guess > number: # print("Guess is too high!") # else: # print("Guess is too low!") # while guess != number: # guess = int(input("Guess my number: ")) # if guess > number: # print("Guess is too high!") # elif guess < number: # print("Guess is too low!") # else: # print("That is correct!")
false
810a9ba68bf4e22c888a6b530265e7be8fbc457d
Amantini1997/FromUbuntu
/Sem 2/MLE/Week 2 - Decision Tree & Boosting/regression.py
1,658
4.375
4
# regression.py # parsons/2017-2-05 # # A simple example using regression. # # This illustrates both using the linear regression implmentation that is # built into scikit-learn and the function to create a regression problem. # # Code is based on: # # http://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.html # http://scikit-learn.org/stable/auto_examples/linear_model/plot_ransac.html import math import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model from sklearn.datasets import make_regression from sklearn.model_selection import train_test_split # # Generate a regression problem: # # The main parameters of make-regression are the number of samples, the number # of features (how many dimensions the problem has), and the amount of noise. X, y = make_regression(n_samples=100, n_features=1, noise = 2) # Split the data into training and test set X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=0) # # Solve the problem using the built-in regresson model # regr = linear_model.LinearRegression() # A regression model object regr.fit(X_train, y_train) # Train the regression model # # Evaluate the model # # Data on how good the model is: print("Mean squared error: %.2f" % np.mean((regr.predict(X_test) - y_test) ** 2)) # Explained variance score: 1 is perfect prediction print('Variance score: %.2f' % regr.score(X_test, y_test)) # Plotting training data, test data, and results. plt.scatter(X_train, y_train, color="black") plt.scatter(X_test, y_test, color="red") plt.scatter(X_test, regr.predict(X_test), color="blue") plt.show()
true
98a0b26efc09b461a8ac2e815e8785d866cf7707
greatwallgoogle/Learnings
/other/learn_python_the_hard_way/ex34.py
883
4.4375
4
# ex34 : 访问列表元素 # 常用函数 # 声明列表:[] # 索引法访问元素: list[index] # 删除某个元素:del(list[index]) # 列表元素反向:list.reverse() # 追加元素:list.append(ele) animals = ['dog','pig','tiger','bear',3,4,5,6] print("animals :",animals) # 索引法访问列表中的值 dog = animals[0] print("animals first ele:", dog) # 使用方括号的形式截取列表 list2 = animals[1:5] #从索引为1的地方开始,读取(5-1)个元素 print("animals[1:5]:",list2) # 追加元素 animals.append("chicken") print("animals :",animals) # 删除元素 print("---list2-----orign:" , list2) del(list2[0]) print("---list2-----new : " ,list2) # 反向元素 print("---reverse-----orign:" , list2) list2.reverse() print("---reverse-----new:" , list2) # 移除列表中的某个元素 list2.pop() print("---pop-----new:" , list2)
false
4ed2d4ef6171647b08629409ec77b488d059bc6f
greatwallgoogle/Learnings
/other/learn_python_the_hard_way/ex9.py
975
4.21875
4
# 打印,打印,打印 days = "Mon Tue Wed Thu Fri Sat Sun" # 第一中方法:将一个字符串扩展成多行 months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJuly\nAug" print("Here are the days :",days) # 等价于 print("Here are the days : %s" % days) print("Here are the months : ", months) #等价于 print("Here are the months : %s" % months) # 第二种方法:使用三引号输出任意行的字符串 print(""" There's something going on here. With the three double-quotes. We'll be able to type as much as we like. Even 4 lines if we want, or 5, or6. """) # for example tabby_cat = "\tI'm tabbed in." print("tabby_cat:",tabby_cat) persian_cat = "I'm split\non a line." print("persian_cat:",persian_cat) backslash_cat = "I'm \\ a \\ cat." print("backslash_cat:",backslash_cat) fat_cat = ''' I'll do a list: \t* Cat food \t* Fishied \t* Catnit\n\t* Grass ''' print(fat_cat) # # while True: # for i in ["/","-","|","\\","|"]: # print("%s\r" % i)
true
a73adc9082e54df28f0db2a9b93496e2f1bcd5ff
thekayode/area_of_shapes
/area_of_triangle _assignment.py
993
4.40625
4
''' This programme is too calculate the area of a triangle. ''' base = float(input('Enter the base of the triangle\n')) height = float(input('Enter the height of the the triangle\n')) area = 1/2 * (base * height) print('area', '=', area) ''' This programme is too calculate the area of a square. ''' length = float(input('Enter the length of the square\n')) area = length**2 print('area', '=', area) ''' This programme is too calculate the area of a cylinder. ''' radius = float(input('Enter the radius of cylinder: ')) pi = 3.142 height = float(input('Enter the heigth of cylinder: ')) area = (2 * pi * radius**2) + (2 * pi * radius * height) print('Enter the area', (round(area,2))) ''' This programme is too calculate the area of a trapezoid. ''' a = float(input('Enter base 1 of trapezoid: ')) b = float(input('Enter base 2 of trapezoid: ')) height = float(input('Enter the height of trapezoid: ')) area = 1/2 * (a + b) * height print('area', '=', area)
true
b1869818de65a93e61f1fc9cf4320396c09ca8bc
oct0f1sh/cs-diagnostic-duncan-macdonald
/functions.py
760
4.21875
4
# Solution for problem 8 def fibonacci_iterative(num = 10): previous = 1 precedingPrevious = 0 for number in range(0,num): fibonacci = (previous + precedingPrevious) print(fibonacci) precedingPrevious = previous previous = fibonacci # Solution for problem 9 # I don't know how to call stuff from the terminal and my python # installation is really screwed up so I'm using PyCharm to run these # and i'm just going to set an input arg = int(input("Enter a number: ")) fibonacci_iterative(arg) print() # Solution for problem 10 def factorial_recursive(num): solution = num while num != 0: solution = solution * (num - 1) print(solution) num = num - 1 factorial_recursive(6)
true
18db5e61c29a777be3bd163202dce195042b6878
dianamorenosa/Python_Fall2019
/ATcontent.py
487
4.125
4
#!/usr/bin/python #1.- Asign the sequence to a variable #2.- Count how many A's are in the sequence #3.- Count how many T's are in the sequence #4.- Sum the number of A's and the number of T's #5.- Print the sum of A's and T's seq1= ("ACTGATCGATTACGTATAGTATTTGCTATCATACATATATATCGATGCGTTCAT") #Asign the sequence to the variable seq1 ATcount= seq1.count ("A") + seq1.count("T") #Use count method for A and T, the + symbol will sum the number of A's and the number of T's print(ATcount)
true
a3037b8de00a8552d355fb5e45a15c6dc0743b77
rsingla92/advent_of_code_2017
/day_3/part_1.py
2,422
4.15625
4
''' You come across an experimental new kind of memory stored on an infinite two-dimensional grid. Each square on the grid is allocated in a spiral pattern starting at a location marked 1 and then counting up while spiraling outward. For example, the first few squares are allocated like this: 17 16 15 14 13 18 5 4 3 12 19 6 1 2 11 20 7 8 9 10 21 22 23---> ... While this is very space-efficient (no squares are skipped), requested data must be carried back to square 1 (the location of the only access port for this memory system) by programs that can only move up, down, left, or right. They always take the shortest path: the Manhattan Distance between the location of the data and square 1. For example: Data from square 1 is carried 0 steps, since it's at the access port. Data from square 12 is carried 3 steps, such as: down, left, left. Data from square 23 is carried only 2 steps: up twice. Data from square 1024 must be carried 31 steps. How many steps are required to carry the data from the square identified in your puzzle input all the way to the access port? ''' from math import sqrt, floor, fabs def calculate_spiral_coords(n): # Determine the radius of the spiral 'n' is in. # If the spiral length is u, then the last element is at u^2. # The next spiral is u^2 + 1 right, continuing u up, then u+1 # leftwards, u+1 downwards, and u+2 right. # Calculate u u = floor(sqrt(n)) if u % 2 == 0: u -= 1 radius = (u - 1) // 2 n -= u ** 2 if n == 0: return radius, radius n -= 1 if n < u: return radius+1, radius-n n -= u if n < u + 1: return radius + 1 - n, radius - u n -= u+1 if n < u + 1: return radius - u, radius - u + n n -= u + 1 if n < u + 2: return radius - u + n, radius + 1 def calculate_steps(n): x, y = calculate_spiral_coords(n) print 'x: ' + str(x) + ' y: ' + str(y) return fabs(x)+fabs(y) if __name__ == '__main__': test_1 = 1 print 'Test 1 result is ' + str(calculate_steps(test_1)) test_2 = 12 print 'Test 2 result is ' + str(calculate_steps(test_2)) test_3 = 23 print 'Test 3 result is ' + str(calculate_steps(test_3)) test_4 = 1024 print 'Test 4 result is ' + str(calculate_steps(test_4)) my_input = 347991 print 'My result is ' + str(calculate_steps(my_input))
true
23241e4ba4dadda493f44610e334ff1dfa533d82
Algorant/HackerRank
/Python/string_validators/string_validators.py
586
4.125
4
# You are given a string . Your task is to find out if the string contains: # alphanumeric characters, alphabetical characters, digits, lowercase # and uppercase characters. if __name__ == '__main__': s = input() # any() checks for anything true, will iterate through all tests # Check for alphanumerics print(any(c.isalnum() for c in s)) # Check for alphabet characters print(any(c.isalpha() for c in s)) # Check for digits print(any(c.isdigit() for c in s)) # Check for lowercase print(any(c.islower() for c in s)) # Check for uppercase print(any(c.isupper() for c in s))
true
aa361a509b9cb245ecbf9448f4df5279cfc078c6
Algorant/HackerRank
/Python/reduce/reduce.py
557
4.25
4
''' Given list of n pairs of rational numbers, use reduce to return the product of each pair of numbers as numerator/denominator fraction by every fraction in list n. ''' # some of this code is supplied to user from fractions import Fraction from functools import reduce def product(fracs): t = reduce(lambda x, y: x * y, fracs) return t.numerator, t.denominator if __name__ == '__main__': fracs = [] for _ in range(int(input())): fracs.append(Fraction(*map(int, input().split()))) result = product(fracs) print(*result)
true
f6b7564f728de2663ab87128b71fd4280236772a
Algorant/HackerRank
/Python/set_add/set_add.py
204
4.25
4
''' Given an integer and a list of items as input, use set.add function to count the number of unique items in the set. ''' n = int(input()) s = set() for i in range(n): s.add(input()) print(len(s))
true
91df05bb5905d70cc260c414ec0f4ba2bcaf3d88
Algorant/HackerRank
/30_days_of_code/d25_running_time_and_complexity/running_time.py
1,020
4.1875
4
''' Given list of integers of length T, separated by /n, check if that number is prime and return "Prime" or "Not Prime" for that integer. ''' # This was first attempt. Naive approach that works but fails 2 test cases # due to timeout! (Too slow) # def ptest(T): # # Make sure greater than 1 # if T > 1: # # Check if its even or has any other factors # for i in range(2, T): # if (T % i) == 0: # print("Not Prime") # break # can end if it finds any # else: # print("Prime") # no factors other than 1 and self # # else: # print("Not Prime") # any other case not prime # # # ptest(31) # ptest(12) # ptest(33) # Attempt 2 def prime(num): if num == 1: return False else: return all((num % r) for r in range(2, round(num ** 0.5) + 1)) T = int(input()) for i in range(1, T+1): num = int(input()) if prime(num)==True: print("Not prime") else: print("Prime")
true
996bb5aa753930626a1a6a45d930437dd015c850
Algorant/HackerRank
/Python/findall_finditer/find.py
482
4.21875
4
''' Given a string S, consisting of alphanumeric characters, spaces, and symbols, find all the substrings of S that contain 2 or more vowels. The substrings should lie between 2 consonants and should contain vowels only. ''' import re vowels = 'aeiou' consonants = 'bcdfghjklmnpqrstvwxyz' regex = '(?<=[' + consonants + '])([' + vowels + ']{2,})[' + consonants + ']' match = re.findall(regex, input(), re.IGNORECASE) if match: print(*match, sep='\n') else: print('-1')
true
0e984975c0d8fb572a673166385a48c9ed14ae7d
JohnErnestBonanno/Turtles
/TurtleExplo.py
634
4.15625
4
#https://www.youtube.com/watch?v=JQPUS1nv5F8&t=970s #Import Statement import turtle my_turtle = turtle.Turtle() #set speed my_turtle.speed(2) """ distance = 100 #move turtle in a square #def square(distance): for x in range(0,4): my_turtle.fd(distance) my_turtle.rt(90) my_turtle.circle(100) my_turtle.stamp() """ """ #increasing spiral distance = 10 for x in range(0,50): my_turtle.fd(distance) my_turtle.rt(90) distance += 3 """ #fill in the box turtle.title("My Turtle") distance = 50 while distance > 0: my_turtle.fd(distance) my_turtle.rt(50) distance = distance - 1 turtle.exitonclick()
false
a4012048e689d6739943728336d07414c7540b0b
luccaplima/estudandoPython
/variaveis.py
2,488
4.71875
5
#estudando variaveis python """ python não necessita de um comando para declarar a variavel uma variavel é criada no momento que um valor é associado a ela uma variavel não precisa ser declarada como um tipo particular e seu tipo pode ser trocado posteriormente O nome de uma variável em python pode ser curto (como x e y) ou pode ser mais descritivo (como idade, nome, curso) Regras para variáveis em Python: 1- O nome de uma variável pode começar com uma letra ou com o caractere underscore ("_") 2- O nome de uma variável não pode começar com um número 3- O nome de uma variável só pode conter caracteres alfa numéricos e underscores 4- Nomes de variável são case-sensitive(idade é diferente de IDADE que é diferente de Idade) """ x=2136 #x é int x=23.50 #x agora é float y="Lucca" #y é string z=2.50 #z é float k=["Lucca", "João", "Matheus"] #k é list aux=[x, y, z] #criando list com as variáveis criadas anteriormente X = "Teste Case-Sensitive" print(x,X) #nomes de váriaveis em python são case-sensitive A, B, C = 'anel', 'bola', 7 #o python deixa associar valores a multiplas variáveis em apenas uma linha print(A, B, C) print(x) print(y) print(z) print(k) print(aux) """ se é necessário especificar o tipo de dado de uma variável, isto pode ser feito com casting """ x1=str('Exemplo') #definindo x1 como string x2=int(3) #definindo x2 como int x3=float(37.5) #definindo x3 como float x4=list(["Elemento1", "Elemento2", "Elemento3"]) #definindo x4 como lista print(x1, x2, x3, x4) """ o tipo de dados de uma variavel pode ser obtido através da funçao type() """ print(type(x1)) print(type(x2)) print(type(x3)) print(type(x4)) """ Variáveis que são criadas fora de uma função são consideradas váriaveis globais e podem ser utilizadas dentro ou fora de funções Uma variável global pode ser criada dentro de uma função utilizando a palavra-chave global """ var1='Python é' var2='uma linguagem de programação interessante!' #var1 e var2 são variáveis globais def myfunc(): #função que utiliza as variáveis globais print(var1+var2) myfunc() #retornar a função """ Python data-types: texto - str numericos- int, float, complex tipos de sequencia - list, tuple, range tipos mapping - dict tipos set - set, frozenset tipo boolean - bool tipos binarios - bytes, bytearray, memoryview """
false
97128f21e73b655557a2dee31dc5610b40b6011a
coding-with-fun/Python-Lectures
/Lec 7/Types of UDF.py
2,476
4.875
5
# Function Arguments: # 1) Required arguments # 2) Keyword arguments # 3) Default arguments # 4) Variable-length arguments # 5) Dictionary arguments # 1) Required arguments: # Required arguments are the arguments passed to a function in correct positional order. # Here, the number of arguments in the function call should match exactly with the function definition. def fn1(a): print (a) fn1("Hello World") #Output:Hello World # 2) Keyword arguments: # Keyword arguments are related to the function calls. # When you use keyword arguments in a function call, # the caller identifies the arguments by the parameter name. def fn2(str): print str fn2(str="Good Evening") #Output:Good Evening # 3) Default arguments: # A default argument is an argument that assumes a default value # if a value is not provided in the function call for that argument,it prints default value if it is not passed def fn3(name,marks=35): print "Name=",name print "Marks=",marks fn3(marks=50,name="XYZ") #Output: # Name=XYZ # Marks=50 fn3(name="ABC") #Output: # Name=ABC # Marks=35 # 4) Variable-length arguments # You may need to process a function for more arguments than you specified while defining the function. # These arguments are called variable-length arguments and are not given in the function definition, # An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments. # This tuple remains empty if no additional arguments are specified during the function call. def fn4(arg1,*tuplevar): print "arg1=",arg1 for var in tuplevar: print "tuple=",var fn4(50) #Output:50 fn4(60,70,"Hello") #Output: # 60 # 70 # Hello # 5) Dictionary arguments # #A keyword argument is where you provide a name to the variable as you pass it into the function. # #One can think of the kwargs as being a dictionary that maps each keyword to the value that we pass alongside it. # #That is why when we iterate over the kwargs there doesn’t seem to be any order in which they were printed out. def fn5(**kwargs): if kwargs is not None: for key,value in kwargs.items(): print("%s = %s" %(key, value)) fn5(fn='Abc',ln='Def') #Output: # fn=Abc # ln=Def
true
fd8100771d5b5e688a470de173dfe3331facc3a1
guntursandjaya/GunturSandjaya_ITP2017_Exercise
/5-6 Stages of life.py
317
4.15625
4
age = input("Insert age : ") age = int(age) if age<2: print("The person is a baby") elif age>=2 and age<4: print("The person is a kid") elif age>=13 and age<20: print("The person is a teenager") elif age>=20 and age<65: print("The person is a adult") elif age>65: print("The person is an elder")
false
0bdd0d5acbe261113fe3ff023be27216a3aad75b
rfpoulos/python-exercises
/1.31.18/blastoff.py
287
4.125
4
import time numbers = int(raw_input("How many numbers should we count down?: ")) text = raw_input("What should we say when we finish out countdown?: ") for i in range(0, numbers + 1): if numbers - i == 0: print text else: print numbers - i time.sleep(1)
true
a2acc5778a677f03e5474f25b9750224c509b316
rfpoulos/python-exercises
/1.30.18/name.py
509
4.5
4
first_name = raw_input('What is your first name? ') last_name = raw_input('%s! What is your last name? ' % first_name) full_name = '%s %s' % (first_name, last_name) print full_name #Below is a qualitative analysis if first_name == 'Rachel': print "That's a great name!" elif first_name == 'Rachael': print "That's the devil's spelling. . ." else: print "That's a fine name, but not the BEST name." print (full_name.upper() + "! Your full name is " + str(len(full_name)) + " character's long")
true
f47fd9998823803e0b731023430aa0d226b12ca0
ssahussai/Python-control-flow
/exercises/exercise-5.py
824
4.34375
4
# exercise-05 Fibonacci sequence for first 50 terms # Write the code that: # 1. Calculates and prints the first 50 terms of the fibonacci sequence. # 2. Print each term and number as follows: # term: 0 / number: 0 # term: 1 / number: 1 # term: 2 / number: 1 # term: 3 / number: 2 # term: 4 / number: 3 # term: 5 / number: 5 # etc. # Hint: The next number is found by adding the two numbers before it terms = int(input("Enter term:")) n1 = 0 n2 = 1 count = 0 if terms <= 0: print("Enter a positive number!") elif terms == 1: print(f"Fibonacci sequence: {n1}") elif terms < 51: print("Fibonacci sequences:") while count < terms: print(n1) nth = n1 + n2 n1 = n2 = nth count += 1 else: print("This function goes only upto 50 terms!")
true
d4a4dd99e068910c239d94119bac23744e7e0e8b
AIHackerTest/xinweixu1_Py101-004
/Chap0/project/ex36_number_guess.py
1,899
4.34375
4
#ex 36 # The task of this exercise is to design a number guessing game. import random goal = random.randint(1, 20) n = 10 print ("Please enter an integer from 0 to 20." ) print ("And you have 10 chances to guess the correct number.") guess = int(input ('> ')) while n != 0: if guess == goal: print ("Yes, you win!") exit(0) elif guess < goal: n = n - 1 print ("Your guess is smaller than the correct number.") print (f"You can still try {n} times.") guess = int(input ('> ')) else: n = n - 1 print ("Your guess is larger than the correct number.") print (f"You can still try {n} times.") guess = int(input ('> ')) #Notes on if-statements & loops: # Rules for if-statements: # 1) every if-statement must have an else # 2) if this else should never run because it doesn't make sense, # then you must use a die function in the else that prints out # an error message and dies # 3) never nest if-statements more than two deep # 4) treat if-statements like paragraphs, where if-elif-else grouping # is like a set of sentences. Put blank lines before and after # 5) Your boolean tests should be SIMPLE! # If they are complex, move their calculations to variables earlier in # your function and use a good name for the variable. # Rules for Loops: # 1) use a while loop ONLY to loop forever, and that means probably never... # this only applies to python, other languages might be different # 2) use for-loop for all other kinds of looping, esp. if there is a # fixed or limited number of things to loop over # Tips for debugging: # 1) The best way to debug is to use print to print out the values of # variables at points in the program to see where they go wrong # 2) Do NOT write massive files of code before you try to run them, # code a little, run a little, fix a little.
true
fa69a550806f7cfcbf2fd6d02cbdf443a9e48622
lepperson2000/CSP
/1.3/1.3.7/LEpperson137.py
1,231
4.3125
4
import matplotlib.pyplot as plt import random def days(): '''function explanation: the print will be of the 'MTWRFSS' in front of 'day' and the print will include the 5-7 days of September ''' for day in 'MTWRFSS': print(day + 'day') for day in range(5,8): print('It is the ' + str(day) + 'th of September') plt.ion() # sets "interactive on": figures redrawn when updated def picks(): a = [] # make an empty list a += [random.choice([1,3,10])] plt.hist(a) plt.show() def roll_hundred_pair(): b = [] b += [random.choice([2,4,6])] plt.hist(b) plt.show() def dice(n): number = range(2-12) number += [random.choice(range(2,12))] return dice(n) def hangman_display(guessed, secret): letter = range(1,26) letter += [hangman_display(range(1,26))] return hangman_display(guessed, secret) def matches(ticket, winners): ticket = list[11,12,13,14,15] winners = list[3,8,12,13,17] for ticket in winners: print(matches) def report(guess, secret): color = range(1,4) color += [report(range(1,4))] return report(guess, secret)
true
8860a1eb440ef0f1249875bc5a97a5157bf0c258
ShamanicWisdom/Basic-Python-3
/Simple_If_Else_Calculator.py
2,753
4.4375
4
# IF-ELSE simple two-argument calculator. def addition(): try: first_value = float(input("Input the first value: ")) second_value = float(input("Input the second value: ")) result = first_value + second_value # %g will ignore trailing zeroes. print("\nResult of %.5g + %.5g is: %.5g\n" % (first_value, second_value, result)) except ValueError: print("Please insert proper numbers!") def subtraction(): try: first_value = float(input("Input the first value: ")) second_value = float(input("Input the second value: ")) result = first_value - second_value # %g will ignore trailing zeroes. print("\nResult of %.5g - %.5g is: %.5g\n" % (first_value, second_value, result)) except ValueError: print("Please insert proper numbers!") def multiplication(): try: first_value = float(input("Input the first value: ")) second_value = float(input("Input the second value: ")) result = first_value * second_value # %g will ignore trailing zeroes. print("\nResult of %.5g * %.5g is: %.5g\n" % (first_value, second_value, result)) except ValueError: print("Please insert proper numbers!") def division(): try: first_value = float(input("Input the first value: ")) second_value = float(input("Input the second value: ")) if second_value == 0: print("Cannot divide by zero!") else: result = first_value / second_value # %g will ignore trailing zeroes. print("\nResult of %.5g / %.5g is: %.5g\n" % (first_value, second_value, result)) except ValueError: print("\nPlease insert proper numbers!\n") print("==Calculator==") user_choice = -1 while user_choice != 0: print("1. Addition.") print("2. Subtraction.") print("3. Multiplication.") print("4. Division.") print("0. Exit.") try: user_choice = int(input("Please input a number: ")) if user_choice not in [0, 1, 2, 3, 4]: print("\nPlease input a proper choice!\n") else: if user_choice == 0: print("\nExiting the program...\n") else: if user_choice == 1: addition() else: if user_choice == 2: subtraction() else: if user_choice == 3: multiplication() else: if user_choice == 4: division() except ValueError: print("\nProgram will accept only integer numbers as an user choice!\n")
true
c6cbfb6a8c91fedba94151405a0e6e064a9cf7dd
pradeep-sukhwani/reverse_multiples
/multiples_in_reserve_order.py
581
4.25
4
# Design an efficient program that prints out, in reverse order, every multiple # of 7 that is between 1 and 300. Extend the program to other multiples and number # ranges. Write the program in any programming language of your choice. def number(): multiple_number = int(raw_input("Enter the Multiple Number: ")) start_range = int(raw_input("Enter the Start Range Number: ")) end_range = int(raw_input("Enter the End Range Number: ")) for i in range(start_range, end_range+1) [::-1]: if i % multiple_number == 0: print i, number()
true
b2825f7313f3834263cc59e8dd49cf3e11d2a86a
AdityaLad/python
/python-projects/src/root/frameworks/ClassCar.py
550
4.125
4
''' Created on Sep 11, 2014 @author: lada the only purpose of init method is to initialize instance variables ''' ''' def __init__(self, name="Honda", *args, **kwargs): self.name = name ''' class Car: #constructor def __init__(self, name="Honda"): self.name = name def drive(self): print "Drive car", self.name #destructor def __del__(self): print "Car object destroyed.." c1 = Car("Toyota") c2 = Car("Nissan") c3 = Car() c1.drive() c2.drive() c3.drive()
true
b673a44965d31b1cb410c1e64fcdae7b466dad3b
alexxa/Python_for_beginners_on_skillfeed_com
/ch_03_conditionals.py
723
4.28125
4
#!/usr/bin/python #AUTHOR: alexxa #DATE: 18.12.2013 #SOURSE: https://www.skillfeed.com/courses/539-python-for-beginners #PURPOSE: Conditionals. a,b = 0,1 if a == b: print(True) if not a == b: print(False) if a != b: print('Not equal') if a > b: print('Greater') if a >= b: print('Greater or equal') if a < b: print('Smaller') if a <= b: # not => print('Smaller or equal') if a==b or a < b: print('This is True') if a!=b and b > 0: print('This is also True') if a!=b and b < 0: print('This is also True') if a > b: print('a is greater than b') elif a < b: print('a is less than b') else: print('a s equal to b') #END
false
ee43a116e8951757f34048101d50a6e43c4eea49
wentao75/pytutorial
/05.data/sets.py
653
4.15625
4
# 堆(Sets)是一个有不重复项组成的无序集合 # 这个数据结构的主要作用用于验证是否包含有指定的成员和消除重复条目 # 堆对象还支持如:并,交,差,对称差等操作 # 可以使用大括号或set()方法来产生堆对象,不要使用{}来产生空的堆对象 # {}会产生一个空的字典而不是堆对象 basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} print(basket) 'orange' in basket 'crabgrass' in basket a = set('abracadabra') b = set('alacazam') a b a - b b - a a | b a & b a ^ b # 堆也支持队列导出式 a = {x for x in 'abracadabra' if x not in 'abc'} a
false
6cbfc9e2bd18f1181041287a56317200b1b789a8
DaehanHong/Principles-of-Computing-Part-2-
/Principles of Computing (Part 2)/Week7/Practice ActivityRecursionSolution5.py
925
4.46875
4
""" Example of a recursive function that inserts the character 'x' between all adjacent pairs of characters in a string """ def insert_x(my_string): """ Takes a string my_string and add the character 'x' between all pairs of adjacent characters in my_string Returns a string """ if len(my_string) <= 1: return my_string else: first_character = my_string[0] rest_inserted = insert_x(my_string[1 :]) return first_character + 'x' + rest_inserted def test_insert_x(): """ Some test cases for insert_x """ print "Computed:", "\"" + insert_x("") + "\"", "Expected: \"\"" print "Computed:", "\"" + insert_x("c") + "\"", "Expected: \"c\"" print "Computed:", "\"" + insert_x("pig") + "\"", "Expected: \"pxixg\"" print "Computed:", "\"" + insert_x("catdog") + "\"", "Expected: \"cxaxtxdxoxg\"" test_insert_x()
true
87f5557c82320e63816047943679b70effe5aecf
DaehanHong/Principles-of-Computing-Part-2-
/Principles of Computing (Part 2)/Week6/Inheritance2.py
437
4.25
4
""" Simple example of using inheritance. """ class Base: """ Simple base class. """ def __init__(self, num): self._number = num def __str__(self): """ Return human readable string. """ return str(self._number) class Sub(Base): """ Simple sub class. """ def __init__(self, num): pass obj = Sub(42) print obj
true
9f045af90875eea13a4954d2a22a8089fd07724a
Thuhaa/PythonClass
/28-July/if_else_b.py
713
4.21875
4
marks = int(input("Enter the marks: ")) # Enter the marks # Between 0 and 30 == F # Between 31 and 40 == D # Between 41 and 50 == C # Between 51 and 60 == B # Above 61 == A # True and True == True # True and False == False # False and False == False # True or True == True # True or False == True # False and False == False # Use elif If there is more than 2 condition if marks <= 30: print("The student has scored an F") elif marks > 30 and marks <=40: print("The student has scored a D") elif marks >40 and marks<=50: print("The student score a C") elif marks > 50 and marks <= 60: print("The student scored a B") else: print("The student scored and A")
true
4e6708d3b8109a6fb5082eb4efb5d0590309f71a
yestodorrow/dataAnalysis
/firstCourse/hello.py
1,252
4.125
4
print("Hello Python") # 交互界面窗口 输入输出交互式 # 编写和调试程序 # 语法词汇高亮显示 # 创建、编辑程序文件 print("hello world") a=3 # 定时器 import time time.sleep(3) a=4 print(a) print(a) # 标量对象 # init 整数 # float 实数 16.0 # bool 布尔 True False # NoneType 空类型 x="this is liu Gang" y="he is a handsome boy" print(x+","+y) #变量 #赋值语句 x,y="liugang","very handsome" sentence =x+" "+ y print(sentence) #注意:分隔符只能是英文的半角逗号 #数字的类型 # 整数 浮点数 布尔型 复数(complex) # 5+3j complex(5,3) # 判断数据类型 # type() isinstance() # print(type(5.0),type(1E+3),type()) #转换数据类型 # int() 转换成整数 print(int(3.9)) # print(int(3.9)) print(3>2>1) #比较运算符 print(0) #数学运算的优先级 print(x,y,x+y*3) #字符串 同js #输入函数 # 如何在交互中变量赋值呢 x=input("name") print(x +" is very handsome") # 注意 语句返回值为字符串,可以通过类型转换 x=input("4") # print(x/4) print(int(4)/4) x=int(input("number")) height=float(input("your savings in wechat or 支付宝")) print(height) # print(x,sep=" ",end="\n") # print(x,y,sep="***",end="!") print("e")
false
137638cb6c3ee7cd32d6d183e2bc898e1a2c8bd1
marczakkordian/python_code_me_training
/04_functions_homework/10.py
1,605
4.125
4
# Stwórz grę wisielec “bez wisielca”. # Komputer losuje wyraz z dostępnej w programie listy wyrazów. # Wyświetla zamaskowany wyraz z widoczną liczbą znaków (np. ‘- - - - - - -‘) # Użytkownik podaje literę. # Sprawdź, czy litera istnieje w wyrazie. Jeśli tak, wyświetl mu komunikat: # “Trafione!” oraz napis ze znanymi literami. # W przeciwnym wypadku pokaż komunikat: # “Nie trafione, spróbuj jeszcze raz!”. # Możesz ograniczyć liczbę prób do np. 10. import random words = ['python', 'java', 'science', 'computer', 'testing', 'learning'] secret_word = random.choice(words) print(secret_word) usr_guesses = '' word = '' fails = 0 def show_word_to_user(word, secret_word, usr_guesses, fails): turns = 0 while turns < 10: for i, char in enumerate(secret_word): if char in usr_guesses: word = word[:i] + char else: word = word[:i] + ''.join(char.replace(char, '- ')) fails += 1 print(word) word = '' if fails == 0: print("You Win") print(f'The correct word is: {secret_word}') break usr_guess = input("Type your letter: ").strip() usr_guesses += usr_guess if usr_guess in secret_word: print("Well done!") else: turns += 1 print("Sorry, try again!") print(f'You have {10 - turns} more guesses') if turns == 10: print("You Loose") if __name__ == '__main__': show_word_to_user(word, secret_word, usr_guesses, fails)
false
6795c4e6e07de121d7dce93da430830b71f0cb3e
akoschnitzki/Module-4
/branching-Lab 4.py
884
4.375
4
# A time traveler has suddenly appeared in your classroom! # Create a variable representing the traveler's # year of origin (e.g., year = 2000) # and greet our strange visitor with a different message # if he is from the distant past (before 1900), # the present era (1900-2020) or from the far future (beyond 2020). year = int(input("Greetings! What is your year of origin?")) # Add the missing quotation mark and an extra equal sign. ''' if year < 1900: ''' if year <= 1900: # Add the missing colon. print("Woah, that's the past!") # Add the missing quotation marks. '''elif year >= 1900 and year < 2020 : ''' elif year >= 1900 and year <= 2020: # Must add the word and to make the statement run. print("That's totally the present!") '''else: ''' elif year >= 2020: # Add the statement to print the years that are in the future. print("Far out, that's the future!!")
true
53303f7123bbd2c1b2f8c07d9002bae85f3cb81a
TrevAnd1/Sudoku-Puzzle-Solver
/Sudoku/Sudoku Puzzle Solver.py
1,725
4.15625
4
import pygame import random from pygame.locals import ( K_1, K_2, K_3, K_4, K_5, K_6, K_7, K_8, K_9, K_RIGHT, K_LEFT, K_UP, K_DOWN, K_KP_ENTER, K_ESCAPE, KEYDOWN, QUIT, ) WHITE = (0,0,0) SCREEN_WIDTH = 1000 SCREEN_HEIGHT = 1000 # TODO : get user input to see how many numbers they want to start with given on the board and use that number in line 54 in a 'for' loop to interate through 'board' as many times as the user wants in their input class Board: board = [ [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0], ] def __init__(self): pass def drawBackground(self): # use pygame.draw.line() to make lines for the board pass def initializeBoard(self): # set 0's in board to random numbers between one and 10 so that they can be solved rand_row = random.randint(0,8) rand_col = random.randint(0,8) self.board[rand_row][rand_col] = random.randint(1,9) # TODO : check if the spot that it randomly chooses already has a number in it (if board[rand_row][rand_col] != 0) pygame.init() screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) running = True while running: screen.fill((WHITE)) for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_ESCAPE: running = False elif event.type == QUIT: running = False
false
55ab453d18e2b12b64378fd70fc3843ec169eb29
Deepak10995/node_react_ds_and_algo
/assignments/week03/day1-2.py
901
4.4375
4
''' Assignments 1)Write a Python program to sort (ascending and descending) a dictionary by value. [use sorted()] 2)Write a Python program to combine two dictionary adding values for common keys. d1 = {'a': 100, 'b': 200, 'c':300} d2 = {'a': 300, 'b': 200, 'd':400} Sample output: Counter({'a': 400, 'b': 400, 'd': 400, 'c': 300}) ''' #ques 1 d1 = {'a': 100, 'b': 200, 'c':300} d2 = {'a': 300, 'b': 200, 'd':400} def sorted_dict_increasing(d1): sorted_d1 = sorted(d1.items(),key= lambda x: x[1]) print(sorted_d1) sorted_d1 = sorted(d1.items(),key= lambda x: x[1],reverse=True) print(sorted_d1) return sorted_d1 sorted_dict_increasing(d1) # Ques 2 from collections import Counter d1 = {'a': 100, 'b': 200, 'c':300} d2 = {'a': 300, 'b': 200, 'd':400} def dict_combine(d1,d2): d_combine = Counter(d1) + Counter(d2) print(d_combine) return d_combine dict_combine(d1,d2)
true
24f3091c067759e7cde9222bfb761a777da668df
Deepak10995/node_react_ds_and_algo
/coding-challenges/week06/day-1.py
2,263
4.28125
4
''' CC: 1)Implement Queue Using a linked list ''' #solution class Node: def __init__(self, data): self.data = data self.next = None class Queue: def __init__(self): self.head = None self.last = None def enqueue(self, data): if self.last is None: self.head = Node(data) self.last = self.head else: self.last.next = Node(data) self.last = self.last.next def dequeue(self): if self.head is None: return None else: to_return = self.head.data self.head = self.head.next return to_return a_queue = Queue() while True: print('enqueue <value>') print('dequeue') print('quit') do = input('What would you like to do? ').split() operation = do[0].strip().lower() if operation == 'enqueue': a_queue.enqueue(int(do[1])) elif operation == 'dequeue': dequeued = a_queue.dequeue() if dequeued is None: print('Queue is empty.') else: print('Dequeued element: ', int(dequeued)) elif operation == 'quit': break ''' 2)Implement Stack using a linked list ''' #solution class Node: def __init__(self, data): self.data = data self.next = None class Stack: def __init__(self): self.head = None def push(self, data): if self.head is None: self.head = Node(data) else: new_node = Node(data) new_node.next = self.head self.head = new_node def pop(self): if self.head is None: return None else: popped = self.head.data self.head = self.head.next return popped a_stack = Stack() while True: print('push <value>') print('pop') print('quit') do = input('What would you like to do? ').split() operation = do[0].strip().lower() if operation == 'push': a_stack.push(int(do[1])) elif operation == 'pop': popped = a_stack.pop() if popped is None: print('Stack is empty.') else: print('Popped value: ', int(popped)) elif operation == 'quit': break
true
a729758b2b951b8c38983b7dd5336c8f36f933da
DajkaCsaba/PythonBasic
/4.py
293
4.53125
5
#4. Write a Python program which accepts the radius of a circle from the user and compute the area. Go to the editor #Sample Output : #r = 1.1 #Area = 3.8013271108436504 from math import pi r = float(input("Input the radius of the circle: ")) print("r = "+str(r)) print("Area = "+str(pi*r**2))
true
3de713f7ca2f61358268815be48dbe7a217db2ee
wojtbauer/Python_challenges
/Problem_2.py
865
4.125
4
#Question 2 # Write a program which can compute the factorial of a given numbers. # The results should be printed in a comma-separated sequence on a single line. # Suppose the following input is supplied to the program: # 8 # Then, the output should be: # 40320 # Factorial = int(input("Wpisz liczbę: ")) # wynik = 1 # # #if/elif solution! - option 1 # if Factorial < 0: # print("Wstaw wartość nieujemną!") # elif Factorial == 0: # print("0! = 1") # else: # for i in range(1, Factorial+1): # wynik = wynik*i # print(Factorial, wynik) #while solution! - option 2 # while Factorial > 0: # wynik = wynik * Factorial # Factorial = Factorial - 1 # print(wynik) #Function solution - option 3 def Fact(x): if x == 0: return 1 elif x > 0: return x * Fact(x-1) x = int(input("Wpisz liczbę: ")) print(Fact(x))
true
8473a7a874e1bf2435049301d45064ecefe4f45d
jackiehluo/projects
/numbers/fibonacci-sequence.py
209
4.1875
4
from math import sqrt def fibonacci(n): return ((1 + sqrt(5)) ** n - (1 - sqrt(5)) ** n) / (2 ** n * sqrt(5)) n = int(raw_input("Enter a digit n for the nth Fibonacci number: ")) print int(fibonacci(n))
false
c5b87a3edc367f76c12b0fa2734ee8deafa4b965
jcbain/fun_side_projects
/unique_digits/unique_digits.py
1,948
4.1875
4
from collections import Counter def separate_digits(val): """ separate the digits of a number in a list of its digits Parameters ----- val : int number to separate out Returns ----- list a list of ints of the digits that make up val """ return [int(x) for x in str(val)] def any_intersection(x,y): """ check to see if there are any intersecting values between two lists Parameters ----- x : list first list of values y : list second list of values Returns ----- bool True if there is an intersection, False otherwise """ inter = set(x).intersection(set(y)) return bool(inter) def run_exponential(exp,upper_bound = 10000): """ finds the values between 0 and an upper bound that contains all unique digits and shares no digits with its value raised to some exponent Parameters ----- exp : int exponent to raise the values to upper_bound : int the upper limit of where the list should stop at Returns lists first list is a list the base values that meet the criteria second list is a list of the base values that work raised to the exponent """ candidates_result = [] candidates_base = [] for i in range(0,upper_bound): num = i ** exp compound = str(i) + str(exp) separate_compound = separate_digits(compound) separate_num = separate_digits(num) base_digit_counts = list(Counter(separate_digits(i)).values()) intersection_check = not any_intersection(separate_num,separate_compound) base_check = not any(i > 1 for i in base_digit_counts) if intersection_check & base_check: candidates_result.append(num) candidates_base.append(i) return candidates_base,candidates_result if __name__ == '__main__': print(run_exponential(6, 1000000000))
true
802480d75cc45bb911de93e28e8e830b743b4db6
Mattx2k1/Notes-for-basics
/Basics.py
2,087
4.6875
5
# Hello World print("Hello World") print() # Drawing a shape # Programming is just giving the computer a set of instructions print(" /!") print(" / !") print(" / !") print("/___!") print() # console is where we have a little window into what our program is doing # Pyton is looking at these instructions line by line in order # The order in which we write the instructions is very important. It matters a lot # Variables and Data Types # In python we'll be dealing with a lot of data, values and information # That data can be difficult to manage # A variable is a container where we can store certain data values, and when we use variables it's a lot easier to work with and manage the information in our programs. # Let's start with this story print("There once was a man named George, ") print("he was 70 years old. ") print("He really liked the name George, ") print("but didn't like being 70.") print() # Let's say we wanted to change the name in the story from George to John, or change the age, we'd have to do it line by line. Except we have Variables which make it easier for us: #variable_name character_name = "John" character_age = "35" #Now we can just add in the variables in the story print("There once was a man named " + character_name + ", ") print("he was " + character_age + " years old. ") print("He really liked the name George, ") print("but didn't like being " + character_age + ".") # Now all you would have to do is change the variables to update many lines in the story. # We can update the variable simply writing it out again character_name = "Tom" print("There once was a man named " + character_name + ", ") print("he was " + character_age + " years old. ") print("He really liked the name George, ") print("but didn't like being " + character_age + ".") # We are storing these names as strings # Strings are plain text # Can store numbers, don't use quotations character_age = 35 # can store whole numbers character age = 35.5 # can store decimal numbers # Boolean returns true or false values. Example: is_male = False
true
cdd823dbe94b600742ba2158e50f516446aba57e
Mattx2k1/Notes-for-basics
/Try Except.py
1,072
4.53125
5
# Try Except # Catching errors # Anticipate errors and handle them when they occur. That way errors don't bring our program to a crashing halt number = int(input("Enter a number: ")) print(number) # if you enter a non number, it will cause the program to crash. So you need to be able to handle the exceptions # Try except block is what is used for this try: number = int(input("Enter a number: ")) print(number) except: print("Invalid input") # Specify the type of error you want to catch with this format for except: try: value = 10 / 0 number = int(input("Enter a number: ")) print(number) except ZeroDivisionError: print("Divided by zero") except ValueError: print("Invalid input") # store error as a variable: try: value = 10 / 0 number = int(input("Enter a number: ")) print(number) except ZeroDivisionError as err: print("err") except ValueError: print("Invalid input") # A best practice is to set up for catching specific errors. "Except:" by itself is too broad and may break your program on it's own
true
0896dad37cd3b5d93a60fb30672ccd902fcdc337
Mattx2k1/Notes-for-basics
/Guessing Game.py
564
4.25
4
# guessing game # start with the variables secret_word = "giraffe" guess = "" guess_count = 0 guess_limit = 3 out_of_guesses = False # use a while loop to continually guess the word until they get it correct # added in the "and not" condition, and new variables to create a limit on guesses while guess != secret_word and not (out_of_guesses): if guess_count < guess_limit: guess = input("Enter guess: ") guess_count += 1 else: out_of_guesses = True if out_of_guesses: print("Out of guesses, YOU LOSE!") else: print("You win!")
true
5284bda9251b8da6fe08e0c44d2721e87738e3ad
samsonwang/ToyPython
/PlayGround/26TicTacToe/draw_pattern.py
1,813
4.34375
4
#! /usr/bin/python3.6 ''' Tic Tac Toe Draw https://www.practicepython.org/exercise/2015/11/26/27-tic-tac-toe-draw.html - For this exercise, assume that player 1 (the first player to move) will always be X and player 2 (the second player) will always be O. - Notice how in the example I gave coordinates for where I want to move starting from (1, 1) instead of (0, 0). To people who don’t program, starting to count at 0 is a strange concept, so it is better for the user experience if the row counts and column counts start at 1. This is not required, but whichever way you choose to implement this, it should be explained to the player. - Ask the user to enter coordinates in the form “row,col” - a number, then a comma, then a number. Then you can use your Python skills to figure out which row and column they want their piece to be in. - Don’t worry about checking whether someone won the game, but if a player tries to put a piece in a game position where there already is another piece, do not allow the piece to go there. ''' import logging # get cordinate and return a tuple def get_player_input(str_player): log = logging.getLogger("root") str_cordinates = input("%s, which col and row? " % str_player) log.debug("%s, input: %s" % (str_player, str_cordinates) ) list_cord = str_cordinates.strip().split(',') return tuple(list_cord) def tic_tac_toe_game(): log = logging.getLogger("root") print("Welcome to tic tac toe") tup_p1 = get_player_input("Player 1") log.debug("Player 1: %s" % (tup_p1, )) def main(): logger = logging.getLogger("root") FORMAT = "%(filename)s:%(lineno)s %(funcName)s() %(message)s" logging.basicConfig(format=FORMAT) logger.setLevel(logging.DEBUG) tic_tac_toe_game() if __name__ == '__main__': main()
true
5521559091299b2af7b6c72fa20cea4dcffe9a03
arun-p12/project-euler
/p0001_p0050/p0025.py
1,056
4.125
4
''' In a Fibonacci series 1, 1, 2, 3, 5, 8, ... the first 2-digit number (13) is the 7th term. Likewise the first 3-digit number (144) is the 12th term. What is the index of the first term in the Fibonacci sequence to contain 1000 digits? ''' def n_digit_fibonacci(number): digits = 1 fibonacci = [1, 1] while(digits < number): fibonacci.append(fibonacci[-1] + fibonacci[-2]) # next term = sum of last two terms digits = len(str(fibonacci[-1])) # how many digits in the new term? if(digits >= number): # is it the required length print("fibonacci = ", len(fibonacci)) return(0) import time # get a sense of the time taken t = time.time() # get time just before the main routine ########## the main routine ############# number = 1000 n_digit_fibonacci(number) ########## end of main routine ########### t = time.time() - t # and now, after the routine print("time = {:7.5f} s\t{:7.5f} ms\t{:7.3f} µs".format(t, t * 1000, t*1_000_000))
true
154cf1ad66e4d8fab9b523676935b615ef831d3d
arun-p12/project-euler
/p0001_p0050/p0038.py
2,093
4.125
4
''' 192 x 1 = 192 ; 192 x 2 = 384 ; 192 x 3 576 str(192) + str(384) + str(576) = '192384576' which is a 1-9 pandigital number. What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (2, ... , n) digits? Essentially n > 1 to rule out 918273645 (formed by 9x1 9x2 9x3 ...) ''' ''' Cycle thru each number, get the multiples, and keep appending the string of numbers. When length of the string goes above 9, move onto the next number. If the length of the string is 9, check if it is pandigital. If yes, check if it is maximum ''' def pandigital_multiple(): target = [1, 2, 3, 4, 5, 6, 7, 8, 9] max_str = "" #for x in range(9876, 0, -1): # start from top, and decrement for x in range(1, 9877): i, pand_len = 1, 0 pand_list = [] # sort and test against target pand_str = "" # this is our actual string while (pand_len < 9): next_num = x * i # take each number, and multiply by the next i pand_str += str(next_num) for c in str(next_num): # append new number to our list pand_list.append(int(c)) pand_len = len(pand_list) i += 1 #print("test : ", x, pand_len, i, pand_list, pand_str, pand_cont) if pand_len == 9: pand_list.sort() if pand_list == target: if(pand_str > max_str): max_str = pand_str print("start_num = ", "{:4d}".format(x), "mult_upto = ", "{:1d}".format(i - 1), "result = ", "{:10s}".format(pand_str), "max = ", "{:10s}".format(max_str)) import time # get a sense of the time taken t = time.time() # get time just before the main routine ########## the main routine ############# pandigital_multiple() ########## end of main routine ########### t = time.time() - t # and now, after the routine print("time = {:7.5f} s\t{:7.5f} ms\t{:7.3f} µs".format(t, t * 1000, t*1_000_000))
true
4cbef49ee1fd1c6b4a15eae4d2dee12be49475a8
arun-p12/project-euler
/p0001_p0050/p0017.py
2,376
4.125
4
''' If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? Ignore spaces ''' def number_letter_count(number=1000): # number of letters in the word form, for each value dict = {0:0, 1:3, 2:3, 3:5, 4:4, 5:4, 6:3, 7:5, 8:5, 9:4, 10:3, 11:6, 12:6, 13:8, 14:8, 15:7, 16:7, 17:9, 18:8, 19:8, 20:6, 30:6, 40:5, 50:5, 60:5, 70:7, 80:6, 90:6, 100:7, 1000:8, 'and':3} # numeric representation of the word dict2 = {1:'one', 2:'two', 3:'three', 4:'four', 5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine', 10:'ten', 11:'eleven', 12:'twelve', 13:'thirteen', 14:'fourteen', 15:'fifteen', 16:'sixteen', 17:'seventeen', 18:'eighteen', 19:'nineteen', 20:'twenty', 30:'thirty', 40:'forty', 50:'fifty', 60:'sixty', 70:'seventy', 80:'eighty', 90:'ninety', 100:'hundred', 1000:'thousand', 'and':'and', 0:''} def word_filler(word): if(word): return(' ') else: return('') word = '' while(number): t = number // 1000 h = (number - t*1000) // 100 d = (number - t*1000 - h*100) // 10 u = int(number - t*1000 - h*100 - d*10) if(t): word += dict2[t] + ' ' + dict2[1000] if(h): word += word_filler(word) + dict2[h] + ' ' + dict2[100] if(((t | h) > 0) & ((d | u) > 0)): word += word_filler(word) + dict2['and'] if(d >= 2): word += word_filler(word) + dict2[d*10] if(d == 1): word += word_filler(word) + dict2[d*10 + u] else: word += word_filler(word) + dict2[u] number -= 1 #print("nlc_2 = ", num, "[[ ", t, h, d, u, word, " ]]") w_len = [len(x) for x in word.split()] return(sum(w_len)) import time # get a sense of the time taken t = time.time() # get time just before the main routine ########## the main routine ############# num = 1000 result = number_letter_count(num) ########## end of main routine ########### t = time.time() - t # and now, after the routine print("Letter count in numbers upto {} = {}".format(num, result)) print("time = {:7.5f} s\t{:7.5f} ms\t{:7.3f} µs".format(t, t * 1000, t*1_000_000))
true
c891fec31546ed93374bc833e0bb4870c7e3e188
rmrodge/python_practice
/format_floating_point_in_string.py
800
4.4375
4
# Floating point number is required in programming for generating fractional numbers, # and sometimes it requires formatting the floating-point number for programming purposes. # There are many ways to exist in python to format the floating-point number. # String formatting and string interpolation are used in the following script to format a floating-point number. format() method with format width is used in string formatting, # and ‘%” symbol with the format with width is used in string interpolation. # According to the formatting width, 5 digits are set before the decimal point, and 2 digits are set after the decimal point. # Use of String Formatting float1 = 563.78453 print("{:5.2f}".format(float1)) # Use of String Interpolation float2 = 563.78453 print("%5.2f" % float2)
true
b82b3928481d538244ec70a34fecb0b7ed761f3c
Jeff-ust/D002-2019
/L2/L2Q6v1.py
1,387
4.375
4
#L2 Q6: Banana Guessing game #Step 1: Import necessary modules import random #Step 2: Welcome Message print('''Welcome to the Banana Guessing Game Dave hid some bananas. Your task is to find out the number of bananas he hid.''') #Step 3: Choose a random number between 1-100 n = random.randint(1,100) print ("shhh, Dave hides %s bananas" % n) # define a flag for found/not found and counter on how many trials found = False count = 0 #Step 4: Give three chances to the players p = int(input("Guess a number between 1 and 100.")) while found == False: if p < 1 or p > 100: print("Your guess is out-of-range!") count = count + 1 elif p > n: print("Your guess is too high!") count = count + 1 elif p < n: print("Your guess is too low!") count = count + 1 elif p == n: found = True count = count + 1 if count == 3 and found == False: print("Game over.") break else: #Step 5: Display a message if found == True: print('You got the correct guess in %d trials' % count) print('Dave\'s banana are now all yours!') else: print("You failed to find the number of bananas Dave hid! Try again next") p = int(input("Guess a number between 1 and 100."))
true
70ca08346178f87b3e7afae3e746481369cba82a
shuhsienhsu/X-Village-DS-Exercise
/bonus3.py
746
4.1875
4
def insertion_sort(list): for i in range(1, len(list)): for j in range(i): j = i - j - 1 if(list[j] > list[j + 1]): temp = list[j] list[j] = list[j + 1] list[j + 1] = temp else: break def bubble_sort(list): for i in range(len(list)): i = len(list) - 1 - i for j in range(i): if(list[j + 1] < list[j]): temp = list[j] list[j] = list[j + 1] list[j + 1] = temp #def merge_sort(list): #def quick_sort(list): mylist = [4,3,2,1] print(mylist) insertion_sort(mylist) print(mylist) mylist2 = [2,4,3,1] print(mylist2) bubble_sort(mylist2) print(mylist2)
false
fbf0406858a0b3cdb529472d4642b2acea5fa3d2
shouryacool/StringSlicing.py
/02_ strings Slicing.py
820
4.34375
4
# greeting="Good Morning," # name="Harry" # print(type(name)) # # Concatining Two Strings # c=greeting+name # print(c) name="HarryIsGood" # Performing Slicing print(name[0:3]) print(name [:5]) #is Same as [0:4] print(name [:4]) #is Same as [0:4] print(name [0:]) #is Same as [0:4] print(name [-5:-1]) # is same as name [0:4] print(name[-4:-2]) # is same as name [1:3] # Slicing with skip value d=name[1::2] print(d) # The index in a string starts from 0 to (length-1) in Python. To slice a string, we use the following syntax: # We can acess any Characters Of String but cant change it # Negative Indices: Negative indices can also be used as shown in the figure above. -1 corresponds to the (length-1) index, -2 to (length-2). # Q Why To use Negative indices??? # # # #
true
d8f89c6f971a5378300db593da07310ed7dfa31d
AlexanderIvanofff/Python-OOP
/defending classes/programmer.py
2,311
4.375
4
# Create a class called Programmer. Upon initialization it should receive name (string), language (string), # skills (integer). The class should have two methods: # - watch_course(course_name, language, skills_earned) # o If the programmer's language is the equal to the one on the course increase his skills with the given one and # return a message "{programmer} watched {course_name}". # o Otherwise return "{name} does not know {language}". # - change_language(new_language, skills_needed) # o If the programmer has the skills and the language is different from his, change his language to the new one and # return "{name} switched from {previous_language} to {new_language}". # o If the programmer has the skills, but the language is the same as his return "{name} already knows {language}". # o In the last case the programmer does not have the skills, so return "{name} needs {needed_skills} more skills" # and don't change his language class Programmer: def __init__(self, name, language, skills): self.name = name self.language = language self.skills = skills def watch_course(self, course_name, language, skills_earned): if self.language == language: self.skills += skills_earned return f"{self.name} watched {course_name}" return f"{self.name} does not know {language}" def change_language(self, new_language, skill_needed): if self.skills >= skill_needed and not self.language == new_language: old_language = self.language self.language = new_language return f"{self.name} switched from {old_language} to {new_language}" elif self.skills >= skill_needed and self.language == new_language: return f"{self.name} already knows {self.language}" return f"{self.name} needs {abs(self.skills - skill_needed)} more skills" programmer = Programmer("John", "Java", 50) print(programmer.watch_course("Python Masterclass", "Python", 84)) print(programmer.change_language("Java", 30)) print(programmer.change_language("Python", 100)) print(programmer.watch_course("Java: zero to hero", "Java", 50)) print(programmer.change_language("Python", 100)) print(programmer.watch_course("Python Masterclass", "Python", 84))
true
6847b974bfa860f4dcec26f502a5b7c6c307e7e8
learn-co-curriculum/cssi-4.8-subway-functions-lab
/subway_functions.py
1,870
4.625
5
# A subway story # You hop on the subway at Union Square. As you are waiting for the train you # take a look at the subway map. The map is about 21 inches wide and 35 inches # tall. Let's write a function to return the area of the map: def map_size(width, height): map_area = width * height return "The map is %d square inches" % (map_area) # Now you give it a shot! It takes about 156 seconds to go between stops and # you'll be taking the train for 3 stops. Write a function that calculates how # long your trip will take. def trip_length(...): # put your code here # The train arrives and you hop on. Guess what time it is? It's showtime! There # are 23 people on the train and each person gives the dancers 1.5 dollars. # Write a function that returns how much money they made. # There is one grumpy lady on the train that doesn't like the dancing though. # Write a function called stop_dancing that returns a message to the dancers in # all caps. # There is also a really enthusiastic rider who keeps shouting "Everything is # awesome!" Write a function that returns everything is awesome 5 times. # You are almost at your stop and you start thinking about how you are going to # get home. You have $18 left on your metro card. Write a function that returns # how many trips you have left. # Call your functions below: print "How big is that subway map?" # Call your function here - like this: map_size(21, 35) # ... but that doesn't output anything. Hmm. See if you can fix it. print "This is how long the trip will take" trip_length(...) print "How much money did the train dancers make?" # call your function here print "That lady told the train dancers to" # call your function here print "That guy kept shouting" # call your function here print "This is how many trips I have left on my metrocard" # call your function here
true
1c832205ec93dc322ab47ed90c339a9d81441282
nyu-cds/asn264_assignment3
/product_spark.py
590
4.1875
4
''' Aditi Nair May 7 2017 Assignment 3, Problem 2 This program creates an RDD containing the numbers from 1 to 1000, and then uses the fold method and mul operator to multiply them all together. ''' from pyspark import SparkContext from operator import mul def main(): #Create instance of SparkContext sc = SparkContext("local", "product") #Create RDD on the list of numbers [1,2,...,1000] nums = sc.parallelize(range(1,1000+1)) #Use fold to aggregate data set elements by multiplicaton (ie multiply them all together) print(nums.fold(1,mul)) if __name__ == '__main__': main()
true
66e9c916b7ea5908c091f4fd5a7a5e2821efd3de
shawsuraj/dailyCode
/100-days-of-code/python/Day006/combination.py
270
4.15625
4
print ("Combination finder.") n = int(input("Enter n: ")) r = int(iinput("Enter r: ")) def factorial ( n ): result = 1 for num in range ( 1 , n + 1 ): result *= num return result print (factorial( n ) // factorial( r ) // factorial( n - r ))
false
9723db9bc6f9d411d0ae62f525c33a410af9f529
george-ognyanov-kolev/Learn-Python-Hard-Way
/44.ex44.py
981
4.15625
4
#inheritance vs composition print('1. Actions on the child imply an action on the parent.\n') class Parent1(object): def implicit(self): print('PARENT implicit()') class Child1(Parent1): pass dad1 = Parent1() son1 = Child1() dad1.implicit() son1.implicit() print('2. Actions on the child override the action on the parent.\n') class Parent2(object): def override(self): print('PARENT override()') class Child2(Parent2): def override(self): print('CHILD override()') dad2 = Parent2() son2 = Child2() dad2.override() son2.override() print('3. Actions on the child alter the action on the parent.\n') class Parent3(object): def altered(self): print('PARENT3 altered()') class Child3(Parent3): def altered(self): print('CHILD BEFORE PARENT altered()') super(Child3, self).altered() print('CHILD AFTER altered()') dad3 = Parent3() son3 = Child3() dad3.altered() son3.altered()
true
e5663cb79ea48d897aacc4350443c713dee27d5e
jejakobsen/IN1910
/week1/e4.py
773
4.15625
4
""" Write a function factorize that takes in an integer $n$, and returns the prime-factorization of that number as a list. For example factorize(18) should return [2, 3, 3] and factorize(23) should return [23], because 23 is a prime. Test your function by factorizing a 6-digit number. """ def get_primes(n): numbers = set(range(n, 1, -1)) primes = [] while numbers: p = numbers.pop() primes.append(p) numbers.difference_update(set(range(p*2, n+1, p))) return primes def factorize(n): P = get_primes(n) ls = [] while n > 1: for p in P: if n%p == 0: ls.append(p) n = n/p break return ls print(factorize(921909)) """ C:\\Users\\jensj\\OneDrive\\Skrivebord\\IN1910\\week1>python e4.py [3, 23, 31, 431] """
true
8e1f774d2d8748ae9f0a7707208ebf6e77ca8f7a
Yousab/parallel-bubble-sort-mpi
/bubble_sort.py
981
4.1875
4
import numpy as np import time #Bubble sort algorithm def bubble_sort(nums): # We set swapped to True so the loop looks runs at least once swapped = True while swapped: swapped = False for i in range(len(nums) - 1): if nums[i] > nums[i + 1]: # Swap the elements nums[i], nums[i + 1] = nums[i + 1], nums[i] # Set the flag to True so we'll loop again swapped = True # Verify it works random_list_of_nums = [5, 2, 1, 8, 4] #User input size arraySize = input("Please enter array size: ") #Generate numbers of size n numbers = np.arange(int(arraySize)) np.random.shuffle(numbers) print("Generated list of size " + str(arraySize) + " is:" + str(numbers)) #start script with parallel processes start_time = time.time() bubble_sort(numbers) print("\n\n Sorted Array: " + str(numbers)) #End of script print("\n\n Execution Time --- %s seconds ---" % (time.time() - start_time))
true
232896bfb010b367fdc7bbfc0c51b56d32208a1b
Amruthglr/PythonPrograms
/Day1/Program2.py
338
4.4375
4
age = int(input("Enter your AGE: ")) if age > 18 : print("You are eligible to vote") print("vote for your favourite candidate") else: print("You still need to wait for {} years".format(18-age)) # Another way to write if age < 18: print(f"You nedd still wait for {18-age} years") else: print("your eligible to vote")
false
0791a754b6620486dd07026672d3e27dd533da7f
helpmoeny/pythoncode
/Python_labs/lab09/warmup1.py
2,104
4.34375
4
## ## Demonstrate some of the operations of the Deck and Card classes ## import cards # Seed the random number generator to a specific value so every execution # of the program uses the same sequence of random numbers (for testing). import random random.seed( 25 ) # Create a deck of cards my_deck = cards.Deck() # Display the deck (unformatted) print( "===== initial deck =====" ) print( my_deck ) print() # Display the deck in 13 columns print( "===== initial deck =====" ) my_deck.pretty_print( column_max=13 ) # Shuffle the deck, then display it in 13 columns my_deck.shuffle() print( "===== shuffled deck =====" ) my_deck.pretty_print( column_max=13 ) # Deal first card from the deck and display it (and info about the deck) card1 = my_deck.deal() print( "First card dealt from the deck:", card1 ) print() print( "Card suit:", card1.get_suit() ) print( "Card rank:", card1.get_rank() ) print( "Card value:", card1.get_value() ) print() print( "Deck empty?", my_deck.is_empty() ) print( "Number of cards left in deck:", my_deck.cards_count() ) print() # Deal second card from the deck and display it (and info about the deck) card2 = my_deck.deal() print( "Second card dealt from the deck:", card2 ) print() print( "Card suit:", card2.get_suit() ) print( "Card rank:", card2.get_rank() ) print( "Card value:", card2.get_value() ) print() print( "Deck empty?", my_deck.is_empty() ) print( "Number of cards left in deck:", my_deck.cards_count() ) print() # Compare the two cards if card1.equal_suit( card2 ): print( card1, "same suit as", card2 ) else: print( card1, "and", card2, "are from different suits" ) if card1.equal_rank( card2 ): print( card1, "and", card2, "of equal rank" ) elif card1.get_rank() > card2.get_rank(): print( card1, "of higher rank than", card2 ) else: print( card2, "of higher rank than", card1 ) if card1.equal_value( card2 ): print( card1, "and", card2, "of equal value" ) elif card1.get_value() > card2.get_value(): print( card1, "of higher value than", card2 ) else: print( card2, "of higher value than", card1 )
true
2a5d3eb589bb0c4591382bf90700987406ff372d
julia-ediamond/python
/recap.py
728
4.34375
4
fruits = ["banana", "apple", "cherry"] print(fruits[-1]) fruits.append("pineapple") print(fruits) fruits.pop(0) print(fruits) digits = [1, 2, 3] decimal = [1, 2, 3] nested = [[1, 2, 3], ["hello"]] for item in fruits: print(item) for item in nested: print(item) for i in item: print(i) people = [ ["Alice", 25, "pink"], ["Bob", 33, "purple"], ["Anne", 18, "red"], ] vaccination = [] # Pseudo code # go through the list # check the age # if age 20 or older add this prson to vaccination list for person in people: # if person[1] >= 20: # first iteration ["Alice", 25, "pink"] person[0] - 0 because e need name to be added # vaccination.append(person[0]) print(vaccination)
false
4983ce5f51d32706025dead611acdbfdea92594c
Ramtrap/lpthw
/ex16.py
1,284
4.125
4
from sys import argv print "ex16.py\n" script, filename = argv print "We're going to erase %r." % filename print "If you don't want that, hit CTRL-C (^C)." print "If you do want that, hit RETURN." raw_input("?") print "Opening the file..." target = open(filename, 'w') print "Truncating the file. Goodbye!" target.truncate() print "Now I'm going to ask you for three lines." line1 = raw_input("line 1: ") line2 = raw_input("line 2: ") line3 = raw_input("line 3: ") print "I'm going to write these to the file." # target.write(line1) # target.write("\n") # target.write(line2) # target.write("\n") # target.write(line3) # target.write("\n") # Above is too long, this is truncated below target.write(line1 + "\n" + line2 + "\n" + line3 + "\n") print "Now let's take a look at what it says!" raw_input("Press ENTER to continue:") print "Here's your file %r:" % filename print "\n" target = open(filename, 'r') print target.read() print "And finally, we close it." target.close() # print "Type the filename again:" # file_again = raw_input("> ") # # txt_again = open(file_again) # # print txt_again.read() # txt.close # txt_again.close # print "Your files, %r and %r, have been closed." % (filename, file_again)
true
f441e2ebbcff6098d0a3e752550f770eb13ed708
brunolomba/exercicios_logica
/banco_itau_funcao.py
2,645
4.34375
4
# 341 - ITAU # Tamanha da Agência - 4 dígitos # Tamanha da conta - 5 dígitos # Exemplo: # Agência: 2545 # Conta: 023661 # Para Obter o DV, multiplica-se cada número da Agência e Conta em sua ordenação. Sequências PAR multiplica-se por 1 e ÍMPARES por 2. Se o número encontrado for maior que 9, soma-se as unidades da dezena. # Conta: AAAACCCCCD # Peso: 212121212 # Módulo (10) 39/10 = 9 ~ Resto = 9 ~ Dígito = 10 - 9 = 1 # OBS: se o RESTO = 0 ~ o Dígito é 0 def calcular_digito_correto(): # Entradas agencia = input('Digite a sua Agência.') conta = input('Digite a sua Conta.') # Junção e conversão da conta em inteiros. conta_completa = list(agencia + conta) conta_convertida = [int(valor) for valor in conta_completa] # Isolamento do digíto. digito_removido = remocao_digito(conta_convertida) # Atualização da conta. conta_convertida_sem_digito = conta_convertida # Multiplicação por 2 dos valores PARES. conta_multiplicada = multiplicao_valores(conta_convertida_sem_digito) # Conversão dos números de 2 digítos. conta_multiplicada_sem_2_digitos = conversao_numero_2_digitos(conta_multiplicada) # Cálculo do digíto. digito = calculo_digito(conta_multiplicada_sem_2_digitos) # Verificação do digíto. if digito == digito_removido: print(f'O digito da conta está correto, é: {digito}') #Exibição da verificação do digíto e da conta completa. exibicao(agencia, conta, digito) # Funções def remocao_digito(conta_convertida): digito_removido = [] if len(conta_convertida) == 10: digito_removido = conta_convertida.pop(9) return digito_removido def multiplicao_valores(conta_convertida_sem_digito): for i in range(len(conta_convertida_sem_digito)): if i % 2 == 0: conta_convertida_sem_digito[i] = conta_convertida_sem_digito[i] * 2 return conta_convertida_sem_digito def conversao_numero_2_digitos(conta_multiplicada): soma_unidade = 0 for i, numero in enumerate(conta_multiplicada): if numero > 9: for unidade in str(numero): soma_unidade += int(unidade) conta_multiplicada[i] = soma_unidade return conta_multiplicada def calculo_digito(conta_multiplicada_sem_2_digitos): soma = sum(conta_multiplicada_sem_2_digitos) resto = soma % 10 digito = 10 - resto return digito def exibicao(agencia, conta, digito): print(f'O número da conta é ag {agencia} / conta: {conta[:-1]}-{digito}') print('FIM DO PROGRAMA') if __name__ == '__main__': calcular_digito_correto()
false
8d38d519cc851e7e8203fcf9d057d6f2404fe07a
maxlauhi/cspy3
/1_7_2_mu_rec.py
246
4.40625
4
"""determine whether a number is odd or even by mutual recursion""" def is_even(n): if n == 0: return True else: return is_odd(n-1) def is_odd(n): if n == 0: return False else: return is_even(n-1)
false
ef3e1712df8cf28034c6ab2fc8d3fd46b4683783
shivsun/pythonappsources
/Exercises/Integers/accessing elements in the list with messages.py
1,294
4.4375
4
# -*- coding: utf-8 -*- """ Created on Sat Apr 25 21:09:17 2020 @author: bpoli """ #Accessing Elements in a List #Lists are ordered collections, so you can access any element in a list by #telling Python the position, or index, of the item desired. To access an element #in a list, write the name of the list followed by the index of the item #enclosed in square brackets. #For example, let’s pull out the first bicycle in the list bicycles: bikes = ["Royal Enfield", "Rajdoot", "Bajaj Chetak", "TVS Super"] name = 'kishore' name2 = 'vidya' name3 = 'Sam' print (bikes[3].title()) print (bikes[2]) print (bikes[-1]) message = "my first bike was " + bikes[2].title().upper() + "\t\nThen i bought" + bikes [0].lower() message = "I have 2 friends, and both" + name.title() + "," + name2.title() + "comes to school on the bikes" print (message + "They ride" + bikes[2]+ "," + bikes [0] + "respectively!") print (message) #Python has a special syntax for accessing the last element in a list. By asking #for the item at index -1, Python always returns the last item in the list: #Tvs Super #Bajaj Chetak #TVS Super #I have 2 friends, and bothKishore,Vidyacomes to school on the bikesThey rideBajaj Chetak,Royal Enfieldrespectively! #I have 2 friends, and bothKishore,Vidyacomes to school on the bikes
true
71fcf1b193e8f96abba78167d65180f062ca59a8
9car/IN1000-1
/oblig5/regnefunksjon.py
1,523
4.15625
4
def addisjon(tall1, tall2): tall1 = int(tall1) tall2 = int(tall2) # Regner ut summen av to tall return tall1 + tall2 print(addisjon(2, 9)) def subtraksjon(tall1, tall2): tall1 = int(tall1) tall2 = int(tall2) # Regner ut differansen return tall1 - tall2 assert subtraksjon(15, 10) == 5 assert subtraksjon(-15, 10) == -25 assert subtraksjon(-5, -5) == 0 def divisjon(tall1, tall2): tall1 = int(tall1) tall2 = int(tall2) # Regner ut kvotienten return tall1/tall2 assert divisjon(10, 5) == 2 assert divisjon(-10, 5) == -2 assert divisjon(-10, -5) == 2 def tommerTilCm(antallTommer): antallTommer = int(antallTommer) assert antallTommer > 0 # Regner ut hvor mange tommer det er i cm antallTommer = antallTommer * 2.54 return antallTommer # skriver ut et eksempel tall print(tommerTilCm(28)) print() # Prosedyre som ved bruk av input utfører regnestykker ved hjelp av funksjonene som er laget over def skrivBeregninger(): print("Utregninger:") tall1 = input("Skriv inn tall 1: ") tall2 = input("Skriv inn tall 2: ") print() print("Resultatet av summering: ", addisjon(tall1, tall2)) print("Resultatet av subtraksjon: ", subtraksjon(tall1, tall2)) print("Resultatet av divisjon: ", divisjon(tall1, tall2)) print() print("Konvertering fra tommer til cm:") tall = input("Skriv inn et tall: ") print("Resultat: ", tommerTilCm(tall)) # Kaller på prosedyren for at den skal kjøres skrivBeregninger()
false
0b111a4e7f476a46248db5680d9c0ab9d1aebc1d
miffymon/Python-Learning
/ex06.py
1,210
4.40625
4
#Python function pulls the value although its not announced anywhere else #string in a string 1 x = "There are %d types of people." % 10 #naming variable binary = "binary" #naming variable do_not = "don't" #assigning sentence to variable and calling other assigned variables #string in a string 2 y = "Those who know %s and those who %s." % (binary, do_not) #printing sentences by their variables print x print y #prints left side of sentence, calls a format and assignes variable which completes the rest of the sentence #string in a string 3 print "I said: %r" % x print "I also said: '%s'" % y #names variable hilarious to false hilarious = False #names variable to rep a sentence and include the ref to another variable to be named #string in a string 4 joke_evaluation = "Isn't that joke so funny?! %r" #calls upon 2 variables and puts them side-by-side #string in a string 5 print joke_evaluation % hilarious #calls variables rep by parts of a sentence w = "This is the left side of ..." e = "a string with a right side." #adds the first variable's value to the other in the same order #w+e makes a longer string because the two assigned sentences assigned to the variables are long print w + e
true
f533dddb9e2ba1ecb1d1a7b0a4a6ceb20976d022
ferisso/phytonexercises
/exercise7.py
893
4.21875
4
# 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. first_input = input("> ") dimensions = [int(x) for x in first_input.split(',')] numero_de_linhas = dimensions[0] numero_de_colunas = dimensions[1] matriz = [[0 for col in range(numero_de_colunas)] for row in range(numero_de_linhas)] for row in range(numero_de_linhas): for col in range(numero_de_colunas): matriz[row][col]= row*col print (matriz)
true
88b7c2b539778c54e9ba2072c44b163fda95e785
fis-jogos/2016-2
/python-101/06 funções.py
739
4.3125
4
# Definimos uma função que calcula a soma de todos os números pares até um # certo valor def soma_pares(x): y = 0 S = 0 while y <= x: S += y y += 2 return y # Agora podemos chamar nossa função e recuperar o valor passado para o "return" valor = soma_pares(100) print('A soma de todos os pares de 1 a 100 é: %s' % valor) # Exercícios # ---------- # # 1) Defina uma função que calcule o fatorial de um número. # # 2) Faça um programa que pergunte para o usuário o fatorial do número e depois # imprima o resultado. O programa deve utilizar a função definida # anteriormente e deve continuar perguntando por mais números até que o # usuário entre com o valor 0.
false
e9f846f5464649428ec8b7a6cdadc76cde91bd2f
sajjad0057/Practice-Python
/DS and Algorithm/Algorithmic_Tools/Devide-n-Conquer/marge_sort.py
1,092
4.15625
4
def marge_sort(a,b): marged_list = [] len_a , len_b = len(a),len(b) index_a, index_b = 0,0 #print(f'index_a , index_b = {index_a} , {index_b}') while index_a<len_a and index_b<len(b): if a[index_a]<b[index_b]: marged_list.append(a[index_a]) index_a +=1 else: marged_list.append(b[index_b]) index_b +=1 #print(f'index_a , index_b = {index_a} , {index_b}') if index_a<len(a): marged_list.extend(a[index_a:]) #print("****",marged_list) if index_b<len(b): marged_list.extend(b[index_b:]) #print("+++++", marged_list) return marged_list def marge(L): if len(L)<=1: return L mid = len(L)//2 left = marge(L[:mid]) right = marge(L[mid:]) return marge_sort(left,right) if __name__ == "__main__": L = [5, 6, 34, 32, 6, 8, 3, 2, 5, 7, 5, 55, 43, 3, 33, 4, 6, 78] sorted_list = marge(L) print("Original List : ", L) print("Sorted List : ", sorted_list)
false
5cf93df98db5fb6fe7444fffbbd1fa79559607cd
lavalio/ChamplainVRSpecialist-PythonAlgorithms
/Week4/Class1/Homework.py
1,080
4.25
4
#Create a list of numbers, randomly assigned. #Scan the list and display several values:The minimum, the maximum, count and average #Don`t use the “min”, “max”, “len ” and “sum” functions #1. Len : gives the number of elements in array. #2. Min, max: Gives the highest highestor lowest number in the array. #3. Sum: Adds all the numbers in array. import random mylist = [] for a in range(10): mylist.append(random.randint(1,101)) print(mylist) # Length of the list len = 0 for x in mylist: len += 1 print('len = ',len) # Sum of the list sum=0 for x in mylist: sum += x print('sum = ',sum) # Average of the list print('ave = ',sum/len) # Max Value maxValue = mylist[0] for y in mylist: if y > maxValue: maxValue = y print ('max = ',maxValue) # Min Value minValue = mylist[0] for y in mylist: if y < minValue: minValue = y print ('min = ',minValue) #print('len = ',len(mylist)) #print('max = ',max(mylist)) #print('min = ',min(mylist)) #print('sum = ',sum(mylist)) #print('ave = ',sum(mylist)/len(mylist))
true
f36cb9863dd96dbf1dfebcc837c8aec18de33967
LXXJONGEUN/Graduation_Project
/web/crypto/RSA2.py
1,398
4.125
4
def gcd(a, b): while b!=0: a, b = b, a%b return a def encrypt(pk, plaintext): key, n = pk cipher = [(ord(char) ** key) % n for char in plaintext] return cipher def decrypt(pk, ciphertext): key, n = pk plain = [chr((char ** key) % n) for char in ciphertext] return ''.join(plain) def get_private_key(e, tot): k=1 while (e*k)%tot != 1 or k == e: k+=1 return k def get_public_key(tot): e=2 while e<tot and gcd(e, tot) != 1: e += 1 return e # m = input("Enter the text to be encrypted:") # # Step 1. Choose two prime numbers # p = 13 # q = 23 # print("Two prime numbers(p and q) are:", str(p), "and", str(q)) # # Step 2. Compute n = pq which is the modulus of both the keys # n = p*q # print("n(p*q)=", str(p), "*", str(q), "=", str(n)) # # Step 3. Calculate totient # totient = (p-1)*(q-1) # print("(p-1)*(q-1)=", str(totient)) # # Step 4. Find public key e # e = get_public_key(totient) # print("Public key(n, e):("+str(n)+","+str(e)+")") # # Step 5. Find private key d # d = get_private_key(e, totient) # print("Private key(n, d):("+str(n)+","+str(d)+")") # # Step 6.Encrypt message # encrypted_msg = encrypt((e,n), m) # print(encrypted_msg) # print('Encrypted Message:', ''.join(map(lambda x: str(x), encrypted_msg))) # # Step 7.Decrypt message # print('Decrypted Message:', decrypt((d,n),encrypted_msg))
false
e8cf2f63f38c417981c670689bbb649ccb1f296d
annikaslund/python_practice
/python-fundamentals/04-number_compare/number_compare.py
301
4.15625
4
def number_compare(num1, num2): """ takes in two numbers and returns a string indicating how the numbers compare to each other. """ if num1 > num2: return "First is greater" elif num2 > num1: return "Second is greater" else: return "Numbers are equal"
true
91e08c304bdf2dcade4f00ad513711d7cadde116
annikaslund/python_practice
/python-fundamentals/18-sum_even_values/sum_even_values.py
235
4.15625
4
def sum_even_values(li): """ sums even values in list and returns sum """ total = 0 for num in li: if num % 2 == 0: total += num return total # return sum([num for num in li if num % 2 == 0])
true
4a5ffb428059845f0761201c602942bb964f0e55
19doughertyjoseph/josephdougherty-python
/TurtleProject/Turtle Project.py
939
4.125
4
import turtle turtle.setup(width=750, height=750) pen = turtle.Pen() pen.speed(200) black_color = (0.0, 0.0, 0.0) white_color = (1.0, 1.0, 1.0) red_color = (1.0, 0.0, 0.0) green_color = (0.0, 1.0, 0.0) blue_color = (0.0, 0.0, 1.0) def basicLine(): moveTo(-50, 0) pen.forward(100) #The origin on the screen is (0,0) def basicSquare(): pen.pencolor(blue_color) moveTo(-100, -100) for x in range(4): pen.forward(200) pen.left(90) def basicCircle(): pen.pencolor(red_color) moveTo(0, -300) pen.circle(300) def basicTriangle(): pen.pencolor('#33cc8c') moveTo(-200, -150) for x in range(3): pen.forward(400) pen.left(120) def moveTo(x, y): pen.penup() pen.setpos(x, y) pen.pendown() #Between drawings we have to pick up the pen and move it to the desired location basicLine() basicSquare() basicCircle() basicTriangle() turtle.exitonclick()
true
0ed3044556e7faa1464a480dbe0550b2a22e20c5
leobyeon/holbertonschool-higher_level_programming
/0x0B-python-input_output/4-append_write.py
360
4.28125
4
#!/usr/bin/python3 def append_write(filename="", text=""): """ appends a string at the end of a text file and returns the number of chars added """ charCount = 0 with open(filename, "a+", encoding="utf-8") as myFile: for i in text: charCount += 1 myFile.write(i) myFile.close() return charCount
true
828a52fcf979bb4c8dc3793babbfcf41a71efa2b
Nipuncp/lyceaum
/lpthw/ex3.py
479
4.25
4
print ("I'll now count my chickens") print ("Hens:", 25 +30 / 6) print ("Roosters", 100-25 *3%4) print ("I'll now count the eggs:") print (3 +2 + 1 - 5 + 4 % 2-1 % 4 + 6) print ("Is it true that 3 + 2 < 5 - 7") print (3 + 2 < 5 -7) print ("What is 3 + 2", 3 + 2) print ("What is 5 - 7", 5 - 7) print ("THat is why, it is false") print ("HOw about some more?") print ("Is it greater?", 5 >= -2) print ("Is it greater or equal?", 5 >= -2) print ("Is it lesser or equal",5 <= -2)
true
fefe99ae80decc1c40885d81430a651ddbcd3541
anupam-newgen/my-python-doodling
/calculator.py
281
4.15625
4
print('Add 2 with 2 = ', (2 + 2)) print('Subtract 2 from 2 = ', (2 - 2)) print('Multiply 2 with 2 = ', (2 * 2)) print('2 raise to the power 2 = ', (2 ** 2)) print('2 divide by 2 = ', (2 / 2)) # This is a comment. # You can use above concept to solve complex equations as well.
true
1fec6ac5c98bcac8bff0fc97d37cf7846021a0b8
MathBosco/exPython
/Ex014.py
293
4.375
4
#Enunciado: # Escreva um programa que converta uma temperatura digitando em graus Celsius e converta para graus Fahrenheit. celsius = float(input('Insira a temperatura em grau Celsius: ')) fahrenheit = (celsius * 9/5) + 32 print('A temperatura em Fahrenheit é: {} °F'.format(fahrenheit))
false
4df2e2270df04452ca0403b08547f2bebad70504
selva86/python
/exercises/concept/guidos-gorgeous-lasagna/.meta/exemplar.py
1,640
4.28125
4
# time the lasagna should be in the oven according to the cookbook. EXPECTED_BAKE_TIME = 40 PREPARATION_TIME = 2 def bake_time_remaining(elapsed_bake_time): """Calculate the bake time remaining. :param elapsed_bake_time: int baking time already elapsed :return: int remaining bake time (in minutes) derived from 'EXPECTED_BAKE_TIME' Function that takes the actual minutes the lasagna has been in the oven as an argument and returns how many minutes the lasagna still needs to bake based on the `EXPECTED_BAKE_TIME`. """ return EXPECTED_BAKE_TIME - elapsed_bake_time def preparation_time_in_minutes(number_of_layers): """Calculate the preparation time. :param number_of_layers: int the number of lasagna layers made :return: int amount of prep time (in minutes), based on 2 minutes per layer added This function takes an integer representing the number of layers added to the dish, calculating preparation time using a time of 2 minutes per layer added. """ return number_of_layers * PREPARATION_TIME def elapsed_time_in_minutes(number_of_layers, elapsed_bake_time): """Calculate the elapsed time. :param number_of_layers: int the number of layers in the lasagna :param elapsed_bake_time: int elapsed cooking time :return: int total time elapsed (in in minutes) preparing and cooking This function takes two integers representing the number of lasagna layers and the time already spent baking and calculates the total elapsed minutes spent cooking the lasagna. """ return preparation_time_in_minutes(number_of_layers) + elapsed_bake_time
true
0a7def488ed51a9d0b3e3a1a5ccc8a29efa89a23
selva86/python
/exercises/concept/little-sisters-vocab/.meta/exemplar.py
1,648
4.3125
4
def add_prefix_un(word): """ :param word: str of a root word :return: str of root word with un prefix This function takes `word` as a parameter and returns a new word with an 'un' prefix. """ return 'un' + word def make_word_groups(vocab_words): """ :param vocab_words: list of vocabulary words with a prefix. :return: str of prefix followed by vocabulary words with prefix applied, separated by ' :: '. This function takes a `vocab_words` list and returns a string with the prefix and the words with prefix applied, separated by ' :: '. """ prefix = vocab_words[0] joiner = ' :: ' + prefix return joiner.join(vocab_words) def remove_suffix_ness(word): """ :param word: str of word to remove suffix from. :return: str of word with suffix removed & spelling adjusted. This function takes in a word and returns the base word with `ness` removed. """ word = word[:-4] if word[-1] == 'i': word = word[:-1] + 'y' return word def noun_to_verb(sentence, index): """ :param sentence: str that uses the word in sentence :param index: index of the word to remove and transform :return: str word that changes the extracted adjective to a verb. A function takes a `sentence` using the vocabulary word, and the `index` of the word once that sentence is split apart. The function should return the extracted adjective as a verb. """ word = sentence.split()[index] if word[-1] == '.': word = word[:-1] + 'en' else: word = word + 'en' return word
true
c2f079ea8d6387e8b64395e0d45271c9c00ee2e6
douglasmsi/sourcePython
/par.py
319
4.125
4
#!/usr/bin/python3 #!/usr/bin/python3 #Ler numero e verificar se ele e par ou impar # e adicionar ele em uma lista com o Resultado #[2, 'par'] #[3,'impar'] # entrada = int(input('Numero: ')) lista = [] if (entrada%2) == 0: lista.insert(0,[entrada,'Par']) else: lista.insert(0,[entrada,'Impar']) print(lista)
false
3db5a554acc92051d4ec7a544a4c922fcad49309
PradipH31/Python-Crash-Course
/Chapter_9_Classes/C2_Inheritance.py
1,094
4.5625
5
#!./ENV/bin/python # ---------------------------------------------------------------- # Inheritance class Car(): """Class for a car""" def __init__(self, model, year): """Initialize the car""" self.model = model self.year = year def get_desc_name(self): """Get the descriptive name of the car""" return (str(self.year) + self.model) # Child class is initialized by super().__init__(paramters(without self)) # Child class iherits the methods from the parent. # Override the parent methods class ElectricCar(Car): """Class from car class""" def __init__(self, model, year, batt_size): """initialize the electric car""" super().__init__(model, year) self.batt_size = batt_size def get_batt(self): """returns the battery""" return self.batt_size def get_desc_name(self): """Get the descriptive name of the car""" return ("Electric " + str(self.year) + self.model) my_tesla = ElectricCar("Audi", 1990, 90) print(my_tesla.get_desc_name()) print(my_tesla.get_batt())
true
c684cf0f8d15e4e684b2668eaf0bfadd8b30306a
PradipH31/Python-Crash-Course
/Chapter_9_Classes/C1_Book.py
959
4.4375
4
#!./ENV/bin/python # ---------------------------------------------------------------- # # Classes class Book(): """Class for a book""" def __init__(self, name, year): """Initialize the book with name and year""" self.name = name self.year = year def get_name(self): """Returns the name of the book""" return self.name my_book = Book("NOSP", "2012") print(my_book.get_name()) class Car(): """Car class""" def __init__(self, name, year): self.name = name self.year = year self.met_traveled = 0 def set_met(self, m): if m > self.met_traveled: self.met_traveled = m def upd_met(self, m): self.met_traveled += m my_car = Car("Toyota", "1999") # Modifying attributes of an object directly through the variable my_car.met_traveled = 20 # through a method my_car.set_met(11) # adding new value to the current value my_car.upd_met(19)
true
3b2023ce61bfa403f7d4f4b340e54b2140614026
yulya2787/python_advanced
/less2/#2.py
1,011
4.21875
4
'''Создать класс магазина. Конструктор должен инициализировать значения: «Название магазина» и «Количество проданных товаров». Реализовать методы объекта, которые будут увеличивать кол-во проданных товаров, и реализовать вывод значения переменной класса, которая будет хранить общее количество товаров проданных всеми магазинами.''' class Market: total = 0 def __init__(self, name, quontity_of_goods): self._name = name self.quontity_of_goods = quontity_of_goods Market.total += quontity_of_goods ATB = Market('ATB', 100) ATB.quontity_of_goods = 100 Novus = Market('Novus', 150) Novus.quontity_of_goods = 150 print(Market.total) print(ATB.quontity_of_goods) print(Novus.quontity_of_goods)
false
9a76041b4f7465fc6061ed4ee3efb65899a258db
alexugalek/tasks_solved_via_python
/HW1/upper_lower_symbols.py
374
4.46875
4
# Task - Count all Upper latin chars and Lower latin chars in the string test_string = input('Enter string: ') lower_chars = upper_chars = 0 for char in test_string: if 'a' <= char <= 'z': lower_chars += 1 elif 'A' <= char <= 'Z': upper_chars += 1 print(f'Numbers of lower chars is: {lower_chars}') print(f'Numbers of upper chars is: {upper_chars}')
true
fea598032ae2a1c7676e6b0286d2fae1362bdfa3
alexugalek/tasks_solved_via_python
/HW1/task_5.py
418
4.40625
4
def add_binary(a, b): """Instructions Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition. The binary number returned should be a string. """ return bin(a + b)[2:] if __name__ == '__main__': a = int(input('Enter 1 number: ')) b = int(input('Enter 2 number: ')) print(add_binary(a, b))
true
6889e39e73935e704d91c750b3a13edb36133afc
alexugalek/tasks_solved_via_python
/HW1/task_23.py
1,327
4.4375
4
def longest_slide_down(pyramid): """Instructions Imagine that you have a pyramid built of numbers, like this one here: 3 7 4 2 4 6 8 5 9 3 Here comes the task... Let's say that the 'slide down' is a sum of consecutive numbers from the top to the bottom of the pyramid. As you can see, the longest 'slide down' is 3 + 7 + 4 + 9 = 23 """ for line in range(len(pyramid) - 2, -1, -1): for column in range(len(pyramid[line])): pyramid[line][column] += max(pyramid[line + 1][column], pyramid[line + 1][column + 1]) return pyramid[0][0] print(longest_slide_down([[3], [7, 4], [2, 4, 6], [8, 5, 9, 3]])) # 23 print(longest_slide_down([ [75], [95, 64], [17, 47, 82], [18, 35, 87, 10], [20, 4, 82, 47, 65], [19, 1, 23, 75, 3, 34], [88, 2, 77, 73, 7, 63, 67], [99, 65, 4, 28, 6, 16, 70, 92], [41, 41, 26, 56, 83, 40, 80, 70, 33], [41, 48, 72, 33, 47, 32, 37, 16, 94, 29], [53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14], [70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57], [91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48], [63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31], [4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23], ])) # 1074
true
acdcddc6a6e17466c36f1ad4ca46efd015689153
alexugalek/tasks_solved_via_python
/HW1/task_53.py
750
4.125
4
def longest_palindromic(a): """The longest palindromic""" result = '' for i in range(len(a)): for j in range(i, len(a)): tmp_val = a[i:j + 1:1] if tmp_val == tmp_val[::-1] and len(a[i:j + 1:1]) > len(result): result = a[i:j + 1:1] return result if __name__ == '__main__': print("Example:") print(longest_palindromic('abacada')) # These "asserts" are used for self-checking and not for an auto-testing assert longest_palindromic('abc') == 'a' assert longest_palindromic('abacada') == 'aba' assert longest_palindromic('artrartrt') == 'rtrartr' assert longest_palindromic('aaaaa') == 'aaaaa' print("Coding complete? Click 'Check' to earn cool rewards!")
false
a5306511c39e1a2bd0e3077f86df25e6e47f2dc6
firozsujan/pythonBasics
/Lists.py
1,629
4.1875
4
# Task 9 # HakarRank # Lists # https://www.hackerrank.com/challenges/python-lists/problem def proceessStatement(insertStatement, list): if insertStatement[0] == 'insert': return insert(insertStatement, list) elif insertStatement[0] == 'print': return printList(insertStatement, list) elif insertStatement[0] == 'remove': return remove(insertStatement, list) elif insertStatement[0] == 'append': return append(insertStatement, list) elif insertStatement[0] == 'sort': return sort(insertStatement, list) elif insertStatement[0] == 'pop': return pop(insertStatement, list) elif insertStatement[0] == 'reverse': return reverse(insertStatement, list) def insert(insertStatement, list): position = int(insertStatement[1]) insert = int(insertStatement[2]) updatedList = [] updatedList = list[:position] + [insert] + list[position:] return updatedList def printList(insertStatement, list): print(list) return list def remove(insertStatement, list): list.remove(int(insertStatement[1])) return list def append(insertStatement, list): list.append(int(insertStatement[1])) return list def sort(insertStatement, list): list.sort() return list def pop(insertStatement, list): list.pop() return list def reverse(insertStatement, list): list.reverse() return list if __name__ == '__main__': N = int(input()) list = [] for i in range(N): insertStatement = [] insertStatement = input().split(' ') list = proceessStatement(insertStatement, list)
true
86b3488e679b6e34d43d0be6e219a6f01761b3e1
firozsujan/pythonBasics
/StringFormatting.py
655
4.125
4
# Task # HackerRank # String Formatting # https://www.hackerrank.com/challenges/python-string-formatting/problem def print_formatted(number): width = len(bin(number)[1:]) printString = '' for i in range(1, number+1): for base in 'doXb': if base == 'd': width = len(bin(number)[2:]) else : width = len(bin(number)[1:]) printString = printString + "{:{width}{base}}".format(i, base=base, width=width) printString = printString + '\n' print(printString) if __name__ == '__main__': n = int(input()) print_formatted(n)
true
ce7a7f3362652f37bbec4c976a02310a007e9c3d
vinikuttan/smallcodes
/dict_normalizer.py
1,275
4.125
4
#!/usr/bin/python __author__ = 'vineesh' def merge_nested_dict(mydict): """ flattening nested dict """ if isinstance(mydict, dict): result = mydict.copy() for each in mydict: if isinstance(mydict[each], dict): result[each] = mydict[each].keys() result.update(merge_nested_dict(mydict[each])) else: result[each] = mydict[each] return result else: return mydict def merge_two_dicts(left, right): """ replacing left dictionary with updated right dictionary """ if isinstance(left, dict) and isinstance(right, dict): result = left.copy() for each in right: if each in left: result[each] = merge_two_dicts(left[each], right[each]) else: result[each] = right[each] return result else: return right if __name__=="__main__": input_dict = {'a':1, 'b':{'c':2, 'e': 4}, 'd': '3'} left_dict = {'a':1, 'b': 2, 'c':{'d':3, 'e':4}} right_dict = {'a':1, 'b': 2, 'c': 3} # merging nested python dictionaries print merge_nested_dict(input_dict) # deep merging two dictionaries print merge_two_dicts(left_dict, right_dict)
false