blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
7e031eb448258d9eaa83f2f7526e6a8c82d66451
Xiankai-Wan/Python-Quiz-Summarize
/Python-语法/Part2/2-17_创建程序段4.py
2,026
4.375
4
# 练习:组合 scores_to_rating 函数 # 先前所有帮助函数都构建得不错!现在可以将所有这些函数组合到一起,使其成为一个整体进行运行。 # # 在该编程练习中,将编写的每个帮助函数放入编码窗口,然后在编写函数 scores_to_rating 时使用。请注意,此函数以五个分数(可能不是数字)开始,取中间三个分数的平均值,并将该平均值转换为返回的书面评分。 # # 需要确保将一个函数的输出正确传递到 scores_to_rating 函数体的下一个输入。一次添加一个,同时还需添加有用的注释,而且调用 print 进进行测试,将有助于控制错误! def convert_to_numeric(score): """Covert the score to a float """ return float(score) def sum_of_middle_three(score1,score2,score3,score4,score5): """ Find the sum of the middle three numbers out of the five given. """ max_score = max(score1,score2,score3,score4,score5) min_score = min(score1,score2,score3,score4,score5) sum = score1 + score2 + score3 + score4 + score5 - max_score - min_score return sum def score_to_rating_string(score): rating = "Excellent" if 0 <= score < 1: rating = "Terrible" elif 1 <= score < 2: rating = "Bad" elif 2 <= score < 3: rating = "OK" elif 3 <= score < 4: rating = "Good" else: rating = rating return rating def scores_to_rating(score1,score2,score3,score4,score5): """ Turns five scores into a rating by averaging the middle three of the five scores and assigning this average to a written rating. """ score11 = convert_to_numeric(score1) score22 = convert_to_numeric(score2) score33 = convert_to_numeric(score3) score44 = convert_to_numeric(score4) score55 = convert_to_numeric(score5) average_score = sum_of_middle_three(score11,score22,score33,score44,score55)/3 rating = score_to_rating_string(average_score) return rating
false
6a7baeecd50abc0b4f7df9229f1cf6b4c0924ede
Xiankai-Wan/Python-Quiz-Summarize
/访问文件与网络/Part1/1-2_元组.py
760
4.125
4
# 练习:天和小时 # 尝试编写一个使用元组返回多个值的函数。编写 hours2days 函数,传入一个整数类型的参数,该参数表示一个以小时为单位的时间段。该函数应该返回一个元组,用天和小时为单位表示传入的时间段,不足一天的时间用小时表示。例如,39 个小时表示 1 天 15 个小时,所以函数返回的应该是 (1,15)。 # # 这些例子演示了该函数的使用: # >>> hours2days(24) # 24 hours is one day and zero hours # (1, 0) # >>> hours2days(25) # 25 hours is one day and one hour # (1, 1) # >>> hours2days(10000) # (416, 16) def hours2days(input_hours): day = int(input_hours/24) hour = input_hours%24 return day,hour print(hours2days(24))
false
7d898892b8d486b5639235ee8e5d5a6f8f186b44
dkbozkurt/Global_AI_Hub_Python_Programming
/Global AI Hub #1.py
1,209
4.15625
4
#!/usr/bin/env python # coding: utf-8 # In[2]: #Python as a calculator # In[3]: 3+5 # # Functions # In[4]: print(4+6) # In[6]: print(7) # In[5]: print("Hello World") # In[7]: #commenting # In[8]: """ It is just a note. 3 2 1 1 2 3 """ # # Variable Assignment # In[9]: n=300 # In[10]: n # In[11]: print(n) # In[12]: type(n) # In[13]: m=n # In[14]: print(m) # In[16]: m=400 # In[17]: print(type(m)) # In[20]: hi= "World" # In[21]: print(hi) # In[22]: print(type(hi)) # In[24]: t=3.5 print(type(t)) # In[26]: t= True print(type(t)) # In[25]: t,f=True, False print(type(t)) # In[29]: print(len(hi)) #veri uzunlugunu yazdırma # In[37]: name="Dogukan" surname = "Bozkurt" print(f"Hi {name} {surname}") # F-String # # Computations # In[38]: 5**2 # In[41]: "35"+"67" # In[42]: "35"* 3 # In[43]: "hello"*4 # In[44]: x=10 # In[45]: print(x+2) # In[46]: print(x**2) #x degisiklige ugramaz sadece etkiler. # In[50]: print(x%3) # In[47]: print(x-2) # In[48]: y=13 # In[49]: print(y/2) # In[51]: z=5 # In[52]: z=z+1 # = z++ , z+=1 # In[53]: z # In[55]: z*=2 print(z)
false
f4e93b4983e001ef62240ee2f29b0eceebaf8384
AngelBlack888/public
/raznoe/4_set_frozenset.py
1,757
4.1875
4
# ================================= # Set (множество) # ================================= print() print('-= set =-') # Множество — «контейнер», содержащий не повторяющиеся элементы в случайном порядке. a = set() print(a) # set() b = set(['a', 'b', 'c', 'c', 'a', 'e']) print(b) c = set('hello') print(c) d = {'a', 'b', 'c', 'd'} print(d) e = {i ** 2 for i in range(10)} # генератор множеств print(e) f = {} # А так получится словарь print(type(f)) # <class 'dict'> # Операции с множествами print (len(e)) print ('b' in b) # s == t c1 = {'e', 'l', 'o', 'h'} print (c==c1) # s.issubset(t) s <= t print(c<=c1) # s.issuperset(t) s >= t print(c>={'h'}) # s.union(t, …) s | t print(b | d) # s.intersection(t, …) s & t print(b & d) # s.difference(t, …) s - t print(d - b) # s.symmetric_difference(t) s ^ t print(d ^ b) # s.copy() f = e g = e.copy() print('e:', id(e)) print('f:', id(f)) print('g:', id(g)) # Методы, изменяющие множества # s.update(other, …) s |= t b |= d print(b) # s.intersection_update(t) s &= t b &= d print(b) # s.difference_update(t) s -= t b -= {'a', 'b'} print(b) # s.symmetric_difference_update(t) s ^= t b ^= c print(b) # s.add(elem) b.add(1) print(b) # s.remove(elem) b.remove('h') print(b) # b.remove('z') # s.discard(elem) b.discard(1) print(b) b.discard('z') # ошибки не возникает # s.pop() print(b.pop()) print(b) # s.clear() b.clear() print(b) # frozenset a = frozenset('hellow') b = set('hellow') print(a==b) print(type(a-b)) print(type(b|a)) b.add('q') # a.add('q') # вызовет ошибку
false
db152888584f85403424f21c0bb6ef79efb75caf
mihau1987/Python_basics
/Trello_Zadania/03_Instrukcje_Warunkowe/02_Zadania_dodatkowe/Zadanie_slodycze.py
1,215
4.15625
4
slodycze = ['paczek', 'drozdzowka', 'gniazdko', 'jagodzianka', 'szarlotka', 'muffin'] '''question = input("Czego sobie życzysz? ") if question in slodycze: print("Podany produkt jest dostepny") else: print("Niestety nie posiadamy artykulu na stanie") q1 = input("Podaj produkt no 1: ") q2 = input("Podaj produkt no 2: ") q3 = input("Podaj produkt no 3: ") if q1 in slodycze: print("Podane produkty sa dostepne") else: print("Niestety nie posiadamy artykulu na stanie") if q2 in slodycze: print("Podane produkty sa dostepne") else: print("Niestety nie posiadamy artykulu na stanie") if q3 in slodycze: print("Podane produkty sa dostepne") else: print("Niestety nie posiadamy artykulu na stanie") q1 = input("Podaj produkt no 1: ") q2 = input("Podaj produkt no 2: ") q3 = input("Podaj produkt no 3: ") if q1 and q2 and q3 in slodycze: print("Podane produkty sa dostepne") else: print("Niestety nie posiadamy produktow na stanie")''' q = input("Podaj nazwę produktu a dowiesz sie ile sztuk posiadamy: ") if q in slodycze: print("Na stanie mamy 12 sztuk podanego produktu") else: print("Niestety w tym momencie nie posiadamy produktu na stanie")
false
04615dd74772aafcd67fe47862bb41368f428b8c
mihau1987/Python_basics
/Trello_Zadania/03_Instrukcje_Warunkowe/02_Zadania_dodatkowe/Exercise_01.py
1,189
4.125
4
''' Napisz program, który zawiera listę zwierząt. Poproś użytkownika o 3 zwierzęta, a następnie sprawdz czy: - wprowadzone napisy są zwierzętami z listy - zawierają taką samą liczbę liter - czy zawierają taka samą liczbę liter A - czy kończą się na tę samą literę ''' #1. Tworzę listę zwierząt #2. Tworzę input z zapytaniem #3. Tworzę warunek który sprawdza czy napisy są zwierzętami z listy animals = ["cat", "dog", "aligator", "anaconda", "albatros", "lemur", "amur"] ani_1 = input("Enter animal no 1 name: ") ani_2 = input("Enter animal no 2 name: ") ani_3 = input("Enter animal no 3 name: ") if ani_1 and ani_2 and ani_3 in animals: print("Animals are in the list") if len(ani_1) == len(ani_2) == len(ani_3): print("Lenght is the same") if ani_1.count("a") and ani_2.count("a") and ani_3.count("a"): print("They all have letter A") if ani_1[-1] == ani_2[-1] == ani_3[-1]: print("They all end's with the same letter") else: print("These animals are not on the list") #Coś mi się wydaje że skopałem temat inputów, może powinny być oddzielone przecinkiem, czyli metoda split się kłania?
false
65b15a041ebd8a1cfc5ff1ca227bf741a9ee45c7
mihau1987/Python_basics
/Udemy/Kurs_Rafal_Modulo/Ify/Calculator_exercise.py
437
4.15625
4
choice = input("* - multiplication, / - division, + - adding, - - subtrackt, ** - exponentiation: ") a = int(input("First: ")) b = int(input("Second: ")) if (choice == "*"): print(a*b) elif (choice == "/"): if (b == 0): print("Dont you dare!") else: print(a/b) elif (choice == "+"): print(a+b) elif (choice == "-"): print(a-b) elif (choice == "**"): print(a**b) else: print("Wrong choice!")
false
8dab454b9b2d3b9fa8e1c7979b921cce2ac269c2
Tcrumy/Startin-Out-with-Python-2nd-Edition-by-Tony-Gaddis
/Chapter 6/Programming Challenges/1. Feet to Inches.py
648
4.4375
4
# One foot equals 12 inches. Write a function named feet_to_inches that accepts # a number of feet as an argument, and returns the number of inches in that many # feet. Use the function in a program that prompts the user to enter a number of # feet and then displays the number of inches in that many feet. def main(): feet = float(input("Enter an amount in feet: ")) inches = feet_to_inches(feet) print(feet, "Feet is", inches, "inches") # This function will accept a float argument for feet # It will return the amount of inches in that many feet def feet_to_inches(feet): return feet * 12 main()
true
22d557acd05c452e8efa0c2a8e5ff15671079373
Tcrumy/Startin-Out-with-Python-2nd-Edition-by-Tony-Gaddis
/Chapter 7/Programming Challenges/6. Average Numbers.py
889
4.53125
5
# Assume that a file containing a series of integers is named numbers.txt and # exists on the computer’s disk. Write a program that calculates the average of # all the numbers stored in the file. def main(): # Open the file num_file = open("numbers.txt") # Read the first line of the file line = num_file.readline() # Initialize an accumulator for the sum of the integers in the file # and an accumulator to the total quantity of numbers stored in the file sum = 0 num_of_nums = 0 while line != "": # Convert the number string into an int num = int(line) # Add the number to sum and add 1.0 to num_of_nums sum += num num_of_nums += 1.0 # Read the next line line = num_file.readline() # Display the sum print("Average:", sum/num_of_nums) main()
true
aba55620a2f212e5e180726919191a05cd7e97f4
Tcrumy/Startin-Out-with-Python-2nd-Edition-by-Tony-Gaddis
/Chapter 5/Programming Challenges/5. Average Rainfall.py
1,292
4.59375
5
# Write a program that uses nested loops to collect data and calculate the # average rainfall over a period of years. The program should first ask for the # number of years. The outer loop will iterate once for each year. The inner # loop will iterate twelve times, once for each month. Each iteration of the # inner loop will ask the user for the inches of rainfall for that month. After # all iterations, the program should display the number of months, the total # inches of rainfall, and the average rainfall per month for the entire period. # Prompt user for number of years years = int(input("Enter how many years of data was collected: ")) # Define accumulator variable for rainfall total total_rainfall = 0 # Calculate the number of months of data collected months_of_data = 12 * years # Write for loop to perform ranfall calculations for year in range(years): for month in range(1,13): print("Enter rainfall data for year", year + 1, "month", month, ": ", end = "") rainfall_this_month = float(input()) total_rainfall += rainfall_this_month print(months_of_data, "Months of data have been collected.") print("Total rainfall: ", total_rainfall) print("Month Average: ", total_rainfall / months_of_data)
true
5540af3451ef8967f49af825150fc02b574ef60f
Tcrumy/Startin-Out-with-Python-2nd-Edition-by-Tony-Gaddis
/Chapter2/Programming Challenges/6. Sales Tax.py
1,410
4.21875
4
# Write a program that will ask the user to enter the amount of a purchase. # The program should then compute the state and county sales tax. Assume the # state sales tax is 4 percent and the county sales tax is 2 percent. The # program should display the amount of the purchase, the state sales tax, the # county sales tax, the total sales tax, and the total of the sale(which is the # sum of the amount of purchase plus the total sales tax). # Hint: use the value 0.02 to represent 2 percent, and 0.04 to represent 4 percent. # Create two variables to hold the county and state sales tax rate respectivly county_tax_rate = .02 state_tax_rate = .04 # Prompt user to enter amount of purchase. This will be the subtotal since # only one item/purchase amount is being asked for subtotal = float(input("Enter Purchase Amount: ")) # Calculate county and state tax county_tax = subtotal * county_tax_rate state_tax = subtotal * state_tax_rate # Calculate total sales tax total_sales_tax = county_tax + state_tax # Calculate total total = subtotal + county_tax + state_tax # Display information to the user formated to 2 decimal places print("Subtotal: ", format(subtotal, ",.2f")) print("State tax: ", format(state_tax, ",.2f")) print("County tax:", format(county_tax, ",.2f")) print("Total tax: ", format(total_sales_tax, ",.2f")) print("Total: ", format(total, ",.2f"))
true
4c3bb32c9e3fd296b507f7f6b173c6e9f36dd0dd
Tcrumy/Startin-Out-with-Python-2nd-Edition-by-Tony-Gaddis
/Chapter 7/Programming Challenges/7. Random Number File Writer.py
626
4.28125
4
# Write a program that writes a series of random numbers to a file. Each random # number should be in the range of 1 through 100. The application should let the # user specify how many random numbers the file will hold. import random def main(): rand_num_file = open("randomNumbers.txt","w") # Ask user how many random numbers to generate nums_to_generate = int(input("Enter the quantity of numebrs to generate: ")) # Write user requested quantity of random numbers to file for num in range(nums_to_generate): rand_num_file.write(str(random.randint(0,100)) + "\n") main()
true
34fca6b8c74ac727ee54a98947ec783ffb0090b9
Tcrumy/Startin-Out-with-Python-2nd-Edition-by-Tony-Gaddis
/Chapter 4/Programming Challenges/4. Magic Dates.py
1,030
4.53125
5
# The date June 10, 1960, is special because when it is written in the # following format, the month times the day equals the year: # 6/10/60 # Design a program that asks the user to enter a month (in numeric form), # a day, and a two digit year. The program should then determine whether the # month times the day equals the year. If so, it should display a message saying # the date is magic. Otherwise, it should display a message saying the date is # not magic. # Prompt user for month as a digit 1-12 month = int(input("Enter the month as a digit 1-12: ")) # Prompt user for day as a digit 1-31 day = int(input("Enter the day as a digit 1-31: ")) # Prompt the user for the year as a two digit number year = int(input("Enter the year as a two digit number ex.(1960 = 60): ")) # Use an if-else structure to determine if # the date is a magic date and display this # to the user if month * day == year: print("The date is magic.") else: print("The date is not magic.")
true
0af906a373f8a62f8bbd15215ca64ae3a4e2396f
Tcrumy/Startin-Out-with-Python-2nd-Edition-by-Tony-Gaddis
/Chapter 4/Programming Challenges/2. Areas of Rectangles.py
1,075
4.4375
4
# The area of a rectangle is the rectangle’s length times its width. Write a # program that asks for the length and width of two rectangles. The program # should tell the user which rectangle has the greater area, or if the areas # are the same. # Prompt user for length and width of the first rectangle length1 = int(input("Enter the length of rectangle 1: ")) width1 = int(input("Enter the width of rectangle 1: ")) # Prompt user for length and width of the second rectangle length2 = int(input("Enter the length of rectangle 2: ")) width2 = int(input("Enter the width of rectangle 2: ")) # Calculate the areas of each triangle area1 = length1 * width1 area2 = length2 * width2 # Use an if else structure to determing which # rectangle has the largest area, and display # that information to the user if area1 > area2: print("Rectangle 1 is larger.") elif area2 > area1: print("Rectangle 2 is larger") # If this else is executed, the rectangles are the same size else: print("Rectangle 1 and rectangle 2 are the same size")
true
4dd50af0c14fa9da080ea1cd951f1d4960c224e9
Tcrumy/Startin-Out-with-Python-2nd-Edition-by-Tony-Gaddis
/Chapter 5/Algorithm Workbench/8.py
324
4.46875
4
# Write code that prompts the user to enter a positive nonzero number and # validates the input. number = int(input("Enter a positive nonzero number: ")) # Validate the input while number <= 0: print("Number was not positive/nonzero, try again") number = int(input("Enter a positive nonzero number: "))
true
dce0e4734a850a9ed0ee2b0fe18171c7fee1a7ca
Tcrumy/Startin-Out-with-Python-2nd-Edition-by-Tony-Gaddis
/Chapter 5/Algorithm Workbench/9.py
330
4.25
4
# Write code that prompts the user to enter a number in the range of 1 through # 100 and validates the input. number = int(input("Enter a number 1-100: ")) # Validate the input while number < 1 or number > 100: print("Number was not in range 1-100, try again") number = int(input("Enter a number 1-100: "))
true
24c43eda8a7fb649df6af835e378411bd86ae44b
99003760/coding_writing
/Hackerrank/Python/Math.py
1,356
4.21875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # @Author: xuezaigds@gmail.com # @Last Modified time: 2016-05-04 20:42:07 ''' You are given a complex z. Your task is to convert it to polar coordinates. ''' import cmath com = raw_input() pha = cmath.phase(complex(com)) r = abs(complex(com)) print "{0}\n{1}".format(r, pha) ''' ABC is a right triangle, 90° at B. Therefore, ∡ABC=90°. Point M is the midpoint of hypotenuse AC. You are given the lengths AB and BC. Your task is to find ∡MBC in degrees. ''' import math AB = int(raw_input()) BC = int(raw_input()) print str(int(round(math.degrees(math.atan2(AB, BC))))) + '°' ''' You are given a positive integer N. Your task is to print a palindromic triangle of size N. For example, a palindromic triangle of size 5 is: 1 121 12321 1234321 123454321 You can't take more than two lines. The first line (a for-statement) is already written for you. You have to complete the code using exactly one print statement. ''' for i in range(1, int(raw_input()) + 1): print ((10 ** i - 1) // 9)**2 ''' You are given a positive integer N. Print a numerical triangle of height N−1 like the one below: 1 22 333 4444 55555 ...... Can you do it using only arithmetic operations, a single for loop and print statement? Use no more than two lines. ''' for i in range(1, input()): print ((10 ** i - 1) // 9) * i
true
d1fbcca104542dd0bba86c0de5028783220d88c0
salvadorraymund/Python
/Algorithms/Sort/merge_sort.py
1,797
4.125
4
from random import randint from timeit import repeat def run_sorting_algo(algorithm, array): setup_code = f"from __main__ import {algorithm}" \ if algorithm != "sorted" else "" stmt = f"{algorithm}({array})" times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=10) print(f"Algorithm: {algorithm}. Minimum execution time:{min(times)}") def merge(left, right): if len(left) == 0: return right if len(right) == 0: return left result = [] index_left = index_right = 0 # instead of using while len(result) < len(left) + len(right) while True: if left[index_left] <= right[index_right]: result.append(left[index_left]) index_left += 1 else: result.append(right[index_right]) index_right += 1 if index_right == len(right): result += (left[index_left:]) break if index_left == len(left): # instead of using append, the remaining items in left/right were added to the list result result += (right[index_right:]) # if break will be removed, index_left and index_right will continuously increase, thereby causing list index # to be out of range break return result def merge_sort(array): if len(array) < 2: return array midpoint = len(array) // 2 left = array[:midpoint] right = array[midpoint:] # print(left) # print(right) return merge(left=merge_sort(array[:midpoint]), right=merge_sort(array[midpoint:])) array = [8, 2, 4, 6, 5] print(merge_sort(array)) array_length = 10000 if __name__ == "__main__": array = [randint(0, 1000) for i in range(array_length)] run_sorting_algo(algorithm="merge_sort", array=array)
true
762c57193b924ce19bf45889c826cbdee91489af
salvadorraymund/Python
/Real Python/Web Scraping/reg_ex_primer.py
1,391
4.375
4
import re # search for the pattern ab*c in the expression ac # Regular expression ab*c matches any part of the string that begins with an "a" # and ends with a "c", and has zero instances of "b" between them # print(re.findall("ab*c", "ac")) # print(re.findall("ab*c", "abcd")) # print(re.findall("ab*c", "acc")) # print(re.findall("ab*c", "abac")) # print(re.findall("ab*c", "abdc")) pattern = "ab*c" # Pattern matching is case sensitive ex1 = re.findall(pattern, "ABC") print(ex1) # pass in re.IGNORECASE as third argument to ignore case sensitivity ex1 = re.findall(pattern, "ABC", re.IGNORECASE) print(ex1) # using period(.) to stand for any single character # in the example below, finding all the strings that contains the letter "a" and "c" separated by a single character ex2 = re.findall("a.c", "abc") print(ex2) # period(.) can only stand for 1 character ex3 = re.findall('a.c', 'abbc') print(ex3) # The pattern .* inside a regular expression stands for any character repeated any number of times. pattern2 = "a.*c" ex4 = re.findall(pattern, "abc") print(ex4) ex5 = re.findall(pattern, "abbc") print(ex5) match_results = re.search(pattern, 'ABC', re.IGNORECASE) print(match_results.group()) string = "Everything is <replaced> if it's in <tags>" my_string = re.sub("<.*>", "ELEPHANTS", string) print(my_string) string2 = re.sub("<.*?>", "ELEPHANTS", string) print(string2)
true
b55342707183858f4babd1aa9a54d888c6ef24d8
salvadorraymund/Python
/Dates and Timels/formatting.py
553
4.1875
4
from datetime import datetime # %Y/%y - Year, %A/%a - weekday, %B/%b - month, %d - day of month now = datetime.now() print(now.strftime("The current year is: %Y")) print(now.strftime("%d, %a %B, %y")) # %c - local date and time, %x - local date, %X - local time print(now.strftime("Local date and time: %c")) print(now.strftime("Local date: %x")) print(now.strftime("Local time: %X")) # %I/%H - 12/24 hour, %M - minute, %S - second # %p - locale's AM/PM print(now.strftime("Current time: %I:%M:%S %p")) print(now.strftime("Current time: %H:%M:%S"))
false
1e3375fc53ea8c23a7433c75d87f4c4a929ee28d
tushar-rishav/Algorithms
/Archive/Contests/Codechef/Contest/Others/CodeStorm/grade.py
490
4.125
4
#! /usr/bin/env python def power(base, exponent): remaining_multiplicand = 1 result = base while exponent > 1: remainder=exponent % 2 if remainder > 0: remaining_multiplicand = remaining_multiplicand * result exponent = (exponent - remainder) / 2 result = result * result return result * remaining_multiplicand def main(): t=input() while t: n=input() res=power(7,n)%(10**9+7) print res t-=1 if __name__=="__main__": main()
true
70f2c7824b157cfe8ca27f0610e5bba00feb488c
jgnotts23/CMEECourseWork
/Week2/Code/lc1.py
1,459
4.59375
5
#!/usr/bin/env python3 """ A demonstration of the use of loops and list comprehensions to output data from a tuple of tuples """ __appname__ = 'lc1.py' __author__ = 'Jacob Griffiths (jacob.griffiths18@imperial.ac.uk)' __version__ = '0.0.1' ### Constants ### birds = ( ('Passerculus sandwichensis','Savannah sparrow',18.7), ('Delichon urbica','House martin',19), ('Junco phaeonotus','Yellow-eyed junco',19.5), ('Junco hyemalis','Dark-eyed junco',19.6), ('Tachycineata bicolor','Tree swallow',20.2), ) ### Functions ### # List comprehensions # Latin names print("Bird data imported:") print(birds) print("\nFinding latin names with list comprehension...") ln_lc = set([item[0] for item in birds]) print(ln_lc) # Common names print("\nFinding common names with list comprehension...") cn_lc = set([item[1] for item in birds]) print(cn_lc) # Mean body masses print("\nFinding mean body masses with list comprehension...") mbm_lc = set([item[2] for item in birds]) print(mbm_lc) # Conventional loops # Latin names print("\nFinding latin names with a loop...") ln_loop = set() for values in birds: ln_loop.add(values[0]) print(ln_loop) # Common names print("\nFinding common names with a loop...") cn_loop = set() for values in birds: cn_loop.add(values[1]) print(cn_loop) # Mean body masses print("\nFinding mean body masses with a loop...") mbm_loop = set() for values in birds: mbm_loop.add(values[2]) print(mbm_loop)
true
79c943c6d2aacb349e7440bb35e8a8ee32c4bfb9
the-hobbes/misc
/smallest_snippet.py
2,571
4.125
4
#!/usr/bin/python ''' Smallest snippet problem: Find the smallest snippet that contains all the search key words. For example: input_list = ['a', 'car', 'has', 'a', 'dog'] search_words = ['a', 'dog', 'has'] Possible output: [0, 4] [2, 4] Desired output (the shortest snippet) is [2, 4] ''' input_list = ['a', 'car', 'has', 'a', 'dog'] search_words = ['a', 'dog', 'has'] def exponential_solution(): # this is the naive solution, that has O(n^2) running time solution = [] shortest_result = [-1, -1] shortest_length = -1 for i in range(len(input_list)): copy = search_words[:] if input_list[i] in copy: shortest_result[0] = i # save away the first hit we've got copy.remove(input_list[i]) # and remove it from the list words to look for, since we've already found it for j in range(i, len(input_list)): # now, look through the rest of the list, if input_list[j] in copy: # we've located another keyword copy.remove(input_list[j]) # remove the keyword from the copied search terms shortest_result[1] = j # update the ending bound of the snippet if len(copy) < 1: # we've found all the values we are searching for, now we see if this snippet is the shortest we've found so far length_of_snippet = shortest_result[1] - shortest_result[0] if shortest_length == -1 or length_of_snippet <= shortest_length: shortest_length = length_of_snippet solution.append(shortest_length) print 'Length of smallest snippet: ' + str(shortest_length) print 'The start and end of smallest snippet: ' + str(sorted(solution)) def linear_solution(): # this is the clever solution, with O(n) running time indecies = {} for item in search_words: # make a dictionary of the search terms indecies[item] = -1 for i in range(len(input_list)): # each time we find a search term, update its position in the dictionary if input_list[i] in indecies: indecies[input_list[i]] = i # now we have the positions of the shortest snippet, we need to pick out the max and min min_index = min(indecies.values()) max_index = max(indecies.values()) print 'Length of smallest snippet: ' + str(max_index - min_index) print 'The start and end of smallest snippet: [%d, %d]' % (min_index, max_index) def main(): print '------------Exponential Solution------------' exponential_solution() print '\n------------Linear Solution------------' linear_solution() if __name__ == '__main__': main()
true
f530c79e55ad41914a21202de56aaf1a2f8ad028
Sourabhsk870/5TH-SEM-NOTES
/18CS55/Sample Programs/Code/prog2.py
225
4.3125
4
# WAP TO READ TWO NUMBERS AND FIND THE LARGEST ONE print("Enter two numbers:") a = int (input() ) b = int (input() ) if a == b: print("Both are equal") else: if a<b: print(b," is greater") else: print(a," is greater")
false
3d8001d043f311922c572254e4c52884969b5e59
vivekkhimani/DataStructuresAndAlgorithmsPractice
/StacksAndQueues/Applications_And_Interview/ThreeInOne.py
2,404
4.28125
4
#Implementing three stacks using a single array (similar implementation can be used for k stacks in one array. The number of elements n in an array would have to be divided with k, which will give size of individual stack) #We will use in-built Python list objects as an array #Initializing an array of fixed size 20 just for the sake of convenience #We will assume it just to be an integer stack stackArray = [0]*18 #Next we define sizes for each of the stack #Let's assume the size of each is 6, therefore, the first stack is allocated indices 0-5, the second stack is allocated indices 6-11, third one is 12-17! class Stack1: def __init__(self,pointer=0): self.__pointer = pointer def getPointer(self): return self.__pointer def incPointer(self): self.__pointer += 1 def decPointer(self): self.__pointer -= 1 def isEmpty(self): return (self.__pointer == 0) def isFull(self): return (self.__pointer == (0 + len(stackArray)/3)) def push(self,newData): if self.isFull(): print("Overflow") return stackArray[self.__pointer] = int(newData) self.incPointer() def pop(self): if self.isEmpty(): print("Underflow") return retVal = stackArray[self.__pointer-1] stackArray[self.__pointer] = 0 self.decPointer() return retVal def returnTop(self): return stackArray[self.__pointer-1] def __str__(self): i = 0 retString = "" while i < self.__pointer: retString+=str(stackArray[i])+"->" i+=1 return retString+"NULL" #The remaining two Stacks can be implemented as different classes with same methods in same manner. The only difference will be the starting point of the pointer and the ending point. Remember, the ending point of the previous stack will be the starting point of the next one, i.e. #Stack1 => Start = 0, End = len(arrayStack)/3 - 1 #Stack2 => Start = len(arrayStack)/3, End = (len(arrayStack)/3 * 2) - 1 #Stack3 => Start = len(arrayStack)/3 * 2, End = len(arrayStack) - 1 #The same logic can be applied for n stacks in an array! if __name__ == "__main__": firstStack = Stack1() firstStack.push(1) firstStack.push(2) print(firstStack) firstStack.pop() print(firstStack) firstStack.push(3) firstStack.push(10) firstStack.push(12) firstStack.push(13) firstStack.push(15) print(firstStack.isEmpty()) print(firstStack.isFull()) firstStack.push(14) print(firstStack) print(firstStack.returnTop())
true
b3d8558939540fed47f84811116d3cb43b71871f
vivekkhimani/DataStructuresAndAlgorithmsPractice
/LinkedLists/Implementation_And_Operations/CircularLinkedList.py
2,263
4.15625
4
#This document demonstrates how to construct a Circular List using Python and perform various operations on the Linked List. class Node: def __init__(self,data=None,nextNode=None): self.__data = data self.__nextNode = nextNode def getNext(self): return self.__nextNode def getData(self): return self.__data def setNext(self,newNext): self.__nextNode = newNext def setData(self,newData): self.__data = newData def __str__(self): return str(self.getData()) class CircularLinkedList: def __init__(self,head=None): self.__head = head def insertHead(self,Data): self.__head = Node(Data) self.__head.setNext(self.__head) def insertBeforeHead(self,Data): current = self.__head while current.getNext() != self.__head: current = current.getNext() current.setNext(Node(Data)) current = current.getNext() current.setNext(self.__head) self.__head = current def insertEnd(self,Data): current = self.__head while current.getNext() != self.__head: current = current.getNext() current.setNext(Node(Data)) current = current.getNext() current.setNext(self.__head) def deleteEnd(self): current = self.__head while current.getNext().getNext() != self.__head: current = current.getNext() current.setNext(self.__head) def deleteHead(self): current = self.__head while current.getNext() != self.__head: current = current.getNext() current.setNext(self.__head.getNext()) self.__head = self.__head.getNext() def countElements(self): if self.__head == None: return str(0) current = self.__head counter = 1 while current.getNext() != self.__head: current = current.getNext() counter+=1 return str(counter) def printList(self): current = self.__head printString = "" while current.getNext() != self.__head: printString+=str(current) + " -> " current = current.getNext() printString+=str(current) + " ->" + str(current.getNext())+"(HEAD)" return printString #Testing if __name__ == "__main__": myList = CircularLinkedList() myList.insertHead(5) myList.insertEnd(10) myList.insertEnd(20) myList.insertEnd(50) myList.insertBeforeHead(39) myList.deleteEnd() myList.deleteHead() print(myList.countElements()) print(myList.printList())
true
0732767b7f22c3554fd22da9738a6bbfd9ddc3a2
Awesome94/Algo_Python
/stringRotation.py
884
4.21875
4
def stringRotation(string1, string2): n = len(string1) indx = 0 if n != len(string2): return False for i in range(n): if string2.count(string1) == 1: break indx+=1 return string1[:indx]+string2[:-indx] == string1 # print(stringRotation("waterbottle", "erbottlewat")) def areRotations(string1, string2): size1 = len(string1) size2 = len(string2) temp = '' if size1 != size2: return 0 temp = string1 + string1 print(temp, string2, temp.count(string2)) if (temp.count(string2)> 0): return 1 else: return 0 # Driver program to test the above function string1 = "ACCD" string2 = "ACDA" if areRotations(string1, string2): print("Strings are rotations of each other") else: print("Strings are not rotations of each other") # This code is contributed by Bhavya Jain
true
6ee56447f2e591c445356f8dacac6d00092f3e38
Awesome94/Algo_Python
/selectionSort.py
399
4.15625
4
def selection(array): """ selection sort finds min index and swaps the numbers in the array accordingly """ for x in range(len(array)): min_index = x if array[min_index] > array[x]: min_index = x array[min_index], array[x] = array[x], array[min_index] return array array = [1, 12, 4, 21, 8, 42, 121] print(selection(array))
true
543a6851d238ea4f34581d20bc0e9f91b4cf936c
RViveka/simple_prog
/max_num.py
343
4.25
4
def max_num(num1,num2,num3): if num1 >= num2 and num1>=num3: print(num1,"is the max numnber") elif num2>=num3: print(num2,"is the max number") else: print(num3,"is the max number") a=int(input("Enter the number1")) b=int(input("Enter the number2")) c=int(input("Enter the number3")) max_num(a,b,c)
true
2c8e30c5efea42cef2df3eeb0098de905236fcae
bhaskarmamillapalli/Python_Examples
/Python_Practice/Strings/String_Functions.py
407
4.21875
4
# this program is to concatenate the strings s="Hello World" s1="Guido Van Rossum" print(s) print(s1) print("Concatenated string::",s+" "+s1) # Repetition -- multiplication of string. "letter z is printed 10 times." letter ="z" print(letter*10) 'String built in methods.' print(s.upper()) print(s.lower()) print(s.split()) print(s1.split()) print("Split the string with letter o",s.split("o")) print(s1.split("o"))
true
8f4ffbb8ef3547047ab10fed8da1e1303fa0ee62
meifu2027/PythonLearn
/20180815-03/conditional.py
1,245
4.4375
4
# 条件判断 age = 20 if age >= 18: print("your age is", age) print("adult") age = 3 if age >= 18: print("your age is", age) print("adult") else: print("teenage") age = 10 if age >= 18: print("your age is", age) print("adult") elif age >=6: print("child") else: print("teenage") # 只要x是非零数值、非空字符串、非空list等,就判断为True,否则为False。 x = 10 if x: print("true") # input()返回的数据类型是str,str不能直接和整数比较, # 必须先把str转换成整数。 # Python提供了int()函数来完成这件事情 s = input("birth:") birth = int(s) if birth < 2000: print("00前") else: print("00后") # practice # 小明身高1.75,体重80.5kg。请根据BMI公式(体重除以身高的平方)帮小明计算他的BMI指数,并根据BMI指数: # 低于18.5:过轻 # 18.5-25:正常 # 25-28:过重 # 28-32:肥胖 # 高于32:严重肥胖 height = 1.75 weight = 80.5 bmi = weight / (1.75 * 1.75) print(bmi) if bmi < 18.5: print("过轻") elif bmi >= 18.5 and bmi < 25: print("正常") elif bmi >= 25 and bmi < 28: print("过重") elif bmi >= 28 and bmi < 32: print("肥胖") else: print("严重肥胖")
false
acfb8546dc2e6b4c62f2ef34b00df24417fbc3c4
AungKyawZaww9/python
/chapter 7 python/Defination_of_class_data2.py
778
4.125
4
from Definition import Date class Employee: def __init__(self, firstName, lastName, birthMonth, birthDay, birthYear, hireMonth, hireDay, hireYear): self.birthDate = Date(birthMonth, birthDay, birthYear) self.hireDate = Date(hireMonth, hireDay, hireYear) self.lastName = lastName self.firstName = firstName print("Employee constructor: %s, %s"\ % (self.lastName, self.firstName)) def __del__(self): print("Employee object about to be destroyed: %s, %s"\ % (self.lastName, self.firstName)) def display(self): print("%s, %s" % (self.lastName, self.firstName)) print("Hired:", self.hireDate.display()) print("Birthdate: ", self.birthDate.display())
false
7b2081e92fe73ced6787897bf25ef99e60384370
annettemathew/count_strings
/count_strings.py
740
4.125
4
#3. Count the number of strings where the string length is 2 or more and the first and #last character are the same from a given list of strings. #Sample List : ['abc', 'xyz', 'aba', '1221'] #Expected Result : 2 #Accept a list of comma-separated strings #Iterate through list, and check length >= 2 #Compare first and last character & increment counter if equal input_str = input("Please enter a string: ") str_list = [x for x in input_str.split(',') if x.strip()] counter = 0 for element in range(0, len(str_list)): if(len(str_list[element]) >= 2): str = str_list[element] #initializing a new string equal to the current list item if(str[0] == str[len(str) - 1]): counter += 1 print(counter)
true
716f5e1096a400c7e4ea186bb8c2e7bb9f0dd63b
YuriPellini/Athon.Py
/Lista 2/Exe_8.py
728
4.78125
5
'''****************************************** ATHON Programa de Introdução a Linguagem Python Disiplina: Lógica de Programação Professor: Francisco Tesifom Munhoz Data: Primeiro Semestre 2021 ********************************************* Atividade: Lista 2 (Ex 3) Autor: Yuri Pellini Data: 19 de Maio de 2021 Comentários: ******************************************''' #Entrada X=float(input("Coloque o tamanho do lado do triângulo em cm:")) Y=float(input("Coloque o segundo valor:")) Z=float(input("Coloque o último valor:")) # Saida if(X==Y and Y==Z): print("Isso é um triângulo equilátero") else: if(X==Y or Y==Z or X==Z): print("Isso é um triângulo isósceles") else: print("Isso é um triângulo escaleno")
false
1f8b0b8f424ff5c82ae3e9b2dd3e407c109ad0dc
KF10/ichw
/pyassign2/currency.py
1,856
4.15625
4
#!/usr/bin/env python3 """currency.py: provide a 'exchange' function which return the amount of another currency when you want to convert a certain amount of currency to another. __author__ = "Kuangwenyu" __pkuid__ = "1800013245" __email__ = "w.y.kuang@pku.edu.cn" """ from urllib.request import urlopen import json def exchange(currency_from, currency_to, amount_from): """Returns: amount of currency received in the given exchange. In this exchange, the user is changing amount_from money in currency currency_from to the currency currency_to. The value returned represents the amount in currency currency_to. The value returned has type float. Parameter currency_from: the currency on hand Precondition: currency_from is a string for a valid currency code Parameter currency_to: the currency to convert to Precondition: currency_to is a string for a valid currency code Parameter amount_from: amount of currency to convert Precondition: amount_from is a float """ doc = urlopen('http://cs1110.cs.cornell.edu/2016fa/a1server.php?from={0}&to={1}&amt={2}'. format(currency_from, currency_to, amount_from)) docstr = doc.read() doc.close() jstr = docstr.decode('ascii') ret_dict = json.loads(jstr) # 将jstr转为字典 convert = ret_dict['to'] mylist = convert.split() amount_to = float(mylist[0]) return amount_to def test_exchange(): """test the 'exchange' function. """ assert(17.13025 == exchange('USD', 'CNY', 2.5)) assert(2.1589225 == exchange('USD', 'EUR', 2.5)) assert(0.018484513053739 == exchange('AOA', 'AUD', 3.7)) def test_all(): """test all cases. """ test_exchange() print('All tests passed') def main(): """main module """ test_all() if __name__ == '__main__': main()
true
6b981828e3b06a05a99f11a543ff178202e1768b
mcelaric/PythonDataRepresentations
/List Mutations/quiz.py
2,775
4.1875
4
# Question 1 # What slicing returns [5,7,9] my_list = [1,3,5,7,9] print(my_list[2:5]) # YES print(my_list[2:]) # YES # Question 2 # What returns a tuple of length 1? print((1,)) # YES print(tuple([1])) # YES # Question 3 # Why does following code snippet raise an error in Python? # instructors = ("Scott", "Joe", "John", "Stephen") # instructors[2 : 4] = [] # print(instructors) # Answer - tuples are immutable # TypeError: 'tuple' object does not support item assignment # Question 4 # Given a non-empty list my_list, # which item in the list does the operation my_list.pop() remove? print("pop operation", my_list.pop()) my_list = [1,3,5,7,9] # Answer print("index -1", my_list[-1]) # Question 5 # What output does the following code snippet print to the console? my_list = [1, 3, 5, 7, 9] my_list.reverse() print(my_list.reverse()) #None """ Given a list fib = [0, 1], write a loop that appends the sum of the last two items in fib to the end of fib. What is the value of the last item in fib after twenty iterations of this loop? Enter the answer below as an integer. As a check, the value of the last item in fib after ten iterations is 89. """ def append_sum(lst,n): for i in range(0,n): last_item = lst[-1] second_last_item = lst[-2] combined = last_item + second_last_item lst.append(combined) #return(lst) return lst.pop() fib = [0,1] print(append_sum(fib,20)) # Question 7 """ One of the first examples of an algorithm was the Sieve of Eratosthenes. This algorithm computes all prime numbers up to a specified bound. The provided code below implements all but the innermost loop for this algorithm in Python. Review the linked Wikipedia page and complete this code. Implement the Sieve of Eratosthenes https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes Running your completed code should print two numbers in the console. The first number should be 46 """ import math primes = [] number = 200 for i in range(2,number+1): primes.append(i) i = 200 #from 2 to sqrt(number) while(i <= int(math.sqrt(number))): #if i is in list #then we gotta delete its multiples if i in primes: #j will give multiples of i, #starting from 2*i for j in range(i*2, number+1, i): if j in primes: #deleting the multiple if found in list primes.remove(j) i = i+1 print (primes) def compute_primes(bound): """ Return a list of the prime numbers in range(2, bound) """ answer = list(range(2, bound)) for divisor in range(2, bound): # Remove appropriate multiples of divisor from answer pass return answer print(len(compute_primes(200))) print(len(compute_primes(2000)))
true
6963e37edd9fc6001544ea8f8174beded61567df
mcelaric/PythonDataRepresentations
/Lists/define_access_lists.py
975
4.3125
4
""" List Literals """ lst1 = [1, 5, 9, -32] print(lst1) lst2 = ["dog", "cow", "horse"] print(lst2) emptylst = [] print(emptylst) """ Range & List Indexing """ lst = list(range(10)) # First element print(lst[0]) # Third element print(lst[2]) # Length print(len(lst)) # Last element print(lst[9]) print(lst[len(lst) - 1]) print(lst[-1]) """ List Slicing """ lst = list(range(10)) # Slice with 3 elements print(lst[4:7]) """ Negative indices may be used in slicing, and they have exactly the same meaning that they did when used as indices. You can even mix positive and negative indices in a slice. """ # Slice with the last 2 elements of the list print(lst[8:10]) print(lst[8:]) print(lst[-2:]) # Slice with the first 4 elements of the list print(lst[0:4]) print(lst[:4]) """ Rather than causing errors, if there are no elements in the list between the indices in the slice, then an empty list is produced. """ # Empty slices print(lst[20:25]) print(lst[7:3])
true
3bba72b9df6fbdcc20528dc7ec4b98d9360d1d46
erdituna/python
/basic examples/format_namefunc.py
552
4.15625
4
def format_name(first_name , last_name): if first_name == "": format_name = str(last_name)+", "+str(first_name) elif last_name =="": format_name = str(last_name)+", "+str(first_name) elif first_name != "" and last_name != "": format_name = str(last_name)+", "+str(first_name) else: format_name = str(last_name)+", "+str(first_name) return format_name print(format_name("Ernst","Hemingway")) print(format_name("","Madonna")) print(format_name("Voltaire","")) print(format_name("",""))
false
b0dd03379603ac1a85949b499a3286e85ef2d24e
AmeyMhaskar/new_repository
/amey.python.py
289
4.21875
4
#Program to iterate through a list using indexing genre=['pop','rock','jazz'] #iterate over the list using index for in range(len(genre)): print("I LIKE",genre[1]) digits=[0,1,5] for i in digits: print(i) else: print("no item left") range(0,10) print(range(10))
true
93cd105809b704154df50b830c2463fb0a2c6e53
pnguyen44/python_code_challenges
/summation.py
442
4.28125
4
# 8 kyu -Grasshopper - Summation # Summation # Write a program that finds the summation of every number between 1 and num. The number will always be a positive integer greater than 0. # # For example: # # summation(2) -> 3 # 1 + 2 # # summation(8) -> 36 # 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 def summation(num): return reduce(lambda x,y: x + y, range(num + 1)) # Alternative Solution: # def summation(num): # return sum(range(1,num+1))
true
68eed5ec07790385fee83fc4fb14aac197a69d73
vinnav/Automate-with-Python
/1-CrashCourse/5-commaCode.py
571
4.25
4
spam = ["apples", "bananas", "tofu", "cats"] # Write a function that takes a list value as an argument and returns a string # with all the items separated by a comma and a space, with and inserted before # the last item. For example, passing the previous spam list to the function would # return 'apples, bananas, tofu, and cats'. But your function should be able to work # with any list value passed to it. def commaCode(list): for i in range(len(list)): print(list[i], end="") if i < len(list)-1: print(", ", end="") commaCode(spam)
true
c463a1fbcaa6aeb1d7b4ad42ea85c70a6afe3ec6
Sankalp679/Competitive-Programming
/Leet Code/30 Days of Code/week_03/construct_binary_search_tree_from_preorder.py
759
4.125
4
""" Return the root node of a binary search tree that matches the given preorder traversal. """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def bstFromPreorder(self, preorder: List[int]) -> TreeNode: def insert_node(root,val): if root is None: return TreeNode(val) elif root.val > val: root.left = insert_node(root.left,val) elif root.val < val: root.right = insert_node(root.right,val) return root root = None for i in preorder: root = insert_node(root,i) return root
true
2488827fbb2e856791fe7eace892ed527136c69c
Grosbin/python-2021
/positiveOrNegative.py
210
4.21875
4
value = int(input("Enter the value: ")) if value < 0: print("The value is negative: ", value) elif value > 0: print("The value is positive: ", value) else: print("The value is cero: " , value)
true
b8440e2fd7e0d2e34f9620cb9e84fea717692834
Grosbin/python-2021
/numeroPalindromo.py
245
4.1875
4
n = int(input("Enter the number palindrieme")) tmp = n reverse = 0 while n >0: dig = n % 10 reverse = reverse*10+dig n = n//10 if tmp == reverse: print("Values are palindrieme") else: print("Values are not palindrieme")
false
d79fe6d261b588cb3883f873fbc033e14728891c
hubbm-bbm101/lab5-exercise-solution-b2210356166
/b2210356166/ex2.py
226
4.1875
4
address=input("write e-mail") if "@" in address: if '.' in address: print("it is a valid e-mail") else: print("it is not a valid e-mail") else: print("it is not a valid e-mail")
true
1a90b10303d76cd69d5807a123543f6dd5dcecbf
bhelga/university
/python/Lab8/Lab8_1.py
895
4.3125
4
# 8.1.1 name = input("Введiть назву роману та натиснiть Enter:\t") author = input("Введiть iм'я автора роману та натиснiть Enter:\t") print(f"Письменник – автор роману:\t{author} – автор роману {name}") # 8.1.2 first = input("Введіть перший рядок:\t") second = input("Введіть другий рядок:\t") if len(first) < 3 or len(second) < 2: print("Error!") else: third = first[1] + first[2] + second[len(second) - 2] print("Third is: " + third) # 8.1.3 word = "голова" print("Our word:\t" + word) word += word[4] word += word[1:4] word += word[0] word += word[5] word = word[6:12] print("Our final word:\t" + word) # 8.1.4 user_str = input("Введіть ваш рядок:\t") user_str = user_str.replace("ах", "ух") print("Finished:\t" + user_str)
false
cd815d6653188c2ec4ca1e1594225a039e794763
bhelga/university
/python/Lab14/try7_1.py
722
4.21875
4
def prime_gen(n): primes = [2] # починаємо з трійки, бо двійка вже в масиві nextPrime = 3 while nextPrime < n: isPrime = True i = 0 # the optimization here is that you're checking from # the number in the prime list to the square root of # the number you're testing for primality squareRoot = int(nextPrime ** .5) while primes[i] <= squareRoot: if nextPrime % primes[i] == 0: isPrime = False i += 1 if isPrime: primes.append(nextPrime) # only checking for odd numbers so add 2 nextPrime += 2 print(primes) prime_gen(1000)
false
2d98befaa1604fa38c07b3874a813b9f3dfee5b0
jameswmccarty/AdventOfCode2019
/day04.py
2,495
4.21875
4
#!/usr/bin/python """ --- Day 4: Secure Container --- You arrive at the Venus fuel depot only to discover it's protected by a password. The Elves had written the password on a sticky note, but someone threw it out. However, they do remember a few key facts about the password: It is a six-digit number. The value is within the range given in your puzzle input. Two adjacent digits are the same (like 22 in 122345). Going from left to right, the digits never decrease; they only ever increase or stay the same (like 111123 or 135679). Other than the range rule, the following are true: 111111 meets these criteria (double 11, never decreases). 223450 does not meet these criteria (decreasing pair of digits 50). 123789 does not meet these criteria (no double). How many different passwords within the range given in your puzzle input meet these criteria? Your puzzle input is 136760-595730. -- Part Two --- An Elf just remembered one more important detail: the two adjacent matching digits are not part of a larger group of matching digits. Given this additional criterion, but still ignoring the range rule, the following are now true: 112233 meets these criteria because the digits never decrease and all repeated digits are exactly two digits long. 123444 no longer meets the criteria (the repeated 44 is part of a larger group of 444). 111122 meets the criteria (even though 1 is repeated more than twice, it still contains a double 22). How many different passwords within the range given in your puzzle input meet all of the criteria? Your puzzle input is still 136760-595730. """ def valid1(password): paired = False for pair in ['00','11','22','33','44','55','66','77','88','99']: if pair in str(password): paired = True if paired: for i in range(5): if int(str(password)[i]) > int(str(password)[i+1]): return False return True return False def valid2(password): paired = False for pair in ['00','11','22','33','44','55','66','77','88','99']: if pair in str(password) and pair+pair[0] not in str(password): paired = True if paired: for i in range(5): if int(str(password)[i]) > int(str(password)[i+1]): return False return True return False if __name__ == "__main__": # Part 1 Solution total = 0 for i in range(136760,595730+1): if valid1(i): total += 1 print(total) # Part 2 Solution total = 0 for i in range(136760,595730+1): if valid2(i): total += 1 print(total)
true
ca6ad1cb025429610a8cc95d7c4db1cf4230e5ec
junipernineaj/python-reeducation
/Chapter2/summary2.py
663
4.28125
4
# 2-8. Number Eight: # Write addition, subtraction, multiplication, and division operations that each result in the number 8. # Be sure to enclose your operations in print() calls to see the results. # You should create four lines that look like this: print(5+3) print(10-2) print((2+2)*2) print((1+3)*2) print((10+5+1)/2) # Your output should simply be four lines with the number 8 appearing once on each line. # 2-9. Favorite Number: Use a variable to represent your favorite number. # Then, using that variable, create a message that reveals your favorite number. Print that message. favourite_number=26 print (f"My favourite number is {favourite_number}")
true
b158cfca77c9366b956c99d28bdbc210453f1357
joseangel-sc/CodeFights
/Challenges/iqAddress.py
901
4.125
4
def iqAddress(n): r = "" n=float(n) while n!=1: r = str(n%10.5) + r n = math.ceil(n/2) return "1"+r '''Have you ever heard of an IQ-address? For the given integer n, it is calculated as follows: Let result = "". If n = 1, prepend "1" to the beginning of result and return it as an answer. Prepend n % 10.5 to the beginning of result. Divide n by 2 with rounding up to the nearest integer. Go to step 2. Given an integer n, your task is to return IQ-address generated from it. Example For n = 21, the output should be iqAddress(n) = "12.03.06.00.50.0". Here's why: 21% 10.5 = 0.0 11% 10.5 = 0.5 6 % 10.5 = 6.0 3 % 10.5 = 3.0 2 % 10.5 = 2.0 Thus, the answer is "1"+"2.0"+"3.0"+"6.0"+"0.5"+"0.0" = "12.03.06.00.50.0". Input/Output [time limit] 4000ms (py) [input] integer n Constraints: 0 ≤ n ≤ 105. [output] string The IQ-address generated from n.'''
true
2948a131295b9fecf0bcb71841e0d91cf3feb844
joseangel-sc/CodeFights
/Arcade/BookMarket/ProperNounCorrection.py
621
4.1875
4
#Proper nouns always begin with a capital letter, followed by small letters. #Correct a given proper noun so that it fits this statement. #Example #For noun = "pARiS", the output should be #properNounCorrection(noun) = "Paris"; #For noun = "John", the output should be #properNounCorrection(noun) = "John". #Input/Output #[time limit] 4000ms (py) #[input] string noun #A string representing a proper noun with a mix of capital and small Latin letters. #Constraints: #1 ≤ noun.length ≤ 10. #[output] string #Corrected (if needed) noun. def properNounCorrection(noun): return noun[0].upper()+noun[1:].lower()
true
27cec83b2b8d6f35a19b67a8fcaccbe2b866d7ca
joseangel-sc/CodeFights
/Arcade/BookMarket/IsMAC48Address.py
1,406
4.28125
4
#A media access control address (MAC address) is a unique identifier assigned to network interfaces for communications on the physical network segment. #The standard (IEEE 802) format for printing MAC-48 addresses in human-friendly form is six groups of two hexadecimal digits (0 to 9 or A to F), separated by hyphens (e.g. 01-23-45-67-89-AB). #Example #For inputString = "00-1B-63-84-45-E6", the output should be #isMAC48Address(inputString) = true; #For inputString = "Z1-1B-63-84-45-E6", the output should be #isMAC48Address(inputString) = false; #For inputString = "not a MAC-48 address", the output should be #isMAC48Address(inputString) = false. #Input/Output #[time limit] 4000ms (py) #[input] string inputString #Constraints: #15 ≤ inputString.length ≤ 20. #[output] boolean #true if inputString corresponds to MAC-48 address naming rules, false otherwise. def isMAC48Address(inputString): if len(inputString)!=17: return False inputStringSplit = inputString.split('-') if len(inputStringSplit)!=6: return False for i in range(0,len(inputStringSplit)): if len(inputStringSplit[i])!=2: return False if (("0"<=inputStringSplit[i][0]<="9" or "A"<=inputStringSplit[i][0]<="F") and ("0"<=inputStringSplit[i][1]<="9" or "A"<=inputStringSplit[i][1]<="F")): return True else: return False
true
76ad0916806228157457a646b305b335bcb2ae87
bawilc01/py_loop_sample_code
/loop_example.py
2,133
4.15625
4
# Looping through numbers in python # will print numbers 1 - 10 using for loop # i = 0 # # for i in range(10): # # same as i = i + 1 # # i = 0, i = 0 + 1, which = 1. # # first number to print will be 1 # # i+=1 # # # print i until reaching the last number in the range # print(i) # # # # will print numbers 0 - 9 using for loop # i = 0 # # for i in range(10): # # print i until reaching the last number in the range # # nothing has been done to i yet, so it will print first value of i, # # which is 0 # print(i) # # # # same as i = i + 1 # # i = 0, i = 0 + 1, which = 1. # # first number to print will be 1 # # i += 1 # THIS WAS A REAL INTERVIEW QUESTION ON A TECHNICAL INTERVIEW # prints the sum of the last sum + sum for 10 numbers using for loop # i interates by 1, all the way up to 10 # example, first answer is 0 + 1 = 1; sum starts at 0, sum increments by 1, then sum = 1 # next answer is 1 + 1 # sum = 0 # # sum will change # # i = 0 # # i is numbers 1 - 10 # # for i in range(10): # sum = sum + i # # or sum += 1 # # first answer 0 + 1 = 1 # # print(sum) # sum is now = 1 # starting over at the loop, we are now going to move to the second number (i) in the range, which is 2. # sum = 1, i = 2 # the next number printed is new sum = 1 (current sum) + 2 (value of i) # sum is now = 3 and will be printed # next number is new sum = 3 (current sum) + 3 ( value of i) # sum is now = 6 # the next 10 sums to be printed will appear in the console until all i's up to 10 are interated through # print numbers i * 1 and interates i by 1 before returning to loop to screen using while loop until i equals 10 # will print numbers 0 - 10 # if you remove the = and make it while i < 10, then 0 - 9 will print to the screen because once i hits 10, the loop will stop because 10 is not less than 10 i = 0 while i<=10: print(i*1) i=i+1 # create an array or list of things and print all to the screen with a loop # data = {"Brittney Coble", "some string", "another string"} # # for data in list: # print(data)
true
ea5d8df4e30e111f2511f5db7ef4ace67d0a5615
hikyru/Python
/FindingOddNumbers_2_22.py
840
4.1875
4
# -*- coding: utf-8 -*- """ Created on Sat Feb 22 7:28 2020 @author: KatherineYu """ # Input a Number x = int(input("Enter a Number: ")) # Find all odd numbers in the number print("Finding all odd numbers in", x, "!") # m is a variable used for counting the number of digits printed m = 0 for i in range(1, x + 1, 1): # if there are remainers after i is divided by 2, that means i is an odd number # because even numbers are perfectly divisible if i % 2 == 1: print(i, end='\t') # for every time an odd number is printed, m a number is stored into m m += 1 if m % 10 == 0: # if m is perfectly divisible by 10, that means there are at least ten odd numbers in x # a new line will be added print() # will only run every every time there are ten more digits added to m
true
c2d6d7c9d1dd7633f2c10492fad2e0a176361ccb
ikshwak/udacity-DS-assign3
/problem_4.py
2,052
4.15625
4
def sort_012(input_list): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: input_list(list): List to be sorted """ if input_list == None: return [] start = 0 end = len(input_list)-1 mid = 0 while mid <= end: if input_list[mid] == 0: input_list[start],input_list[mid] = input_list[mid],input_list[start] start += 1 mid += 1 elif input_list[mid] == 1: mid += 1 elif input_list[mid] == 2: input_list[end],input_list[mid] = input_list[mid],input_list[end] end -= 1 else: print("invalid 012 list") return [] return input_list def test_function(test_case): sorted_array = sort_012(test_case) print("Solution: " + str(sorted_array)) print("Library sort: " + str(sorted(test_case))) """ TEST CASE 1 """ test_function([0, 0, 2, 2, 2, 1, 1, 1, 2, 0, 2]) """ Result: Solution: [0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 2] Library sort: [0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 2] """ """ TEST CASE 2 """ test_function([2, 1, 2, 0, 0, 2, 1, 0, 1, 0, 0, 2, 2, 2, 1, 2, 0, 0, 0, 2, 1, 0, 2, 0, 0, 1]) """ Result: Solution: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2] Library sort: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2] """ """ TEST CASE 3 """ test_function([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]) """ Result: Solution: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2] Library sort: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2] """ """ TEST CASE 4 """ test_function([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 4, 2, 2, 2, 2, 2, 3]) """ Result: invalid 012 list Solution: [] Library sort: [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 4] """ """ TEST CASE 5 """ test_function([]) """ Result: Solution: [] Library sort: [] """
true
eca5ae226d964703e3a0c91ee43581d601edd3c2
clair3st/python-prework
/lpthw-exercises/ex11.py
695
4.125
4
# ex11: Asking questions # comma at the end of the print statements so the print doesn't # end the line with the new line character and go to the next line. # raw_input is an inbuilt python function, it reads a line from # input and converst to a string and retunrs that print "How old are you?", age = raw_input() print "How tall are you?", height = raw_input() print "How much do you weigh?", weight = raw_input() print "So, you're %r old, %r tall and %r heavy." % (age, height, weight) print "What is your favourite color?", age = raw_input() print "What is your favourite food?", food = raw_input() print "What is your 2 favourite numbers?", number1 = raw_input() number2 = raw_input()
true
664221f1a7fea12548cc719acc0df9ed218324ce
pengliangs/python-learn
/基础语法/day2/2.序列.py
1,032
4.25
4
# 序列是 python 中的基本数据结构的一种 # 序列分类: # 可变序列: # > 列表(list) # 不可变序列: # > 字符串(str) # > 元组 (tuple) username = "张师傅" print(username[:2]) # list修改 usernames = ["张三","李四","王五","赵六"] print("修改前",username) usernames[0]="zhangs" print("修改后",usernames) # 切片赋值 # usernames[:2] = 123 # 切片修改必须使用对应序列进行赋值,如果赋值元素个数大于匹配个数则插入元素 usernames[:2] = ["zs","lis"] print("切片修改",usernames) # 设置切片后修改赋值,值元素个数必须跟切片数匹配 usernames[::2] = ["a","b"] print("切片修改步长",usernames) # 删除列表元素 del usernames[0] print("删除第一个元素",usernames) # 通过切片删除 del usernames[:1] print("切片删除",usernames) # 修改操作只能是可变序列 s = "hello" # s[0] = "H" # 如果要改变则需要将其转为可变序列 ss = list(s) print(ss)
false
08012e5618ba7a9157ea532c6eff58b431155b9b
pengliangs/python-learn
/基础语法/day4/3.对象的初始化.py
841
4.1875
4
class Person: # 在类中可以定义一些特殊方法(魔术方法) # 特殊方法都是__开头,__结尾的方法 # 特殊方法不需要我们自己调用,不要自己去尝试调用外部是可以调用到的 # __init__ 有点像java中的构造函数,在对象创建的时候被调用 # 创建对象流程 # p1 = Person() # 1.创建一个变量 # 2.在内存中创建一个新对象 # 3.__init__(self) 方法执行 # 4.将对象的id赋值给变量 def __init__(self,name): # 初始化一个属性 #self.name = "" self.name = name print("Person.__init__执行") def hello(self): print("你好~ 我是:%s"%self.name) print("Person中代码块,执行") # p1 = Person() # p1.name = "p1" # p1.hello() p2 = Person("p2") p2.hello()
false
5e3e5af970159cc30d5bd5600f4c146a475e9f90
TadayoshiCarvajal/Intro-to-Programming-Tutorial
/episode09.py
1,291
4.375
4
''' Here is the Python script that corresponds to the 9th episode in my YouTube tutorial series, Intro to Programming in Python. Follow me at KaizenMachina on YouTube for daily content. ''' ''' From the last video: ''' firstName = 'Jon' lastName = 'Snow' fullName = firstName + ' ' + lastName ''' Sequences are a positional ordering of elements. 'Jon' is NOT the same as 'Noj' or 'ojN'! How do we access the various elements (characters) of a string? Answer: Indexing ''' print(fullName[0]) print(fullName[1]) print(fullName[2]) print(fullName[3]) print(fullName[4]) print(fullName[5]) print(fullName[6]) print(fullName[7]) ''' We use the len functio to get the length of a sequence (# of elements) ''' print(len(firstName)) print(len(lastName)) print(len(fullName)) long_word = 'supercalifragilisticexpialidocious' print(len(long_word)) ''' Use length of the string to access the last index: ''' print(long_word[len(long_word) - 1]) #fullName[len(fullName)] #this will give us an error since 8 is out of bounds. ''' long_word[len(long_word) - 1] this is pretty tedious a more concise way is to use negative indexes. long_word[len(long_word) - 1] is the same as long_word[-1] ''' print(long_word[-1]) #fullName[-len(fullName)-1] #this will give us an error since -1 is out of bounds.
true
2364c53ba0411024f81e21041d02eae9d9e613a5
daniela-mejia/Python-Net-idf19-
/PhythonAssig/5-06-19 Assigment7/loan.py
682
4.21875
4
#Determine the monthly payment for a car loan.Example output #Daniela Mejia def main (): loan_Amount = float(input('Enter the amount of your loan: ')) loan_interest = float(input('Enter the interest rate (%): ')) loan_years = int(input('Enter the numbers of years for this loan: ')) repayment_years = loan_years * 12 repayment_interest = loan_interest/100 #Formula #Month_payment = L[i(1+i)n] / [(1+i)n-1] monthlyRepay =(loan_Amount * repayment_interest * (1+repayment_interest) * repayment_years / ((1+repayment_interest) * repayment_years - 1)) print (' You have to pay monthly : ', (monthlyRepay)) #print (monthlyRepay) main ()
true
176de592151a412ca29ede7f749c6d11d92c5959
daniela-mejia/Python-Net-idf19-
/PhythonAssig/4-25-19 Assigment5/4-25 Assigment1(Lottery).py
655
4.21875
4
# Design a program that generates 7 random digit lottery number. import random #Initialise an empty list that will be used to store the 6 lucky numbers! lotNumbers = [] for i in range (0,7): number = random.randint(0,9) #Check if this number has already been picked and ... while number in lotNumbers: # ... if it has, pick a new number instead number = random.randint(0,9) #Now that we have a unique number, let's append it to our list. lotNumbers.append(number) #Sort the list in ascending order lotNumbers.sort() #Display the lsit on screen: print("LUCKY! Lottery numbers are: ") print(lotNumbers)
true
a62686e9025fec93281ca7ba22e8ea7cb77dbbdd
daniela-mejia/Python-Net-idf19-
/PhythonAssig/5-15-19 Assigment 12/evendigits.py
480
4.1875
4
# This Program finds how many even numbers are in the input number by the user # Start defining a function def Even(a): return a % 2 == 0 def countEven(): count = 0 string_of_Num = int(input("Please enter a numbers separated by spaces: ")) list_of_Num = string_of_Num.split(' ') for number in list_of_Num: num = int(number) if Even(num) == True: count += 1 print ("There are" + str (count) + "even numbers.")
true
31fb656137a5cc30fe2958fb5dcd5087474b7071
daniela-mejia/Python-Net-idf19-
/PhythonAssig/4-25-19 Assigment6/Employeeclass.py
657
4.15625
4
#Daniela Mejia 04/25/2019 #python object oriented programming Employee Class class Employee: def __init__(self, name, Id, dep, job): self.name = name self.Id = Id self.dep = dep self.job = job #method def fulldata(self): return 'Name:{},Id: {}, Department{},Job: {}'.format(self.name,self.Id,self.dep,self.job) #data instance variables emp1 = Employee('Susan Meyers','45899','Accounting','Vice President') emp2 = Employee('Mark Jones','39119','IT','Programmer') emp3 = Employee('Joy Rogers','81774','Manufacturing','Engineer') print(emp1.fulldata()) print(emp2.fulldata()) print(emp3.fulldata())
false
e07a29aa104446c327b18fdaa0dceaf756937a40
MarinaGoto/python-basic
/Turtle_Graphics/bigX.py
1,057
4.5625
5
# P 1. p. 244 #Give a set of instructions for controlling the turtle to draw a line from the top-left corner of the screen #to the bottom-right corner, and from the top-right corner to the bottom-left corner, #thereby making a big X on the screen. There should be no other lines drawn on the screen. import turtle # set window size turtle.setup(800, 600) # get reference to turtle window window = turtle.Screen() window.title('Drawing an X') #get default turtle and hide the_turtle = turtle.getturtle() the_turtle.hideturtle() #shape the_turtle.shape('turtle') the_turtle.fillcolor('black') #color turtle.colormode(255) the_turtle.pencolor(169, 71, 169) #size the_turtle.pensize(41) #resize the_turtle.resizemode('user') the_turtle.turtlesize(3, 3) #create square (absolute postioning) the_turtle.penup() the_turtle.setposition(-400, 300) the_turtle.pendown() the_turtle.setposition(400, -300) the_turtle.penup() the_turtle.setposition(400,300) the_turtle.pendown() the_turtle.setposition(-400,-300) the_turtle.speed(1) turtle.exitonclick()
true
76ba3708402ebbb24a5875b25caa19664357c9fa
MarinaGoto/python-basic
/Simple programs/T2.py
2,336
4.125
4
# get month and year month = int(input('Please write a month (1-12): ')) year = int(input('Please write a year (1800-2099): ')) # determine if leap year if (year % 4 == 0) and (not (year % 100 == 0) or (year % 400 == 0)): leap_year = True else: leap_year = False ##################################################################################################3 # Stage 2 # Determining the Day of the Week (using the day of the week algorithm) century_digits = year // 100 year_digits = year % 100 # century_digits = int(str(year)[:2]) # year_digits = int(str(year)[-2:]) value = year_digits + (year_digits // 4) if century_digits == 18: value = value + 2 if century_digits == 20: value = value + 6 if (month == 1) and not leap_year: value = value + 1 elif month == 2: if leap_year: value = value + 3 else: value = value + 4 elif (month == 3) or (month == 11): value = value + 4 elif month == 5: value = value + 2 elif month == 6: value = value + 5 elif month == 8: value = value + 3 elif month == 10: value = value + 1 elif (month == 9) or (month == 12): value = value + 6 #  for this program, we will need to determine only the day of the week # for the first day of any given month # the day value in the day of the week algorithm is hard-coded to 1 day_of_the_week = (value + 1) % 7 # determine week day name if day_of_the_week == 1: dayName = 'Sunday' elif day_of_the_week == 2: dayName = 'Monday' elif day_of_the_week == 3: dayName = 'Tuesday' elif day_of_the_week == 4: dayName = 'Wednesday' elif day_of_the_week == 5: dayName = 'Thursday' elif day_of_the_week == 6: dayName = 'Friday' elif day_of_the_week == 0: dayName = 'Saturday' # determine month name if month == 1: monthName = 'January' if month == 2: monthName = 'February ' if month == 3: monthName = 'March' if month == 4: monthName = 'April' if month == 5: monthName = 'May' if month == 6: monthName = 'June' if month == 7: monthName = 'July' if month == 8: monthName = 'August ' if month == 9: monthName = 'September' if month == 10: monthName = 'October ' if month == 11: monthName = 'November' if month == 12: monthName = 'December' # display results print('The first day of ', monthName, 'is', dayName)
false
b0dccffa020a21a621ac176da8b6d415d5b27c27
MarinaGoto/python-basic
/Simple programs/ordered3Function.py
368
4.40625
4
#Write a Python function named ordered3 that is passed three integers, #and returns true if the three integers are in order from smallest to largest, #otherwise it returns false. def ordered3(integer): if integer[0] < integer[2]: print('True') else: print('False') ############################### integ = [8,0,11] ordered3(integ)
true
ac0680af71765fdda7b96d0bf4390983c281305f
MarinaGoto/python-basic
/Simple programs/Temperature Conversion Program.py
1,049
4.40625
4
# coding: utf-8 # In[1]: #Temperature Conversion Program (Fahrenheit to Celsius) #This program will convert a temperature entered in Fahrenheit #to the equivalent degrees in Celsius #program greeting print('This program will convert degrees Fahrenheit to degrees Celsius') #get temperature in Fahrenheit fahren = float(input('Enter degrees Fahrenheit: ')) #calc degrees Celsius celsius = (fahren - 32) * 5/9 #output degrees Celsius print(fahren, 'degrees Fahrenheit equals', format(celsius, '.1f'), 'degrees Celsius') # In[ ]: #Temperature Conversion Program (Celsius to Fahrenheit) #This program will convert a temperature entered in Celsius #to the equivalent degrees in Fahrenheit #program greeting print('This program will convert degrees Celsius to degrees Fahrenheit ') #get temperature in Fahrenheit celsius = float(input('Enter degrees Celsius: ')) #calc degrees Celsius fahren = (celsius * 9/5) +32 #output degrees Celsius print(celsius, 'degrees Celsius equals', format(fahren, '.1f'), 'degrees Fahrenheit')
true
a4feacf6c4a2f22d166803f1fbbca953a33319d3
edarakchiev/Functions
/Exercise/04.negative_vs_positive.py
775
4.125
4
def negative_numbers(numbers): return [n for n in numbers if n < 0] def positive_numbers(numbers): return [num for num in numbers if num >= 0] def print_negative_bigger(): print("The negatives are stronger than the positives") def print_positive_bigger(): print("The positives are stronger than the negatives") def positive_vs_negative(pos_num, neg_num): if pos_num >= abs(neg_num): return True return False nums = [int(el) for el in input().split()] negative_num = sum(negative_numbers(nums)) positive_num = sum(positive_numbers(nums)) print(f"{negative_num}") print(f"{positive_num}") if positive_vs_negative(positive_num, negative_num): print_positive_bigger() else: print_negative_bigger()
false
a9c779035d7b9c5c9cf8aa45dda84db478bf0ccf
gaohank/python-coding-proj
/02_algorithm/02_leetcode/sum_2_values.py
1,825
4.375
4
""" 给出两个非空的链表用来表示两个非负的整数。 其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/add-two-numbers 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ n = l1 i = 1 num_l1 = 0 # get num of l1 while n: num_l1 = num_l1 + n.val * i i = i * 10 n = n.next m = l2 j = 1 num_l2 = 0 # get num of l2 while m: num_l2 = num_l2 + m.val * j j = j * 10 m = m.next str_num = str(num_l1 + num_l2) str_num = str_num[::-1] res = list_result = ListNode(0) for s in str_num: list_result.next = ListNode(int(s)) list_result = list_result.next return res.next if __name__ == '__main__': s = Solution() l1 = ListNode(3) l1_2 = ListNode(4) l1_3 = ListNode(2) l1_2.next = l1_3 l1.next = l1_2 l2 = ListNode(4) l2_1 = ListNode(6) l2_2 = ListNode(4) l2_1.next = l2_2 l2.next = l2_1 l3 = s.addTwoNumbers(l1, l2) print(l3.val) print(l3.next.val) print(l3.next.next.val)
false
df7028948b7d894b0a0bef88ece106788a555d26
wyh2023/Software-Eng-Computing-I
/PythonCode/verification.py
402
4.15625
4
def password_verification(user, pwd): """ :param user: The username stored in the computer. :param pwd: The password for the user stored in the computer. """ input_user = input('What is the user name?') input_pwd = input('What is the password?') if input_pwd == pwd and input_user == user: print('Welcome!') else: print("I don't know you.")
true
483f0059ed617267e0ca7b28aa15814e07fda842
vatsalgamit/CodingBat_Python_Problems
/Practice_Examples_Python.py
918
4.40625
4
""" The parameter weekday is True if it is a weekday, and the parameter vacation is True if we are on vacation. We sleep in if it is not a weekday or we're on vacation. Return True if we sleep in. sleep_in(False, False) → True sleep_in(True, False) → False sleep_in(False, True) → True """ def sleep_in(weekday,vacation): if not weekday or vacation: return True return False print(sleep_in(False,True)) """ We have two monkeys, a and b, and the parameters a_smile and b_smile indicate if each is smiling. We are in trouble if they are both smiling or if neither of them is smiling. Return True if we are in trouble. monkey_trouble(True, True) → True monkey_trouble(False, False) → True monkey_trouble(True, False) → False """ def monkey_trouble(a_smile,b_smile): if a_smile == b_smile: return True return False print(monkey_trouble(True,True))
true
45984492066285c083760ac97cc51fca64600164
unitrium/02180-Introduction-to-AI-SP21-BOARD-GAME-ASSIGNMENT
/code/game/player.py
2,781
4.3125
4
"""Class for defining a player.""" from typing import List, Tuple from abc import ABC, abstractmethod class Action: x: int y: int direction: int def __init__(self, x: int, y: int, direction: int) -> None: self.x = x self.y = y self.direction = direction def direction_position(self) -> Tuple[int, int]: """Determines the position of the black tile.""" if self.direction == 0: return (self.x, self.y-1) elif self.direction == 1: return (self.x+1, self.y) elif self.direction == 2: return (self.x, self.y+1) else: return (self.x-1, self.y) class Player(ABC): """A player that can interact with a board.""" white: bool def __init__(self, white: bool) -> None: self.white = white @abstractmethod def receive(self, board: "Board") -> None: """Receive the state of the board.""" pass class Human(Player): """A player who is also human.""" def display(self, state: List[List[int]]) -> None: """Displays a state to the human when it's their turn. White tiles are represented by X, black tiles are represented by O.""" print("Your turn, the board looks like this:") print() print(" 0 1 2 3 4 5 6 7 8 9 10") number = 0 for line in state: printed_line = str(number) if number < 10: printed_line += " " for col in line: if col is None: printed_line += "_ " elif col == 0: printed_line += "X " else: printed_line += "O " print(printed_line[0:-1]) number += 1 def ask_action(self) -> Action: """Asks the human for a move.""" correct_move = False while not correct_move: try: print("What is your move ?") x = int(input("Start by giving the x coordinate of the white part.")) y = int(input("Now give the y coordinate of the white part.")) direction = int(input( "The direction of the black part? 0 is up, 1 is right, 2 is down, 3 is left")) correct_move = True except ValueError: print("Error please enter an integer") return Action(x, y, direction) def receive(self, board: "Board") -> None: move_accepted = False while not move_accepted: self.display(board.state) if board.receive(self.ask_action()): move_accepted = True else: print("Your move isn't possible. Please choose again.")
true
463cd52817d0e8bbf3dfb3649eaa205f9f1d7bc3
rakaar/OOP-Python-Notes
/3-methods.py
1,795
4.25
4
''' regular methods: methods that take instance as an argument by default class methods: methods that take class as an argument by default static methods: just ordinary functions decorators: things needed to define method type unless its a regular method alternative constructors: class methods that are capable of creating instances other than __init__ ''' class Employee: # class variable bonus = 100 def __init__(self, firstName, lastName, salary): self.firstName = firstName self.lastName = lastName self.salary = salary def fullName(self): return self.firstName + ' ' + self.lastName def increase_salary(self): # a regular method self.salary = self.salary + self.bonus # a function that takes class as a argument: class method @classmethod # this is a decorator which tells that this is a class method def change_class_bonus(cls, increment): cls.bonus += increment # a ordinary function in a class @staticmethod # decorator required to tell that this is a regular function def subtract(x, y): return x - y # a alternative constructor: able to create an instance @classmethod def from_string(cls, the_string): first, last, salary = the_string.split('-') return cls(first, last, salary) # Suppose I want a method that takes class as an argument an increases the bonus # one thing that can be simply done is Employee.bonus = 200 print(Employee.bonus) # 200 Employee.change_class_bonus(800) print(Employee.bonus) # 200+800 = 1000 print(Employee.subtract(1, 2)) # 1-2 = -1 # using the alternative constructor alt_emp = Employee.from_string('alt-emp-100') print(alt_emp.firstName) # alt print(alt_emp.lastName) # emp print(alt_emp.salary) # 100
true
6f298ee034c8c5042e533f5d2cc15744ff3f3432
BrandonLim8890/python
/projects/numbers/005next-prime.py
636
4.15625
4
''' Name: next-prime.py Purpose: Have the program look for the next prime number until the user stops Author: Brandon Lim ''' def isPrime(number): for i in range(2, int(number ** 0.5 + 1)): if number % i is 0: return False return True def nextPrime(number=2): user = '' print('Hit enter to keep finding prime numbers') while user is '': while not isPrime(number): number += 1 print(str(number)) number += 1 user = str(input()) print('Enter a starting number(Defualt value is 2):') val = input() if val is '': nextPrime() else: nextPrime(int(val))
true
f39f6201fca53c33b92841c21390c81b00f3ce9f
nss-cohort-36/011420_orientation_args-n-kwargs
/index.py
1,016
4.21875
4
# args and kwargs # args - takes any number of positional argument values and adds them to a list def list_fave_colors(name, *args): for color in args: print(f"My name is {name}, and one of my fave colors is {color}") # Pass in any number of arguments after the name ("Fred" or "Tia", and the function works, thanks to *args) list_fave_colors("Fred", "red", "green", "blue", "orange") list_fave_colors("Tia", "puce", "goldenrod") #kwargs -- takes any number of keyword arguments and adds them to a dictinary def make_family(name, **tacos): family_stuff = tacos.items() family_str = f"We are the {name} family. " for title, person in family_stuff: family_str += f"The {title} is {person}. " return family_str # Now we can make families of any size, and have flexibility to have those family members have whatever role we want family = make_family("Shepherd", mom="Anne", dad="Joe", dog="Murph") other_family = make_family("Parker", aunt="May", nephew="Peter") print(family) print(other_family)
true
c474daf715193c3f1b4b1e0cbd1abdf61e0b6685
heltonavila/MC102
/lab04/lab04_jogo_da_velha.py
1,234
4.1875
4
# O programa criado consiste num jogo da velha. Para a realização do mesmo é solicitado a entrada de 9 caracteres, sendo eles escolhidos entre 3 opções: X,O ou -. # Sendo assim, é verificada a igualdade dos termos por linha, coluna e diagonal. # Caso a igualdade seja verdadeira para os caracteres X ou O, o programa apresenta como saída o termo que torna válida essa igualdade, seguido da palavra "venceu". # Caso não se confirme a igualdade, a saída do programa é a palavra "empate". v1 = input() v2 = input() v3 = input() v4 = input() v5 = input() v6 = input() v7 = input() v8 = input() v9 = input() if (v1 == v2 == v3) or (v1 == v5 == v9) or (v1 == v4 == v7): # Os comandos a seguir testam a igualdade dos termos por linha, coluna e diagonal. if (v1 == "X") or (v1 == "O"): print(str(v1) + " venceu") elif (v5 == v2 == v8) or (v5 == v4 == v6): if (v5 == "X") or (v5 == "O"): print(str(v5) + " venceu") elif (v9 == v6 == v3) or (v9 == v8 == v7): if (v9 == "X") or (v9 == "O"): print(str(v9) + " venceu") elif (v7 == v5 == v3): if (v7 == "X") or (v7 == "O"): print(str(v7) + " venceu") else: # Caso a igualdade seja falsa, o programa imprime "empatou". print("empatou")
false
18d996fd62f260065a15039544dd12bd9722805b
davetek/linearAlgebraRefresher
/linalgL2Q8.py
2,066
4.34375
4
#for lesson 2 of Linear Algebra Refresher course, part 1, Quiz 8 # covering vector magnitude and direction #import support module containing vector operation functions import vectorOperations print "Lesson 2: 1.8 Quiz exc 1" #declare the vectors to perform operations on inputVectors = [[7.887, 4.138], [-8.802, 6.776]] print "dot product of " + str(inputVectors) + ":" #get and print the vector magnitude print vectorOperations.dotProductOfVectors(inputVectors) print "" print "Lesson 2: 1.8 Quiz exc 2" #declare the vectors to perform operations on inputVectors = [[-5.955, -4.904, -1.874], [-4.496, -8.755, 7.103]] print "dot product of " + str(inputVectors) + ":" #get and print the vector magnitude print vectorOperations.dotProductOfVectors(inputVectors) print "" print "Lesson 2: 1.8 Quiz exc 3" #declare the vectors to perform operations on inputVector3a = [3.183, -7.627] inputVector3b = [-2.668, 5.319] print "angle between " + str(inputVector3a) + " and " + str(inputVector3b) + ":" #compute and print the angle between the input vectors print "radians: " + str(vectorOperations.angleBetweenVectors(inputVector3a, inputVector3b)) print "" print "Lesson 2: 1.8 Quiz exc 4" #declare the vectors to perform operations on inputVector4a = [7.35, 0.221, 5.188] inputVector4b = [2.751, 8.259, 3.985] print "angle between " + str(inputVector4a) + " and " + str(inputVector4b) + ":" #compute and print the angle between the input vectors, passing True for optional third parameter to output degrees print "degrees: " + str(vectorOperations.angleBetweenVectors(inputVector4a, inputVector4b, True)) print "" #test zero vector #declare the vectors to perform operations on inputVectorZero = [0, 0, 0] inputVector4b = [2.751, 8.259, 3.985] print "angle between " + str(inputVectorZero) + " and " + str(inputVector4b) + ":" #compute and print the angle between the input vectors, passing True for optional third parameter to output degrees print "degrees: " + str(vectorOperations.angleBetweenVectors(inputVectorZero, inputVector4b, True)) print ""
true
9dcbf1ca0b86cde7ad3bd956ae583ee9a06cad2d
mrAvi07/data_structures_algorithms
/2. Sorting Algorithms/selection_sort.py
645
4.15625
4
""" Selection Sort """ def find_smallest(arr): smallest = arr[0] smallest_index = 0 for i in range(1, len(arr)): if arr[i] < smallest: smallest = arr[i] smallest_index = i return smallest_index def selection_sort(arr): new_arr = [] for i in range(len(arr)): smallest = find_smallest(arr) new_arr.append(arr.pop(smallest)) return new_arr if __name__=="__main__": print(" Unsorted List ") number_list = [17, 3, 25, 4, 9, 10, 2] print(number_list) print("selection sort ") new_arr = selection_sort(number_list) print(new_arr)
true
3471f166f59483988681af0c0bd3e721dc3bde46
Gabospa/python-crud
/sort.py
1,649
4.125
4
secuencia = [5,2,4,1] def bubble_sort(array): n = len(array) for i in range(n): for j in range(n-i-1): if array[j] > array[j+1]: array[j], array[j+1] = array[j+1], array[j] return array def merge_sort(array, low, high): if low < high: #divide and conquer length = len(array) mid = (low + high)/2 merge_sort(array, low, mid) merge_sort(array, mid+1,high) def merge(arr, l, m, h): #calcula la mitad del sub arreglo n1 = m-l+1 n2 = h-m #crea sub arreglo 1 for i in range(n1): new_arr1[i] = arr[l+1] #crea sub arreglo 2 for j in range(n2): new_arr2[j] = arr[m+j+1 for k in range(length): if def quick_sort(array): pass def selector_ordenamiento(num): if num == 1: secuencia_ordenada = bubble_sort(secuencia) print(secuencia_ordenada) print('Metodo ordenado por Bubble Sort') elif num == 2: secuencia_ordenada = merge_sort(secuencia, low, high) print(secuencia_ordenada) print('Metodo ordenado por Merge Sort') else: secuencia_ordenada = quick_sort(secuencia) print(secuencia_ordenada) print('Metodo ordenado por Quick Sort') def run(): print('1. Bubble Sort \n2. Merge Sort \n3. Quick Sort') seleccion = int(input('Seleccione metodo ordenamiento: ')) print(f'La secuencia original es {secuencia}') selector_ordenamiento(seleccion) if __name__ == '__main__': run()
false
bafb6c09ecd0017428441e109733ebcb189863ad
spkibe/calc
/calc.py
606
4.15625
4
operation = input('operation type: ').lower() num1 = input("First number: ") num2 = input("First number: ") try: num1, num2 = float(num1), float(num2) if operation == 'add': result = num1 + num2 print(result) elif operation == 'subtract': result = num1 - num2 print(result) elif operation == 'multiply': result = num1 * num2 print(result) elif operation == 'divide': result = num1 / num2 print(result) else: print('You didi choose the right operation') except: # print("Impoper numbers or Operation")
true
4483f2cd521246a0f333a06908b66dbead1a865b
kmoreno08/Programming_Projects
/Chapter2_PP#4.py
2,260
4.375
4
#Chapter 2_Programming Project - Weird Multiplication '''You will be implementing the Russian Peasant method for multiplication. a) Write a program to find the product of two intergers. b) Modify your program so that it repeatedly asks whether you want to find another product.''' #Entry message print("Welcome to the russian peasant method for multiplication.") print("This program will show each step and what process took place.") print("To exit: type 'exit' at anytime.") print() #Loop to keep asking user for input while True: innerLoop = True numberA = input("What is your first integer? : ") numberA = numberA.lower() #exit program by user if str(numberA) == 'exit': break numberA = int(numberA) numberB = input("What is your second integer? : ") numberB = numberB.lower() #exit program by user if str(numberB) == 'exit': break numberB = int(numberB) #Zero sum, empty comment and message for table sum = 0 comment = "" message = "" print("__" * 21) #Headline print(f'{"A":>5}|{"B":>5}|{"Comment":<30}|') while innerLoop: #If B is odd if numberB % 2 == 1: #If B is zero, exit inner loop to print answer if numberB == 0: break comment = "Add A to the product, B is odd" #Table message = f'{numberA:>5}|{numberB:>5}|{comment:<20}|' print(message) #Calculation if B is odd numberB = int(numberB/2) sum = sum + numberA numberA = numberA * 2 else: #exit inner loop to print answer if numberB == 0: break comment = "Ignore this A value, B is even" #Table message = f'{numberA:>5}|{numberB:>5}|{comment:<20}|' print(message) #Calculation if B is even numberA = numberA * 2 numberB = int(numberB/2) #Answer print("__" * 21) print("Your total is " + str(sum)) print("**" * 21) #Exit message print("Thank you for trying the Russian method multiplication calculator.") print("Have a great day!")
true
369cb12749638b0613a81d2d86172dad72c00ba0
Amidala1/GBPython
/Lesson3/Lesson_3_1.py
973
4.21875
4
"""1. Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление. Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль. """ def division(num1, num2): """ Функция для расчета деления двух чисел """ try: return round(num1/num2, 2) except ZeroDivisionError: return "Деление на ноль!" print("*** Программа деления двух чисел ***") while True: try: number1 = int(input("Введите первое число: ")) number2 = int(input("Введите второе число: ")) except ValueError: print("Введите числовое значение") else: print(division(number1, number2)) break
false
0a6a97d35f72d46753285d3b29f9df118009cbee
Amidala1/GBPython
/Lesson4/Lesson_4_2.py
1,019
4.34375
4
""" 2. Представлен список чисел. Необходимо вывести элементы исходного списка, значения которых больше предыдущего элемента. Подсказка: элементы, удовлетворяющие условию, оформить в виде списка. Для формирования списка использовать генератор. Пример исходного списка: [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55]. Результат: [12, 44, 4, 10, 78, 123]. """ from random import randint start_number = 1 end_number = 1000 el_count = 9 numbers_list = [randint(start_number, end_number) for x in range(el_count)] new_numbers_list = [value for index, value in enumerate(numbers_list) if (index > 0) and (numbers_list[index] > numbers_list[index - 1])] print(f"Исходный список: {numbers_list}\nОбработанный список: {new_numbers_list}")
false
1ea2adeb0c26ef4d01beb83f4393902b79a35678
krrishsgk/Data-Structures
/LeetCode/04-NumberPalindrome.py
930
4.28125
4
""" Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Example 1: Input: 121 Output: true Example 2: Input: -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. Example 3: Input: 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome. Follow up: Coud you solve it without converting the integer to a string? """ class Solution: def isPalindrome(self, number: int) -> bool: string = str(number) palindrome = True counter = 0 while counter < len(string) and palindrome == True: if string[counter] == string[-(counter+1)]: pass else: palindrome = False break counter = counter + 1 return palindrome
true
20186fc7f5e9b93c5bea045b3a094399e3b99957
krrishsgk/Data-Structures
/LeetCode/2-ReverseInteger.py
743
4.25
4
""" Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. """ class Solution: def reverse(self, x: int) -> int: sign = (x>0)-(x<0) x = abs(x) digits = [0] while(x > 0): digits.append(x%10) x = x // 10 reverse = sign*int(''.join(map(str, digits))) return reverse*(-2**31 < reverse < 2**31)
true
ca0b23af364b9ce99ae61898adfa1525c2fca981
mengyuqianxun/Python-Algorithm-interview
/ch2_stack_queue/3.py
1,412
4.25
4
class Stack: #模拟栈 def __init__(self): self.items=[] #判断栈是否为空 def isEmpty(self): return len(self.items)==0 #返回栈的大小 def size(self): return len(self.items) #返回栈顶元素 def top(self): if not self.isEmpty(): return self.items[len(self.items)-1] else: return None #弹栈 def pop(self): if len(self.items)>0: return self.items.pop() else: print(u"栈已经为空") return None #压栈 def push(self,item): self.items.append(item) #把栈底元素移动到栈顶 def moveBottomToTop(s): if s.isEmpty(): return top1 = s.top() s.pop() if not s.isEmpty(): #递归处理不包含栈顶元素的子栈 moveBottomToTop(s) top2 = s.top() s.pop() #交换栈顶元素与子栈栈顶元素 s.push(top1) s.push(top2) else: s.push(top1) def reverse_stack(s): if s.isEmpty(): return moveBottomToTop(s) top1 = s.top() s.pop() reverse_stack(s) s.push(top1) if __name__ == "__main__": s = Stack() s.push(1) s.push(2) s.push(3) s.push(4) s.push(5) reverse_stack(s) print(u"翻转后出栈顺序为") while not s.isEmpty(): print(s.top()) s.pop()
false
8ba957ec1958047c49a57a4fcf096ba0a7fe1d9b
arpitrajput/20_Days_of_Code
/Day_12_Compound_Interest.py
412
4.125
4
# Python3 program to find compound interest for given values. def compound_interest(principle, rate, time): CI = principle * (pow((1 + rate / 100), time)) - principle print("Compound interest is", CI) principal = float(input("Enter the principal amount: \n")) rate = float(input("Enter the interest rate: \n")) time = float(input("Enter the time in years: \n")) compound_interest(principal,rate,time)
true
c2b946b650e88d82d8c2f166218e70f9e871e294
truongnguyenlinh/procedural_python
/A1/random_game.py
1,126
4.1875
4
# Linh Truong # A01081792 # 01-25-2019 import random def rock_paper_scissors(): """Generate a game of rock, paper or scissors with the computer. """ random_num = random.randint(0, 2) options = ['rock', 'paper', 'scissors'] random_choice = options[random_num] guess = input("Rock, paper or scissors?").strip().lower() if (guess != "rock") and (guess != "paper") and (guess != "scissors"): print("Incorrect value entered.") elif (guess == "paper") and (random_choice == "rock"): print("The computer entered rock so you've won!") elif (guess == "scissors") and (random_choice == "paper"): print("The computer entered paper so you've won!") elif (guess == "rock") and (random_num == "scissors"): print("The computer entered scissors so you've won!") elif guess == random_choice: print("The computer also entered", random_choice, "so it was a tie.") else: print("The computer entered", random_choice, "so you've lost.") def main(): """Execute the program.""" rock_paper_scissors() if __name__ == '__main__': main()
true
6f2af4445305821d674ca2888ac325eead368c38
candytale55/list-comprehension-challenges-Python-3
/greetings.py
275
4.375
4
# Create a new list named greetings that adds "Hello, " in front of each name in the list names. names = ["Elaine", "George", "Jerry", "Cosmo"] greetings = ["Hello, " + x for x in names] print(greetings) # ['Hello, Elaine', 'Hello, George', 'Hello, Jerry', 'Hello, Cosmo']
false
67ff4b0237870ed57bfa8c65698e8d9d4eb28c7f
Environmental-Informatics/python-learning-the-basics-RedpandaTheNinja
/Exercise_3.3.py
1,236
4.375
4
#Kevin Lee #Assin 1 #examples from text book # print('+','-','-','-','-','+','-','-','-','-','+') # print('+', end=' ') # print('-') # print('|', ' ', ' ', ' ',' ', '|', ' ', ' ', ' ',' ' ,'|') #creating 2x2 #first create each side by string of charc string1 = "+----+----+" string2 ="| | |" # print(string1) #create a function 2 different aruments as inputs #cprint as much as problem asks to def easy(arg1, arg2): print(arg1) print(arg2) print( arg2 ) print( arg2 ) print( arg2 ) print( arg1 ) print(arg2) print( arg2 ) print( arg2 ) print( arg2 ) print( arg1 ) easy(string1,string2) #double the length from previous stringg #since it is being called later, overwirte can be performed string1 = "+----+----+----+----+" string2 ="| | | | |" def easy2(arg1, arg2): print( arg1 ) print( arg2 ) print( arg2 ) print( arg2 ) print( arg2 ) print( arg1 ) print( arg2 ) print( arg2 ) print( arg2 ) print( arg2 ) print( arg1 ) print( arg2 ) print( arg2 ) print( arg2 ) print( arg2 ) print( arg1 ) print( arg2 ) print( arg2 ) print( arg2 ) print( arg2 ) print( arg1 ) easy2( string1 , string2 )
true
55d50be16cfd0fa6606a4fab7974eec5eb33c32b
liliarc96/Aula-Python
/Exercicios_2/positivo_negativo.py
670
4.1875
4
''' • Faça um programa que lê 10 números, calcula e exibe: • O triplo de cada número; • A mensagem “É positivo”, caso o número digitado seja positivo, ou “É negativo”, caso seja negativo; ''' cont = 1 #Em while while (cont <= 10): numero = int(input("Digite um número:")) numero = numero*3 print("O triplo desse número é",numero) if (numero >= 0): print("É positivo!") else: print("É negativo!") cont += 1 cont_2 = 0 #Em for for cont_2 in range (0,10): numero = int(input("Digite um número:")) numero = numero*3 print("O triplo desse número é",numero) if (numero >= 0): print("É positivo!") else: print("É negativo!")
false
fdcc61259401bb0fe0f23c59e36a95fa4d334eaa
liliarc96/Aula-Python
/Exercicios_2/mercadinho.py
1,075
4.15625
4
''' • Faça um programa que repita as seguintes tarefas, até que o código 0 seja digitado: •Leia o código do produto; •Leia a quantidade adquirida; •Se o código for 1, escreva 'Caderno - R$ 12.00'; •Se for 2, escreva 'Régua - R$ 2.50'; •Se for 3, escreva 'Borracha - R$ 0.25'; •Se for 4, escreva 'Mochila - R$ 50.00'; •Calcule e exiba o total a ser pago (valor * quantidade); ''' codigo = 5 valor_total = 0.00 quantidade = 0 print(''' CÓDIGO 1 = Caderno - R$ 12.00; CÓDIGO 2 = Régua - R$ 2.50; CÓDIGO 3 = Borracha - R$ 0.25; CÓDIGO 4 = Mochila - R$ 50.00; SAIR - 0 ''') while codigo != 0: codigo = int(input("\nDigite o código do produto: ")) if codigo == 1: valor = 12.00 elif codigo == 2: valor = 2.50 elif codigo == 3: valor = 0.25 elif codigo == 4: valor = 50.00 else: valor = 0.00 if codigo > 0 and codigo < 5: quantidade = int(input("\nDigite a quantidade adquirida: ")) else: quantidade = 0 valor_total = (valor_total + (valor * quantidade)) print("\nO valor total da compra foi de R$",valor_total)
false
798484ec330a30ff093df934a8f70878cc38801c
AriHiggs89/INFOTC-2040-CHALLENGES
/Python Challenges/animalclass.py
1,053
4.28125
4
# This is the program that defines an animal's class # By: Ariana Higgins import random class Animal: # function that defines what happens when a new animal object is created def __init__(self, animal_type, animal_name): self.__animal_type = animal_type self.__name = animal_name # generates a random number between 1 and 3 random_number = random.randint(1, 3) # this gives the animal it's mood based on the random number generated if random_number == 1: self.__animalmood = "happy" elif random_number == 2: self.__animalmood = "hungry" elif random_number == 3: self.__animalmood = "sleepy" # function that returns the animal type def get_animal_type(self): return self.__animal_type # function that returns the animal name def get_name(self): return self.__name # function that returns animal mood def check_mood(self): return self.__animalmood
true
c47ad8c8f14f73ba726a9ed664f72cba10622e6d
Nandita-20/pythoncode
/miscellanous_finctions.py
1,650
5.0625
5
#Range() function provides us list of number to iterate andis used with loop '''print("print negative values on reverse order\n") for i in range(-7,-3): print(i) print("print negative to positive values on reverse order\n") for i in range(-7,3): print(i) print("print values in reverse order by jumping r values\n") for i in range(7,1,-2): print(i) print("print values upto the given limit\n") for i in range(8): print(i) print("print values from lower to upper limit m-n\n") for i in range(1,8): print(i)''' ####################################################################################### #zip() : is a built-in Python function that gives us an iterator of tuples '''Like a .zip file holds real files within itself, a zip holds real data within. It takes iterable elements as input and returns an iterator on them (an iterator of tuples). It evaluates the iterables left to right.''' #zip function using multiple argument of same length '''a=[1,2,3] b=['nandita','sangita','ankita'] print(dict(zip(a,b)))''' '''for i in zip(['red','green'],['rose','leaves'],['%','#','$']): print(i)''' #zip function using multiple argument of same length #Note: When we provide multiple lists of different lengths, it stops at the shortest one. '''for i in zip(['red','green'],['rose','leaves'],['%']): print(i)''' #op: ('red', 'rose', '%') #zip() function using single argument '''for i in zip([1,2,3]): print(i)''' #unzipping() function in python '''z=zip(['red','green'],['rose','leaves'],['%','#']) a,b,c=zip(*z) print(a,b,c)''' #O/P: Now it is unpacked: ('red', 'green') ('rose', 'leaves') ('%', '#')
true
363d5bdc3d0430f439f2b7865f17f1a612d875c2
farjadfazli/code-challenges
/binarysearch_rotate-by-90-degrees-counter-clockwise.py
531
4.25
4
""" Rotate by 90 Degrees Counter-Clockwise Given a two-dimensional square matrix, rotate it 90 degrees counter-clockwise. Example 1 Input matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] Output [ [3, 6, 9], [2, 5, 8], [1, 4, 7] ] """ class Solution: def solve(self, matrix): # first we zip the matrix in order to combine every ith element of each list zipped = zip(*matrix) # then we can reverse this to obtain the desired rotation return (list((reversed(list(zipped)))))
true
58b41bfbc73e9ff14f1d5a2b74a25e7901abc1e5
farjadfazli/code-challenges
/reverse-integer.py
1,078
4.125
4
""" Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. Source: https://leetcode.com/problems/reverse-integer/ """ class Solution: def reverse(self, x: int) -> int: negative = False if (x < 0): negative = True reversed = 0 current = x if (negative): current *= -1 while current > 0: reversed *= 10 calculation = current % 10 reversed += calculation import math current = current // 10 print(reversed) if (negative): reversed *= -1 if (reversed > 2147483647 or reversed < -2147483648): return 0 return reversed
true
f35b661e6f549c3b00e5a7d865b43082fb0b5a0a
farjadfazli/code-challenges
/palindrome-number.py
1,316
4.28125
4
""" Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. Follow up: Could you solve it without converting the integer to a string? Example 1: Input: x = 121 Output: true Example 2: Input: x = -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. Example 3: Input: x = 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome. Example 4: Input: x = -101 Output: false Constraints: -231 <= x <= 231 - 1 Source: https://leetcode.com/problems/palindrome-number/ """ class Solution: def isPalindrome(self, x: int) -> bool: # we will determine if the integer is a palindrome by reversing it # and seeing if reversed integer == integer if x < 0: return False reversed = 0 current = x while current > 0: reversed *= 10 calculation = current % 10 reversed += calculation current = current // 10 if reversed == x: return True return False # alternate solution by converting integer to string: # if str(x) == "".join(reversed(str(x))): # return True
true
d84a0fb6c8a41613165765593791dd1a86080b6e
farjadfazli/code-challenges
/binarysearch_transpose-of-a-matrix.py
975
4.1875
4
""" Transpose of a Matrix Given an integer square (n by n) matrix, return its transpose. A transpose of a matrix switches the row and column indices. That is, for every r and c, matrix[r][c] = matrix[c][r]. For example, given matrix [1, 2, 3] [4, 5, 6] [7, 8, 9] it becomes [1, 4, 7] [2, 5, 8] [3, 6, 9] Constraints n ≤ 100 Example 1 Input matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] Output [ [1, 4, 7], [2, 5, 8], [3, 6, 9] ] """ class Solution: def solve(self, matrix): # we will take the nth element of each sublist and put it in the nth sublist of the new matrix result = [] length = len(matrix) counter = 0 while counter < length: for row in matrix: result.append(row[counter]) counter += 1 i = 0 final = [] while i < len(result): final.append(result[i:i+length]) i+=length return final
true
f331ba6ce83fe06967d7ed9948d1b0f50eb9a602
farjadfazli/code-challenges
/binarysearch_counting-dinosaurs.py
809
4.125
4
""" Counting Dinosaurs You are given a string animals and another string dinosaurs. Every letter in animals represents a different type of animal and every unique character in dinosaurs represents a different dinosaur. Return the total number of dinosaurs in animals. Example 1 Input animals = "abacabC" dinosaurs = "bC" Output 3 Explanation There's two types of dinosaurs "b" and "C". There's 2 "b" dinosaurs and 1 "C" dinosaur. Note we didn't count the lowercase "c" animal as a dinosaur. """ class Solution: def solve(self, animals, dinosaurs): from collections import Counter dinosaurs = set(dinosaurs) counter = 0 animalsDict = Counter(animals) print(animalsDict) for i in dinosaurs: counter += animalsDict[i] return counter
true
f4e1b664751849880849d57b522313e4ce1a92b5
macraiu/software_training
/leetcode/py/414_Third_Maximum_Number.py
1,103
4.125
4
""" Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n). """ def thirdMax(nums): a = sorted(set(nums)) if len(a) < 3: return max(a) else: return a[-3] import time import random A = [] for i in range(0,10000): n = random.randint(-10000,10000) A.append(n) t0 = time.clock() print(thirdMax(A)) t1 = time.clock() - t0 print("first ", t1) def thirdMax2(nums): # ONE SUBMISSIONS WITH GOOD TIME # Make a Set with the input. nums = set(nums) # Find the maximum. maximum = max(nums) # Check whether or not this is a case where # we need to return the *maximum*. if len(nums) < 3: return maximum # Otherwise, continue on to finding the third maximum. nums.remove(maximum) second_maximum = max(nums) nums.remove(second_maximum) return max(nums) t0 = time.clock() print(thirdMax2(A)) t1 = time.clock() - t0 print("second ", t1) # FOR HIGH VARIANCE IN THE DISTRIBUTION MINE PERFORMS BETTER
true