blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
0ec823ff787e42cbc840d8e7b10d0779bc084006
taramakhija/repository
/triangles.py
218
4.21875
4
import math def triangle_3rd_side(): a = int(input(" what does a equal")) b = int(input(" what does b equal")) csqr= a*2 + b*2 c = math.sqrt(csqr) print(f"the third side is {c}") triangle_3rd_side()
false
b11a066923bb37615bf23d01bcc5c22055fbda08
gosub/programming-praxis-python
/010-mardi-gras/mardi_gras.py
2,337
4.21875
4
# Mardi Gras # Compute the date of Easter # Programming Praxis Exercise 10 # http://programmingpraxis.com/2009/02/24/mardi-gras/ from datetime import date, timedelta def computus(year): """ Return the date of Easter for every year in the Gregorian Calendar. The original algorithm was submitted to Nature in 1877 by an anonymous. See: http://en.wikipedia.org/wiki/Computus#Anonymous_Gregorian_algorithm""" # years don't float! assert isinstance(year, int) # gregorian calendar only assert year > 1752 # the actual computus a = year % 19 b, c = divmod(year, 100) d, e = divmod(b, 4) f = (b + 8) / 25 g = (b - f + 1) / 3 h = (19 * a + b - d - g + 15) % 30 i, k = divmod(c, 4) L = (32 + 2 * e + 2 * i - h - k) % 7 m = (a + 11 * h + 22 * L) / 451 n = h + L - 7 * m + 114 month, day = divmod(n, 31) day += 1 return date(year, month, day) def paschal(year): """ Alternative implementation for computus(year). Calculate the date of paschal full moon in the gregorian calendar, then find the following sunday, which is easter. See: http://www.oremus.org/liturgy/etc/ktf/app/easter.html """ assert isinstance(year, int) assert year > 1752 # Golden number gn = year % 19 + 1 # Solar correction sc = (year - 1600) / 100 - (year - 1600) / 400 # Lunar correction lc = (year - 1400) / 100 * 8 / 25 # Paschal full moon (num of days after vernal equinox) pfm = (3 - 11 * gn + sc - lc) % 30 if pfm == 29 or (pfm == 28 and gn > 11): pfm -= 1 # Paschal full moon (date) pfmd = date(year, 3, 21) + timedelta(days=pfm) # Easter is the first sunday after pfmd day, sunday = timedelta(days=1), 6 easter = pfmd + day while not easter.weekday() == sunday: easter += day return easter def mardi_gras(year): easter = computus(year) mardi = easter - timedelta(days=47) return mardi def main(years): for year in years: easter = computus(year) mardi = mardi_gras(year) print "easter in", year, "falls on", easter print "mardi gras in", year, "falls on", mardi if __name__ == '__main__': import sys if sys.argv[1:]: years = map(int, sys.argv[1:]) else: years = [2009, 1989, 2049] main(years)
false
89ebfba3b074ecdf011aff1e1f0a1013f980ab56
rafa761/algorithms-example
/insertion_sort.py
585
4.28125
4
unsorted_list = [7, 3, 9, 2, 8, 4, 1, 5, 6] def insertion_sort(num_list): # We don't need to consider the index 0 because there isn't any number on the left for i in range(1, len(num_list)): # store the current value to sort value_to_sort = num_list[i] # While there are greater values on the left while num_list[i - 1] > value_to_sort and i > 0: # switch the values num_list[i], num_list[i - 1] = num_list[i - 1], num_list[i] i -= 1 return num_list if __name__ == '__main__': print('Before:', unsorted_list) print('After: ', insertion_sort(unsorted_list))
true
55ca73caa0515d4f6a514e9869b0a65a9bfeb602
CaioJrVS/Algest
/python/DS/linkedlist/singlyllist.py
1,856
4.125
4
class Node: def __init__(self,data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def traverse(self): temp = self.head while temp != None: print(temp.data, end = " ") temp = temp.next print() def insert_begining(self,data): new_node = Node(data) new_node.next = self.head self.head = new_node def insert_end(self,data): new_node = Node(data) new_node.next = None temp = self.head while temp.next != None: temp=temp.next temp.next = new_node def insert_after(self,node,data): new_node = Node(data) temp1 = self.head temp2 = self.head.next while temp1.data != node: temp1 = temp1.next temp2 = temp2.next new_node.next = temp2 temp1.next = new_node def delete_node(self,node): temp1 = self.head temp2 = self.head.next while temp2.data is not node and temp1.data is not node: temp1=temp1.next temp2=temp2.next temp2 = temp2.next temp1.next = temp2 def delete_at_position(self,pos): temp = self.head for i in range(pos-1): temp=temp.next print(temp.data) self.delete_node(temp.data) if __name__ == "__main__": llist = LinkedList() llist.head = Node(1) second = Node(2) third = Node(3) llist.head.next = second second.next = third third.next = None llist.traverse() llist.insert_begining(0) llist.traverse() llist.insert_end(5) llist.traverse() llist.insert_after(3,4) llist.traverse() llist.delete_node(3) llist.traverse() llist.delete_at_position(3) llist.traverse()
false
eda70418204060e275cfb778bd85bc9852ae72dd
17764591637/jianzhi_offer
/剑指offer/15_ReverseList.py
528
4.15625
4
''' 输入一个链表,反转链表后,输出新链表的表头。 思路: step1:None step2:1->None step3:2->1->None ... ''' class Solution: # 返回ListNode def ReverseList(self, pHead): # write code here if not pHead or not pHead.next: return pHead p_before = None pNode = pHead while pNode != None: pNext = pNode.next pNode.next = p_before p_before = pNode pNode = pNext return p_before
false
981ca7c3e0a1e0ee84e20a4869e6c564cb5e9fce
17764591637/jianzhi_offer
/剑指offer/63_GetMedian.py
953
4.25
4
''' 如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值, 那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值, 那么中位数就是所有数值排序之后中间两个数的平均值。 我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。 ''' class Solution: def __init__(self): self.nums = [] def Insert(self, num): # write code here self.nums.append(num) return self.nums def GetMedian(self,nums): # write code here nums = self.nums nums.sort() n = len(nums)//2 if len(nums)%2 != 0: return nums[n] else: return (nums[n]+nums[n-1])/2.0 s = Solution() s.Insert(1) s.Insert(2) s.Insert(4) s.Insert(6) s.Insert(3) res = s.GetMedian([1,2,4,6,3]) print(res)
false
7fac6b0e87c550f517d9bea7834585812ff6ddac
Raeebikash/python_class2
/practice/exercise77.py
538
4.25
4
# define is_palindrome function that take one world in string as input # and return True if it is palindrome else return false # palindrome - word that reads same backwards as forwards #example # is_palindrome ("madam") ------> True # is_palindrome ("naman")------> True #is_palindrome ("horse")----->False # logic (algorithm) #step 1-> reverse the string # step 2 - compare reversed string with original string def is_palindrome(word): return word == word[::-1] print(is_palindrome("naman")) print(is_palindrome("horse"))
true
2a4e100e806ffed91ee5ed7098dc89644e06b084
ijaha/PY100
/1.1.py
222
4.1875
4
# Записать условие, которое является истинным , когда целое А кратно двум или трем. A = int(input()) if A % 2 == 0 or A % 3 == 0: print('True')
false
32d93101bcb08f1af155821534a19e7098a0100f
gargchirayu/Python-basic-projects
/factorial.py
217
4.125
4
num = int(input("Enter number:")) fac = 1 if num<0: print("Negative number invalid") elif num == 0: print("Factorial = 1") else: for i in range(1, num+1): fac = fac*i print("Factorial = ",fac)
false
8fa3d457aeb3c0162a2b0d677ce3b089dd8e1e25
BalaKumaranKS/Python
/codes/assignment 01- 01.py
209
4.4375
4
#program for calculating area ofcircle value01 = int (input('Enter radius of circle in mm ')) value02 = (value01 * value01) value03 = (3.14 * value02) print ('The area of circle is',str(value03),'mm^2' )
true
628bfaf8e262ab8186103f95e52f478ed7381082
BalaKumaranKS/Python
/codes/assignment 02- 02.py
235
4.3125
4
# Program to check number is positive or negative inp = int(input('Enter the Number: ')) if inp > 0: print('The number is Positive') elif inp== 0: print ('The number is 0') else: print('The number is Negative')
true
0bd9287e31945c94caf4cb3ee7c41635435a7273
heecho/Database
/webserver-3.py
2,628
4.1875
4
''' Phase three: Templating Templating allows a program to replace data dynamically in an html file. Ex: A blog page, we wouldn't write a whole new html file for every blog page. We want to write the html part, and styling just once, then just inject the different blog data into that page. 1) Add the following line to index.html in the body <h2>###Title###</h2> 2) When a request come in for index (/) - read the file data for index.html - change the ###Title### string to the string "This is templating" - return the changed html 3) Write a function render_template to take an html template, and a hash context Ex: render_template("<html>...",{"Title":"This is templating"}) - Render will then try to replace all the fields in that hash Ex: context = {"Title":"This is the title","BlogText":"this is blog data"} In the html template replace ###Title### and ###BlogText### with corresponding key values. - Test by using this context {"Title":"This is the title","BlogText":"this is blog data"} 4) Add render_template to index_page with the sample context above ''' import socket HOST, PORT = '', 8888 VIEWS_DIR = "./views" def run_server(): listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listen_socket.bind((HOST, PORT)) listen_socket.listen(1) urls = {'/': index_page(), '/about': about_page()} print 'Serving HTTP on port %s ...' % PORT while True: client_connection, client_address = listen_socket.accept() request = client_connection.recv(4096) request_line = request.split('\r\n') request_first_part = request_line[0].split(' ') request_verb = request_first_part[0] request_page = request_first_part[1] print request_verb, request_page http_response = """HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n""" if request_page in urls.keys(): http_response += urls[request_page] if not request: continue client_connection.sendall(http_response) client_connection.close() def read_file(page): page_file = VIEWS_DIR + page with open(page_file, 'r') as f: return f.read() def index_page(): filehash = {"Title":"This is a New Title"} filedata = read_file('/index.html') return render_template(filedata,filehash) def about_page(): return read_file('/about.html') def render_template(filedata, data_hash): for k,v in data_hash.iteritems(): filedata = filedata.replace('###%s###' %k, v) return filedata run_server()
true
afc147e559f9589487ce969973e8342beae3a05b
Ulkuozturk/SQL_Python_Integration
/movie_Create_AddData.py
648
4.4375
4
import sqlite3 connection = sqlite3.connect("movie.db") cursor= connection.cursor() cursor.execute('''CREATE TABLE IF NOT EXISTS Movies (Title TEXT, Director TEXT, Yera INT)''' ) famousfilms=[("Pulp Fiction","Quantin Tarantino", 1994),("Back To The Future","Steven Spielberg", 1985), ("Moonrise Kingdom","Wes Anderson", 2012)] cursor.executemany('INSERT INTO Movies VALUES (?,?,?)', famousfilms) # To insert multiple values. records=cursor.execute("SELECT * FROM Movies ") print(cursor.fetchall()) for record in records: print(record) connection.commit() connection.close() ## Simply run the file to create db file we just create.
true
35f0ae91acf3ccd76a04ed1aeca5faef42eae435
EdwardRamos2/EstruturaDeDecisao
/03.py
453
4.28125
4
#!/usr/bin/env python #*-*coding: utf-8 *-* #Faça um Programa que verifique se uma letra digitada é "F" ou "M". #Conforme a letra escrever: F - Feminino, M - Masculino, Sexo Inválido. sexo = input('Digite (F Feminino) ou (M Masculino): ') print(sexo) if sexo.upper() == 'M': print ('(+) Sexo escolhido: Masculino') elif sexo.upper() == 'F': print('(+) Sexo escolhido: Feminino') else: print('(-) Caractere invalido! Tente novamente')
false
f3c5fe7381107bb91c110a7cb9bf708b699b3d5b
andkashkaha/GeekBrains_lessons
/Lesson1_Task2.py
534
4.15625
4
#Пользователь вводит время в секундах. Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс. Используйте форматирование строк. user_time=int(input("Введите время в секундах: ")) all_minutes=user_time//60 seconds=user_time%60 hours=all_minutes//60 minutes=all_minutes%60 print(f"Время в нужном формате: {hours:02}:{minutes:02}:{seconds:02}")
false
554f4435cd9ec0bdbdff8e5f6b61a50b3ae8f355
taylortom/Experiments
/Python/MyFirstPython/Lists.py
518
4.3125
4
# # Lists # list = [0,1,'two', 3, 'four', 5, 6, 'Bob'] # add to the list list.append('kate') print list # remove an item list.pop(3) # can also use list.pop() to remove last item print list # sort a list list.sort() print list # reverse a list list.reverse() print list # list nesting matrix = [[-1,0,0], [0,-1,0], [0,0,1]] print matrix[2], matrix[2][2] # access a 'column' in the matrix print [row[0] for row in matrix] # add 1 to each item in column 1 matrix2 = [row[0] + 1 for row in matrix] print matrix2
true
3bf15f4e63a239fd34a0806ff00bbae0163a417a
wesley-1221/python_learning
/python类编程/进阶篇/双下划线方法_one.py
947
4.3125
4
# -*- coding:utf-8 -*- """ 作者:wesley 日期:2020年11月29日 """ # __len__ # __hash__ # __eq__ class Student(object): def __init__(self, name): self.name = name def __len__(self): print("____len____") return 1 # 需要返回一个整数 def __hash__(self): print("____hash____") return 2 def __eq__(self, other): print(other.name) print("call eq method.") if self.name == other.name and self.name == other.name: return True else: print("不相等 ") return False s = Student("wesley") s1 = Student("linda") len(s) # 触发__len__ # print(hash(s)) # -922337184451311246 没有重写__hash__ hash(s) # 触发__hash__ s == s1 # 触发__eq__ print("__________________________________________________")
false
8666c0e53861a399e74c4e8f0808e6d1ea1eb7f0
wesley-1221/python_learning
/python类编程/进阶篇/双下划线方法_three.py
1,465
4.46875
4
# -*- coding:utf-8 -*- """ 作者:wesley 日期:2020年11月29日 """ # 重要 ''' str函数或者print函数调用时--->obj.__str__() repr或者交互式解释器中调用时--->obj.__repr__() 如果__str__没有被定义,那么就会使用__repr__来代替输出 注意:这俩方法的返回值必须是字符串,否则抛出异常 ''' # class Student(object): # # def __init__(self, name, age): # self.name = name # self.age = age # # def __repr__(self): # print("__触发了__repr__") # return "a" # 必须返回字符串 # # def __str__(self): # print("__触发了__str__") # return "a" # # 必须返回字符串 # # s = Student("wesley", 18) # print('from repr: ', repr(s)) # from repr: a # print('from str: ', str(s)) # from str: a # print(s) # a class Student(object): def __init__(self, name, age): self.name = name self.age = age def __repr__(self): print("__触发了__repr__") return 'Student(%s,%s)' %(self.name,self.age) def __str__(self): print("__触发了__str__") return '(%s,%s)' %(self.name,self.age) s = Student("wesley", 18) print('from repr: ', repr(s)) # from repr: Student(wesley,18) print('from str: ', str(s)) # from str: (wesley,18) print(s) # (wesley,18)
false
fa5e9a2770fbc24836104db247d0d1e6866ee77b
sidmaskey13/python_assignments_2
/P12.py
599
4.375
4
# Create a function, is_palindrome, to determine if a supplied word is # the same if the letters are reversed. givenString = input('Enter string: ') def check_palindrome(given_string): word_length = len(given_string) half_word_length = int(word_length/2) match = 0 for i in range(0, half_word_length): if given_string[i] == given_string[-i-1]: match += 1 if match == half_word_length: return f"{given_string} is Palindrome" else: return f"{given_string} is not Palindrome" print(check_palindrome(givenString))
true
61e354e9f4d5c5cabbd6a804150cf5e6c505285a
sidmaskey13/python_assignments_2
/P3.py
586
4.3125
4
# Write code that will print out the anagrams (words that use the same # letters) from a paragraph of text. givenString = input('Enter string: ') def check_anagrams(given_string): word_length = len(given_string) half_word_length = int(word_length/2) match = 0 for i in range(0, half_word_length): if given_string[i] == given_string[-i-1]: match += 1 if match == half_word_length: return f"{given_string} is Anagram" else: return f"{given_string} is not Anagram" print(check_anagrams(givenString))
true
8d085c2ca7fe0c47b2c772c551466919c24899c2
lgd405/hello
/tutorial/bmi.py
791
4.15625
4
# -*- coding: utf-8 -*- while True : name = input("Your name : ") h = input("Your Height (m) : ") w = input("Your Weight (kg) : ") Height = float(h) Weight = float(w) bmi = Weight / (Height*Height) if bmi < 18.5: print("Your are too light(name = %s , BMI = %d) !" % (name, bmi)) elif bmi >= 18.5 and bmi < 25: print("Congratulation you are health(name = %s , BMI = %d)!" % (name, bmi)) elif bmi >= 25 and bmi < 32: print("You are Heavy , Please pay a attension(name = %s, BMI = %d)!" % (name, bmi)) else: print("You are too Heavy , you must get your weight down(name = %s, BMI = %d)!" % ( name, bmi)) q = input("Press any key to continue , <q> to quit ......") if q == 'q': break
false
70a2412549fe5a7e8bf54f626457e529363f3a9b
mccricardo/project_euler
/problem_46/python/problem46.py
627
4.3125
4
# Start with prime 3. # # If none of the primes in prime_list divide n, then it's also prime and # add it to the list. # # If not, let's put the problem formula with another aspect: # prime = odd_number - 2 * pow(i, 2) # # This means that we can check if any of the primes can be constructed in terms # of the odd number. If not, we found our number. number = 3 primes_list = set() while True : if all(number % p for p in primes_list) : primes_list.add(number) else : if not any((number-2*pow(i,2)) in primes_list for i in xrange(1, number)): break number += 2 print "The number is:", number
true
365df8c8ca7c12b37c84963376692b16a476c503
mohammadrezamzy/python_class
/List_sample1.py
707
4.28125
4
students = [ ("John", ["CompSci", "Physics"]), ("Vusi", ["Maths", "CompSci", "Stats"]), ("Jess", ["CompSci", "Accounting", "Economics", "Management"]), ("Sarah", ["InfSys", "Accounting", "Economics", "CommLaw"]), ("Zuki", ["Sociology", "Economics", "Law", "Stats", "Music"])] print(len(students) , len(students[3]),len(students[3][1])) for name, subjects in students: print(name, "takes", len(subjects), "courses") # Count how many students are taking CompSci counter = 0 for name, subjects in students: for s in subjects: # A nested loop! if s == "CompSci": counter += 1 print("The number of students taking CompSci is", counter)
false
a3def7eec0586d8dfdbef1aa55c6feec20b5c854
wreyesus/Learning-to-Code
/python/python_crash_course/chapter_4/4-1.pizzas.py
273
4.6875
5
""" Store three kinds of pizza in a list 1. print them in a for loop 2. write about why you love pizza """ pizzas = ['americana', 'hawaina', 'peperoni'] for pizza in pizzas: #1 print(f'I like {pizza}') print('I REALLY LOVE PIZZA IS MY FAVORITE FOOD IN THE WORLD') #2
true
d1076809fe1826dad2117b9ced283dcb7173fcdb
wreyesus/Learning-to-Code
/python/python_crash_course/chapter_10/10-2.learning_c.py
458
4.28125
4
""" Read in each line from the file you just created, learning_python.txt, and replace the word Python with the name of another language, such as C. Print each modified line to the screen. """ filename = './learning_python.txt' with open(filename) as f: lines = f.readlines() for line in lines: if 'Python' in line: c = line.replace('Python', 'C') print(c.strip()) def if the name of iquales main is more than just
true
ee10c39f6ec686f1644016633282fdaacd279843
wreyesus/Learning-to-Code
/python/python_crash_course/chapter_6/6-8.pets.py
691
4.4375
4
""" Make three dictionaries representing different pets, and store all three dictionaries in a list called pets. Loop through your list of pets. As you loop through the list, print everything you know about each pet """ pets = [] chulu = { 'kind': 'cat', 'owner': 'james', 'name' : 'chulu' } pets.append(chulu) laica = { 'kind': 'dog', 'owner': 'luis', 'name' : 'laica' } pets.append(laica) mickey = { 'kind': 'mouse', 'owner': 'walt', 'name' : 'mickey' } pets.append(mickey) for pet in pets: name = pet['name'].title() owner = pet['owner'].title() kind = pet['kind'].title() print(f'{name.upper()}:\n- Owner: {owner}\n- Kind: {kind}')
false
8655935a7d3a32c2e1a89ef3091db2f3f3de256a
wreyesus/Learning-to-Code
/python/python_crash_course/chapter_9/9-2.three_restaurants.py
838
4.4375
4
""" Start with your class from Exercise 9-1. Create three different instances from the class, and call describe_restaurant() for each instance. """ class Restaurant: def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): print(f'Welcome to {self.restaurant_name.title()}') print(f'Our cousine type is: {self.cuisine_type.title()}') def open_restaurant(self): print(f'The {self.restaurant_name.title()} is OPEN') restaurant1 = Restaurant('Don Pancho', 'fried chicken') restaurant2 = Restaurant('American Store', 'burguer') restaurant3 = Restaurant('Healthy place', 'burguer') restaurant1.describe_restaurant() restaurant2.describe_restaurant() restaurant3.describe_restaurant()
true
085723b30c9de5a3dae534fa25a02f3deaafe065
wreyesus/Learning-to-Code
/python/python_crash_course/chapter_8/8-12.sandwiches.py
545
4.15625
4
""" Write a function that accepts a list of items a person wants on a sandwich. The function should have one parameter that collects as many items as the function call provides, and it should print a summary of the sandwich that is being ordered. """ def sandwiches_order(*sandwich): print('ORDER:') for order in sandwich: print(f'- {order.title()}') sandwiches_order('peruvian', 'mcburger', 'chicken junior') sandwiches_order('american classic', 'fish burger', 'chicken') sandwiches_order('onion', 'simple burger', 'turkey')
true
2565e37340942909c482bb4501d45d057fb3960e
wreyesus/Learning-to-Code
/regExp/scripts/exercise_2.py
323
4.25
4
"""Write a Python program that matches a string that has an a followed by zero or more b's.""" import re def finder(string): """using 're.match'""" regex = re.match('^a[\w]*', string) if regex: print('We have a MATCH') else: print('NO MATCH') finder('abc') finder('abbc') finder('abbba')
true
2264c01614e3ba01e621b7cc9ae50920f2a54bc0
wreyesus/Learning-to-Code
/python/python_crash_course/chapter_5/5-2.more_conditional_tests.py
1,021
4.3125
4
# 1. Tests for equality and inequality with strings print('='*5) car = 'Tesla' print(car == 'tesla') print(car == 'Tesla') # 2. Tests using the lower() function print('='*5) name = 'James' test = name.lower() == 'james' print(test) # 3. Numerical tests involving equality and inequality, # greater than and less than, greater than or equal to, # and less than or equal to print('='*5) age = 18 print(age != 19) 20 > 10 print(20 < 10) 10 >= 10 print(10<10) print(10==10) # 4. Tests using the and keyword and the or keyword print('='*5) tickets = 5 10 >= 10 test_2 = (tickets == 5) and (10 > 10) test_3 = (tickets == 5) or (10 > 10) print(test_2) print(test_3) # 5. Test whether an item is in a list print('='*5) pets = ['cat', 'dog', 'mouse'] print(pets) if 'cat' in pets: print(f'The {pets[0]} is a cute pet') else: print('I do not like that one') # 6. Test whether an item is not in a list print('='*5) foods = ['ceviche', 'peruavian beans', 'pizza'] food = 'turkey' if food not in foods: print('OK')
true
e93ba2f959698ef3a4d35bfd8d32dfa0b4907974
mmonali/monisha2007
/2007 assignment4 module3(chapter 1).py
2,227
4.15625
4
#!/usr/bin/env python # coding: utf-8 # In[1]: #numbers frm 0 to 6(excluding 3 n 6) for x in range(6): if (x == 3 or x==6): continue print(x,end=' ') print("\n") # In[2]: #counting odd or even numbers numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) count_odd = 0 count_even = 0 for x in numbers: if not x % 2: count_even+=1 else: count_odd+=1 print("Number of even numbers :",count_even) print("Number of odd numbers :",count_odd) # In[3]: #reversing a word word = input("Input a word to reverse: ") for char in range(len(word) - 1, -1, -1): print(word[char], end="") print("\n") # In[1]: #gcd or hcf def gcd(a,b): if (a == 0): return b if (b == 0): return a if (a == b): return a if (a > b): return gcd(a-b, b) return gcd(a, b-a) a = int(input("enter first num:")) b = int(input("enter second num:")) if(gcd(a, b)): print('GCD of', a, 'and', b, 'is', gcd(a, b)) else: print('not found') # In[3]: #avg of integers print ("calculate an average of first n natural numbers") n = 10 average = 0 sum = 0 for num in range(0,n+1,1): sum = sum+num; average = sum / n print("Average of first ", n, "natural number is: ", average) # In[4]: rows = 4 for i in range(0, rows): for j in range(0, i + 1): print("*", end=' ') print("\r") # In[5]: #multiplication table num = int(input("Enter the number: ")) print("Multiplication Table of", num) for i in range(1, 11): print(num,"X",i,"=",num * i) # In[6]: #fibonacci series n = int(input("Enter the value of 'n': ")) a = 0 b = 1 sum = 0 count = 1 print("Fibonacci Series: ", end = " ") while(count <= n): print(sum, end = " ") count += 1 a = b b = sum sum = a + b # In[7]: #binary to decimal def binaryToDecimal(binary): binary1 = binary decimal, i, n = 0, 0, 0 while(binary != 0): dec = binary % 10 decimal = decimal + dec * pow(2, i) binary = binary//10 i += 1 print(decimal) if __name__ == '__main__': binaryToDecimal(100) binaryToDecimal(101) binaryToDecimal(1001) # In[ ]:
false
ab3e9f61cd9942019c125f1d940daff547c80888
Abdulvaliy/Tip-calculator
/Tip calculator.py
468
4.125
4
#If the bill was $150.00, split between 5 people, with 12% tip. #Each person should pay (150.00 / 5) * 1.12 = 33.6 print("Welcometo the tip calculator.") bill = float(input("What was the total bill? $")) percent = int(input("What percentage tip would you like to give? 10, 12 or 15? ")) people = int(input("How many people to split the bill? ")) cost = str(round((bill * (100 + percent)/100) / people , 2)) print(f"Each person should pay: ${cost}")
true
240cad4398853e25f993842413a88eef365af76b
brian-rieder/DailyProgrammer
/DP146E_PolygonPerimeter.py
1,903
4.3125
4
__author__ = 'Brian Rieder' # Link to reddit: http://www.reddit.com/r/dailyprogrammer/comments/1tixzk/122313_challenge_146_easy_polygon_perimeter/ # Difficulty: Easy # A Polygon is a geometric two-dimensional figure that has n-sides (line segments) that closes to form a loop. # Polygons can be in many different shapes and have many different neat properties, though this challenge is about # Regular Polygons . Our goal is to compute the permitter of an n-sided polygon that has equal-length sides # given the circumradius . This is the distance between the center of the Polygon to any of its vertices; # not to be confused with the apothem! # Input Description # Input will consist of one line on standard console input. This line will contain first an integer N, then # a floating-point number R. They will be space-delimited. The integer N is for the number of sides of the Polygon, # which is between 3 to 100, inclusive. R will be the circumradius, which ranges from 0.01 to 100.0, inclusive. # Output Description # Print the permitter of the given N-sided polygon that has a circumradius of R. Print up to three digits precision. # Sample Inputs & Outputs # Sample Input 1 # 5 3.7 # Sample Output 1 # 21.748 # Sample Input 2 # 100 1.0 # Sample Output 2 # 6.282 from math import sin from math import pi class Polygon: def __init__(self, num_sides, circumradius): self.num_sides = float(num_sides) self.circumradius = float(circumradius) def find_side_length(self): return 2 * self.circumradius * sin(pi / self.num_sides) def find_perimeter(self, side_length): return side_length * self.num_sides if __name__ == "__main__": user_input = input("Enter arguments as <number of sides> <circumradius>: ").split() polygon = Polygon(user_input[0], user_input[1]) print("Perimeter: %.3f" % polygon.find_perimeter(polygon.find_side_length()))
true
7bbd62ff212c1a9a6b33b8bab369ba3b9c025488
amandazhuyilan/Breakfast-Burrito
/Data-Structures/BinarySearchTree.py
2,911
4.1875
4
# Binary Search tree with following operations: # Insert, Lookup, Delete, Print, Comparing two trees, returning tree # elements # example testing tree: # 8 # / \ # 3 10 # / \ \ # 1 6 14 # / \ / # 4 7 13 class node: def __init__(self, data): self.left = None self.right = None self.data = data # Insert node with value data. Look for right location recursively. # ex. root.insert(3) def insert(self,data): if self.data: if data > self.data: if self.right is None: self.right = node(data) else: self.right.insert(data) elif data < self.data: if self.left is None: self.left = node(data) else: self.left.insert(data) elif data == self.data: print("Node already exists!") else: self.data = data # Lookup node with given data, do it recursively until find it. Returns # node and its parent # ex: root.lookup def lookup(self, data, parent=None): if data < self.data: if self.left is None: return None, None return self.left.lookup(data, self) elif data > self.data: if self.right is None: return None, None else: return self.right.lookup(data,self) else: return self, parent # Removes the node in the tree. Need to consider if the removed node has # 0, 1 or 2 children (added in count_children function) # Always need to consider different scenrios when node is root def delete(self, data): def count_children(self): count = 0 if self.left: count += 1 if self.right: count += 1 return count node, parent = self.lookup(data) if node: if count_children == 0: if parent: if parent.left is node: parent.left = None else: parent.right = None del node # If the node to be removed is a root: else: self.data = None if count_children == 1: if node.left: n = node.left if node.right: n = node.right if parent: if parent.left is node: parent.left = n else: parent.right = n else: self.left = n.left self.right = n.right self.data = n.data if count_children == 2: parent = node successor = node.right while successor.left: parent = successor successor = successor.left node.data = successor.data if parent.left == successor: parent.left = successor.right else: parent.right = successor.right # Use recursive to walk tree depth-first. Left subtree->Root->Right # subtree def print_tree(self): if self.left: self.left.print_tree() print self.data if self.right: self.right.print_tree() #Tests root = node(8) root.insert(3) root.insert(1) root.insert(6) root.insert(4) root.insert(7) root.insert(2) root.insert(5) root.insert(10) root.insert(14) root.insert(13) print(root.lookup(6))
true
d2ece47f1eed48fffd1e820e18d84f12598b017f
amandazhuyilan/Breakfast-Burrito
/Problems-and-Solutions/python/isPalindrome.py
477
4.28125
4
def is_Palindrome_Recrusive(s): if s == "": return True if s[0] == s[-1]: return is_Palindrome_Recrusive(s[1:-1]) def is_Palindrome_Iteration(s): if s == "": return True for i in range(len(s)//2): if s[i] != s[-(i+1)]: return False return True TEST_CASE1 = "abuttuba" TEST_CASE2 = "word" print("Original string is:", TEST_CASE1) print("Recursive method:",is_Palindrome_Recrusive(TEST_CASE1)) print("Iterative method:",is_Palindrome_Iteration(TEST_CASE1))
false
0971f0292c5f040685704da9a064f5328a180615
mayank-gubba/Compiler-Design
/Complier_Design/lexical/type_of_operator.py
860
4.3125
4
"""CODE BY MAYANK GUBBA this lexical analyser uses regular expression to find out the type of operator of data that is given as input""" import re t=int(input('enter the number of test cases: ')) for i in range(t): s=input("enter operator/data: ") if (re.match('^\*$',s)): print('multiplication operator') elif (re.match('^\+$',s)): print('addition operator') elif (re.match('^-$',s)): print('subtraction operator') elif (re.match('^/$',s)): print('division operator') elif (re.match('^>*$',s)): print('greater than operator') elif (re.match('^<*$',s)): print('less than operator') elif (re.match('^[0-9]+$',s)): print('integer data') elif (re.match('^[a-zA-z]+$',s)): print('alphabetical data') else: print('alphanumeric data')
false
7c9c7bfbaac7077ec4beaa4dac1405d726799eb7
hayleymathews/data_structures_and_algorithms
/Lists/examples/insertion_sort.py
819
4.34375
4
"""python implementation of Insertion Sort with Positional List >>> p = PositionalList() >>> p.add_first(1) Position: 1 >>> p.add_first(3) Position: 3 >>> p.add_first(2) Position: 2 >>> insertion_sort(p) PositionalList: [1, 2, 3] """ from Lists.positional_list import PositionalList def insertion_sort(List): if len(List) > 1: marker = List.first() while marker != List.last(): pivot = List.after(marker) value = pivot.element() if value > marker.element(): marker = pivot else: walk = marker while walk != List.first() and List.before(walk).element() > value: walk = List.before(walk) List.delete(pivot) List.add_before(walk, value) return List
true
cbe8c75f0538700abf4c7e528176c83944be8080
hayleymathews/data_structures_and_algorithms
/Arrays/examples/insertion_sort.py
439
4.28125
4
""" python implementation of Insertion Sort >>> insertion_sort([3, 2, 1]) [1, 2, 3] """ def insertion_sort(array): """ sort an array of comparable elements in ascending order O(n^2) """ for index in range(1, len(array)): current = array[index] while index > 0 and array[index - 1]> current: array[index] = array[index - 1] index -= 1 array[index] = current return array
true
f06dce01ee6561b52c9abd3681fba7c55ddc618c
RodrigoCh99/basic-challenges-in-python-language
/desafio37.py
856
4.3125
4
""" Escreva um programa que leia um número inteiro qualquer e peça para o usuario escolher qual será a base de conversão: """ print('\nESSE PROGRAMA É UM CONVERSOR DE BASES!') print('*'*25) print('Os codigos das bases são:') print('1 para binario,\n2 para octal\n3 para hexadecimal') print('*'*25) num = int(input('\nInsira um valor para ser convertido: ')) base = int(input('Insira um codigo de base para conversão: ')) if base == 1: print('\nO valor {} em decimal \nEquivale a: {} em binario'.format(num, bin(num)[2:])) elif base == 2: print('\nO valor {} em decimal \nEquivale a: {} em octal'.format(num, oct(num)[2:])) elif base == 3: print('\nO valor {} em decimal equivale a: {} em hexadecimal'.format(num,hex(num)[2:])) else: print('\nVoce digitou um codigo invalido!\nPor favor tente denovo!')
false
3845efa0fa83dbbddb300186fbc3b8f7a04daf21
RodrigoCh99/basic-challenges-in-python-language
/desafio55.py
479
4.125
4
print('Esse programa calcula o peso de 5 pessoas e mostra a mais pesada!') pesado = 0 leve = 0 for c in range(1,6): peso = float(input('Informe o peso da {}° pessoa: '.format(c))) if c == 1: pesado = peso leve = peso else: if peso > pesado: pesado = peso elif peso < leve: leve = peso print('\nA pessoa mais pesada pesa: {} Kg'.format(pesado)) print('A pessoa mais leve pesa: {} Kg'.format(leve))
false
13aeaa9b88bb275c2cddb52ca10b6574371b8794
RodrigoCh99/basic-challenges-in-python-language
/desafio45.py
1,087
4.1875
4
""" Crie um Programa que faça o computador jogar pedra papel tesoura com voce! """ from random import randint print('\nVamos jogar pedra, papel e tesoura?') numc = randint(1,3) print('-'*25) print('Escolha [1] para pedra\nEscolha [2] para papel\nEscolha [3] para tesoura') print('-'*25) numj = int(input('qual a sua escolha? ')) if numj == 1: if numc == 1: print('\nEMPATE!\nNós 2 jogamos pedra') elif numc == 2: print('\nEU GANHEI!\nEu joguei papel e voce pedra') else: print('\nVOCE GANHOU!\nEu joguei tesoura e voce pedra') elif numj == 2: if numc == 1: print('\nVOCE GANHOU!\nEujoguei pedra e voce papel') elif numc ==2: print('\nEMPATE!\nNós dois jogamos papel') else: print('\nEU GANHEI!\nVoce escolheu papel e eu tesoura') else: if numc == 1: print('\nEU GANHEI!\nEU escolhi pedra e voce tesoura') elif numc == 2: print('\nVOCE GANHOU!\nEu escolhi papel e voce tesoura') else: print('\nEMPATE!\nNós dois escolhemos tesoura')
false
8bffdf5b0bbccc50713e33273c9dfd9c678e4e68
leo-0101/exercicios-python
/exercicio_rpg-poo.py
1,963
4.28125
4
class Personagem: # PRECISA SER UM ATRIBUTO BASE PARA NÃO DAR PROBLEMA # vida = 150 mana = 100 inteligencia = 30 forca = 30 agilidade = 30 carisma = 20 def __init__(self, nome): self.nome = nome def atacar(self, inimigo): inimigo.vida -= self.forca print(f'O {self.nome} atacou e tirou {self.forca} de pontos do {inimigo.nome}') class Guerreiro(Personagem): inteligencia = 10 agilidade = 20 forca = 80 def __init__(self, nome): self.nome = nome # Inicialmente eu havia reescrito esse método em todas as outras classes, # mas não é necessário. Se tirar, ok. Se deixar, ok também, não muda nada. def esmagar(self, inimigo): inimigo.vida -= 2*self.forca print(f'O guerreiro {self.nome} esmagou o {inimigo.nome} e tirou {2*self.forca} pontos de vida!') class Mago(Personagem): inteligencia = 80 forca = 10 agilidade = 20 def magia(self, inimigo): inimigo.vida -= 2*self.inteligencia print(f'O mago {self.nome} lançou uma bola de fogo no {inimigo.nome} e tirou {2*self.inteligencia} de vida!') class Bardo(Personagem): carisma = 70 inteligencia = 20 forca = 10 agilidade = 20 def curar(self, aliado): aliado.vida += 2*self.carisma print(f'O bardo {self.nome} curou seu aliado {aliado.nome} com {2*self.carisma} pontos de vida!') class Arqueiro(Personagem): agilidade = 80 forca = 20 inteligencia = 20 carisma = 10 def flechar(self, inimigo): inimigo.vida -= 2*self.agilidade print(f'O arqueiro {self.nome} flecha o {inimigo.nome} e tira {2*self.agilidade} pontos de vida!') g1 = Guerreiro('Leo') m1 = Mago('Leonidas') b1 = Bardo('Rodrigo') a1 = Arqueiro('Carlos') # Atacar é um método da classe pai que todos tem em comum, # sendo assim, todos podem usar. a1.atacar(b1) g1.atacar(b1) b1.atacar(b1) m1.atacar(b1)
false
17d8341915e5f154a32bc5080e3685999b4a0c70
Sincab/d_s01
/yout-03.py
401
4.25
4
# floor division // ---- 3 // 2 = 1 # exponent ** ---- 3 ** 2 = 9 # modulus % ----- 5 % 3 = 2 # equal 3 == 2 # not equal 3 != 2 # greater or equal 3 >= 2 # smaller or equal 3 <= 2 num_1 = 3 # int num_2 = 3.5 # float num = 1 num = num + 2 print(num) num = 1 num **= 2 print(num) print(abs(-7)) print(round(3.7589, 2)) print(num_1 != num_2) num = '100' print(int(num) / 2) # convert it to number #
false
97e9c3f73ab4dfa755eb467fa8bba65f2d4c71f5
epicmonky/Project-Euler-Solutions
/problem020.py
430
4.125
4
# n! means n x (n - 1) x ... x 3 x 2 x 1 # For example, 10! = 10 x 9 x ... x 3 x 2 x 1 = 3628800, # and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. # Find the sum of the digits in the number 100! import math def sum_of_digits(n): s = 0 while n > 0: s += n % 10 n = n // 10 return s if __name__ == '__main__': n = math.factorial(100) print(sum_of_digits(n))
true
9f443ffa4598eeb84214fa77e7d6d1a9bfa27e2b
xujundong/demo
/列表.py
1,300
4.3125
4
#申明列表 list1 = ["a","b","c",1,2,3] #打印列表 print(list1) #通过索引获取元素,0开始,-1末尾 print(list1[0]) # a #添加元素("增"append, extend, insert) #append增加元素 list1.append("A") print(list1) #extend列表A增加到列表B list2 = ["aa","bb"] list1.extend(list2) print(list1) #insert在指定位置index前插入元素object----注意是前面 list1.insert(2,"AA") print(list1) #修改元素,直接通过索引= 什么来修改 list1[0]="XXX" print(list1) #查找元素 in not in 返回True False print("a" in list1) print("a" not in list1) #index, count 索引和出现的次数 ,注意左闭右开区间 print(list1.index("XXX")) print(list1.count("XXX")) #删除元素("删"del, pop, remove) #del 全部删除 del list2 # print(list2) #pop默认删除最后一个元素,给指定的下标删除指定的元素 list1.pop() print(list1) list1.pop(2) print(list1) #remove 根据元素的值进行删除第一个 list1.remove("XXX") print(list1) #排序(sort, reverse) #sort方法是将list按特定顺序重新排列,默认为由小到大,参数reverse=True可改为倒序,由大到小。 a=[5,2,1,3,4] a.sort() print(a) #reverse逆序排 a.reverse() print(a) #enumerate打印出下标,不常用 for i,chr in enumerate(list1): print(i,chr)
false
7d734ce53f66b6ffbd13b9a18332428188d0bec3
Lizi2hua/Understanding-Python
/python/Python_base/python基本知识.py
905
4.1875
4
"""python的/y永远返回浮点""" a = 25 b = 5 print(type(a / b)) """floor除法, //得到整数结果""" a1 = 7 a2 = 3 print(a1 // a2) # 2 # 7//3.5=2.0 """转义""" print("\"Yes,\"he said") print("C:\some\name") # \n是换行符,使用r来使用原始字符串 print(r"C:\some\name") """使用 \ 作为连续符""" print("liu\ mengyuan") # liumengyuan """或者这样""" print('liu' ' mengyuan') # liu mengyuan word = "python" # 当索引的右边值大于实际长度时,会被字符串的实际长度代替 print(word[3:44]) # 左边过大返回空 print(word[22:]) # list也适用 lis = [0, 1, 2, 3, 4, 5] print(lis[2:22]) """序列类型,可以索引的类型""" set = (0, 2, 3, 4, 4, 2, 3, 4) print(set[1:5]) squares = [1, 3, 5, 6, 7, 10] b = [2, 2, 2] print(type(squares + b)) """变量由右边赋值,右边先计算""" a, b = 0, 1 while b < 10: print(b) a, b = b, a + b
false
440f7e019f7621b8f497beb4dd3d6156870bfb3c
colehoener/DataStructuresAndAlgorithms
/Hash/open_hash.py
1,809
4.15625
4
#Mark Boady - Drexel University CS260 2020 #Implement an OPEN hash table import random #Hash Functions to test with def hash1(num,size): return num % size def hash2(num,size): x=2*(num**2)+5*num+num return x % size def hash3(num,size): word=str(num) total=0 for x in range(0,len(word)): c=word[x] total=total+ord(c) total=total*1010 return total % size #Here is a helper function for testing #It gives you a random sequence #with no duplicates def random_sequence(size): X=[x for x in range(0,5*size+1)] random.shuffle(X) return X[0:size] #The class for the open hash table class OpenHash: #n is the size of the table #h_fun is the hash function to use #h_fun must be a function that takes two inputs #the number to hash and size of the table. #It returns an integer between 0 and n-1 #The index to put the element. def __init__(self,n,h_fun): self.size = n self.data = [ [] for x in range(0,n)] self.hash_func = h_fun #You can use this str method to help debug def __str__(self): res="" for x in range(0,self.size): res+="Row "+str(x)+" "+str(self.data[x])+"\n" return res #Insert num into the hashtable #Do not keep duplicates in the table. #If the number is already in the table, do not #Insert it again def insert(self,num): pos = self.hash_func(num, self.size) if not(num in self.data[pos]): self.data[pos].append(num) return #Member returns True is num is in the table #It returns False otherwise def member(self,num): pos = self.hash_func(num, self.size) if (num in self.data[pos]): return True return False #Delete removes num from the table def delete(self,num): pos = self.hash_func(num, self.size) if (num in self.data[pos]): self.data[pos].remove(num) return #You may create any additional #Helper methods you wish
true
980aeca14a04f2727cd917c4acf0151646b92e52
andresbonett/python-basico
/diccionarios.py
1,026
4.15625
4
def run(): mi_diccionario = { 'llave1': 1, 'llave2': 2, 'llave3': 3, } print(mi_diccionario) # {'llave1': 1, 'llave2': 2, 'llave3': 3} print(mi_diccionario['llave2']) # 2 ############## poblacion_paises = { "Colombia": 50, "Argentina": 44, "Brasil": 210, } print(poblacion_paises['Colombia']) # 50 ## Bucles: for pais in poblacion_paises.keys(): print(pais) ## Colombia - Argentina - Brasil for pais in poblacion_paises.values(): print(pais) ## 50 - 44 - 210 for pais in poblacion_paises.items(): print(pais) ## ('Colombia', 50) - ('Argentina', 44) - ('Brasil', 210) for pais, poblacion in poblacion_paises.items(): print(pais + " tiene " + str(poblacion) + " millones de habitantes") # Colombia tiene 50 millones de habitantes # Argentina tiene 44 millones de habitantes # Brasil tiene 210 millones de habitantes if __name__ == "__main__": run()
false
abf112da79470c8d9b14e7d17747ad699858718b
arcPenguinj/CS5001-Intensive-Foundations-of-CS
/homework/HW1/tables.py
1,226
4.25
4
''' Yici Zhu CS 5001, Fall 2020 it's a program calculating how many table can be assembled test cases : 4 tops, 20 legs, 32 screws => 4 tables assembled. Leftover parts: 0 table tops, 4 legs, 0 screws. 20 tops, 88 legs, 166 screws => 20 tables assembled. Leftover parts: 0 table tops, 8 legs, 6 screws. 100 tops, 88 legs, 200 scews => 22 tables assembled. Leftover parts: 78 table tops, 0 legs, 24 screws. ''' def main (): tabletop_number = int(input("Number of tops: ")) leg_number = int(input("Number of legs: ")) screw_number = int(input("Number of screws: ")) top_per_table = tabletop_number / 1 legs_per_table = leg_number / 4 screw_per_table = screw_number / 8 table_can_be_assembled = int(min(top_per_table, legs_per_table, screw_per_table)) top_leftover = int(tabletop_number - table_can_be_assembled) leg_leftover = int(leg_number - table_can_be_assembled * 4) screw_leftover = int(screw_number - table_can_be_assembled * 8) print (str(table_can_be_assembled) + " tables assembled. Leftover parts: " + str(top_leftover) + " tops, " + str(leg_leftover) + " legs, " + str(screw_leftover) + " screws.") if __name__ == "__main__": main()
true
e6146ffced7b19a485620bbac781e8cf59774471
arcPenguinj/CS5001-Intensive-Foundations-of-CS
/in_class_excercise/lecture5_inclass_excercise.py
216
4.3125
4
for i in range(0, 6): print (i) for i in range(5, -1, -1): print(i) for i in range(1, 12, 2): print(i) word = "Hello, World" for letter in range(1, len(word), 2): print(word[letter])
false
cc47e4a1c80f09bbeb121b624dc1f5d2fca087f8
arcPenguinj/CS5001-Intensive-Foundations-of-CS
/homework/HW2/exercise.py
1,669
4.21875
4
''' Fall2020 CS 5001 HW2 Yici Zhu it's a program for planning exercise based on different conditions ''' def main(): days = input("What day is it? ").title() holidays = input("Is it a holiday? ").title() rains = input("Is it raining? ").title() temps = float(input("What is the temperature? ")) # print(days, holidays, rains, temps) holidaybool = True workoutdays_bool = True rainsbool = True if days != "M" and days != "Tu" and days != "W" and days != "Th" and \ days != "F" and days != "Sa" and days != "Su": print("Swim for 35 minutes") return if holidays == "Y": holidaybool = True elif holidays == "N": holidaybool = False else: print("Swim for 35 minutes") return if rains == "Y": rainsbool = True elif rains == "N": rainsbool = False else: print("Swim for 35 minutes") return if days == "M" or days == "W" or days == "F" or \ days == "Sa" or holidaybool: workoutdays_bool = True else: print("Take a rest day") return excersice = "" if days == "M" or days == "W" or days == "F": excersice = "Run" if days == "Sa" or holidaybool: excersice = "Hike" if rainsbool and workoutdays_bool: excersice = "Swim" excersice_time = "" if excersice == "Run" and (temps > 75 or temps < 35): excersice_time = "30" else: excersice_time = "45" print(excersice + " for " + excersice_time + " minutes") if __name__ == "__main__": main()
true
a77c1e503d0e39d55e2915962131bad2f0970126
algorithmsmachine/PythonAlgorithms
/misc/factorial.py
256
4.1875
4
num = 90 factorial=1 if num <0: print("cannot print factorial of negative num ") elif num == 0: print("The factorial of 0 is 1") else: for i in range(1,num + 1): factorial = factorial*i print("The factorial of",num," is ",factorial)
true
84a41b50164514518b02a83722820605d0468e0e
prabhakarzha/pythonimportantcode
/main.py
2,146
4.125
4
# reduce() function is not a built-in function anymore ,and it can be found in the functools module from functools import reduce def add(x,y): return x+y list =[2,3,4,5,6] print(reduce(add,list)) # map() function -The map() function iterates through all items in the given iterable # and execute the function we passes as an argument on each of them def starts_with_A(s): return s[0]=="A" fruit =["Apple","Banana","pear","mango","Apricot"] map_object =map(starts_with_A,fruit) print(list(map_object)) #another example def sq(a): return a*a num =[2,3,4,5,6,7,8,9,] square = list(map(sq,num)) print(square) #filter() function forms a new list that contains only elements that satisfy a certain condition def starts_with_A(s): return s[0]=="A" fruit =["Apple","Banana","pear","mango","Apricot"] filter_object =filter(starts_with_A,fruit) print(list(filter_object)) #--------------------------MAP------------------------------ numbers = ["3", "34", "64"] numbers = list(map(int, numbers)) for i in range(len(numbers)): numbers[i] = int(numbers[i]) numbers[2] = numbers[2] + 1 print(numbers[2]) def sq(a): return a*a num = [2,3,5,6,76,3,3,2] square = list(map(sq, num)) print(square) num = [2,3,5,6,76,3,3,2] square = list(map(lambda x: x*x, num)) print(square) def square(a): return a*a def cube(a): return a*a*a func = [square, cube] num = [2,3,5,6,76,3,3,2] for i in range(5): val = list(map(lambda x:x(i), func)) print(val) #--------------------------FILTER------------------------------ list_1 = [1,2,3,4,5,6,7,8,9] def is_greater_5(num): return num>5 gr_than_5 = list(filter(is_greater_5, list_1)) print(gr_than_5) #--------------------------REDUCE------------------------------ from functools import reduce list1 = [1,2,3,4,2] num = reduce(lambda x,y:x*y, list1) # num = 0 # for i in list1: # num = num + i print(num) from array import* # vals = array('i',[1,2,3,4,5,]) # # for i in range(5): # print(vals[i]) # val =array('i',[2,3,4,5,]) # for i in range(4): # print(val[i]) val=array('i',[2,3,4,5,6,7]) val.reverse() print(val)
true
ca3819dc5cd360988f9eb8c2f6f3ae7942ac1446
Gowthini/gowthini
/factorial.py
261
4.28125
4
num=int(input("enter the number")) factorial=1 if num<0: print("factorial does not exist for negative numbers") elif num==0: print("The factorial is") else: for i in range(1,num+1): factorial=factorial*i print("The factorial of"num,"is",factorial)
true
d33fb48a41a852ab3d3bfcb4624e7693dad18f9c
jwmarion/daily
/euler/35multiple.py
427
4.21875
4
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. # # Find the sum of all the multiples of 3 or 5 below 1000. multiples = [] result = 0 for x in range(0,1000): if x % 3 == 0: multiples.append(x) if x % 5 == 0 and x % 3 != 0: multiples.append(x) for x in range(len(multiples)): result += multiples[x] print result
true
d19cef12494dc50a7beb21a625a23823ce93d98c
eghadirian/Python
/P10-FindTwoElements.py
377
4.15625
4
# find the if sum of two elements is a value # find pythagoream triplets def sum_of_two(arr, val): found = set() for el in arr: if val - el in found: return True found.add(el) return False def func(arr): n = len(arr) for i in range(n): if sum_of_two(arr[:i]+arr[i+1:], arr[i]): return True return False
true
e358e998f4b59281e990ffd5b41dc2ecc81db548
devpatel18/PY4E
/ex_05_02.py
484
4.21875
4
largest=None smallest=None while True: num1=input("Enter a number:") if num1=="done": break try: num=int(num1) except: print("Please enter numeric value") continue if largest is None: largest=num elif num>largest: largest=num if smallest is None: smallest=num elif num<smallest: smallest=num print("ALL DONE") print("largest is :",largest,"\n smallest is:",smallest)
true
109af5cbe8647fef80c83a92b088cbe77505d3ce
joelmedeiros/studies.py
/Fase12/Challange37.py
385
4.125
4
number = int(input('Write a number ')) base = int(input('''Chose an option: \n 1 - binary 2 - octal 3 - hexadecimal ''')) if base == 1: print("The number {0} in binary is {0:b}".format(number)) elif base == 2: print("The number {0} in octal is {0:o}".format(number)) elif base ==3: print("The number {0} in octal is {0:x}".format(number)) else: print('Invalid option')
false
a6d8a0779cfc7092ef6f8651f0b8bc9ab9da774c
joelmedeiros/studies.py
/Fase7/Challange6.py
265
4.28125
4
number = int(input("Tell me the number you want to know the double, triple and square root: ")) double = number*2 triple = number*3 sqrt = number**(0.5) print("The double of {} is {} and the triple is {} and the sqrt is {:.2f}".format(number, double, triple, sqrt))
true
8907a33161a9922cca2925059520c857ee7c4451
Jay-mo/Hackerrank
/company_logo.py
1,604
4.53125
5
""" A newly opened multinational brand has decided to base their company logo on the three most common characters in the company name. They are now trying out various combinations of company names and logos based on this condition. Given a string S, which is the company name in lowercase letters, your task is to find the top three most common characters in the string. Print the three most common characters along with their occurrence count. Sort in descending order of occurrence count. If the occurrence count is the same, sort the characters in alphabetical order. For example, according to the conditions described above, Sample Input aabbbccde b 3 a 2 c 2 """ from operator import itemgetter from collections import Counter, OrderedDict if __name__ == "__main__": company_name = input() #use counter to get dictionary of the all the elements in the strings and their count as values name_dict = Counter(list(company_name)) #because sorted keeps the original order of sorted items when the sorted keys are the same, I have to sort the keys firsts in ascending order. s = sorted(name_dict.items(), key=itemgetter(0)) #using sorted and passing itemgetter to get sort based on the values. Reverse flag set to sort in descending order sorted_name_tuple = sorted(s, key=itemgetter(1), reverse=True) #use ordered dict so that the order is maintained. sorted_name_dict = OrderedDict({ k:v for k, v in sorted_name_tuple}) #print only the first 3 items for i in list(sorted_name_dict.keys())[:3]: print( i , sorted_name_dict[i])
true
a163cf56718a5fe33b00f120073ba193292a5933
VickeeX/LeetCodePy
/desighClass/ShuffleArray.py
1,198
4.25
4
# -*- coding: utf-8 -*- """ File name : ShuffleArray Date : 18/05/2019 Description : 384. Shuffle an Array Author : VickeeX """ import random class Solution: def __init__(self, nums: list): # # trick # self.reset = lambda: nums # self.shuffle = lambda: random.sample(nums, len(nums)) self.nums = nums def reset(self) -> list: """ Resets the array to its original configuration and return it. """ return self.nums def shuffle(self) -> list: """ Returns a random shuffling of the array. """ # # random comparision: reduce the swap times for element # return sorted(self.nums, key=(lambda x: random.random())) count, l = 0, len(self.nums) - 1 tmp = [i for i in self.nums] while count < l: choice = random.randint(count, l) tmp[count], tmp[choice] = tmp[choice], tmp[count] count += 1 return tmp # Your Solution object will be instantiated and called as such: # obj = Solution(nums) # param_1 = obj.reset() # param_2 = obj.shuffle()
true
cea604980474aeb6996ab3b925b4c1fe8dc17cd2
Qurbanova/PragmatechFoundationProjects
/Algorithms/week09_day04.py
2,679
4.5625
5
# 1)Write a Python function to sum all the numbers in a list. Sample List : (8, 2, 3, 0, 7) Expected Output : 20 # 2)Write a Python function to multiply all the numbers in a list. Sample List : (8, 2, 3, -1, 7) Expected Output : -336 # 3)Write a function called returnDay. This function takes in one parameter ( a number from 1-7) and returns the day of the week ( 1 is Sunday, 2 is Monday etc.). If the number is less than 1 or greater than 7, the function should return None. Expected Output: returnDay(1) --> Sunday # 4)-Write a function called lastElement. This function takes one parameter (a list) and returns the last value in the list. It should return None if the list is empty. Example Output lastElement([1,2,3]) # 3 lastElement([]) # None # 5)Write a Python program to print the even numbers from a given list. Sample List : [1, 2, 3, 4, 5, 6, 7, 8, 9] Expected Result : [2, 4, 6, 8] #GOOD LUCK FOR ME ! #FUNCTIONS # def my_function(): # print('hello from a function!') # my_function() ''' def lst(): lst=[] mylist=[8, 2, 3, 0, 7] num=0 num+=1 if num in mylist: lst.append(mylist) print("Sum of elements in given list is :", sum(lst)) ''' ''' mylist=[8, 2, 3, 0, 7] Sum=sum(mylist) print(Sum) ''' ''' def hasil(my_list): netice=1 for i in my_list: netice=netice*i return(netice) hasil([8, 2, 3, -1, 7]) ''' ''' def hefteninGunleri(eded): hefteninGunleri={ 1:'Sunday', 2:'Monday', 3:'Tuesday', 4:'Wensday', 5:'Thursday', 6:'Friday', 7:'Saturday' } if 1<=eded<=7: return(hefteninGunleri[eded]) else: return None eded=int(input("Bir gun qeyd edin 1-7 arasi: ")) x=hefteninGunleri(eded) if x[0]=='F': print('cume gunu') ''' # def last_element(my_list): # if my_list: # return my_list[-1] # return None # print(last_element([1,2])) even_list=[] def even_element(my_list): for i in my_list: if i%2==0: even_list.append(i) even_element([1,2,3,4,5,6,7,8]) even_element([10,5,6,367,6]) print(even_list) ''' def topla(my_list): cem=0 for i in my_list: cem+=i return cem print(topla([8,2,3,0,7])) ''' #lst = [] #num = int(input('How many numbers: ')) #for n in range(num): # numbers = int(input('Enter number ')) # lst.append(numbers) #print("Sum of elements in given list is :", sum(lst)) ''' def my_function(fname, fsurname): print(fname + " " +fsurname +" Refsnes") my_function("Emil","Quliyev") def my_function(*kids): print("The youngest child is " + kids[2]) my_function("Emil", "Tobias", "Linus") '''
true
7dc89b6e60710ae6437519899cb6e3520e6cf53f
nandhinipandurangan11/CIS40_Chapter4_Assignment
/CIS40_Nandhini_Pandurangan_P4_9.py
664
4.15625
4
# CIS40: Summer 2020: Chapter 4 Assignment: Problem 9 : Nandhini Pandurangan # This program reads a string and prints the string in reverse. # print_reverse() reads user input and prints it in reverse def print_reverse(): string = input("Please enter a word: ").strip() for i in range(len(string) - 1, -1, -1): # iterate in reverse print(string[i], end="") # print string in reverse print_reverse() ''' Output: Please enter a word: harry yrrah ---------------------------- Please enter a word: She sells seashells by the seashore erohsaes eht yb sllehsaes slles ehS ----------------------------- Please enter a word: 123456789 987654321 '''
true
a9be48c1b64fc1dfdf33f58b9d6c35f8b9caae1a
sich97/WakeyWakey
/server/server_setup.py
2,149
4.375
4
""" File: server_setup.py This file creates / or resets the server database. """ import sqlite3 import os DATABASE_PATH = "server/db" def main(): """ In the case that a database already exists, ask the user if it's really okay to reset it. If no, then do nothing and exit. If yes, delete the existing database and create a new one. :return: None """ reset = False # A database already exists if os.path.isfile(DATABASE_PATH): # Ask the user what to do print("Database already exists. Do you want it reset? [NO]: ", end="") reset = input() # User answered yes if reset == "YES" or reset == "Yes" or reset == "yes": # Delete the database os.remove(DATABASE_PATH) # Create a new one create_database() # A database does not exist else: create_database() def create_database(): """ Creates a database and fills it with initial information. :return: None """ # Establish database connection db = sqlite3.connect(DATABASE_PATH) cursor = db.cursor() # Create the server settings table sql_query = """CREATE TABLE server_settings(id INTEGER PRIMARY KEY, address TEXT, port INTEGER, alarm_state INTEGER)""" cursor.execute(sql_query) # Fill the table with data sql_query = """INSERT INTO server_settings(address, port, alarm_state) VALUES(?, ?, ?)""" data = "", 49500, 0 cursor.execute(sql_query, data) # Create the user preferences table sql_query = """CREATE TABLE user_preferences(id INTEGER PRIMARY KEY, wakeup_time_hour INTEGER, wakeup_time_minute INTEGER, utc_offset INTEGER, wakeup_window INTEGER, active_state INTEGER)""" cursor.execute(sql_query) # Fill the table with data sql_query = """INSERT INTO user_preferences(wakeup_time_hour, wakeup_time_minute, utc_offset, wakeup_window, active_state) VALUES(?, ?, ?, ?, ?)""" data = 16, 00, 2, 2, 0 cursor.execute(sql_query, data) # Save changes to database db.commit() # Close database db.close() if __name__ == '__main__': main()
true
8a2e5a2ed33489e1db0dc410db6cc3aa8e083f44
sweekar52/APS-2020
/Daily-Codes/Median of an unsorted array using Quick Select Algorithm.py
2,067
4.15625
4
# Python3 program to find median of # an array import random a, b = None, None; # Returns the correct position of # pivot element def Partition(arr, l, r) : lst = arr[r]; i = l; j = l; while (j < r) : if (arr[j] < lst) : arr[i], arr[j] = arr[j],arr[i]; i += 1; j += 1; arr[i], arr[r] = arr[r],arr[i]; return i; # Picks a random pivot element between # l and r and partitions arr[l..r] # around the randomly picked element # using partition() def randomPartition(arr, l, r) : n = r - l + 1; pivot = random.randrange(1, 100) % n; arr[l + pivot], arr[r] = arr[r], arr[l + pivot]; return Partition(arr, l, r); # Utility function to find median def MedianUtil(arr, l, r, k, a1, b1) : global a, b; # if l < r if (l <= r) : # Find the partition index partitionIndex = randomPartition(arr, l, r); # If partion index = k, then # we found the median of odd # number element in arr[] if (partitionIndex == k) : b = arr[partitionIndex]; if (a1 != -1) : return; # If index = k - 1, then we get # a & b as middle element of # arr[] elif (partitionIndex == k - 1) : a = arr[partitionIndex]; if (b1 != -1) : return; # If partitionIndex >= k then # find the index in first half # of the arr[] if (partitionIndex >= k) : return MedianUtil(arr, l, partitionIndex - 1, k, a, b); # If partitionIndex <= k then # find the index in second half # of the arr[] else : return MedianUtil(arr, partitionIndex + 1, r, k, a, b); return; # Function to find Median def findMedian(arr, n) : global a; global b; a = -1; b = -1; # If n is odd if (n % 2 == 1) : MedianUtil(arr, 0, n - 1, n // 2, a, b); ans = b; # If n is even else : MedianUtil(arr, 0, n - 1, n // 2, a, b); ans = (a + b) // 2; # Print the Median of arr[] print("Median = " ,ans); # Driver code arr = [ 12, 3, 5, 7, 4, 19, 26 ]; n = len(arr); findMedian(arr, n); # This code is contributed by AnkitRai01
true
fa9b017ec497e894b7222af17575ad0abe015f52
sajaram/Projects
/text_adventure_starter.py
1,609
4.375
4
start = ''' You wake up one morning and find that you aren’t in your bed; you aren’t even in your room. You’re in the middle of a giant maze. A sign is hanging from the ivy: “You have one hour. Don’t touch the walls.” There is a hallway to your right and to your left. ''' print(start) print("Type 'left' to go left or 'right' to go right.") user_input = input() if user_input == "left": print("You decide to go left and you see that there are two doors: one door is red and one door is green. What door do you choose?") print("Type 'green' to go through the green door or 'red' to go through the red door") user_input = input() if user_input == "green": print ("Congrats, you are safe!") elif user_input == "red": print("Sorry, you fell through the Earth and died!") #while user_input != "red" or "green": #user_input == input("Enter red or green ") elif user_input == "right": print("You choose to go right and you come across a shoreline. You can decide whether you want to swim or take the boat that is next to the shoreline. What do you choose?") # finished the story writing what happens print ("Type 'swim' to swim across or type 'boat' to take the boat across.") user_input = input() if user_input == "swim": print("Wow, you are an amazing swimmer, and you survived!") elif user_input == "boat": print("I'm sorry, the boat had a hole and you drowned!") #while user_input != "swim" or "boat": #user_input == input("Enter swim or boat ") #while user_input != "right" or "left": #user_input == input("Enter right or left ") #these aren't supposed to work
true
bb7219177527b96c77d15869c247ad16615a0693
sagdog98/PythonMiniProjects
/Lab_1.py
2,248
4.34375
4
# A list of numbers that will be used for testing our programs numbers = [1, 2, 3, 4, 5, 6, 7, 8] # Question 1: Create a function called even, which takes in an integer as input and returns true if the input is even, and false otherwise def even(num): # Provide your code here return True if num % 2 == 0 else False print("even(1):\t\t\t\t", even(1)) # should return False print( "even(2):\t\t\t\t", even(2)) # shourd return True print() # Question 2: Create a function called odd, which takes in an integer as input and returns true if the input is odd, and false otherwise def odd(num): # Provide your code here return False if num % 2 == 0 else True print("odd(1):\t\t\t\t\t", odd(1)) # should return True print("odd(2):\t\t\t\t\t", odd(2)) # shourd return False print() # Question 3: Given a list of integers, create a function called count_odd, which takes in a list and counts the number of odd. Your function should employ a divide and conquer approach. Select an appropriate base case and implement a recursive step. def count_odd(list): # Provide your code here return 0 if len(list) == 0 else (list[0] % 2 + count_odd(list[1:])) print("count_odd([1, 2, 3, 4, 5, 6, 7, 8]):\t", count_odd(numbers)) # should return 4 print() # Question 4: Given a list of integers, use a divide and conquer approach to create a function named reverse, which takes in a list and returns the list in reverse order. def reverse(list): # Provide your code here if len(list) == 0: return [] else: return reverse(list[1:]) + list[:1] if list else [] print("reverse([1, 2, 3, 4, 5, 6, 7, 8]):\t", reverse(numbers)) # should return [8, 7, 6, 5, 4, 3, 2, 1] print() # Question 5: Given two sorted lists, it is possible to merge them into one sorted lists in an efficient way. Design and implement a divide and conquer algorithm to merge two sorted lists. def merge(list1, list2): # Provide your code here if list1 and list2: if list1[0] > list2[0]: list1, list2 = list2, list1 return [list1[0]] + merge(list1[1:], list2) return list1 + list2 print("merge([1, 3, 5, 7], [2, 4, 6, 8]):\t", merge([1, 3, 5, 7], [2, 4, 6, 8])) # should return [1, 2, 3, 4, 5, 6, 7, 8]
true
61fe504a5f0ef1f70db4799e6901f84b8e9f3333
roince/Python_Crash_Course
/Mosh_Python/guessing_game.py
1,073
4.125
4
chance = 3 # get a myth number, and check : whether it is a number and whether it is in # range (0-9) myth = input("your myth number: ") if myth.isdigit(): myth = int(myth) if myth > 9 or myth < 0: print("please enter a number in range (0-9)") quit() else: print("only numbers are allowed!") quit() # guess game implemented below print(f'This is a guessing game, and you have {chance} chances to guess the ' f'mythical number (0-9)') guess = 11 while chance > 0: guess = input("Guess: ") # checking the input whether is a number and whether in range if guess.isdigit(): guess = int(guess) if guess > 9 or guess < 0: print("please enter a number in range (0-9)") elif int(guess) == int(myth): print(f"You guess right! Good one! Only takes you {4-chance} " f"times to guess") break else: print("Wrong guess! Try again!") else: print("only numbers are allowed!") chance -= 1 else: print("Sorry, you loose :(")
true
d331294da6be5b723d9ee85d749f692c4d6b5d70
maximkavm/ege-inf
/23/Количество программ с обязательным этапом/8 - 13749.py
476
4.21875
4
""" Сколько существует программ, для которых при исходном числе 2 результатом является число 12 и при этом траектория вычислений программы содержит числа 8 и 10? +1 +2 *3 """ def f(x, y): if x < y: return f(x + 1, y) + f(x + 2, y) + f(x * 3, y) elif x == y: return 1 else: return 0 print(f(2, 8) * f(8, 10) * f(10, 12)) # Ответ: 60
false
d3c4602b79623679ac3a07bdd09ff55eeb222b8f
lorenzobrazuna/cursopython
/exer33.py
365
4.125
4
num1 = int(input('Digite o numero 1: ')) num2 = int(input('Digite o numero 2: ')) num3 = int(input('Digite o numero 3: ')) if (num1 > num2): maior = num1 menor = num2 else: maior = num2 menor = num1 if maior < num3: maior = num3 elif menor > num3: menor = num3 print('O numero {} é o maior, e o numero {} é o menor'.format(maior,menor))
false
434e727b3400f54428c65c146ec4e44eab74bc6c
Lewis-blip/python
/volume.py
233
4.125
4
pie = 3.14 radius = int(input("input radius: ")) height = float(input("input height: ")) rradius = radius**2 volume = pie * rradius * height final_volume = volume//1 print("the volume of the cyclinder is ", final_volume, "m^3")
true
9962385de6e1191e9e664a4ad9b9be20a55e2a79
fccoelho/PH-Translations
/Manipulating-Strings-Python/codigo_teste.py
1,960
4.25
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jun 2 16:56:08 2021 @author: Felipe Marques Esteves Lamarca Script teste dos códigos da tradução para o português da lição "Manipulating Strings in Python" do The Programming Historian. """ # ------------------------------------- mensagem = "Olá Mundo" # ------------------------------------- mensagem1 = 'olá' + ' ' + 'mundo' print(mensagem1) # ------------------------------------- mensagem2a = 'olá ' * 3 mensagem2b = 'mundo' print(mensagem2a + mensagem2b) # ------------------------------------- mensagem3 = 'oi' mensagem3 += ' ' mensagem3 += 'mundo' print(mensagem3) # ------------------------------------- mensagem4 = 'olá' + ' ' + 'mundo' print(len(mensagem4)) # ------------------------------------- mensagem5 = "olá mundo" mensagem5a = mensagem5.find("mun") print(mensagem5a) # ------------------------------------- mensagem6 = "olá mundo" mensagem6b = mensagem6.find("esquilo") print(mensagem6b) # ------------------------------------- mensagem7 = "OLÁ MUNDO" mensagem7a = mensagem7.lower() print(mensagem7a) # ------------------------------------- mensagem8 = "OLÁ MUNDO" mensagem8a = mensagem8.replace("O", "pizza") print(mensagem8a) # ------------------------------------- mensagem9 = "Olá Mundo" mensagem9a = mensagem9[1:7] print(mensagem9a) # ------------------------------------- loc_inicial = 2 loc_final = 7 mensagem9b = mensagem9[loc_inicial:loc_final] print(mensagem9b) # ------------------------------------- mensagem9 = "Olá Mundo" print(mensagem9[:5].find("d")) # ------------------------------------- print(len(mensagem7)) # ------------------------------------- mensagem7 = "OLÁ MUNDO" mensagem7a = mensagem7.lower() print(mensagem7a) # ------------------------------------- print('\"') # ------------------------------------- print('O programa imprimiu \"olá mundo\"') # ------------------------------------- print('olá\tolá\tolá\nmundo')
false
2e3a8be86da4c724d636afc20f3dbf784c23b6c5
Snafflebix/learning_python
/ex9.py
507
4.125
4
# Here's some new strange stuff, remember type it exactly days = "Mon Tue Wed Thu Fri Sat Sun" #this makes each thing after \n on a new line months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug" #this puts days after the string with a space print "Here are the days: ", days print "Here are the months: ", months print """ There's something going on here. With the three double-quotes. We'll be able to type as much as we like. Even 4 lines if we want, or 5, or 6. """ #but you can't do that with comments!
true
608b3cff314db322da9d826b8491f8d3d9026796
ranog/python_work
/capitulo_03-Introducao_as_listas/nomes.py
283
4.125
4
# 3.1 - Nomes: # Armazene os nomes de alguns de seus amigos em uma lista chamada # names. Exiba o nome de cada pessoa acessando cada elemento da lista, # um de cada vez. nomes = ["joao", "paulo", "joao paulo", "paulo joao"] print(nomes[0]) print(nomes[1]) print(nomes[2]) print(nomes[3])
false
f023205fbfb15d2d12ee1460cb13ab31a27e504b
shalemppl/PythunTuts
/Tuples.py
2,143
4.59375
5
# Tuples are similar to lists, but once a tuple is created it cannot be changed #List (created with []) mylist = [1, 2, 3] print(mylist) mylist[2] = 4 print(mylist) #Tuple (created with ()) mytuple = (1, 2, 3) print(mytuple) #mytuple[2]=4 would result in a traceback, as an item within a tuple cannot be changed #So why use a tuple instead of a list? # 1. Tuples are more memory efficient and are faster to access # 2. CANNOT sort, append or reverse a tuple (as you can with a list) # 3. CAN count and index a tuple # 4. Tuples are normally used as temporary variables in limited scopes #Comparing and Sorting tuples d = {'a':10, 'b':1, 'c':22} #create a dictionary d.items() print(sorted(d.items())) #sort the disctionary (will sort by the first item in the dict first, so a,b,c) for (k, v) in sorted(d.items()): print(k,v) #create and print a sorted tuple based on the dict #Sort by the values instead: tmp = list() for k,v in d.items(): tmp.append((v,k)) #flip the values, put v first -- notice the double () print(tmp) tmp = sorted(tmp) print(tmp) tmp = sorted(tmp,reverse=True) #reverse the order of the items print(tmp) #Print the 10 most common words in a file: fhand = open('intro.txt') counts = {} #create a dictionary for line in fhand: words = line.split() #split each line in the file into a dictionary of words for word in words: counts[word] = counts.get(word,0)+1 #for each word, add it to the dict and count it lst=[] #create a new list for key,val in counts.items(): #create a tuple containing each pair in the dict we created newtup=(val,key) #when creating the tuple, reverse the key/val into val/key so that we can sort by val lst.append(newtup) #place the tuple pairs into the list, so we can sort them lst=sorted(lst,reverse=True) #sort the list, based on val, in reverse (descending) order for val,key in lst[:10]: #print just the first 10 (most commont) words print(key,val) print('\n') #A shorter version of the above: print(sorted([(val,key) for key,val in counts.items()],reverse=True)) #but prints the entire item list, not just the top 10 #the [] creates a "list comprehension"
true
4a3c26ab8368289cdb8e20912c26def8660bdd52
AFishyOcean/py_unit_five
/fibonacci.py
482
4.34375
4
def fibonacci(x): """ Ex. fibonacci(5) returns "1 1 2 3 5 " :param number: The number of Fibonacci terms to return :return: A string consisting of a number of terms of the Fibonacci sequence. """ fib = "" c = 0 a = 0 b = 1 for x in range(x): c = a + b a = b b = c fib +=str(c)+ " " return fib def main(): x = int(input("How many terms would you like?")) fibonacci(x) print(fibonacci(x)) main()
true
21d9d56ea3e130d01489144c7e118a9bb147e21b
tatianimeneghini/exerciciosPython_LetsCode
/Aula 2/exercicio1.py
348
4.1875
4
numero1 = int(input("Insira um número ")) numero2 = int(input("Insira um número ")) if numero1 > numero2: print("O número " , numero1 , " é maior que o número " , numero2) elif numero1 < numero2: print("O número " , numero1 , " é menor que o número " , numero2) else: print("O número " , numero1 , " é igual que o número " , numero2)
false
31bb7ccdea6104bfacbd18e099f0935b3bc2d0e7
eecs110/spring2020
/course-files/lectures/lecture_04/in_class_exercises/08_activity.py
869
4.15625
4
# Write a function that prints a message for any name # with enough stars to exactly match the length of the message. # Hint: Use the len() function. def print_message(first_name:str, symbol:str='*'): message = 'Hello ' + first_name + '!' print(symbol * len(message)) print(message) print(symbol * len(message)) print() def print_message_alt(first_name:str): symbol = input('Enter your favorite symbol (one character only please): ') if symbol == '': symbol = '*' message = 'Hello ' + first_name + '!' print(symbol * len(message)) print(message) print(symbol * len(message)) print() # invoking it... # my_symbol = input('Enter your favorite symbol (one character only please): ') print_message('Sarah', symbol='%') print_message('Caroline', symbol='$') print_message('Peter', '^') print_message('Matthew')
true
d740731f12f6aff6f7175086263f0c9308b43b4a
eecs110/spring2020
/course-files/lectures/lecture_03/challenge_problem_2.py
1,900
4.34375
4
from tkinter import Canvas, Tk ##################################### # begin make_grid function definition ##################################### def make_grid(canvas, w, h): interval = 100 # Delete old grid if it exists: canvas.delete('grid_line') # Creates all vertical lines at intevals of 100 for i in range(0, w, interval): canvas.create_line(i, 0, i, h, tag='grid_line') # Creates all horizontal lines at intevals of 100 for i in range(0, h, interval): canvas.create_line(0, i, w, i, tag='grid_line') # Creates axis labels offset = 2 for y in range(0, h, interval): for x in range(0, w, interval): canvas.create_oval( x - offset, y - offset, x + offset, y + offset, fill='black' ) canvas.create_text( x + offset, y + offset, text="({0}, {1})".format(x, y), anchor="nw", font=("Purisa", 8) ) ################################### # end make_grid function definition ################################### ''' 1. Write a program that prompts the user for a color, which can be any string representation of a color 2. Then, draw a rectangle (of any dimensions) with that color ''' user_color = input('Hey, what color do you want this circle to be? ') center_x = int(input('Hey, what\'s the center x coord? ')) center_y = int(input('Hey, what\'s the center y coord? ')) radius = 100 # initialize window window = Tk() canvas = Canvas(window, width=700, height=550, background='white') canvas.pack() canvas.create_oval( [(center_x - radius, center_y - radius), (center_x + radius, center_y + radius)], # coords: top-left, bottom-right fill=user_color) make_grid(canvas, 700, 550) canvas.mainloop()
true
3d2de0860b3c106661671232cffcef522c187993
liturreg/blackjack_pythonProject
/deck.py
2,389
4.125
4
import random card_names = { 1: "Ace", 2: "Two", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine", 10: "Ten", 11: "Jack", 12: "Queen", 13: "King" } card_suits = { 0: "Hearts", 1: "Diamonds", 2: "Clubs", 3: "Spades" } def generate_deck_dict(): """Function to generate a full deck of cards in form of a dictionary. Currently not used""" list = [] # This list first to create the dictionary for num in range(0,4): for i in range(1, 14): suit = num number = i value = 0 if i == 1: # This used to be a tuple before value = (1) elif i > 10: value = 10 else: value = i list.append((suit, number, value)) dict = {} for card in list: # Use another function to generate all the keys # dict[cardname_from_tuple(list, card)] = card suit = card_suits.get(card[0]) number = card_names.get(card[1]) dict[f"{number} of {suit}"] = card return dict def generate_deck_list(): """Function to generate a whole deck of cards as list""" list = [] for num in range(0,4): for i in range(1, 14): suit = num number = i value = 0 if i == 1: # I'm assigning only 1 for now, it will become 11 later value = (1) elif i > 10: value = 10 else: value = i list.append((suit, number, value)) return list def cardname_from_index(list, index): """Funcion to print a card name when list name and index are known. Asks for list name and list index.""" suit = card_suits.get((list[index])[0]) number = card_names.get((list[index])[1]) return f"{number} of {suit}" def cardname_from_tuple(list, name): """Function to print a card name when only the values are known. Asks for list name and card object name.""" result = cardname_from_index(list, list.index(name)) return result def print_deck(deck_name): """Function to print a whole deck card by card. Mostly used during development.""" for i in range(len(deck_name)): print(cardname_from_index(deck_name, i))
true
eee192feba564a8682d06b98c26abc33c0c31a38
alisiddiqui1912/rockPaperScissors
/Rock Pap S/finalVersion.py
1,229
4.34375
4
import random player_win = 0 computer_win = 0 win_score = input("Enter the Winning Score: ") win_score = int(win_score) while win_score > player_win and win_score > computer_win: print(f"Your Score:{player_win},Computer Score:{computer_win}") player = input("Make your move: ").lower() rand_num = random.randint(0,2) if rand_num == 0: computer = "rock" elif rand_num == 1: computer = "paper" else: computer = "scissors" print("Computer move is: " + computer) if player == computer: print("It's a tie.") elif player == "rock": if computer == "scissors": print("You win!!") player_win += 1 else: print("computer wins!!") computer_win += 1 elif player == "paper": if computer == "rock": print("You win!!") player_win += 1 else: print("computer wins!!") computer_win += 1 elif player == "scissors": if computer == "rock": print("computer wins!!") computer_win += 1 else: print("You win!!") player_win += 1 else: print("Plese enter valid move.") print(f"Final Score:-Your Score:{player_win},Computer Score:{computer_win}") if player_win > computer_win: print("You Win!!") else: print("Computer Wins")
true
a3f70a3c9d8b47aa53eaa3ca9c4337b9b7bb4d2e
vukasm/Problem-set-2019-Programming-and-Scripting-
/question-vii.py
619
4.46875
4
#Margarita Vukas, 2019-03-09 #Program that takes a positive floating number as input and outputs an approximation of its square root. #This will import math module. import math #Asking user to enter a positive floating number which will be tha value of f. f=float(input("Please enter a positive number:")) #Using math.sqrt module to calculate the square root of the number. sqrtf=math.sqrt(f) #Using round() method rounding the square root to only two decimals which is approximation of the full number. sqrtf=round(sqrtf,2) #Printing the result on the screen. print ("The square root of", f, "is approx.", sqrtf)
true
eee3e14ebd6c8df03effc41e02b8abb0784b5f05
musflood/code-katas
/direction-reduction/dir_reduct.py
1,666
4.25
4
"""Kata: Directions Reduction. #1 Best Practices Solution by Unnamed and others opposite = {'NORTH': 'SOUTH', 'EAST': 'WEST', 'SOUTH': 'NORTH', 'WEST': 'EAST'} def dir_reduct(plan): new_plan = [] for d in plan: if new_plan and new_plan[-1] == opposite[d]: new_plan.pop() else: new_plan.append(d) return new_plan """ def dir_reduct(arr): """Collapse a set of directions to minimize movements. Given a list of string directions 'NORTH', 'SOUTH', 'EAST', 'WEST', removes directions that will cancel each other out. That is, the pairs ['NORTH', 'SOUTH'] or ['EAST', 'WEST'] cancel each other and therefore are removed from the directions. Pairs must be adjacent to cancel each other out. """ if not arr or len(arr) == 1: return arr direct = arr[:] new_direct = ['start'] while len(new_direct) != len(direct): if new_direct != ['start']: direct = new_direct[:] new_direct = [] i = 0 while i < len(direct) - 1: if direct[i] == 'NORTH' and direct[i + 1] != 'SOUTH': new_direct.append(direct[i]) elif direct[i] == 'SOUTH' and direct[i + 1] != 'NORTH': new_direct.append(direct[i]) elif direct[i] == 'EAST' and direct[i + 1] != 'WEST': new_direct.append(direct[i]) elif direct[i] == 'WEST' and direct[i + 1] != 'EAST': new_direct.append(direct[i]) else: i += 1 i += 1 if i == len(direct) - 1: new_direct.append(direct[-1]) return new_direct
true
ebb7e4b3143c89f27a322cd6adaf718a37115d7c
musflood/code-katas
/string-pyramid/string_pyramid.py
2,807
4.25
4
"""Kata: String Pyramid. #1 Best Practices Solution by zebulan def watch_pyramid_from_the_side(characters): if not characters: return characters width = 2 * len(characters) - 1 output = '{{:^{}}}'.format(width).format return '\n'.join(output(char * dex) for char, dex in zip(reversed(characters), xrange(1, width + 1, 2))) def watch_pyramid_from_above(characters): if not characters: return characters width = 2 * len(characters) - 1 dex = width - 1 result = [] for a in xrange(width): row = [] for b in xrange(width): minimum, maximum = sorted((a, b)) row.append(characters[min(abs(dex - maximum), abs(0 - minimum))]) result.append(''.join(row)) return '\n'.join(result) def count_visible_characters_of_the_pyramid(characters): if not characters: return -1 return (2 * len(characters) - 1) ** 2 def count_all_characters_of_the_pyramid(characters): if not characters: return -1 return sum(a ** 2 for a in xrange(1, 2 * len(characters), 2)) """ def watch_pyramid_from_the_side(characters): """Side view of a pyramid where each row is a char in the given string. a watch_pyramid_from_the_side('abc') => bbb ccccc """ if not characters: return characters pyramid = '' width = 1 + 2 * (len(characters) - 1) row_width = 1 for ch in characters[::-1]: pyramid += '{:^{width}}\n'.format(ch * row_width, width=width) row_width += 2 return pyramid[:-1] def watch_pyramid_from_above(characters): """Top view of a pyramid where each row is a char in the given string. ccccc cbbbc watch_pyramid_from_above('abc') => cbabc cbbbc ccccc """ if not characters: return characters pyramid = [] row_width = 1 + 2 * (len(characters) - 1) edge = '' for ch in characters: pyramid.append('{}{}{}'.format(edge, ch * row_width, edge[::-1])) edge += ch row_width -= 2 pyramid.extend(pyramid[-2::-1]) return '\n'.join(pyramid) def count_visible_characters_of_the_pyramid(characters): """Count the number of visible blocks in the pyramid.""" if not characters: return -1 return (1 + 2 * (len(characters) - 1)) ** 2 def count_all_characters_of_the_pyramid(characters): """Count the total number of blocks in the pyramid.""" if not characters: return -1 width = 1 + 2 * (len(characters) - 1) return sum(n**2 for n in range(1, width + 1, 2))
true
f3b7fb3044363da065c2e7e85fc0efeb46eaf89e
Ifeoluwakolopin/ECX-30daysofcode-2020
/code files/Ifeoluwa_Are_day23.py
897
4.34375
4
# -*- coding: utf-8 -*- """ Created on Fri Apr 17 17:14:20 2020 @author: TheAre """ def find_Armstrong(start, end): '''This function takes in two integers indicating the start and end of an interval it returns the armstrong numbers within that interval. Note: An armstrong number is a number that is equal to the sum of the cubes of it's digit Example: find_Armstrong(152, 155) :... [153] ** since, 1^3 + 5^3 + 3^3 = 153, then 153 is the armstrong number in that range ''' armstong_numbers = [] for number in range(start, end+1): number = str(number) sum_of_digits = 0 for i in number: sum_of_digits += (int(i) ** 3) if sum_of_digits == int(number): armstong_numbers.append(int(number)) return armstong_numbers print(find_Armstrong(1, 1000)) print(find_Armstrong(200,500))
true
73ecc8d7a746aa750721f0fc79e3d80ea5db1098
Ifeoluwakolopin/ECX-30daysofcode-2020
/code files/Ifeoluwa_Are_day6.py
411
4.3125
4
# -*- coding: utf-8 -*- """ Created on Tue Mar 31 18:07:11 2020 @author: TheAre """ import itertools def power_list(list1: list): ''' Takes in a list and returns the corresponding power list of the list''' pow_list = [] for i in range(len(list1)+1): for j in itertools.combinations(list1, i): pow_list.append(list(j)) return pow_list print(power_list([1,2,3]))
true
55c3a23948c26489410b73cb44ee07a42a249c67
UchechiUcheAjike/programming_with_functions
/checkpoint_02_boxes.py
922
4.4375
4
#A manufacturing company needs a program that will help its employees # pack manufactured items into boxes for shipping. Write a Python # program named boxes.py that asks the user for two integers: 1) # the number of manufactured items and 2) the number of items that # the user will pack per box. Your program must compute and print # the number of boxes necessary to hold the items. This must be a # whole number. Note that the last box may be packed with fewer # items than the other boxes. #import the math module import math #Ask user for input, and convert it to integer num_items = int(input('Enter the number of items: ')) items_per_box = int(input('Enter the number of items per box: ')) #number of boxes num_boxes = math.ceil(num_items / items_per_box) #display results for user to see print(f'For {num_items} items, packing {items_per_box}' f' items in each box, you will need {num_boxes} boxes.' )
true
62c46356a8e61d296ca3f6cf44723477950d6a44
FrenchBear/Python
/Learning/130_Fluent_Python/fp2-utf8/blocinteractive/example 2-22.py
517
4.375
4
# Example 2-22. Basic operations with rows and columns in a numpy.ndarray >>> import numpy as np >>> a = np.arange(12) >>> a array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) >>> type(a) <class 'numpy.ndarray'> >>> a.shape (12,) >>> a.shape = 3, 4 >>> a array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> a[2] array([ 8, 9, 10, 11]) >>> a[2, 1] 9 >>> a[:, 1] array([1, 5, 9]) >>> a.transpose() array([[ 0, 4, 8], [ 1, 5, 9], [ 2, 6, 10], [ 3, 7, 11]])
false
67610b84cdcde5d34e0a974c544262fb7871922a
FrenchBear/Python
/Pandas/base2.py
531
4.71875
5
# Learning Pandas # 2021-03-01 PV # https://www.learndatasci.com/tutorials/python-pandas-tutorial-complete-introduction-for-beginners/ import pandas as pd data = { 'apples': [3, 2, 0, 1, 4, 3], 'oranges': [0, 3, 7, 2, 5, 0] } # Create from scratch # Each (key, value) item in data corresponds to a column in the resulting DataFrame. # By default, the Index of this DataFrame was given to us on creation as the numbers 0-3 purchases = pd.DataFrame(data) print(purchases) pp = purchases[purchases.oranges>0] print(pp)
true
65f6092cc51de46f8dd6cabbba3594df83c11ec2
FrenchBear/Python
/Learning/107_Multiple_Constructors/a_newinit.py
680
4.375
4
# Play with Python contructors # 01 Refresher about __new__ and __init__ # # 2022-03-19 PV # A base class is object, identical to class A(object): class A: def __new__(cls): print("Creating instance of A") return super(A, cls).__new__(cls) # Should return None def __init__(self): print("A Init is called") A() print() class B: # Actually, __new__ can return anything... def __new__(cls): print("Creating instance of B") return "Hello world" # Note that __init__ is not called, since __new__ did not return a __B__ object def __init__(self): print("B Init is called") b = B() print(b)
true
c40ebfa80afc506486e4818d013a524c499f7d37
FrenchBear/Python
/Learning/013_Arrays/13_Arrays.py
1,664
4.4375
4
# Arrays # Learning Python # 2015-05-03 PV # Simple array myList = [] for i in range(10): # mylist[i]=1 # IndexError: list assignment index out of range myList.append(1) myList = [i*i for i in range(10)] # Array of squares [0, ..., 81] # Creates a list containing 5 lists initialized to 0 using a comprehension Matrix = [[0 for x in range(5)] for x in range(5)] Matrix[0][0] = 1 Matrix[4][0] = 5 print(Matrix[0][0]) # prints 1 print(Matrix[4][0]) # prints 5 # Retrieve a column as a list j = 0 col = [row[j] for row in Matrix] # Transpose a matrix t = [[row[i] for row in Matrix] for i in range(len(Matrix))] # shorter notation for initializing a list of lists: m = [[0]*5 for i in range(5)] # Unfortunately shortening this to something like 5*[5*[0]] doesn't really work because you end up with 5 copies of the same list, so when you modify one of them they all change, for example: matrix = 5*[5*[0]] print(matrix) # [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]l matrix[4][4] = 2 print(matrix) # [[0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2], [0, 0, 0, 0, 2]] # With numpy import numpy as np print(np.zeros((3, 3))) # Array of doubles print(np.matrix([[1, 2], [3, 4]])) print(np.matrix('1 2; 3 4')) print(np.arange(9).reshape((3, 3))) print(np.array(range(9)).reshape((3, 3))) print(np.ndarray((3, 3))) # Real arrays, compare size with list print() import array, sys tl = [2,3,5,7,11,13,17,19,23,27] ta = array.array('i', tl) tn = np.array(tl, dtype=int) print(tl, sys.getsizeof(tl)) print(ta, sys.getsizeof(ta)) print(tn, sys.getsizeof(tn))
true
4fb893b494e6206e6125d67f4af89fd65b4d5610
Som94/Python-repo
/20 july/Test 1.py
1,347
4.1875
4
def proverb1(): print ('from func proverb1 --- God\'s mill grinds slow but sure ') def proverb2(): print ('from func proverb2 --- All THAT GLITTERS IS NOT GOLD ') def greet(): print ('welcome ...good day') print ('happy to note that all is well ') def add(a,b): if ((a > 9 and a < 100) and (b > 9 and b < 100)): total = a + b print ('total is ',total,' of a value ',a,' b value is ',b) else: print ('either ',a,' or ' , b , ' is not 2 digit number !!') def adding_numbers(a,b): if ((a > 9 and a < 100) and (b > 9 and b < 100)): total = a + b return total else: msg = 'either '+str(a)+' or ' +str(b)+ ' is not 2 digit number !!' return msg print ('i am here ') print ('i am about to invoke greet funtion ') greet() proverb2() proverb1() print ('hey i am back to the next line after completing the function greet') add(12,38) print (' -------------------------- ') add(2,38) print (' -------------------------- ') add(12,13) print (' -------------------------- ') print ( '*** total is ' , adding_numbers(19,81), ' ****') print ( adding_numbers(29,81)) adding_numbers(14,15) # function could be assigned to a variable temp=adding_numbers(14,15) print (temp)
false
73e2c938ecb79fc89af46158f1f448c90ec10a31
Som94/Python-repo
/14 July/test-4.py
939
4.125
4
''' 1) union a union b ''' a = {12,55,66,77} b = {10,12,25,55} # 12,55,66,77,10,25 (12,55 are common HENCE APPEARS once) print('union',a.union(b)) ''' 2) intersection a intersection b a = {12,55,66,77} b = {10,12,25,55} o/p 12,55 (which are common in a and b) ''' print('intersection ',a.intersection()) ''' 3) symmetric difference meaning .... method returns a set that contains all items from both set, but not the items that are present in both sets. a = {12,55,66,77} 66,77 b = {10,12,25,55} 10,25 common 12,55 sym diff is 66,77,10,25 ''' print('symmetric_difference : ',a.symmetric_difference(b)) ''' 4) difference a = {12,55,66,77} b = {10,12,25,55} a-b elements present is a BUT NOT IN b intersection result is 12,55 66,77 b-a o/p 10,25 ''' print("Difference : ",a.difference(b))
false
fe32573df0314ce6dc03a27a607ce75fa63ca174
Som94/Python-repo
/display no of 2nd n 4th saturday in given range of date.py
908
4.125
4
""" Given two dates d1 to d2 ( both inclusive) Print all the 2nd and 4th Saturdays Count how many are there? """ import datetime print("Enter dates input format example: 8 Feb 2021") date_start_str = '20 Feb 2010' #input("Enter start date: ") date_end_str = '12 Dec 2011' # input("Enter end date: ") # convert string to date format date_start = datetime.datetime.strptime(date_start_str, '%d %b %Y') date_end = datetime.datetime.strptime(date_end_str, '%d %b %Y') # initialization of the initial number of weekends day = datetime.timedelta(days=1) count_saturday = 0 count_sunday = 0 # iteration over all dates in the range while date_start <= date_end: if date_start.isoweekday() == 6: print(date_start.isoweekday()) print(date_start.day) count_saturday += 1 date_start += day # output a single line containing two space-separated integers print(count_saturday)
true
c878f65bfb95acf1b9495ad2cbb0f9c66e42c6a7
Som94/Python-repo
/9th july/Largest nad smallest among 3 numbers.py
907
4.28125
4
''' Input 3 numbers from user and find out highest and lowest number among them ''' fist_number=int(input("Enter first number : ")) second_number=int(input("Enter second number : ")) third_number=int(input("Enter third number : ")) if fist_number>second_number and second_number>third_number: print("highest number is : ",fist_number,"Lowest number is : ",third_number) if second_number>third_number and third_number>fist_number: fist_number,third_number=third_number,fist_number fist_number,second_number=second_number,fist_number print("highest number is : ",fist_number,"Lowest number is : ",third_number) if third_number>fist_number and fist_number>second_number: third_number,fist_number=fist_number,third_number third_number,second_number=second_number,third_number print("highest number is : ",fist_number,"Lowest number is : ",third_number)
false
7ce7a8f93858d069aec1cb98d795f07c9c506a88
Som94/Python-repo
/21st july/Assignment 2.txt
506
4.25
4
''' Take several input from user as string , check wether it is palindrome or not store into a dictionary as if it is palindrome assign the value as true else assign false {'liril': True, 'abc' : False} And so on ''' def palindrome(n): for i in range(n): str1=input("Enter any String :") if str1==str1[::-1]: dic[str1]=True else: dic[str1]=False return dic n=int(input("Enter number of input you want :")) dic={} print(palindrome(n))
true
50063f065de4c19c68024ee8410f49a68456dd80
polinaya777/goit-python
/python_1/lesson_02/hw_03.py
1,089
4.34375
4
flag = True while (flag): num_1 = input('Enter number 1: ') try: num_1 = int(num_1) except ValueError: print(f"Number {num_1} is not a number") else: flag = False flag = True while (flag): num_2 = input('Enter number 2: ') try: num_2 = int(num_2) except ValueError: print(f"Number {num_2} is not a number") else: flag = False result = 0 flag = True while (flag): oper = input('Enter operand: ') if oper == '+': result = num_1 + num_2 print(f'Result is {result}') flag = False elif oper == '-': result = num_1 - num_2 print(f'Result is {result}') flag = False elif oper == '*': result = num_1 * num_2 print(f'Result is {result}') flag = False elif oper == '/': try: result = num_1 / num_2 print(f'Result is {result}') flag = False except ZeroDivisionError: print('Number 2 could not be zero') else: print('This is not an operand!')
true
0d56bd057ee09a9eddf0d6079cfc31129e576c33
diazinmotion/LearnCode
/Python/Part I/06. Conditions/IFElseComparison.py
730
4.28125
4
## # IFElseComparison.py # Simple if else (conditions) with comparison example # # @package LearnCode # @author Dimas Wicaksono # @since 2018-15-25 ## # create a function def max_number(num1, num2, num3): if num1 >= num2 and num1 >= num3: return num1 elif num2 >= num1 and num2 >= num3: return num2 else: return num3 print(max_number(3, 4, 5)) # build a calculator num1 = float(input("Enter first number: ")) op = input("Enter an operator: ") num2 = float(input("Enter second number: ")) # process if op == '+': print(num1 + num2) elif op == '-': print(num1 - num2) elif op == '*': print(num1 * num2) elif op == '/': print(num1 / num2) else: print("Invalid Operator")
false
45e96a7a37eb0e6c7ecf0c6779426d83266b2c00
pkoarmy/Learning-Python
/sorting/sorting.py
684
4.40625
4
# Sort in Python def sort(array): # run loops two times: one for walking through the array # and the other for comparison for i in range(len(array)): for j in range(0, len(array) - i - 1): # To sort in descending order, change > to < in this line. if array[j] > array[j + 1]: # swap if greater is at the rear position (array[j], array[j + 1]) = (array[j + 1], array[j]) data = [7, 3, 22, 11, 17, 5, 19] sort(data) print('Sorted List in Ascending Order:') print(data) # Sort in Python data = [7, 3, 22, 11, 17, 5, 19] print(data) print('Sorted List in Ascending Order:') data.sort() print(data)
true
a7bb9bd5fa9535112126b900f360f4cd1978b685
Monsteryogi/Python
/string_methods.py
308
4.4375
4
#string methods used for manuputlating the Strings word=input("Enter the string:") lenght_word=len(word) upper_case=word.upper() lower_case=word.lower() print ("Lenth of String: %s" %(lenght_word)) print ("Upper case of String: %s" %(upper_case)) print ("Lower case of String: %s" %(lower_case))
true