blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
43ccb8b12668d73c52ce2a05bf5084d97cf74ebf
mariascervino/basics
/Algoritimos/ChildrenHope.py
987
4.1875
4
# Fazer uma doação to o criança esperanca, incluindo a opcao de um valor escolhido pelo usuario print ("------------------------------") print (" WELCOME TO CHILDREN HOPE ") print ("------------------------------") print (" THANK YOU FOR DONATING! ") print ("[1] to donate R$10") print ("[2] to donate R$25") print ("[3] to donate R$50") print ("[4] to donate other values") print ("[5] to cancel") D = int(input("Insert your opition: ")) if ( D == 1 ): print("You donated R$10") print("We appreciate your donation") elif( D == 2 ): print("You donated R$25") print("We appreciate your donation") elif( D == 3 ): print("You donated R$50") print("We appreciate your donation!") elif( D == 4 ): D = int(input("How much would you like to donate? ")) print ("You donated R$", D) print("We appreciate your donation") elif( D == 5 ): print("The operation was canceled") else: print("Invalid Character")
false
15dc717ca6ab36098948ad026d04c3095a1ddfcd
greenstripes4/CodeWars
/ipadress.py
2,063
4.40625
4
""" Task An IP address contains four numbers(0-255) and separated by dots. It can be converted to a number by this way: Given a string s represents a number or an IP address. Your task is to convert it to another representation(number to IP address or IP address to number). You can assume that all inputs are valid. Example Example IP address: 10.0.3.193 Convert each number to a 8-bit binary string (may needs to pad leading zeros to the left side): 10 --> 00001010 0 --> 00000000 3 --> 00000011 193 --> 11000001 Combine these four strings: 00001010 00000000 00000011 11000001 and then convert them to a decimal number: 167773121 Input/Output [input] string s A number or IP address in string format. [output] a string A converted number or IP address in string format. Example For s = "10.0.3.193", the output should be "167773121". For s = "167969729", the output should be "10.3.3.193". """ def numberAndIPaddress2(s): if "." in s: lst=s.split(".") result=0 for i in lst: result = (result << 8) + int(i) return str(result) else: input = int(s) results = '' for i in range(4): results = str(input % 256) + '.' + results input = input >> 8 return results[:-1] def numberAndIPaddress(s): if "." in s: lst=s.split(".") binary_list = [] for i in lst: binary_number = str(bin(int(i)))[2:] padding = 8-len(binary_number) eight_bit = "0"*padding + binary_number binary_list.append(eight_bit) joined = ''.join(x for x in binary_list) return str(int(joined,2)) else: binary_number = str(bin(int(s)))[2:] padding = 32 - len(binary_number) eight_bit = "0"*padding + binary_number lst = [eight_bit[x:x+8] for x in range(0, len(eight_bit), 8)] new_lst = [] for i in lst: new_lst.append(str(int(i,2))) return '.'.join(z for z in new_lst) print(numberAndIPaddress2("10.0.3.193"))
true
9f77a05bef30a373aa6099a9b4ee181fc3d51b1e
greenstripes4/CodeWars
/DataReverse.py
694
4.40625
4
""" A stream of data is received and needs to be reversed. Each segment is 8 bits long, meaning the order of these segments needs to be reversed, for example: 11111111 00000000 00001111 10101010 (byte1) (byte2) (byte3) (byte4) should become: 10101010 00001111 00000000 11111111 (byte4) (byte3) (byte2) (byte1) The total number of bits will always be a multiple of 8. The data is given in an array as such: [1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0] """ def data_reverse(data): if len(data) == 0: return [] return data[-8:] + data_reverse(data[0:len(data)-8]) print(data_reverse([0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1]))
true
0ad5b8175ba2ae7b9d4e563e6ecc1ad591232314
greenstripes4/CodeWars
/digital_root.py
522
4.21875
4
""" A digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has two digits, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers. Here's how it works: digital_root(16) => 1 + 6 => 7 """ def digital_root(n): if n<10: return n sum_of_digits=0 while n != 0: sum_of_digits += n%10 n=int(n/10) return digital_root(sum_of_digits) print(digital_root(16))
true
06f8cd83c2cb510474d0788e473731b5cfc9b40e
carlos-hereee/Intro-Python-I
/src/05_lists.py
858
4.1875
4
# For the exercise, look up the methods and functions that are available for use # with Python lists. x = [1, 2, 3] y = [8, 9, 10] # For the following, DO NOT USE AN ASSIGNMENT (=). # Change x so that it is [1, 2, 3, 4] # YOUR CODE HERE x.append(4) print("\n Adds 4 to the end: ", x) # Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10] # YOUR CODE HERE print("\n Combines array x and y: ", x + y) # Change x so that it is [1, 2, 3, 4, 9, 10] # YOUR CODE HERE x.extend((8, 9, 10)) print("\n add 8, 9, 10 to array x: ", x) # Change x so that it is [1, 2, 3, 4, 9, 99, 10] # YOUR CODE HERE x.insert(6, 99) print("\n Add 99 in array x: ", x) # Print the length of list x # YOUR CODE HERE print("\n Length of list: ", len(x)) # Print all the values in x multiplied by 1000 # YOUR CODE HERE n = [i * 1000 for i in x] print("\n Multiplied by 1000", n)
true
82d9cd4a618eb4d035049bf4570942c7ca1cbe43
millerg09/python_lesson
/ex20.py
1,914
4.1875
4
# imports the `argv` module from sys from sys import argv # sets up the script name and input_file as script argument variables script, input_file = argv # creates the first function `print_all`, which accepts one input variable `f` def print_all(f): # the function is designed to use the read function with no extra parameters print f.read() # creates the second function "rewind", which accepts one input variable `f` def rewind(f): # the function goes back to the first byte of the input file `f` f.seek(0) # creates the third function "print a line", which accepts two input variables def print_a_line(line_count, f): # this function prints `line_count` and a readline function from `f` print line_count, f.readline() # opens the input file from the script argument and assigns opened file to a variable current_file = open(input_file) # prints a string decribing what we are about to do print "First let's print the whole file:\n" # uses the function `print_all` and passes one input variable in `current file` # print all will go ahead and print out the "read" input->current file print_all(current_file) # prints a string describing what we are about to do print "Now let's rewind, kind of like a tape." # calls the `rewind` function and passes in one input variable rewind(current_file) # prints a string describing what we are about to do print "Let's print three lines:" # creates a variable and assigns an integer value of 1 current_line = 1 # calls the `print a line` function with two input variables: 1, "input file" print_a_line(current_line, current_file) # recursively increments 1 to the current_line variable and the prints the line current_line = current_line + 1 print_a_line(current_line, current_file) # recursively increments 1 to the current_line variable and the prints the line current_line = current_line + 1 print_a_line(current_line, current_file)
true
8c23df48951b0371225a507dffa4fb3198290d9d
utk09/BeginningPython
/2_Variables/2_variables.py
534
4.15625
4
# Variables are like Boxes. Their name remains the same, but values can be changed over the time. number1 = 7 number2 = 4 print(number1 * number2) # insted of values, we now write variables here. print(number1 - number2 * 3) alpha = number1 / number2 beta = number1 // number2 print(type(alpha)) # Prints type of variable print(type(beta)) # Now, let us change the value of variable 'number1' number1 = 32 print(number1 * number2) # Task1: Try printing the values in a more informative format, as done in "1_Syntaxes.py" file.
true
9297906d5a60f20b9081d2a280e5fc91646c1ec0
utk09/BeginningPython
/8_MiniPrograms/14_Recursion.py
1,215
4.375
4
# We will find the sequence of Fibonacci Numbers using recursion. # Recursive function is a function that calls itself, sort of like loop. # Recursion works like loop but sometimes it makes more sense to use recursion than loop. # You can convert any loop to recursion. ... Recursive function is called by some external code. # If the base condition is met then the program do something meaningful and exits. # Let us use recursion to find fibonacci numbers. # Fibonacci numbers are: 0, 1, 1, 2, 3, 5, 8, 13, 21.... def fibonacci(n): if n == 0 or n == 1: # this is the base condition -- it is the index value of the above sequence. return n # so, if user wants fibonacci number at index 0, it'll return 0 and if at index 1, it'll return 1 return fibonacci(n - 2) + fibonacci(n - 1) # but if user wants fibonacci number at index 4, it'll add # the fibonacci number at index (n-2) i.e. (4-2) and index (n-1) i.e. (4-1) # so, it'll return 2nd position element i.e. 1 and 3rd position element i.e. 2 and then it's sum i.e. 3 n = int(input("Enter the number of Fibonacci numbers you want: ")) for i in range(n): # we print all the numbers in range that user inputs print(fibonacci(i))
true
62bd1fc8066ef085eee494f2d5277a7f68437f81
cugis2019dc/cugis2019dc-Najarie
/Code Day_3.py
2,818
4.1875
4
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import plotly dir(plotly) print("My name is Najarie") print("Hello how are you doing") print(5*2) print(5/2) print(5-2) print(5**2) print((8/9)*3) print("5*2") def multiply(a,b): multiply = a*b print(multiply) multiply(3,4) def sum(a,b,c): sum = a+b+c print(sum) sum(12,3,5) def area(a,base,height): area = a*base*height print(area) area(1/2,6,3) def area(base,height): area = (0.5)*base*height print('The area of the triangle with the base of',base,'and a height of',height, 'is',area,) area(6,3) def cadburyBox(w,d,m): print("There is", m, ",", d, "," , w, "in the box") cadburyBox("White Chocolate", "Dark Chocolate", "Milk Chocolate") Cadbury1="Milk Chocolate" Cadbury2="Dark Chocolate" Cadbury3="White Chocolate" print("There is",Cadbury1,",",Cadbury2,",", "and",Cadbury3, "in the box.") name= input("please enter your name") print("your name is", name) age= input ("please enter your age") print("Thank you. You entered ", age) ageint = int(age) ageint import math dir(math) math.pow(6,15) def cubic(x): cubic= math.pow(x,.33) print("The Cubic root of" ,x, "is" ,cubic,) cubic(8) x cubic= input("Please enter your variable") v= int(cubic) cubic2= math.pow(v,.33) print("This is your answer" ,cubic2,) def cadburyBox(w,d,m): print("There is", m, ",", d, "," , w, "in the box") cadburyBox("White Chocolate", "Dark Chocolate", "Milk Chocolate") Cadbury1= "White Chocolate" Cadbury2= "Dark Chocolate" Cadbury3= "Milk Chocolate" print("There is" , Cadbury1, "," ,Cadbury2, ", and" ,Cadbury3, "bars in the box.") Cadbury1= "8 White Chocolate" Cadbury2= "5 Dark Chocolate" Cadbury3= "6 Milk Chocolate" print("There are" , Cadbury1, "," ,Cadbury2, ", and" ,Cadbury3, "bars in the box.") name= input("please enter your name") age= input ("please enter your age") print("Your name is",name, "and you are",age, "years old.") studentage= {"Steve":32,"Lia":28,"Vin":45,"Katie":38} studentage studentgender = {"Steve":M,"Lia":F,"Vin":M,"Katie":F} Studentlist=[["Steve" ,32, "M"],["Lia" ,28, "F"],["Vin" ,45, "M"],["Katie" ,38, "F"]] Studentlist student =[studentage,studentgender] student import pandas dir(pandas) studentdf = pandas.DataFrame(Studentlist,columns=("name","age","gender")) studentdf chocolate = [["Milk",5],["Dark",8],["White",3]] chocodf = pandas.DataFrame(chocolate, columns=("Chocolate","Quantity") print(chocodf)
true
df639a127a816b127c320bfd00ed5b68b7d9ae27
amahfouz/tweet-analyser
/count_freq.py
784
4.21875
4
''' Counts word frequencies in a text file. Words to be counted are read from a file. ''' import codecs import sys import re import time def count_occurrences(f, w): count = 0 for line in f: index = 0 words = re.split(r'[\n\r\t-_ #]', line) for word in words: if (word == w): count = count + 1 return count ''' Main. Iterate over all words and find each in the file ''' start = time.time() reload(sys) sys.setdefaultencoding('utf8') if len(sys.argv) < 2: print "Please provide filename as a command argument" sys.exit(100) word_file = codecs.open("words.txt", 'r', 'utf-8') for word in word_file: f = open(sys.argv[1]) print word.rstrip(), "\t\t", count_occurrences(f, word.rstrip()) f.close() end = time.time() print end - start, " seconds"
true
5588d38839089141af8036a5f953c48640166fc1
whyfzhou/intropython
/list.py
1,895
4.3125
4
# --------------------------------------------------------------------- # 列表 list li = [2, 4] print('Repeating {} {} times: {}'.format(li, 3, li * 3)) # 重复三次 li.append(1) # 添加元素 li.append(3) li.extend([10, 20]) # 扩展列表 print('The list: {}'.format(li)) print('List {} contains {} elements'.format(li, len(li))) print() # 列表的索引 indexing print('The first element is indexed by 0: {}'.format(li[0])) print('The second element is indexed by 1: {}'.format(li[1])) print('The last element is indexed by -1: {}'.format(li[-1])) print('The second to last element is indexed by -2: {}'.format(li[-2])) print() del li[-1] # 删除最后一个元素 # 查找 find the index m = 3 if m in li: print('The index of {} is {}'.format(m, li.index(m))) else: print('{} is not in {}.'.format(m, li.index(m))) print() # 切片 slicing print('The first half: {}'.format(li[:len(li) // 2])) print('The second half: {}'.format(li[len(li) // 2:])) print('All even indices: {}'.format(li[::2])) print('All odd indices: {}'.format(li[1::2])) print('Reverse order: {}'.format(li[::-1])) print() # 排序 sort print('A sorted copy of list {} is {}'.format(li, sorted(li))) print() # --------------------------------------------------------------------- # 复制 copy li1 = li li2 = li.copy() li3 = li[::] li[0] = -100 li2[1] = -100 print('The original list: {}'.format(li)) print('The one assigned by reference: {}'.format(li1)) print('The one assigned by calling `copy` member: {}'.format(li2)) print('The one assigned by indexing all: {}'.format(li3)) print() # --------------------------------------------------------------------- # 列表推导 list comprehension r = range(20) # r 是一个 range 对象 print([x + 1 for x in r]) # 遍历 r,各个元素 +1,生成一个新列表 print([x ** 2 for x in r if x % 2 == 1]) # r 中所有奇数的平方
false
ea4bb376bc5c3f27b6020fe3cbb8ec7b07183251
erikgust2/OpenAI-Feedback-Testing
/dataset/Fahrenheit/Fahrenheit_functionality.py
344
4.25
4
def celsius(): fahrenheit = float(input("Enter a temperature in Fahrenheit: ")) celsius = ((fahrenheit - 32) * 5) / 9 print("The equivalent temperature in Celsius is", celsius) if(celsius > 32): print("It's hot!") elif(celsius < 0): print("It's cold!") else: print("It's just right!") celsius()
true
705173744a8f66d1d65cf99066aad1e8831b7089
erikgust2/OpenAI-Feedback-Testing
/dataset/AgeName/AgeName_syntax.py
657
4.21875
4
def greet_user(): # Get the user's name and age name = input("What's your name? ") age = int(input("How old are you? ")) # Print a greeting message with the user's name and age print(f"Hello, {name}! You are {age} years old.") # Check the user's age and print a message based on it if age < 18 print("You're underage!") elif age >= 66: print("You're old!") years_retired = age - 66 print(f"You've been retired for {years_retired} years.") else: years_left = 66 - age print(f"You have {years_left} years left until retirement.") print("You are an adult.")
true
a3e2f2ad2ea860a442caa073587ee156bc1a1f69
MFTI-winter-20-21/DIVINA_2020
/09 palindrom 2.0.py
726
4.34375
4
""" Пользователь за один инпут вводит вам разные слова программа разделяет их на отдельные слова и проверяет, является ли слово палиндромом Если является - выводит его нам ВВЕДЕНО: шалаш, казак, ракета ВЫВОД: шалаш, казак """ words = input("Введите слова: ").lower().split() palindroms = [] for word in words: if word == word[::-1]: # print(word) palindroms.append(word) if len(palindroms)>0: print('ПАЛИНДРОМЫ: ', ", ".join(palindroms)) else: print("Тут нет палиндромов")
false
b17474f526fe2477e64276c73297618417b6c334
Shriukan33/Skyjo
/src/cards.py
1,460
4.15625
4
from random import shuffle class Deck: """ Deck class handles original deck building and drawing action. """ def __init__(self): self.cards = [] # Deck is represented with a list of numbers from -2 to 12 self.minus_two = 5 # Number of minus two in build self.zeroes = 15 # Number of zeroes in build self.other_cards = 10 # Number of -1 and 1->12 in build self._build() # Populates self.cards def _build(self): """ Adds cards as defined in properties to the deck and shuffles it. """ for _ in range(self.minus_two): self.cards.append(-2) for _ in range(self.zeroes): self.cards.append(0) for _ in range(self.other_cards): self.cards.append(-1) for k in range(1, 13): self.cards.append(k) shuffle(self.cards) def draw(self): return self.cards.pop() class Discard: def __init__(self): self.cards = [] self._build() def _build(self): """ At game initialization, the discard is composed of the first card of the deck Deck has to be initialized first """ self.cards.append(deck.draw()) def show_top_card(self): """ Top card of discard is visible at any time by players """ return self.cards[-1] deck = Deck() discard = Discard()
true
d823f2c91294dcc305f292d808f71707d95de09d
ntnshrm87/Python_Quest
/Prob6.py
588
4.125
4
# Prob 6 list_a = ['Raman', 'Bose', 'Bhatt', 'Modi'] # Case 1 print(list_a[10:]) # Case 2 try: print(list_a[10]) except IndexError as e: print("Error is: ", e) # Case 3 print(list_a[:-10]) # Solution: # [] # Error is: list index out of range # [] # Reference: # Its really a tricky one # The problem is if you are accessing a particular value # whose index is out of range from the list, error will be # shown. However, if you are trying to access the list slice # in either lef or right side exceeding the number of members # in the list will simply result in empty list.
true
15734f950406d76a0c1e67dede382e095b0e1a34
shokri-matin/Python_Basics_OOP
/05InputQutputImport.py
622
4.25
4
# Python Output Using print() function print('This sentence is output to the screen') # Output: This sentence is output to the screen a = 5 print('The value of a is', a) # Output: The value of a is 5 print(1,2,3,4) # Output: 1 2 3 4 print(1,2,3,4,sep='*') # Output: 1*2*3*4 print(1,2,3,4,sep='#',end='&') # Output: 1#2#3#4& print('I love {0} and {1}'.format('bread','butter')) # Output: I love bread and butter print('I love {1} and {0}'.format('bread','butter')) # Output: I love butter and bread # Python Input num = input('Enter a number: ') # Python Import import math print(math.pi) #from math import pi
true
0449ecdfe040d45fc538696b97d0f7e0de6f106f
shokri-matin/Python_Basics_OOP
/17Files.py
1,443
4.125
4
# Hence, in Python, a file operation takes place in the following order. # 1-Open a file # 2-Read or write (perform operation) # 3-Close the file # f = open("test.txt") # open file in current directory # f = open("C:/Python33/README.txt") # specifying full path # f = open("test.txt") # equivalent to 'r' or 'rt' # f = open("test.txt",'w') # write in text mode # f = open("img.bmp",'r+b') # read and write in binary mode # f = open("test.txt",mode = 'r',encoding = 'utf-8') # f.close() with open("test.txt",'w',encoding = 'utf-8') as f: f.write("my first file\n") f.write("This file\n\n") f.write("contains three lines\n") f = open("test.txt", 'r', encoding='utf-8') f.read(4) # read the first 4 data : 'This' f.read(4) # read the next 4 data : ' is ' f.read() # read in the rest till end of file : 'my first file\nThis file\ncontains three lines\n' f.read() # further reading returns empty sting f.tell() # get the current file position: 56 f.seek(0) # bring file cursor to initial position: 0 f.read() # read the entire file # This is my first file # This file # contains three lines for line in f: print(line, end = '') # This is my first file # This file # contains three lines f.readline() # 'This is my first file\n' f.readline() # 'This file\n' f.readline() # 'contains three lines\n' f.readline() # '' f.readlines() # ['This is my first file\n', 'This file\n', 'contains three lines\n']
true
4380065a6a07c72549544d4fe1cc38ee0d7fd623
dmyerscough/codefights
/sumOfTwo.py
728
4.25
4
#!/usr/bin/env python def sumOfTwo(a, b, v): ''' You have two integer arrays, a and b, and an integer target value v. Determine whether there is a pair of numbers, where one number is taken from a and the other from b, that can be added together to get a sum of v. Return true if such a pair exists, otherwise return false. >>> a = [1, 2, 3] >>> b = [10, 20, 30, 40] >>> v = 42 >>> sumOfTwo(a, b, v) True >>> a = [1, 2, 3] >>> b = [10, 20, 30, 40] >>> v = 50 >>> sumOfTwo(a, b, v) False ''' s = set(b) for i in a: if (v - i) in s: return True return False if __name__ == '__main__': import doctest doctest.testmod()
true
1eb28eb14c6dc0144de440ee62f1b560978a7f3c
shraddha136/python
/assn7.2.py
1,116
4.625
5
#7.2 Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form: # X-DSPAM-Confidence: 0.8475 # Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. # You can download the sample data at http://www.pythonlearn.com/code/mbox-short.txt when you are testing below enter mbox-short.txt as the file name. # Use the file name mbox-short.txt as the file name fname = raw_input("Enter file name: ") #initialize the variable to store the floating point values num = 0 #initialize the variable to store the number of lines of the required form line_count = 0 fh = open(fname) #read through the file to get the line of the required format, extract the floating point number for line in fh: if not line.startswith("X-DSPAM-Confidence:") : continue line_count=line_count+1 start = line.find(':') num = num + float(line[start+2:len(line)]) #pint the average of the floating point number print "Average spam confidence:", num/line_count
true
085f1364d25c4bf0d60c3ae0f3c140c8bf2aa024
Chewie23/PythonAlgo
/One-Offs/General/circle_problem.py
1,334
4.34375
4
""" prompt: Given a point and a radius which designate a circle, return a random point within that circle. """ #Fun math #The solution is a fun formula. I am hesitant to delve further into this since #I would never be required to derive the Pythagoreas formula and customize it #to a circle. I mean, it's logical IF AND ONLY IF you have been practicing math #The magic formula is basically create a right angle triangle and one of the #three points == our "rando" point. So we simply say: #(x - x_center)^2 + (y - y_center) < radius^2 #see: https://www.veritasprep.com/blog/2016/10/how-to-use-the-pythagorean-theorem-with-a-circle/ #Low key though? I kind of miss math. It was beautiful and logical ONCE you got #it. Until that point it is a tough nut to crack. But filled with Eureka #moments and figuring out how to normalize variables for stuff #So. Area of a circle == pi * r^2 #circumference == 2*r*pi import math def get_area(radius): return math.pi*(radius ** 2) def get_circumference(radius): return math.pi*2*radius def is_point_in_circle(point, center, radius): #Again, fun math stuff x, y = point x_center, y_center = center return ((x - x_center)**2 + (y - y_center)**2 < radius ** 2) center = (1, 1) point = (0, 0) radius = 5 print(is_point_in_circle(point, center, radius))
true
1dd547f756e6e226c03f9caebc596c826c64480e
Chewie23/PythonAlgo
/Recursion/bubble_sort.py
536
4.28125
4
#Recursion bubble sort. If you though regular bubble sort was bad #Remember, it's comparing two elements, and swapping. Then keep on going #through until no more swapping #Iteratively, we have a swapping bool, and a while loop #Or we have outer for loop that will go through ALL of the array def bubble(arr): #This just iterates through it #What is the smallest bit of work that I can tease out of it if len(arr) == 0: return print(arr[0]) bubble(arr[1:]) disarray = [1, 4, 6, 5, 3, 2] bubble(disarray)
true
c8ab267b2a2aa07725c50f09c7d74b7ceb855e34
fuanruisu/Py
/listas.py
544
4.1875
4
# Nombre: listas.py # Objetivo: muestra la funciòn de las listas en python # Autor: alumnos de Mecatrònica # Fecha: 27 de agosto de 2019 #crear lista vacía lista = [] # agregamos elementos a la lista lista.append("hola") lista.append(False) lista.append(23.13) lista.append('c') lista.append(23) lista.append(-12) print(lista[1]) # Imprimir los elementos de una lista print(lista) #Imprimir for i in lista: print(i) n=len(lista) for i in range(n): lista.pop(0) # Imprimir un item de la lista por medio de su indice #print("Item en: ", lista[0])
false
c5e7ae3880cb279a8837f51072056598c7c04c67
mvkopp/pythagore_dates
/pythagore_dates.py
1,991
4.5625
5
def main(): """ Main function that caluclate all Pythagore dates between two years (here between 2000 and 2100) Params: / """ for y in range(10,3000): for m in range(1,13): dTotal = month_length(m,y) for d in range(1,dTotal+1): if is_pythagore(d,m,y): print(str(d)+"/"+str(m)+"/"+str(y)+" est une date pythagore") def is_pythagore(day,month,year): """ Return True if a date is Pyhtagore, False otherwise Params: day (int) - the day of the date month (int) - the month of the date year (int) - the year of the date Examples: >>> is_pythagore(16,12,2020) True >>> is_pythagore(17,12,2020) False >>> is_pythagore(24,7,2025) True """ year=str(year)[-2:] # Recover the 2 last number of the year if ((day**2 + month**2) == int(year)**2) : return True return False def month_length(month,year): """ Return the number of day in a month Params: month (int) - the month number year (int) - the year in YYYY format Examples: >>> month_length(12,2020) 31 >>> month_length(3,2009) 30 >>> month_length(2,2020) 29 >>> month_length(2,2021) 28 """ if month in (1,3,5,7,8,10,12): return 31 elif month == 2 : if is_bissextile(year): return 29 else: return 28 else: return 30 def is_bissextile(year): """ Return True if a year is bissextile, False otherwise Params: year (int) - the year in YYYY format Examples: >>> is_bissextile(2017) False >>> is_bissextile(2020) True >>> is_bissextile(2022) False >>> is_bissextile(2024) True """ if(year%4==0 and year%100!=0 or year%400==0): return True else: return False if __name__ == "__main__": # execute only if run as a script main()
false
9fc2d9c7597c35c254505f3a19e53ee17a9e2dca
DanielMelero/Search-engine
/ordsearch.py
2,085
4.15625
4
def linear(data, value): """Return the index of 'value' in 'data', or -1 if it does not occur""" # Go through the data list from index 0 upwards i = 0 # continue until value found or index outside valid range while i < len(data) and data[i] != value: # increase the index to go to the next data value i = i + 1 # test if we have found the value if i == len(data) or data[i] > value: # no, we went outside valid range; return -1 return 'Does not occur' else: # yes, we found the value; return the index return i def binary(data, value): low = 0 # enter the lowest possible index high = len(data)-1 # enter the highest possible index while low <= high != 0: mid = (low + high)//2 # find the midpoint between the low and high indexes if data[mid] == value: return mid # if mid index contains the target value return index number elif data[mid] < value: low = mid + 1 # if value in mid index is lower than target value set new low at mid +1 elif data[mid] > value: high = mid - 1 # if value in mid index is higher than target set new high as mid - 1 return "Does not occur" def binary_pairs(data, value): low = 0 # enter the lowest possible index high = len(data)-1 # enter the highest possible index while low <= high != 0: mid = (low + high)//2 # find the midpoint between the low and high indexes if data[mid][0] == value: return mid # if mid index contains the target value return index number elif data[mid][0] < value: low = mid + 1 # if value in mid index is lower than target value set new low at mid +1 elif data[mid][0] > value: high = mid - 1 # if value in mid index is higher than target set new high as mid - 1 return -1
true
6b7c7ddae9d6d57e407648aedf281330bc7e69b9
asset311/comp-sci-fundamentals
/strings/permutation_palindrome.py
1,224
4.25
4
''' Check if any permutation of a string is a valid palindrome. A brute force approach is to generate all permutations of the string = O(n!) Then for each of those permutations to check if it is a palindrome = 0(n) For the total time of O(n*n!) - that's extremely long. A simple solution is to think about what a palindrome is. In a palindrome, each letter needs to appear even number of times, except maybe one appearing odd number of times. Our approach is to check that each character appears an even number of times, allowing for only one character to appear an odd number of times (a middle character). This is enough to determine if a permutation of the input string is a palindrome. ''' # O(n) time complexity # O(1) space for possible characters added to the set def has_palindrome_permutation(the_string): #track characters we've seen an odd number of times unpaired_characters = set() for char in the_string: if char in unpaired_characters: unpaired_characters.remove(char) else: unpaired_characters.add(char) # the string has a palindrome permutation if it # has one or zero characters without a pair return (len(unpaired_characters)) <= 1
true
a95868ce9c1ac1482b03c42db38b972225059858
asset311/comp-sci-fundamentals
/arrays/permutations_list.py
1,058
4.28125
4
''' Generate all permutations of a set Permutation is an arrangement of objects in a specific order. Order of arrangement of object is very important. The number of permutations on a set of n elements is given by n!. Example 2! = 2*1 = 2 permutations of {1, 2}, namely {1, 2} and {2, 1} 3! = 3*2*1 = 6 permutations of {1, 2, 3}, namely {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2} and {3, 2, 1}. ''' # one by one extract all elements, place them at first position and them recur on the remaining list def permutation(lst): # base cases if len(lst) == 0: return [] if len(lst) == 1: return lst # permutations for 1st if there are more than 1 characters l = [] #list to hold permutations for i in range(len(lst)): m = lst[i] #extract m from the list, and permute with the remaining list remList = lst[:i] + lst[i+1:] #generate all permutations where m is the first element for p in permutation(remList): l.append([m] + p) return l
true
2199fc314341dea159789cdf6b0e899e38c0be4f
asset311/comp-sci-fundamentals
/queues/queue_using_stacks.py
1,039
4.25
4
''' 232. Implement Queue using Stacks Implement the following operations of a queue using stacks. push(x) -- Push element x to the back of queue. pop() -- Removes the element from in front of queue. peek() -- Get the front element. empty() -- Return whether the queue is empty. ''' class MyQueue: def __init__(self): self._push_stack = [] self._pop_stack = [] def push(self, x: int) -> None: self._push_stack.append(x) def pop(self) -> int: if len(self._pop_stack) == 0: while self._push_stack: self._pop_stack.append(self._push_stack.pop()) return self._pop_stack.pop() def peek(self) -> int: if len(self._pop_stack) == 0: while self._push_stack: self._pop_stack.append(self._push_stack.pop()) return self._pop_stack[-1] def empty(self) -> bool: return (not self._push_stack) and (not self._pop_stack) ''' COMPLETE THIS SOLUTION '''
false
e6a2b110b16792d4de45200f61cb9bfb1be2e2e0
Hansen-L/MIT-6.0001
/ps4/test.py
1,207
4.125
4
import string letter_to_number_dict={} number_to_letter_dict={} num = 1 shift = 2 #First make a dictionary that holds the default letter-number correspondence for char in string.ascii_lowercase: letter_to_number_dict[char] = num number_to_letter_dict[num] = char num = num + 1 for char in string.ascii_uppercase: letter_to_number_dict[char] = num number_to_letter_dict[num] = char num = num + 1 #Now create a new dictionary with letter-shifted letter correspondence by referencing other dict with a shift encryption_dict={} for char in string.ascii_lowercase: unshifted_number = letter_to_number_dict[char] if unshifted_number <= 26-shift: shifted_number = unshifted_number+shift else: shifted_number = unshifted_number+shift-26 encryption_dict[char]=number_to_letter_dict[shifted_number] for char in string.ascii_uppercase: unshifted_number = letter_to_number_dict[char] if unshifted_number <= 52-shift: shifted_number = unshifted_number+shift else: shifted_number = unshifted_number+shift-26 encryption_dict[char]=number_to_letter_dict[shifted_number]
true
126f12b64e6b63454b5843e73dc6dc87ed0e0e45
akashgkrishnan/simpleProjects
/calc/app.py
760
4.125
4
from calc.actual_calc import ActualCalulator repeat = 'y' print(''' Enter the operation you are interested in : 1) Enter 1 for performing addition of 2 numbers 2) Enter 2 for performing subraction on 2 numbers 3) Enter 3 for perforiming multiplication on 2 numbers 4) Enter 4 for performing division on 2 numbers 5) Enter 5 to check the parity of a number (Odd/Even) ''') while repeat == 'y': ch = int(input("Enter Your Choice:")) c = ActualCalulator() if ch == 1: c.getsum() elif ch == 2: c.getdiff() elif ch == 3: c.getprod() elif ch == 4: c.getdiv() elif ch ==5: c.getparity() else: print("invalid choice") repeat = input("Do you want to continue(y/n): ").lower()
true
1ebaa91a786113a75d78c6e9f46c0f02e3cd0787
beyzabutun/Artificial-Intelligence
/MonteCarlo/mcs.py
1,864
4.125
4
#!/usr/bin/python3 import random # Evaluate a state # Monte Carlo search: randomly choose actions def monteCarloTrial(player,state,stepsLeft): if stepsLeft==0: return state.value() ### Randomly choose one action, executes it to obtain ### a successor state, and continues simulation recursively ### from that successor state, until there are no steps left. actions = state.applicableActions(player) if actions==[]: return state.value() random_action = random.choice(actions) state2 = state.successor(player,random_action) return monteCarloTrial(1-player,state2,(stepsLeft-1)) def monteCarloSearch(player,state,trials): sum = 0 for x in range(0,trials): sum += monteCarloTrial(player,state,20) return sum / trials ### TOP-LEVEL PROCEDURE FOR USING MONTE CARLO SEARCH ### The game is played by each player alternating ### with a choice of their best possible action, ### which is chosen by evaluating all possible ### actions in terms of the value of the random ### walk in the state space a.k.a. Monte Carlo Search. def executeWithMC(player,state,stepsLeft,trials): if stepsLeft==0: return state.show() if player==0: bestScore = float("inf") # Default score for minimizing player else: bestScore = 0-float("inf") # Default score for maximizing player actions = state.applicableActions(player) if actions==[]: return for action in actions: state0 = state.successor(player,action) v = monteCarloSearch(1-player,state0,trials) if player==1 and v > bestScore: # Maximizing player chooses highest score bestAction = action bestScore = v if player==0 and v < bestScore: # Minimizing player chooses lowest score bestAction = action bestScore = v state2 = state.successor(player,bestAction) executeWithMC(1-player,state2,stepsLeft-1,trials)
true
46e72161442c45fa2a5e6dbc580bd86db5202a85
EzraBC/CiscoSerialNumGrabber
/mytools.py
1,581
4.375
4
#!/usr/bin/env python """ INFO: This script contains functions for both getting input from a user, as well as a special function for handling credentials (usernames/passwords) in a secure and user-friendly way. AUTHOR: zmw DATE: 20170108 21:13 PST """ #Make script compatible with both Python2 and Python3. from __future__ import absolute_import, division, print_function #Import funtion to get password without echoing to screen. from getpass import getpass #Make input function compatible with both Python2 and Python3. def get_input(prompt=''): try: line = raw_input(prompt) except NameError: line = input(prompt) return line #Use one of the following 3 options to get username and password #(uncomment to use) #Preset username and password. def get_credentials(): username = "your-username" password = "your-password" return username, password #Prompt for username once and password once, return both. # def get_credentials(): # username = get_input(' Enter Username: ') # password = getpass(' Enter RSA PASSCODE: ') # return username, password #Prompt for username once and password twice, return both. #While loop to ask for password twice to verify that it was typed correctly. # def get_credentials(): # username = get_input(' Enter Username: ') # password = None # while not password: # password = getpass(' Enter Password: ') # password_verify = getpass(' Retype Password: ') # print() # if password != password_verify: # print('Passwords do not match. Please try again.') # password = None # return username, password
true
e794133843ab561393b55627675f3f419884527b
rembrandtqeinstein/learningPy
/pp_e_11.py
342
4.125
4
num = input("Enter a number to check if it's a prime: ") try: num = int(num) except: print("Not a number") def prime(x): div = range(1, x) lis = [y for y in div if x % y == 0] if len(lis) == 1: print(x, "is a prime number") else: print(x, "is not a prime number, it's divisible by", *lis) prime(num)
true
327b2644b39d5364ca15d8eed74c8f2e7945902a
rembrandtqeinstein/learningPy
/coursera_test.py
343
4.1875
4
#import pandas as pd hours = input("How many hours you work: ") rate = input("How many you are payed per hour: ") try: hrs = float(hours) fra = float(rate) except: print("That is not a number") quit() if hrs >= 40: pay = 40 * fra pay = pay + ((hrs - 40) * 1.5) else: pay = hrs * fra print(pay) #print(pd.datetime)
true
9af4f4db42d1ee0ed61b0a8ab99ba76d7fbf803f
joshey-bit/Python_Projects
/2-D Game/alien.py
1,544
4.15625
4
''' A program to create alien class ''' import pygame from pygame.sprite import Sprite class Alien(Sprite): '''A class to create an alien and draw it on the screen''' def __init__(self,alien_settings,screen): super().__init__() self.alien_settings = alien_settings self.screen = screen #load the alien image and get the resctangle self.image = pygame.image.load(r'images/alien.bmp').convert() self.image.set_colorkey((255,255,255)) #to match image background with screen background self.img = pygame.transform.scale(self.image,(40,35)) self.rect = self.img.get_rect() #to get the rectangle of image #position the alien to top left corner self.rect.x = self.rect.width self.rect.y = self.rect.height #set the float value of alien postion self.x = float(self.rect.x) self.y = float(self.rect.y) def update(self): '''method to update the x posistion of alien''' self.x += (self.alien_settings.alien_speed_factor * self.alien_settings.fleet_direction) self.rect.x = self.x def blitme(self): '''method to add alien on screen''' self.screen.blit(self.img, self.rect) def check_edges(self): '''method to check whether the alien reaches edges''' screen_rect = self.screen.get_rect() if self.rect.right >= screen_rect.right: return True if self.rect.left <= 0: return True
true
56f5016e2b78ae1611742dc99d3876c394095160
JavierVaronBueno/python_3.x_Estructuras_Datos_Busquedas_Hilos
/Estructura Pila/Pila.py
2,132
4.34375
4
""" ESTRUCTURA DE DATO PILA: Una pila es una lista ordenada o estructura de datos en el que el modo de acceso a sus elementos es de tipo 'LIFO' (Last In First Out, Ultimo En Entrar es el Primero en Salir), que permite almacenar datos. Para el manejo de los datos se cuenta con dos operaciones basicas: -Apilar(push): que coloca un objeto en la pila -Desapilar(pop): que retira el ultimo elemento apilado. OPERACIONES: -Crear: Se crea la pila vacía. (constructor) -Tamaño: Regresa el numero de los elementos de la pila (tam) -Apilar: Se añade un elemento a la pila.(push) -Desapilar: Se elimina el elemento ultimo en apilarse en la pila.(pop) -Cima:Devuelve el elemento que esta en la cima de la pila.(top o peek) -Vacía: Devuelve cierto si la pial esta vacía de lo contrario retorna falso.(empty) Las pilas pueden ser de tamaño estatico y dinamico, se pueden implementar en listas, arreglos, colecciones de datos o en listas enlazadas. """ class Pila(): #Constructor def __init__(self,tam): self.lista = [] self.tope = 0 self.tam = tam #Tamaño de la pila #Empty def vacia(self): if self.tope== 0: return True else: return False #Push def apilar(self, dato): if self.tope < self.tam: self.lista += [dato]#self.lista = self.lista + [dato] self.tope += 1#self.tope = self.tope + 1 else: print("La pila esta llena") """ Pila dinamica self.tam += 1#self.tam = self.tam + 1 self.lista +=[dato]#self.lista = self.lista + [dato] self.tope += 1#self.tope = self.tope + 1 """ #Pop def desapilar(self): if self.vacia(): print("La pila esta Vacia") else: self.tope -= 1# self.tope = self.tope - 1 self.lista = [self.lista[x] for x in range(self.tope)] """ #La anterior linea es igua a esto: aux = [] for x in range(self.tope): aux += [self.lista[x]]#aux = aux + [self.lista[x]] self.lista = aux """ #Show def imprimir(self): i = self.tope - 1 while i > -1: print("[%d]:-> %d"%(i,self.lista[i])) i -= 1 #Size def Tam(self): return self.tope #Top o peek def ultimoElemento(self): return self.lista[-1]
false
2dbbd238faafed78e70b6a51c7c173eb917087b0
JavierVaronBueno/python_3.x_Estructuras_Datos_Busquedas_Hilos
/02_ordenamientoSeleccion.py
899
4.34375
4
""" METODO ORDENAMIENTO POR SELECCION: Es un algoritmo que consiste en ordenar los elementos de manera acedendente o descendente PASOS: -Busca el dato mas pequeño de la lista -Intercambiarlo por el actual -Seguir buscando el dato mas pequeño de la lista -Intercambiarlo por el actual -Esto se repetira sucecivamente Ejemplo: Entrada: [4, 2, 6, 8, 5, 7, 0] Solucion: [0, 2, 6, 8, 5, 7, 4] [0, 2, 6, 8, 5, 7, 4] [0, 2, 4, 8, 5, 7, 6] [0, 2, 4, 5, 8, 7, 6] [0, 2, 4, 5, 6, 7, 8] Salida: [0, 2, 4, 5, 6, 7, 8] """ lista = [4,2,6,8,5,7,0] #Loop para recorrer los elementos de la lista for i in range(len(lista)): minimo = i #loop para buscar el menor elemento d ela lista for x in range(i,len(lista)): if lista[x]< lista[minimo]: minimo = x #intercambio del menor valor en sus pocision correcta aux = lista[i] lista[i] = lista[minimo] lista[minimo] = aux print(lista)
false
d2e486d034b40bf3820b402361fc59aabb09dd4b
SValeriey/PySL
/0014_Class3.py
2,192
4.34375
4
# 继承 # 一个类继承另一个类时,子类获得父类的所有属性和方法,子类可以定义自己的属性和方法 class Car: def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): print("This car has " + str(self.odometer_reading) + " miles on it.") def update_odometer(self, mileage): if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!") def increment_odometer(self, miles): self.odometer_reading += miles class Battery: """模拟电瓶车电瓶""" def __init__(self, battery_size=70): self.battery_size = battery_size def describe_battery(self): print("This car has a " + str(self.battery_size) + "-kWh battery.") class ElectricCar(Car): # 定义子类时,括号内指定父类的名称 """电动车的独特之处""" def __init__(self, make, model, year): """初始化父类属性""" super().__init__(make, model, year) # super()将子类和父类关联 self.battery = Battery() my_tesla = ElectricCar('tesla', 'model s', 2016) print(my_tesla.get_descriptive_name()) my_tesla.battery.describe_battery() # 子类重写父类方法 -- 在子类中重新定义同名函数 # Demos: # 1.冰淇淋小店 class Restaurant: def __init__(self, name, ttype): self.restaurant_name = name self.restaurant_type = ttype def describe_restaurant(self): print('The name is ' + self.restaurant_name) print('Its type is ' + self.restaurant_type) @staticmethod def open_restaurant(): print('The restaurant is opening.') class IceCreamStand(Restaurant): def __init__(self, name, type, flavors): super().__init__(name, type) flavors = ['haciendas', 'green bean']
false
92c0d35d31f7727ac542ad1d5661a15e4e2bc64c
ChengzhangBai/Python
/LAB10/task2.py
700
4.5
4
# Write a python program that prompts the user for the name of .csv file # then reads and displays each line of the file as a Python list. # Test your program on the 2 csv files that you generated in Task 1. fileName = input('Please input "boy" or "girl" to open a file: ') if fileName == "" or fileName not in('boy','girl'): fileName = 'boy' try: fileName = '2000_'+ fileName.capitalize() + 'sNames.csv' names = open(fileName,'r') nameList = [] for name in names: nameList.append(name.replace('\n','')) print(nameList) nameList=[] names.close() except FileNotFoundError: print("File not found, please generate a csv file first.")
true
acd4218bb27771db82a4796d8dd21479cf3cab5c
humblefo0l/PyAlgo
/DP/MaximumProductSubarray.py
1,261
4.1875
4
""" Maximum Product Subarray Medium 11755 362 Add to List Share Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product. The test cases are generated so that the answer will fit in a 32-bit integer. A subarray is a contiguous subsequence of the array. Example 1: Input: nums = [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6. Example 2: Input: nums = [-2,0,-1] Output: 0 Explanation: The result cannot be 2, because [-2,-1] is not a subarray. Constraints: 1 <= nums.length <= 2 * 104 -10 <= nums[i] <= 10 The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. """ from typing import List class Solution: def maxProduct(self, nums: List[int]) -> int: imax = imin = nums[0] res = nums[0] for i in range(1, len(nums)): if nums[i] < 0 : imax, imin = imin, imax imax = max(imax * nums[i], nums[i]) imin = min(imin * nums[i], nums[i]) res = max(res,imax) return res s = Solution() nums = [2,3,-2,4] print(s.maxProduct(nums)) nums = [-2,0,-1] print(s.maxProduct(nums)) nums = [-2,3,-4] print(s.maxProduct(nums))
true
cecc70dbe060dcdfd840322a2bb44a649b751ecc
humblefo0l/PyAlgo
/Recursion/Permutation.py
478
4.21875
4
""" 46. Permutations Medium Add to List Share Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order. Example 1: Input: nums = [1,2,3] Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]] Example 2: Input: nums = [0,1] Output: [[0,1],[1,0]] Example 3: Input: nums = [1] Output: [[1]] """ from typing import List class Solution: def permute(self, nums: List[int]) -> List[List[int]]: pass
true
ffeb082d317527637ee17b7dd36c0c4f7f11ea40
trieuchinh/DynamicProgramming
/howSum.py
1,063
4.21875
4
''' Write a function called "howSum(targetSum, number)" that takes in a targetSum and an array of numbers as arguments. The function should return an array containing any combination of elements that add up to exactly the targetSum. If there is no combination that adds to the targetSum, then return null. If there are multiple combinations possible, you may return any single one ''' def howSum(targetSum, numbers, memo): if targetSum in memo: return memo[targetSum] if targetSum == 0: return [] if targetSum < 0: return None; for num in numbers: remainder = targetSum - num; remainderResult = howSum(remainder, numbers, memo) if remainderResult != None: remainderResult = remainderResult + [num] memo[targetSum] = remainderResult return memo[targetSum] memo[targetSum] = None return None m = dict() print(howSum(7, [2, 3], m)) m = dict() print(howSum(8, [5, 3, 2], m)) m = dict() print(howSum(300, [7, 14], m))
true
c95bc18ced7fafa924d4c59a8402f14fb1d178c8
Philipotieno/Grokking-Algorithms
/02_selection_sort.py
658
4.15625
4
# Find the smallest valuein an array def findSmallest(arr): # Store the smalest value smallest = arr[0] # Store the smallest index of the smallest value smallest_index = 0 for i in range(1, len(arr)): if arr[i] < smallest: smallest = arr[i] smallest_index= i return smallest_index # Sort array def selectionSort(arr): newArr = [] for i in range(len(arr)): # find the smallest elemet in the array smallest = findSmallest(arr) # add the element to the new array newArr.append(arr.pop(smallest)) return newArr print(selectionSort([5, 3, 6, 2, 100, "e", "a"]))
true
5f7e437af4b36a47030cc7d25357dfd100bc128d
Kallshem/iterators
/exercises/generators.py
2,783
4.125
4
"""Övningar på generators""" from math import sqrt def cubes(x=0): """Implementera en generator som skapar en serie med kuber (i ** 3). Talserien utgår från de positiva heltalen: 1, 2, 3, 4, 5, 6, ... Talserien som skapas börjar således: 1, 8, 27, 64, 125, 216, ... Talserien ska inte ha något slut. """ while True: x += 1 yield x**3 def primes(i=1): """Implementera en generator som returnerar primtal. Talserien som förväntas börjar alltså: 2, 3, 5, 7, 11, 13, 17, 19, 23, ... """ def _prime(x): for i in range(2, int(sqrt(x)) + 1): if x % i == 0: return False return True while True: i += 1 if _prime(i) == True: yield i def fibonacci(): """Implementera en generator som returnerar de berömda fibonacci-talen. Fibonaccis talserie börjar med 0 och 1. Nästa tal är sedan summan av de två senaste. Alltså börjar serien: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ... """ first = None second = -1 summa = 1 while True: first = second second = summa summa = first + second yield summa def alphabet(): """En generator som returnerar namnen på tecknen i det hebreiska alfabetet. Iteratorn returnerar namnen för de hebreiska bokstäverna i alfabetisk ordning. Namnen och ordningen är: Alef, Bet, Gimel, Dalet, He, Vav, Zayin, Het, Tet, Yod, Kaf, Lamed, Mem, Nun, Samekh, Ayin, Pe, Tsadi, Qof, Resh, Shin, Tav """ alph = ["Alef", "Bet", "Gimel", "Dalet", "He", "Vav", "Zayin", "Het", "Tet", "Yod", "Kaf", "Lamed", "Mem", "Nun", "Samekh", "Ayin", "Pe", "Tsadi", "Qof", "Resh", "Shin", "Tav"] index = -1 while True: index += 1 if index < 22: yield alph[index] else: raise StopIteration def permutations(): """En generator som returnerar alla permutationer av en inmatad sträng. Då strängen 'abc' matas in fås: 'abc', 'acb', 'bac', 'bca', 'cba', 'cab' """ pass def look_and_say(): """En generator som implementerar look-and-say-talserien. Sekvensen fås genom att man läser ut och räknar antalet siffror i föregående tal. 1 läses 'en etta', alltså 11 11 läses 'två ettor', alltså 21 21 läses 'en tvåa, en etta', alltså 1211 1211 läses 'en etta, en tvåa, två ettor', alltså 111221 111221 läses 'tre ettor, två tvåor, en etta', alltså 312211 """ count = 0 chars = list() def sequence(text): for index in range(len(text)): chars.append(text[index]) for i in chars: count += 1 val = "{}, {}".fomrat(count, i)
false
b3bb07853979e7dfec06b2d6c75e0c2ece5e250d
plankobostjan/practice-python
/06StringLists
238
4.3125
4
#!/usr/bin/python word = str(input("Enter a word: ")) rev = word[::-1] print word + " reversed is written as: " + rev if word == rev: print "Word you've enetered is a palidnrome." else: print "Word you've enetered is not a palidnrome."
true
6c4ba4568fe819c4401605d5080b4c885a542773
venkataramadurgaprasad/Python
/Python-For-Everybody/Programming For Everybody(Getting Started With Python)/Week-5/Assignment_3.1.py
690
4.3125
4
''' 3.1 Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Pay the hourly rate for the hours up to 40 and 1.5 times the hourly rate for all hours worked above 40 hours. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). You should use input to read a string and float() to convert the string to a number. Do not worry about error checking the user input - assume the user types numbers properly. ''' hrs = input("Enter Hours:") rate = input("Enter rate:") h = float(hrs) rate = float(rate) if h <= 40: pay = h * rate else: pay = (rate*40) + ((h-40)* (rate*1.5)) print(pay)
true
ffe435dc3d49254e68777112b99d531f75b982b0
nagasaimanoj/Python-Trails
/Basics/Basic_Programs/matrix_iter.py
490
4.3125
4
matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] print("row-wise") for i in range(3): for j in range(3): print(matrix[i][j]) print("col-wise") for j in range(3): for i in range(3): print(matrix[i][j]) print("skipping a row") for i in range(3): if i == 1: continue for j in range(3): print(matrix[i][j]) print("skipping a col") for j in range(3): if j == 1: continue for i in range(3): print(matrix[i][j])
false
c0eeee6004b9acb0f8e6dfd61edde5a3b80e5a1d
kaustubhvkhairnar/PythonPrograms
/Lambda Functions/Assignment2.py
339
4.3125
4
#2.Write a program which contains one lambda function which accepts two parameters and return #its multiplication. def main(): value1 = input("Enter number1 : ") value2 = input("Enter number2 : ") ret=fp(value1,value2); print(ret) fp=lambda no1,no2 : int(no1)*int(no2); if __name__=="__main__": main();
true
3abedfd55165751b0cfb93e6b2f291113af556cf
kaustubhvkhairnar/PythonPrograms
/Object Orientation/Assignment3.py
1,761
4.59375
5
#3. Write a program which contains one class named as Arithmetic. #Arithmetic class contains three instance variables as Value1 ,Value2. #Inside init method initialise all instance variables to 0. #There are three instance methods inside class as Accept(), Addition(), Subtraction(), Multiplication(), Division(). #Accept method will accept value of Value1 and Value2 from user. #Addition() method will perform addition of Value1 ,Value2 and return result. #Subtraction() method will perform subtraction of Value1 ,Value2 and return result. #Multiplication() method will perform multiplication of Value1 ,Value2 and return result. #Division() method will perform division of Value1 ,Value2 and return result. #After designing the above class call all instance methods by creating multiple objects. class Arithmetic: def __init__(self): self.Value1=0; self.Value2=0; def Accept(self): self.Value1 = int(input("Enter First Number")); self.Value2 = int(input("Enter Second Number")); def Addition(self,no1,no2): return no1+no2; def Subtraction(self,no1,no2): return no1-no2; def Multiplication(self,no1,no2): return no1*no2; def Division(self,no1,no2): return no1//no2; def main(): obj1= Arithmetic(); obj1.Accept(); obj1.Addition(Value1,Value2); obj1.Subtraction(Value1,Value2); obj1.Multiplication(Value1,Value2); obj1.Division(Value1, Value2); obj2=Arithmetic() obj2.Accept(); obj2.Addition(Value1, Value2); obj2.Subtraction(Value1, Value2); obj2.Multiplication(Value1, Value2); obj2.Division(Value1, Value2); if __name__ == "__main__": main();
true
952f16d1be7dcf93fbf5afd931546da2e11b027e
kaustubhvkhairnar/PythonPrograms
/Object Orientation/Assignment5.py
1,806
4.34375
4
#5. Write a program which contains one class named as BankAccount. #BankAccount class contains two instance variables as Name & Amount. #That class contains one class variable as ROI which is initialise to 10.5. #Inside init method initialise all name and amount variables by accepting the values from user. #There are Four instance methods inside class as Display(), Deposit(), Withdraw(), #CalculateIntrest(). #Deposit() method will accept the amount from user and add that value in class instance variable #Amount. #Withdraw() method will accept amount to be withdrawn from user and subtract that amount #from class instance variable Amount. #CalculateIntrest() method calculate the interest based on Amount by considering rate of interest #which is Class variable as ROI. #And Display() method will display value of all the instance variables as Name and Amount. #After designing the above class call all instance methods by creating multiple objects. class BankAccount: ROI = 10.5 def __init__(self,value1,value2): self.Name = value1 self.Amount = value2 def Display(self): print("Name : ",self.Name) print("Amount : ",self.Amount) def Deposit(self,value): self.Amount = self.Amount+value def Withdraw(self,value): self.Amount = self.Amount - value def CalculateInterest(self,value): Rate = value + BankAccount.ROI//100 print("Rate of interest for ",value,"is",Rate) def main(): obj = BankAccount("Kaustubh",int(200000)) obj.Display() obj.Deposit(int(200)) print("Deposting") obj.Display() obj.Withdraw(int(300)) print("Withdrawing") obj.Display() obj.CalculateInterest(int(30000)) if __name__=="__main__": main()
true
a1999438dca6b16a76dec892d29ce8da066b731b
Eunaosei24788/lista3
/oi7.py
288
4.15625
4
print("Esse programa serve para desenhar um quadrado em #") lado = int(input("Insira o número de cada lado: ")) while lado <= 0: print("insira apenas números positivos") lado = int(input("Insira o número de cada lado: ")) for quadrado in range(lado): print(" # "*lado)
false
bc5c6752015df561abe9e8d67a7120398eb893d0
NatTerpilowska/DailyChallengeSolutions
/Daily3.py
218
4.21875
4
min = int(input("Enter the lowest number: ")) max = int(input("Enter the highest number: ")) print("Even numbers from %d to %d are: " % (min, max)) for i in range(min, max+1): if(i%2==0): print(i, end=" ")
true
9f9c815d3a02685db5cf792468f0c96eea59a16f
penguincookies/GWSSComputerScience
/Python/AcidRain.py
880
4.125
4
# comments use pound ACID_THRESHOLD = 6.4 ALKALINE_THRESHOLD = 7.4 print("This program will take the pH of a body of water and") print("determine if it's habitable to the fish living there.") print() pH = eval(input("Enter the water's pH: ")) # instead of "else if", Python uses "elif # Python also relies on colons and spacing rather than brackets to denote what's in the if statement if pH > 14 or pH < 0: print("Not a valid pH.") elif pH > 7: if pH < ALKALINE_THRESHOLD: print("Alkaline, the fish will survive in this water.") else: print("Too alkaline, the fish will not survive in this water.") elif pH < 7: if pH > ACID_THRESHOLD: print("Acidic, the fish will survive in this water.") else: print("Too acidic, the fish will not survive in this water.") else: print("Neutral, the fish will survive in this water.")
true
251c1e495dc417088b243b50369e2d68e20aaa81
hikarocarvalho/Blue_Module_01
/exercicios_Aulas/Codelab_Saturday_Study_Class/26-06-2021/exercicio01.py
1,904
4.1875
4
#01 - Crie um programa que gerencie o aproveitamento de um jogador de futebol.O # programa vai ler o nome do jogador e quantas partidas ele jogou. Depois vai ler a # quantidade de gols feitos em cada partida. No final, tudo isso será guardado em um # dicionário, incluindo o total de gols feitos durante o campeonato. #create the player dict player=dict({ 'name' : '', 'numberofgames': 0, 'goalsbygame' : dict(), 'goals':0 }) #create the players dict players = dict() #entry function def main(): count = 0 while True: #get the values from player player['player'] = input("Enter with the name of this player: ") player['numberofgames'] = int(input("Enter with the number of games this player play: ")) #get the number of goals by game goals = 0 for i in range(player['numberofgames']): goals = player['goalsbygame']['game'+str(i+1)] = int(input(f"Enter with the number of goals you maked in the {i+1}º game: ")) #Add the dictionary from player in another dictionary player['goals'] = goals players['player'+str(count)] = player count+=1 #Ask if the user has another value if input("Are You have other player to Enter ?(Y|N): ").lower().strip(" ").startswith('n'): break #Show function def showResults(): for f in players.keys(): temp = players[f] print(f""" The name of player: {temp['player']} in games this player maked this points: """) #show number of goals by game for i in range(temp['numberofgames']): print(f"game{i} = {str(temp['goalsbygame']['game'+str(i+1)])}".rjust(50)) #show number of all goals print("The sum of all goals are: ".rjust(50),temp['goals']) #call the functions main() showResults()
false
75ef83f749abf57e09d9d174459d2d3833dacbe3
hikarocarvalho/Blue_Module_01
/exercicios_Aulas/Aula_14/ex06.py
610
4.1875
4
#Escreva uma função que, dado um número nota representando a nota de um estudante, #converte o valor de nota para um conceito (A, B, C, D, E e F) #perform the conversion def convertNote(note): if note >8.9: return "A" elif note >6.9: return "B" elif note >4.9: return "C" elif note >4.4: return "D" else: return "F" #get the value from user def getNote(): note = float(input("Enter with the note from this student: ")) return convertNote(note) #show the reference result print("The reference of the note from the student is:",getNote())
false
bcd517d5144f761cee2ce9993dbaeff2dea939fe
AbhijitEZ/PythonProgramming
/Beginner/ClassDemo.py
1,997
4.1875
4
from abc import ABC, abstractmethod class Car: default_value = "All remain same" # static def __init__(self, wheels_count=2): self.wheels_count = wheels_count # property def __str__(self): # default function is when calling print return(f"This is default print") def __eq__(self, other): # equality check magic method for the object return self.wheels_count == other.wheels_count @classmethod def zeroWheel(cls): # class method, cls points to the class itself return cls(0) def wheels(self, wheels_count): # method self.wheels_count = wheels_count print(f"{wheels_count} number of wheels") Car.default_value = "changed" honda = Car(4) print(honda.default_value) honda.default_value = "lamda" honda.wheels(15) another = Car(3) print(another.default_value) nullWheel = Car.zeroWheel() print(nullWheel) # equality check magic method for the object jeep = Car(4) maruti = Car(4) print(jeep == maruti) # Container like representation in class class TagCloud: def __init__(self): self.tags = {} def add(self, tag): self.tags[tag.lower()] = self.tags.get(tag.lower(), 0) + 1 cloud = TagCloud() cloud.add("Python") cloud.add("python") cloud.add("PythOn") print(cloud.tags) class Product: def __init__(self, price): self.__price = price def getItem(self): return self.__price # private property def setIntem(self, value): self.__price = value dust = Product(10) print(dust.getItem()) # inheritance class Animal: def eat(self): print("eat") class Human(Animal): def walk(self): print("walk") John = Human() John.walk() John.eat() # abstract class Mammal(ABC): def eat(self): print("FOOD") @abstractmethod def walk(self): pass # used when there is no implemetation class Bear(Mammal): def walk(self): print("With 4 legs") lupa = Bear() lupa.walk()
true
3d1ab6dfd6a8555720824f71c4cf794825000aed
mogubess/python_test
/nyumon/6chapter/68Property.py
461
4.15625
4
''' Property ''' class Duck(): def __init__(self, inputName): self.hiddenName = inputName def getName(self): print('inside the getter') return self.hiddenName def setName(self, inputName): print('inside the setter') self.hiddenName = inputName #変数のGetterとSetterを定義できる name = property(getName,setName) fowl = Duck('Howard') print(fowl.name) fowl.name = 'Daffy' print(fowl.name)
false
d459fd0fab2c9cb4ae601dea2a57363828d70632
theinsanetramp/AnkiAutomation
/genSentenceDB.py
2,925
4.125
4
import sqlite3 from sqlite3 import Error import csv def create_connection(db_file): """ create a database connection to a SQLite database """ try: conn = sqlite3.connect(db_file) return conn except Error as e: print(e) return None def create_table(conn, create_table_sql): """ create a table from the create_table_sql statement :param conn: Connection object :param create_table_sql: a CREATE TABLE statement :return: """ try: c = conn.cursor() c.execute(create_table_sql) except Error as e: print(e) def create_sentence(conn, sentence): """ Create a new sentence into the sentences table :param conn: :param sentence: :return: sentence id """ sql = """ INSERT INTO sentences(japanese,english) VALUES(?,?) """ try: cur = conn.cursor() cur.execute(sql, sentence) return cur.lastrowid except Error as e: print(e) return None sql_create_projects_table = """ CREATE TABLE IF NOT EXISTS sentences ( id integer PRIMARY KEY, japanese text NOT NULL, english text NOT NULL ); """ conn = create_connection("tatoeba/japTatoeba.db") jpnList = [] engList = [] if conn is not None: # create projects table create_table(conn, sql_create_projects_table) with open('tatoeba/sentences.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter='\t') line_count = 0 for row in csv_reader: if row[1] == 'jpn': jpnList.append((int(row[0]),row[2])) line_count += 1 if row[1] == 'eng': engList.append((int(row[0]),row[2])) line_count += 1 print(f'Processed {line_count} sentences.') #print(create_sentence(conn, sentence)) with open('tatoeba/links.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter='\t') line_count = 0 for row in csv_reader: iRow = (int(row[0]), int(row[1])) if iRow[0] > 6241747: for jpnSentence in jpnList: if iRow[0] == jpnSentence[0]: for engSentence in engList: if iRow[1] == engSentence[0]: create_sentence(conn, (jpnSentence[1],engSentence[1])) conn.commit() print(jpnSentence[1]) print(engSentence[1]) print("-"*40) line_count += 1 if line_count % 1000 == 0: print(f'Processed {line_count} lines.') conn.close() else: print("Error! cannot create the database connection.")
true
bbabed6baee00637d9459da02a4339440ea8799a
avieshel/python_is_easy
/fizz_buzz.py
2,606
4.34375
4
def is_divisible_by_5(number): return number % 5 == 0 def is_divisible_by_3(number): return number % 3 == 0 def is_prime(number): for divisor in range (2, number): if (number % divisor == 0): return False return True ''' A Prime number has exactly two divisors 1 and itself. To check number primality we need to loop over all the numbers from 2 to 'number to check' and make sure that the % (modulo) is not 0 (zero). we can do a better job of not checking 'things twice' assume we are checking primality for 13. start by checking 13 % 2 == 0? it's false, we move on to check 13 % 3 == 0?, again false so we move on... after checking 13 % 2 == 0 is false we know that 13 % 7, 13 % 8 ... 13 % 12 will all be false. after checking 13 % 3 we can limit the search to 5 the following function takes advantage of this to check primality faster (little faster) than the function is_prime(number) above. ''' def is_prime_fast(number): if number == 1: return False return is_prime_fast_helper(2, number, number) def is_prime_fast_helper(divisor, numer, limit): if divisor >= limit: return True elif numer % divisor == 0: return False else : limit = (numer // divisor) + 1 divisor += 1 return is_prime_fast_helper(divisor, numer, limit) # # primality testing # assert is_prime_fast(1) is False, '1 is not prime' # assert is_prime_fast(2) is True, '2 is prime' # assert is_prime_fast(3) is True, '3 is prime' # assert is_prime_fast(4) is False, '4 is not prime' # assert is_prime_fast(5) is True, '5 is prime' # assert is_prime_fast(6) is False, '6 is not prime' # assert is_prime_fast(7) is True, '7 is prime' # assert is_prime_fast(8) is False, '8 is not prime' # assert is_prime_fast(9) is False, '9 is not prime' # assert is_prime_fast(10) is False, '10 is not prime' # assert is_prime_fast(11) is True, '11 is prime' # assert is_prime_fast(12) is False, '12 is not prime' # #some more tests # for t in (2, 101): # assert is_prime(t) is is_prime_fast(t) def fizz_buzz(limit): for n in range(1, limit + 1): nothing_printed_yet = True if is_divisible_by_3(n): print('fizz ', end='') nothing_printed_yet = False if is_divisible_by_5(n): print('buzz ', end='') nothing_printed_yet = False if nothing_printed_yet: print(n, end='') if is_prime_fast(n): print(' (',n,' is prime)', end='') print('',end='\n') #Add new line just to make the output clearer fizz_buzz(100)
true
d888bdf090097a515dbc7815e75ab5cb5f42344d
anubhav-shukla/Learnpyhton
/finbonacci.py
431
4.21875
4
# here we write a program for fibonacci series def fibonacci_seq(n): a=0 b=1 if n==1: print (a) elif n==2: print(b) else: print(a,b,end=" ") for i in range(n-2): c=a+b #c==1 a=b #a==1 b=c #b==1 It is called swapping print(b,end=" ") fibonacci_seq(10) # python finbonacci.py # python fibonacci_.py
false
5fbbabee18776cc21049d33131e117c5f32db22a
anubhav-shukla/Learnpyhton
/guessing.py
520
4.1875
4
# it is while loop program # python guessing.py print("It is a guessing game") import random random_number =random.randrange(1,10) guess=int(input("what could be tthe Number? ")) correct=False print(random_number) while not correct: if guess==random_number: print("congrats you got it") correct=True elif guess>random_number: print("too high") break elif guess<random_number: print("too low") break else: print("try something else")
true
0afb2f0b115724f3440cf755d094fe68e6597ee2
anubhav-shukla/Learnpyhton
/some_method.py
452
4.15625
4
# here we learn some useful method #python some_method.py fruits=['mango','orange','apple','apple'] # print(fruits.count('apple')) # 2 # fruits.sort() it gives an sorted array # print(sorted(fruits)) #it just use for print or temporary sorting # fruits.clear() # it gives you an empty list fruit1=fruits.copy() print(fruit1) print(fruits) # what we learn: # count(),sort(),sorted(),clear(),copy() # it is done
true
3c0c943512655eed6dc6e8ee92420cc6ba2f4e79
anubhav-shukla/Learnpyhton
/list_comprehension.py
1,054
4.625
5
# most powerful topic in python # list comprehension # python list_comprehension.py # today we create a list with the help o list comprehension # create a list of squares from 1 to 10 # it is a simple way to create a list square # square=[] # for i in range(1,11): # square.append(i**2) # print(square) # Now we see using list comprehension # square2=[i**2 for i in range(1,11)] # print(square2) # result is same hope it clear # create a list of negative number # negative=[] # for i in range(1,11): # negative.append(-i) # print(negative) # you got a negative list # # now see list comprehendion # negative2=[-i for i in range(1,11)] # print(negative2) #result is same hope it now clear in your mind # see something unique names=['Anubhav','Golu','Snaghrs'] new_list=[] #form upper list first character store in new_list for name in names: new_list.append(name[0]) print(new_list) # now see using list comprehension name2=[name[0] for name in names] print(name2)
true
b8d1ff3381a518f89f764c2b26d1b687c3be7824
anubhav-shukla/Learnpyhton
/chapter5_exe3.py
256
4.34375
4
# here we take input as list and reverse each element # python chapter5_exe3.py def reverse_all(l): reverse=[] for i in l: reverse.append(i[::-1]) return reverse listj=['mango','apple','banana'] print(reverse_all(listj))
true
718cb952f0b24a475eee0b032ec687a8dfc0157c
anubhav-shukla/Learnpyhton
/add.py
487
4.3125
4
# here we learn how to add two list and items # python add.py # cancatenation fruits=['mango','orange','apple'] fruits1=['banana','grapes'] fruit=fruits+fruits1 # print(fruit) print all in single list # using extend method # exetnd fruits.extend(fruits1) print(fruits) # it is doing same work # append() list in list [a,[b,c]] fruits.append(fruits1) print(fruits) # insert() fruits.insert(0,'Apple') print(fruits) # thankyou meet tomarrow with new things
true
b6ae26fd8a595771abaf2e25b551685f8f5bd307
anubhav-shukla/Learnpyhton
/gen_comprehension.py
355
4.125
4
# use generator comprehension # it is a generator comprehension square=(i**2 for i in range(1,11)) s=square for i in s: print(i) for i in s: print(i) for i in s: print(i) # you can also use next but remove above code # print(next(s)) # use () for generator comprehension # hope it clear .... # if any doubt ask
false
ef4c42f4cab534e847afc7d0cbddc586797edc0f
anubhav-shukla/Learnpyhton
/check_empty_or_not.py
318
4.375
4
# here we see check empty or not # important #python check_empty_or_not.py # name="Golu" it print not empty # name='' it show empty # here you can use it name =input('Enter your name: ') # name='India' if name: print('your name is '+name) else: print("You did't enter your name")
true
7805a27b5f2e6ca6cd329c82b5242c6b6668cdda
shuxinzhang/nltk-learning
/exercises/Chapter 02/02-23.py
1,631
4.28125
4
# -*- coding: utf-8 -*- import matplotlib matplotlib.use('TkAgg') import nltk import math ''' ★ Zipf's Law: Let f(w) be the frequency of a word w in free text. Suppose that all the words of a text are ranked according to their frequency, with the most frequent word first. Zipf's law states that the frequency of a word type is inversely proportional to its rank (i.e. f × r = k, for some constant k). For example, the 50th most common word type should occur three times as frequently as the 150th most common word type. Write a function to process a large text and plot word frequency against word rank using pylab.plot. Do you confirm Zipf's law? (Hint: it helps to use a logarithmic scale). What is going on at the extreme ends of the plotted line? Generate random text, e.g., using random.choice("abcdefg "), taking care to include the space character. You will need to import random first. Use the string concatenation operator to accumulate characters into a (very) long string. Then tokenize this string, and generate the Zipf plot as before, and compare the two plots. What do you make of Zipf's Law in the light of this? ''' from nltk import FreqDist import pylab import numpy from nltk.corpus import brown def zipfProof(text): fdist = FreqDist([w.lower() for w in text]) values = fdist.values() rankedValues = list(reversed(sorted(values))) x = [] y = [] for i in range(0,len(rankedValues)): rank = math.log10(i+1) freq = math.log10(rankedValues[i]) x.append(rank) y.append(freq) rankavg = numpy.mean(x) freqavg = numpy.mean(y) pylab.plot(x,y) return pylab.show() zipfProof(brown.words())
true
73762233b5fc0d1de3d02a74fde9ae76b7a71cd3
jonathancox1/Python104-medium
/leetspeek.py
759
4.21875
4
#convert user input to 'leetspeak' # A -> 4 # E -> 3 # G -> 6 # I -> 1 # O -> 0 # S -> 5 # T -> 7 #ask user for input input = str(input("Give me your text: ")) user_input = input.upper() #define function to check which letter is a leet letter def convert(a): if a == 'A': return '4' elif a == 'E': return '3' elif a == 'G': return '6' elif a == 'I': return '1' elif a == 'O': return '0' elif a == 'S': return '5' elif a == 'T': return '7' else: return a #loop throught the indexes to determin if the character needs to be changed for letter in user_input: leeted = convert(letter) print(leeted, end='') #prints a % at the end of the line???????????
true
4898a3847fde7a21d295238a02391ac968351e7b
yamonc/bigData_course
/base_python/0127/yuanzu.py
816
4.1875
4
# 元组:元组与列表类似也是一种容器数据类型,可以用一个变量(对象)来存储多个数据, # 不同之处在于元组的元素不能修改,在前面的代码中我们已经不止一次使用过元组了。顾名思义, # 我们把多个元素组合到一起就形成了一个元组,所以它和列表一样可以保存多条数据。 t = ('yamon', 24, True, '河北邯郸') print(t) # 获取元组内的内容 print(t[0]) for i in t: print(i) # 重新赋值 t = ('陈亚萌' ,24 ,True , '天津') print(t) # 将元组转化为列表: person = list(t) print(person) # 利用列表修改元素,元组不允许修改元素 person[0] = 'yyh' person[1] = 22 print(person) # 列表转为元组 fruits_list = ['apple', 'banana', 'orange'] tuple=tuple(fruits_list) print(tuple)
false
102d1dacc8b140fb06aa890ad6d866b02a0cfae5
barney1538/CTI110
/P2T1_BarneyHazel.py
446
4.28125
4
#Write a program that ask the user to enter projected total sales then will display the profit that'll be made from that amount. #February 20th, 2020 #CTI-110 P2T1-Sales Prediction #Hazel Barney #Get the projected total sales. total_sales = float(input('Enter the projected sales: ')) #Calculate the profit as 23 percent of total sales. profit = total_sales * 0.23 # Display the profit. print('The profit is $', format(profit, ',.2f'))
true
24074952dc46122d645ee137a840ae05483e7f1e
tgo93/nug
/nug.py
1,491
4.40625
4
""" nug.py - A simple (and silly) calculator that, given a height in feet and inches Tells you how many chicken nuggets tall you are Inspired by https://www.reddit.com/r/CasualConversation/comments/ao63rv/im_approximately_39_chicken_nuggets_tall/ on /r/CasualConversation tgo93 """ import re def main(): playAgain = True pattern = "^(?!$|.*\'[^\x22]+$)(?:([0-9]+)\')?(?:([0-9]+)\x22?)?$" prog = re.compile(pattern) # Avg height of chicken nugget nugget = 1.969 while True: # User inputs height in ft and inches while True: try: height = input("How tall are you? (ex. 5'10\"): ") if prog.match(height) != None: break except ValueError: continue h = height.split("'") # Calculate feet/inches into inches feet = int(h[0]) inches = h[1] if len(inches) == 3: inches = int(h[1][:2]) elif len(h[1]) == 2: inches = int(h[1][:1]) else: inches = 0 totalInches = (feet * 12) + inches totalInches = float(totalInches) # Calculate output heightNugs = round(totalInches / nugget) print("You are " + str(heightNugs) + " chicken nuggets tall!") again = input("Try again? Yes or No: ") if again.lower() not in ['y', 'yes']: break if __name__ == "__main__": main()
false
5b9ce39e7cadfa5a8c91d2f37701345f0e97f366
fernandalozano/-AprendiendoPython
/Conversiones.py
529
4.125
4
# Se declara la variable str con 4 dígitos numero= "1234" # Se muestra el tipo de variable # el type no es un str, es un dato type print(type(numero)) # La cadena se convierte a su equivalente int numero=int(numero) # Se muestra como cambió el tipo pero se usa la misma variable print(type(numero)) # Se declara la str con sustitución salida="El número utilizado es {}" # Al final se muestra el resultado # La sustitución hará que en los corchetes se coloque el valor del número print(salida.format(numero))
false
72e9820a494760fc8146df05992c5f4684442a04
abhijit-mitra/Competitive_Programming
/7_pythagorean_triplet.py
1,070
4.25
4
''' Is pythagorean triplet exist in the given array. Pythagorean triplet means: a^2 + b^2 = c^2. a,b,c could be any elemnt in array. for array = [3,1,4,5,6], one combination is present i.e: 3^2 + 4^2 = 5^2 Optimum solution is having time complexity of n^2. **Trick** 1/Sort the given array. [1,3,4,5,6] 2/Iterate and mutate all elemenst to square of its own value. [1,9,16,25,36] 3/ Set three pointers: [1,9,16,25,36] | | | l r i 4/ if arr[l]+arr[r]==arr[i]:return True else: arr[l]+arr[r]<arr[i]?l++:r-- ''' def is_pythagorean_triplet_exist(arr): arr.sort() arr = [elm*elm for elm in arr] for i in range(len(arr)-1, 1, -1): left = 0 right = i-1 while left < right: res = arr[left]+arr[right] if res == arr[i]: return True if res < arr[i]: left += 1 else: right -= 1 return False if __name__ == '__main__': arr = [3, 1, 4, 5, 6] result = is_pythagorean_triplet_exist(arr) print(result)
true
60a6eb1505bb2788859387d4af931ae036e0de1f
Edmartt/canbesplitted
/tests/test_basic.py
1,816
4.125
4
import unittest from code.backend_algorithm import Splitter class BasicTestCase(unittest.TestCase): """Contiene los metodos para las pruebas unitarias.""" def setUp(self): self.splitter = Splitter() self.empty = [] # empty array for testing empty array result==0 self.array = [1, 3, 3, 8, 4, 3, 2, 3, 3] # an array with the values that add up to 15 each division giving 1 as output self.notsplit = [1, 3, 3, 8, 4, 3, 2, 3, 2] # The output of this array must be -1 self.resultempty = self.splitter.canBeSplitted(self.empty) self.result = self.splitter.canBeSplitted(self.array) self.resultnotsplit = self.splitter.canBeSplitted(self.notsplit) def tearDown(self): del self.splitter self.empty = None self.array = None self.resultempty = None self.result = None def test_splitter_exists(self): """Comprueba que el objeto de Splitter exista.""" self.assertNotEqual(self.splitter, None) def test_arrayIsEmpty(self): """Comprueba si el array ingresado esta vacio. La salida esperada es 0 """ self.assertEqual(self.resultempty, 0) self.assertNotEqual(self.result, 0) def test_array_can_be_splitted(self): """Comprueba si se puede separar el array. La salida esperada es 1. """ self.assertEqual(self.result, 1) self.assertNotEqual(self.result, -1) self.assertNotEqual(self.result, 0) def test_array_cannot_be_splitted(self): """Comprueba si el array no puede ser separado. La salida esperada es -1 """ self.assertEqual(self.resultnotsplit, -1) self.assertNotEqual(self.resultnotsplit, 1) self.assertNotEqual(self.resultnotsplit, 0)
true
6776f5e9be955e1f39672fa52979fa11e606856b
rfdickerson/cs241-data-structures
/A6/app/astar/priorityqueue.py
1,591
4.3125
4
import math def parentindex( curindex): return (curindex - 1) // 2 def leftchild( i ): return i*2 + 1 class PriorityQueue ( object ): """ A priority queue implemented by a list heap You can insert any datatype that is comparable into the heap. The lowest value element is kept at the root of the tree. """ def __init__(self): self.a = [] def insert(self, value): """ insert a node into priority queue""" # WRITE THIS FUNCTION pass def remove(self): """ Returns the element at the top of the heap. Moves the bottom element to the top of the tree and then reheapifies from the top of the heap""" # WRITE THIS FUNCTION pass def reheapify(self, i): """ checks if the left or right is smaller than the top, if so, flips their positions in the heap. Then reheapifies from the the position of the largest child. """ # WRITE THIS FUNCTION pass def __len__(self): """ returns the size of the heap """ return len(self.a) def __str__(self): """ returns the comma seperated values for the heap """ return ",".join(map(str,self.a)) if __name__ == "__main__": """ Use the following code to ensure that the heap will remove the elements from lowest to highest values """ p = PriorityQueue() p.insert(30) p.insert(10) p.insert(80) p.insert(60) p.insert(20) p.insert(30) while len(p): # print p print p.remove()
true
324731e01eddde2390c9fef2645ec76ca9eca3d5
Rim-El-Ballouli/Python-Crash-Course
/solutions/chapter4/ex_4_10.py
305
4.3125
4
cubes = [number**3 for number in range(1, 10)] for cube in cubes: print(cube) print('The first three items in the list are:') print(cubes[:3]) print('Three items from the middle of the list are:') print(cubes[len(cubes)//2:]) print('The last three items in the list are') print(cubes[-3:])
true
534baa4384cb36ce87d60bc82c428bd7a876f532
Rim-El-Ballouli/Python-Crash-Course
/solutions/chapter4/ex_4_11.py
455
4.28125
4
pizza_names = ["Cheese", "Vegetarian", 'Hawaiian', "Peperoni"] for pizza_name in pizza_names: print('I like ' + pizza_name + 'pizza') print('I really like pizza!') friend_pizzas = pizza_names[:] pizza_names.append('Barbecue') friend_pizzas.append('Honey Mustard') print('My friend’s favorite pizzas are:') for pizza in friend_pizzas: print(pizza) print('My original list of pizzas are:') for pizza in pizza_names: print(pizza)
true
dfc48b4f6feadae7923fc0dfd795258492d4f5ed
soundestmammal/machineLearning
/bootcamp/flow.py
1,915
4.125
4
# -*- coding: utf-8 -*- if 3>2: print('This is true') hungry = True if hungry: print('feed me') else: print('Not now, im full') loc = 'Bank' if loc == 'Auto Shop': print('Cars are cool!') elif loc == "Bank": print("You are at the bank") else: print('I do not know much.') name = 'Sammy' if name == 'Frankie': print('Hello Frankie') elif name == 'Sammi': print('Hello Sammi') else: print('What is your name?') #While loops will continue to execute until condition x = 0 while x < 5: print(f'The current value of x is {x}') x += 1 else: print("X is not less than 5") # Break out of th ecurrent closest loop mystring = "This one" for letter in mystring: if letter == "a": continue print(letter) # Continue: goings to the top of the closest englosing loop mystring = "This one" for letter in mystring: if letter == "a": break print(letter) x = 0 while x < 5: if x == 2: break print(x) x += 1 # pass: does nothing at all # Useful operators for num in range(0,11,2): print(num) list(range(0,10,2)) index_count = 0 word = 'abcde' for letter in word: print('At index {} the letter is {}'.format(index_count,letter)) index_count += 1 for index,letter in enumerate(word): print(index) print(letter) print('\n') mylist1 = [1,2,3] mylist2 = ['a','b','c'] for item in zip(mylist1, mylist2): print(item) 'x' in ['x', 'y', 'z'] 'a' in 'a world' 'mykey' in {'mykey' : 355} d = {'mykey': 345} 345 in d.keys() 345 in d.values() mylist = [10,20,30] min(mylist) max(mylist) from random import shuffle mylist = [1,2,3,4,5,6,7,8,9] random_list = shuffle(mylist) mylist from random import randint randint(0,10) result = input('Enter a number here: ') print(result) float(result)
true
41988de645aae080c0fc964cc7656acca922f431
soundestmammal/machineLearning
/bootcamp/oop.py
970
4.40625
4
# This is part one of learning about how objects work in Python. # Python is a class based language. This is different that other languages such as javascript. # How to define a class? class car: pass car = Vehicle() print(car) # Here car is an object (or instance) of the class Vehicle #Vehicle class has 4 attributes: # Number of wheels # Type of tank # Seating capacity # Maximum Velocity class Vehicle: def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity): self.number_of_wheels = number_of_wheels self.type_of_tank = type_of_tank self.seating_capacity = seating_capacity self.maximum_velocity = maximum_velocity class Person: def __init__(first_name, last_name, address): self.number_of_wheels #Above we used the init method. We call it a constructor method. #When we create the vehicle object, we can define this attributes. # Let's create a tesla model s. tesla_model_s = Vehicle(4, 'electric', 5, 250)
true
145b40261b3506d9605fff2a67e135b9e5fc4b6a
soundestmammal/machineLearning
/bootcamp/lists.py
626
4.15625
4
# -*- coding: utf-8 -*- # Lists general version of sequence my_list = [1,2,3] # Lists can hold different object types new_list = ['string', 23, 1.2, 'o'] len(my_list) # Indexing and Slicing my_list = ['one', 'two', 'three', 4, 5] # my_list[0] returns 'one' #my_list[1:] returns 'two' , 'three', 4, 5 my_list[:3] 'hello' + ' world' # Appends to the end of the list # Does not reassign variable. Temporary my_list + ['new item'] my_list = my_list + ['new item'] my_list # Lists are like arrays, but more flexible # They have no type contstraint # Methods l = [1,2,3] l.append('append me') l l.pop() l x = l.pop(0) x
true
592052a96d70f124fe17a0248b4df1f93ada8a14
yarik335/GeekPy
/HT_1/task6.py
412
4.375
4
# 6. Write a script to check whether a specified value is contained in a group of # values. # Test Data : # 3 -> [1, 5, 8, 3] : True # -1 -> (1, 5, 8, 3) : False def Check(mylist,v): return print (v in mylist) myList1 = [1, 5, 8, 3] myList2 = (1, 5, 8, 3) value = int(input("enter your value: ")) print(myList1) Check(myList1,value) print(myList2) Check(myList2,value)
true
66a9a58b8ee04c9a903a6eaacb7c3b7d2c394807
pramilagm/coding_dojo
/python/random_problems/decorator.py
970
4.3125
4
# Decorators are a way to dynamically alter the functionality of your functions. So for example, if you wanted to log information when a function is run, you could use a decorator to add this functionality without modifying the source code of your original function. def decorator_function(original_function): def wrapper_function(*args, **kwargs): return original_function(*args, **kwargs) return wrapper_function # decorated_display = decorator_function(display) # decorated_display() # //with class class decorator_class(object): def __init__(self, original_function): self.original_function = original_function def __call__(self, *args, **kwargs): return self.original_function(*args, **kwargs) @decorator_class def display(): print("Display function ran") @decorator_class def display_info(name, age): print("My name is {} and I am {} years old".format(name, age)) display() display_info("Pramila", 25)
true
6e71070883296d0f4fa69456eb390a2a788114e1
mrmoore6/Module2
/main/camper_age_input.py
463
4.1875
4
""" Program: camper_age_input.py Author: Michael Moore Last date modified: 9/5/2020 The purpose of this program is to convert years into months. """ from main import constants def convert_to_months(year): months = year * constants.MONTHS return(months) if __name__ == '__main__': age_in_years = int(input("Enter years")) age_in_months = convert_to_months(age_in_years) print("{} Year is {} months".format(age_in_years, age_in_months)) #FFF
true
57e01f83db8e55704098bd6fe9910bbcf0643cd3
struppj/pbj-practice
/pbj.py
1,366
4.21875
4
#goal 1 peanut_butter = 1 jelly = 1 bread = 7 if peanut_butter == 1 and jelly == 1 and bread >=2: print "I can make exactly one sandwich" if peanut_butter < 1 or jelly < 1 or bread <=1: print "No sandwich for me" #goal 2 peanut_butter = 4 jelly = 6 bread = 9 if bread >= 2 and peanut_butter >= 1 and jelly >= 1: print "I can make exactly one sandwich!" if bread < 2 and peanut_butter < 1 and jelly < 1: print "No sandwich for me" #goal 3 peanut_butter = 5 jelly = 5 bread = 9 if bread % 2 == 1 and peanut_butter % 2 == 1 and jelly % 2 == 1: print "You have an open faced sandwich" #goal 4 peanut_butter = 3 jelly = 3 bread = 5 if bread % 2 == 1 and peanut_butter % 2 == 1 and jelly % 2 == 1: print "You have an open faced sandwich" if bread % 2 == 1 and peanut_butter % 2 == 1 and jelly % 2 == 0: print "You are missing jelly" if bread % 2 == 0 and peanut_butter % 2 == 1 and jelly % 2 == 1: print "You are missing bread" if bread % 2 == 1 and peanut_butter % 2 == 0 and jelly % 2 == 1: print "You are missing peanut butter" #goal 5 peanut_butter = 5 jelly = 5 bread = 9 if bread >= 2 and peanut_butter is >= 1 and jelly is >=1: print "You can make a peanut butter and jelly sandwich!" if bread >= 2 and peanut_butter is >= 1 and jelly is <1: print "You can make a peanut butter sandwich"
true
6b8b4085784cded514229f7744463d282b03563e
K-Roberts/codewars
/Greed Is Good.py
1,492
4.34375
4
''' Created on Nov 13, 2018 @author: kroberts PROBLEM STATEMENT: Greed is a dice game played with five six-sided dice. Your mission, should you choose to accept it, is to score a throw according to these rules. You will always be given an array with five six-sided dice values. Three 1's => 1000 points Three 6's => 600 points Three 5's => 500 points Three 4's => 400 points Three 3's => 300 points Three 2's => 200 points One 1 => 100 points One 5 => 50 point A single die can only be counted once in each roll. For example, a "5" can only count as part of a triplet (contributing to the 500 points) or as a single 50 points, but not both in the same roll. Example scoring Throw Score --------- ------------------ 5 1 3 4 1 50 + 2 * 100 = 250 1 1 1 3 1 1000 + 100 = 1100 2 4 4 5 4 400 + 50 = 450 ''' def score(dice): twos = dice.count(2) threes = dice.count(3) fours = dice.count(4) fives = dice.count(5) six = dice.count(6) ones = dice.count(1) total = 0 if twos >= 3: total += 200 if threes >= 3: total += 300 if fours >= 3: total += 400 if six >= 3: total += 600 if fives >= 3: total += 500 if fives > 3: total+=50*(fives-3) if ones >= 3: total += 1000 if ones>3: total+=100*(ones-3) if fives < 3: total += 50*(fives) if ones < 3: total += 100*(ones) return total
true
4fd336444011052fc5280b737aab042cfb0ecd1c
jcjessica/Python
/test.py
738
4.25
4
# program that prints out a table with integers from decimal 0 to 255, it's hex number, and the character corresponding to the unicode with UTF-8 encoding # using a loop #for x in range(0, 256): # print('{0:d} {0:#04x} {0:c}'.format(x)) # using list comprehension #ll = [('{0:d} {0:#04x} {0:c}'.format(x)) for x in range(0, 256)] #print( "\n".join(ll) ) def numUpper(str): upper = 0 nonwhite = 0 for x in range(0, len(str)): if str[x].isupper(): upper += 1 if str[x].isspace(): nonwhite += 1 print('Upper {0}'.format(upper)) print('Non-whitespace {0}'.format(nonwhite)) return; # call function with user input from command line (python3 syntax) str = input("input the text: ") numUpper(str)
true
37003d9f0f7ebeba14500e2f9e9d0c535e3c7b04
hacksman/learn_python
/call/calll_demo.py
2,664
4.21875
4
#!/usr/bin/env python # coding:utf-8 # @Time :11/17/18 10:30 """ 📋 --->>> 控制台输出(ter) 🤔 --->>> 解析(thi) 📢 --->>> 说明(exp) 🌰 --->>> 例子(exa) ------>>> 分割线(sep) materials: # Python __call__ special method practical example 1. https://stackoverflow.com/questions/5824881/python-call-special-method-practical-example # 理解 Python 装饰器看这一篇就够了 2. https://foofish.net/python-decorator.html # 简述 __init__、__new__、__call__ 方法 3. https://foofish.net/magic-method.html """ # 1. python中对象可调用和不可调用的概念 # def foo(x): # return x # # # a = foo(3) # # print(callable(a)) # print(callable(foo)) # print(callable(foo(1))) # # # 📋: # # False # # True # # False # # # 📢: # # python中一切皆对象,而对象又分为可调用和不可调用,如上结果所示,其中a是实例对象,不可以再被调用, # # 因此为False,而foo是函数对象,可以被继续调用,因此为True # -------------------------------------------- 分割线 -------------------------------------------- # # 2. __call__ 方法打破实例不可被调用的魔法 # # 🤔: # # 谁说不可被调用我们就一定不可被调用?只要是方便我们的,就拿来玩。call方法就是用来实现实例可以再被调用的黑魔法 # # # class Foo: # # pass # # # # a = Foo() # # a() # # # 📋: # # TypeError: 'Foo' object is not callable # # 📢: # # 提示Foo对象是不可被调用对象,其实这里更准确的说法是a实例,是不可以被调用的对象。而Foo是可以的,我们试下__call__ # # 方法的神奇之处,黑喂狗~ # # # 🌰: # # class Foo: # # def __call__(self, *args, **kwargs): # print("I am __call__ magic...") # return 1 # # a = Foo() # print(a()) # # # 📋: # # I am __call__ magic... # # 1 # # # 📢: # # 神奇吧?将a的实例化对象再次变成了可调用对象了。 # -------------------------------------------- 分割线 -------------------------------------------- # 3. __call__方法的实际应用 import time from datetime import timedelta class RunTime: def __call__(self, f): def inner(*args, **kwargs): time_start = time.time() result = f(*args, **kwargs) time_end = time.time() print("{} run {}".format(f.__name__, timedelta(seconds=time_end-time_start))) return result return inner @RunTime() def foo(x): time.sleep(10) return x print(foo(3))
false
5aec73356d0c740bcc4550dcbacb369edac7d333
theTransponster/Problem-Solving-
/Python/FindSubString.py
1,562
4.1875
4
#This script find a certain substring within a string, and counts how many times it appears def count_substring(string, sub_string):     aux = 0     for i in range(0, len(string), len(sub_string)-1):         #print(i)         if (i + len(sub_string) - 1 ) < len(string):             if i > 0:                  if i + len(sub_string) >= len(string) - 1:                     #print(string[i:i+len(sub_string)+1])                     if sub_string in string[i:i+len(sub_string)+1]:                         aux = aux + 1                         #print(aux)                 else:                     #print(string[i:i+len(sub_string)])                     if sub_string in string[i:i+len(sub_string)]:                         aux = aux + 1                         #print(aux)             else:                  #print(string[i:i+len(sub_string)])                 if sub_string in string[i:i+len(sub_string)]:                     aux = aux + 1                     #print(aux)     return aux if __name__ == '__main__':     string = input().strip()     sub_string = input().strip()          count = count_substring(string, sub_string)     print(count)
false
7e39ffe21c7c929daa5a7e52806206c839427ea8
NamJueun/Algorithms-with-Data-Structure-using-Python
/chap2/리스트스캔/list2.py
370
4.21875
4
## 리스트 스캔 2 : 인덱스와 원소를 짝지어 enumerate() 함수로 반복해서 꺼냅니다. # 리스트의 모든 원소를 enumerate() 함수로 스캔 ➞ enumerate() 함수는 인덱스와 원소를 짝지어 튜플로 꺼내는 내장 함수 x = ['John', 'George', 'Paul', 'Ringo'] for i, name in enumerate(x): print(f'x[{i}] = {name}')
false
4c05f6717795444de47d9c1f73332924cb41eb67
BradleyMidd/learnwithbrad
/calc.py
499
4.3125
4
# Basic Calculator action = True while action: num1 = int(input("Type a number: ")) info = input("Do you want to add, subtract, multiply or divide? \nType [+], [-], [*] or [/]: ") num2 = int(input("Type a second number: ")) if info == "+": print(num1 + num2) elif info == "-": print(num1 - num2) elif info == "*": print(num1 * num2) elif info == "/": print(num1 / num2) else: print("Invalid input") action = False
true
eeadea36a30f7259237e2a1b35219f6bba1d2b1e
ginajoerger/Intro-to-Computer-Programming
/Homework 0/exercise2.py
524
4.28125
4
# HOMEWORK 0 - EXERCISE 2 # Filename: 'exercise2.py' # # In this file, you should write a program that: # 1) Asks the user for a number # 2) Prints 'odd' or 'even' depending on the number's parity # # Example1: # *INPUT FROM THE USER # Enter a number: 17 # *PRINTED OUTPUT # odd # # Example2: # *INPUT FROM THE USER # Enter a number: 4 # *PRINTED OUTPUT # even # new_number = int(input("Please enter a number: ")) if (new_number % 2) == 0: print("Even") else: print("Odd")
true
fa53d19d965f3f5ca2e14ff0bbb84e1841fedce7
DenisVargas/PhytonRoadToMaster
/Tutorial/ListComprehensions.py
991
4.21875
4
#Source: https://www.learnpython.org/en/List_Comprehensions #List Comprenhensions permite crear una nueva lista utilizando una linea mas fácil de enteder. #Example of program # sentence = "the quick brown fox jumps over the lazy dog" # words = sentence.split() # word_lengths = [] # for word in words: # if word != "the": # word_lengths.append(len(word)) # print(words) # print(word_lengths) #El mismo programa podríamos reducirlo a: sentence = "the quick brown fox jumps over the lazy dog" words = sentence.split() word_lengths = [len(word) for word in words if word != "the"] print(words) print(word_lengths) #Funciona encadenanto cosas :O #Otro ejemplo: numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7] newlist = [number for number in numbers if number > 0] print(newlist) #El primer "number" es el resultado final, ahí podemos aplicar algún postprocesado. # seguido de for que se declara como un loop for normal. # if es un condicional que se pone al final.
false
24acebf08c5a78d24db1fd06a3943e4b9f9e23a3
NayoungBae/algorithm
/week_3/08_queue.py
1,518
4.15625
4
class Node: def __init__(self, data): self.data = data self.next = None class Queue: def __init__(self): self.head = None self.tail = None def enqueue(self, value): new_node = Node(value) # 새 노드 생성 if self.is_empty(): # head 또는 tail이 비었는지 안 비었는지에 따라 예외처리 self.head = new_node self.tail = new_node return self.tail.next = new_node # 현재 tail의 다음 노드가 새 노드가 됨 self.tail = new_node # tail을 new_node로 변경 def dequeue(self): if self.is_empty(): # head와 tail이 비어있는 경우 예외처리 return "Queue is empty" delete_node = self.head # 반환하기 위해 미리 저장 self.head = self.head.next # head의 위치 변경 return delete_node.data def peek(self): if self.is_empty(): # 예외처리 return "Queue is empty" return self.head.data # head 노드 반환 def is_empty(self): return self.head is None # head가 비었는지 아닌지만 반환 queue = Queue() queue.enqueue(3) print(queue.peek()) # 3 queue.enqueue(4) print(queue.peek()) # 3 queue.enqueue(5) print(queue.peek()) # 3 print(queue.dequeue()) # 3 print(queue.peek()) # 4 print(queue.is_empty()) # False print(queue.dequeue()) # 4 print(queue.dequeue()) # 5 print(queue.is_empty()) # True
false
cf7107f26f2531a68e5a23c9ffa51090d1d1be7b
NayoungBae/algorithm
/week_2/03_add_node_linked_list_nayoung.py
1,567
4.15625
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self, data): self.head = Node(data) def append(self, data): if self.head is None: self.head = Node(data) return current_node = self.head while current_node.next is not None: current_node = current_node.next current_node.next = Node(data) def print_all(self): if self.head is None: print("Node is None") return current_node = self.head while current_node is not None: print(current_node.data) current_node = current_node.next def get_node(self, index): current_index = 0 current_node = self.head while current_node is not None: if current_index == index: return current_node current_node = current_node.next current_index += 1 return "Node is None!!" # index 번째 원소값을 추가 def add_node(self, index, data): current_index = 0 current_node = self.head while current_index < index - 1: current_node = current_node.next current_index += 1 next_node = current_node.next current_node.next = Node(data) current_node.next.next = next_node linked_list = LinkedList(5) linked_list.append(12) linked_list.print_all() # 5 -> 12 print() linked_list.add_node(1, 3) linked_list.print_all() # 5 -> 3 -> 12
true
338ae906f91e5ab7dd8a9f7df31384bb894ba409
kukaiN/Sudoku_solver
/sudoku_checker.py
1,787
4.125
4
def num_in_row(board, row_number, col): """ returns a list of values that are on the same row""" return list({board[row_number][i] for i in range(len(board)) if col != i } - set([0])) def num_in_column(board, column_number, row): """ returns a list of values that are on the same column""" return list({board[i][column_number] for i in range(len(board)) if row != i} - set([0])) def main(): # the board to be checked board = [[8, 9, 3, 5, 1, 2, 6, 7, 4], [4, 1, 7, 6, 3, 8, 2, 9, 5], [2, 5, 6, 4, 7, 9, 3, 8, 1], [5, 6, 2, 7, 8, 3, 1, 4, 9], [1, 7, 4, 9, 5, 6, 8, 3, 2], [9, 3, 8, 1, 2, 4, 5, 6, 7], [7, 8, 9, 2, 6, 5, 4, 1, 3], [6, 4, 5, 3, 9, 1, 7, 2, 8], [3, 2, 1, 8, 4, 7, 9, 5, 6] ] n = 9 root_n = 3 # checks if there's inconsistencies in the horizonatal and vertical components for j in range(n): for i in range(n): current_num = board[j][i] x = num_in_column(board, i, j) y = num_in_row(board, j, i) if current_num in x or current_num in y: print("False") # check if there's inconsistencies in the boxes of the sudoku board for j in range(n): # iterating through the points for i in range(n): box_x, box_y = int(i/root_n)*root_n, int(j/root_n)*root_n for ni in range(root_n): # iterating through the box for nj in range(root_n): coor_x, coor_y = box_x+ni, box_y+nj if coor_x != i or coor_y != j: if board[j][i] == board[coor_y][coor_x]: print("box false,", i, j, coor_x, coor_y) if __name__ == "__main__": main()
true
397ac1c9fe38ca7a4352d42e0da2e1c0e794c2b9
grayreaper/pythonProgrammingTextbook
/futval.py
1,131
4.125
4
# futval.py # A program to compute the value of an investment # carried 10 years into the future ###This is not working properly!! ###This is not working properly!! ###This is not working properly!! ###This is not working properly!! ###This is not working properly!! ###This is not working properly!! ###This is not working properly!! ###This is not working properly!! ###This is not working properly!! def main(): print("This program calculates the future value") print("of an investment.") total = eval(input("Enter the amount of initial principal: $")) add = eval(input("Enter any additional amount you plan to add each year: $")) apr = eval(input("Enter the annual percentage rate as a decimal: ")) compound = eval(input("How many times per year does the interest compound?\nEnter 1 if you don't know. ")) years = eval(input("How many years will this be invested?")) for i in range(years * compound): total = (1 + (apr / compound)) * (total + add) print("The value in", years, "years will be $",total) main()
true
a3ed36e4bdedfb614019876ac85e1071883a9625
grayreaper/pythonProgrammingTextbook
/feetToMilesConvert.py
333
4.25
4
# feetToMilesConvert.py # This program converts feet to miles # BY: Gray Reaper def main(): print("This Program converts a distance in feet to miles") feet = eval(input("Enter the distance in feet: ")) miles = feet / 5280 print("The distance in miles is", miles) input("Press ENTER to exit.") main()
true
c3560cced795faf82745f4beeea0e21cf802aa51
WenJuing/scrapy-douBan
/study/dog.py
1,336
4.15625
4
'''一个关于狗的类''' class Dog(): '''一只可爱的小狗''' def __init__(self, name, age): # 使用类时自动运行,接收参数并返回实例 self.name = name self.age = age def sit(self): '''坐下命令''' print(self.name.title(), "is now sitting!") def describe_dog(self): '''输出小狗信息''' print("Dog's name is", self.name.title(), "and age is", str(self.age) + ".") def roll_over(self): '''打滚命令''' print(self.name.title(), "is rolled over!") def update_age(self, age): '''修改年龄''' if age > self.age: self.age = age else: print("You can't roll back age!") '''一个关于聪明狗的类''' class SmartDog(Dog): '''较聪明的狗''' def __init__(self, name, age, IQ='high'): super().__init__(name, age) # 注意,这里不需要self参数 self.IQ = IQ # 新增属性 def show_IQ(self): # 新增方法 '''展示IQ''' print(self.name + "'s IQ is " + self.IQ + ".") def describe_dog(self): # 重写方法 '''新的输出小狗信息''' print("Smart dog's name is " + self.name.title() + ",IQ is", self.IQ + " and age is " + str(self.age) + ".")
false
6b2d62a961fbc59098767452676fe067a3e6755b
WenJuing/scrapy-douBan
/C3-ComPythonScript/3.5-inheritClass.py
1,246
4.375
4
# 演示新类的继承 class Spider(object): '''蜘蛛子,最原始的蜘蛛形态''' eyes = 4 legs = 8 weight = 0.02 iq = '低下' def __init__(self): '''初始化''' self.name = '蜘蛛子' self.show() def show(self): print("我叫%s" % self.name) print("我有%d个眼睛和%d条腿,体重为%.2f,智力%s" % (self.eyes, self.legs, self.weight, self.iq)) print("\n") class BigSpider(Spider): '''于原本小小的蜘蛛相比,体积猛增了好几倍''' eyes = 6 weight = 5.55 iq = '一般' def __init__(self): self.name = '巨型蜘蛛' self.show() class SmallSipder(BigSpider): '''着重于智慧与灵敏度,智慧上升体重反而减少''' legs = 10 weight = 2.33 iq = '较高' def __init__(self): self.name = '智慧蜘蛛子' self.show() class MaxSpider(SmallSipder): '''终极进化''' eyes = 10 weight = 3.12 iq = '无所不知' def __init__(self): self.name = '蜘蛛女王' self.show() if __name__ == '__main__': spider = Spider() bigSpider = BigSpider() smallSipder = SmallSipder() maxSpider = MaxSpider()
false