blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
0362b46a7b6e51d5443da1f634cc7cd6cd93265a
tarak1006/python
/finaltest_problem1.py
1,715
4.15625
4
__author__ = 'Kalyan' max_marks = 25 problem_notes = ''' A 'consword' is a word which has only consonents. For this problem, you have to write code to return all maximal conswords that are substrings of a given string. A consword is called maximal if it cannot be extended on either side with a consonent. Sort the result in descending order of length. In case of a length tie, sort them in descending order lexicographically (case insensitive) Examples: - "Pepper" -> ["pp", "r", "P"] - "flyiNGHigh" -> ["NGH", "fly", "gh"] - "aoi" -> [] Additional Notes/Constraints: - Only letters (a-zA-Z) are allowed, any other characters like digits or spaces should raise a ValueError - Non strings should raise a TypeError - Use python builtins as appropriate. - Maintain the original casing of the letters. ''' def get_conswords(word): for q in word: if type(q).__name__ != 'str': raise ValueError if type(word).__name__!='str': raise TypeError vowel={'a','e','i','o','u'} res=[] i=0 while i<len(word): v=[] if word[i].lower() not in vowel: for k in range(i,len(word),1): if word[k] not in vowel: v.append(word[k]) else: i=k-1 break b=''.join(v) if b.upper() not in res: if b.lower() not in res: res.append(b) i+=1 res=set(res) res=list(res) res.sort(key=lambda x:x[0].upper(),reverse=True) res.sort(key=len,reverse=True) return res[:3] # write your own tests def test_get_conswords(): pass
true
494f9a3c2ff059382c74032d6cc4b4daf73ef13d
dmsenter89/learningProgramming
/Python/lang/kick.py
706
4.21875
4
#! /usr/bin/python3 # Exercise 1.11 # Evaluating a football. from math import pi def fD(cD,rho,a,v): vals = 0.5*cD*rho*a*v**2 return vals rho = 1.2 # kg m^-3 a = 0.11 # radius in meters A = pi*a mass = 0.43 # kg cD = 0.2 # what unit? g = 9.81 # m s^-2 fG = mass*g v1 = 120 * 0.2778 # converted to m/s v2 = 10 * 0.2778 # converted to m/s fd1 = fD(cD,rho,A,v1) fd2 = fD(cD,rho,A,v2) print(''' The drag forces of a football kicked at 120 kph is {fd1:.2f}. The drag forces of a football kicket at 10 kph is {fd2:.2f}. Compare this to the universal gravitational forces experienced by the ball, {fG:.2f}. '''.format(fd1=fd1,fd2=fd2,fG=fG))
false
316d4429e271c5854ffd1871b664cc662b8367e0
dmsenter89/learningProgramming
/Python/zelle/ch7/zch07ex01.py
408
4.125
4
#! /usr/bin/python # input: hours worked and hourly rate # output: total wages for week def main(): hrs = float(input("How many hours were worked this week? ")) wage = float(input("Hourly wage: ")) if hrs<=40: pay = hrs*wage else: hrs = hrs-40 pay = 40*wage+1.5*hrs*wage print("Wages for this week are ${}".format(pay)) if __name__ == '__main__': main()
true
c812c8bac4efb5ca178046847524246885d1d9f8
Tsirtsey/Python
/1lab/zad5.py
263
4.1875
4
text = input("Enter the text: ") def strings(text): word = text.split() for i in range (len(word)): if(word[i].istitle()): print (word[i].upper(), end=" ") else: print(word[i], end = " ") strings(text)
true
d2e78672d0d3b7982112a5e7918e431c85b40e32
DierSolGuy/Python-Programs
/maximum_dict.py
682
4.15625
4
# Consider a dictionary my_points with single letter keys, each followed by a 2-element tuple representing # the coordinates of a point in an x-y coordinate plane. # my_points={'a':(4,3),'b':(1,2),'c':(5,1)} # Write a program to print the maximum value from within all the values tuples at same index. my_points={'a':(4,3),'b':(1,2),'c':(5,1)} highest=[0,0] init=0 for a in range(3): init=0 for b in my_points.keys(): val=my_points[b][a] if init==0: highest[a]=val init+=1 if val > highest[a]: highest[a]=val print("Maximum Value at index(my_points,", a, ")=", highest[a])
true
f2792439ff6072ac015715ddb01227d0e399ff22
jioblack/pythontutorial
/i_decorator.py
958
4.875
5
""" Decorators are used to add/modify an existing object. They take in functions and return functions Format is: def myDecorFuncName(fun) """ #Decorator that doubles the result of a function. def decorFunc(func): def internal(): result = func() return result * 2 return internal #Let define a function that would use the decorator function def decorMe(): return 7 #Use the decorator function to decorate the decoreMe function. d = decorFunc(decorMe) print(d()) """ Using @Decorator Apply the decorFunc function using @decorFunc """ @decorFunc def decorMeAgain(): return 8 print(decorMeAgain()) """ Decorating a String This example shows how to pass an argument to a decorator functions """ def decorString(func): def internal(n): return func(n) + " how are you?" return internal @decorString def deccorMyString(n): return 'Hello ' + n print(deccorMyString("John"))
true
1120bf50034927608946ff0b2c497124b49f4594
jioblack/pythontutorial
/j_generators.py
357
4.28125
4
""" Generators are functions that return a sequence of values back. A generator function is returned like any other function but makes use of the 'yield' keyword when doing so. """ def myGenerator(x, y): while x <= y: yield x x += 1 result = myGenerator(1, 20) #Gives a generator object print(result) for i in result: print(i)
true
a49fc6a5d06fbec5e053d8720a440452ce10344d
lsb530/Algorithm-Python
/파이썬챌린지/13.텍스트파일읽기와쓰기/109.메뉴선택.py
562
4.5
4
menu = """1) Create a new file 2) Display the file 3) Add a new item to the file """ print(menu) select = int(input("Make a selection 1, 2 or 3: ")) if select == 1: file = open("Subject.txt", "w") subject = input("Enter a subject: ") file.write(subject + '\n') file.close() elif select == 2: file = open("Subject.txt", "r") print(file.read()) file.close() elif select == 3: file = open("Subject.txt", "a") subject = input("Enter a new subject: ") file.write(subject + '\n') file.close() else: print("Input Error")
true
ae922a09f706a1d3d7135a18706d73afee60e967
lsb530/Algorithm-Python
/Do_it!/2.기본 자료구조와 배열/list/list3.py
312
4.21875
4
# 리스트의 모든 원소를 enumerate() 함수로 스캔하기 # enumerate 함수는 인덱스와 원소를 짝지어 튜플로 꺼내는 내장 함수 # (1,'John'), (2,'George')식으로 꺼냄 x = ['John', 'George', 'Paul', 'Ringo'] for i, name in enumerate(x, 1): print(f'{i}번째 = {name}')
false
8cc0b548ee90e9d13ee4e822e377de71109e3694
EshwarSR/miscellaneous
/python/tensorflow_practice/tf_practice-1.py
1,669
4.15625
4
import tensorflow as tf x = tf.Variable(3, name="x") y = tf.Variable(4, name="y") f = x*x*y + y + 2 """ The above code does not perform any computation. It just creates the variables. It DOESNOT even initialize the variables. """ """ Now that the graph is created, we need to 1. Open a tf session 2. Initialise the parameters 3. Evaluate the f 4. Close the session to free up the space """ # 1. Open a tf session sess = tf.Session() # 2. Initialise the parameters sess.run(x.initializer) sess.run(y.initializer) # 3. Evaluate the f result = sess.run(f) print("result", result) # 4. Close the session to free up the space sess.close() # Faster way of doing with tf.Session() as sess: x.initializer.run() y.initializer.run() # equivalent to tf.get_default_session().run(x.intializer) type(x.initializer)=Operation (node in graph) result = f.eval() # equivalent to tf.get_default_session().run(f) and type(f)=Tensor # eval() because we always evaluate a tensor and run() an operation print("Result", result) """ x.initializer.run() y.initializer.run() If there are many variables to be initialized, init = tf.global_variables_initializer() with tf.Session() as sess: init.run() result = f.eval() """ """ Managing graphs Any node created will be added to the default graph. >>> x1 = tf.Variable(1) >>> x1.graph is tf.get_default_graph() True But if we want to add it to a custom graph, we can create a new graph and make it default in a with block. >>> graph = tf.Graph() >>> with graph.as_default(): ... x2 = tf.Variable(2) ... >>> x2.graph is graph True >>> x2.graph is tf.get_default_graph() False """
true
495835efac17e6302f47d81e89358639c076509f
EricChanXX/python-demo
/py_data_type.py
1,621
4.125
4
#!/usr/bin/python # -*- coding: UTF-8 -*- counter = 100 #赋值整型变量 miles = 1000.0 #浮点型 name = "Jason" #字符型 a , b , c = 1 , 2, "abc" print counter print miles print name print a print b print c #python 五种标准 数据类型 #number (数字),string(字符串),list(列表),tuple(元组),dictionary(字典) #数字number,4种基本类型 int(有符号整形) long(长整形) float(浮点型) complex(复数) a = 15.0 b = complex(a,b) print a print b #字符串string str = "My name is Jason Chen,oranges is my favorite!!!" print str print str[1] print str[3:7] print str*2 #列表list,可以二次赋值,复合数据结构,元素可以是数字和字符 list = ['My' , 'name' , 'is' , 'Jason' , 'Chen'] list1 = ['oranges' , 'is' , 'my' , 'favorite!!!'] print list list[1] = 'NAME' print list[1] print list print list[3:7] print list +list1 #元组tuple 类似于列表list ,但是使用小括号(),赋值变量,且后边赋值不能更改 #元组相当于只读列表。 tu = ('My' , 'favorite' , 'is' , 'Oranges') print tu #字典dictionary #列表是有序的对象结合,字典是无序的对象集合。 #两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。 #字典使用花括号{},字典由索引(key)和它对应的值value组成。 dic = {} dic['v1'] = "hello world!" dic [1] = "welcome to python world!" dic1 = {'lastName': 'JSON' , 'firstName': 'CHEN'} print dic1['lastName'] print dic[1] print dic1.values()
false
11a055d431526db01f7d9c522489ae3e65b886da
vicenteneto/online-judge-solutions
/URI/1-Beginner/1074.py
354
4.125
4
# -*- coding: utf-8 -*- for i in range(int(raw_input())): x = int(raw_input()) if x == 0: print 'NULL' elif x < 0: if x % 2 == 0: print 'EVEN NEGATIVE' else: print 'ODD NEGATIVE' else: if x % 2 == 0: print 'EVEN POSITIVE' else: print 'ODD POSITIVE'
false
50eee6794763cc94f39a6f7a29cacc0aa49039ba
gaofan0906/Practise
/栈/栈.py
598
4.125
4
from collections import deque # 双端队列实现栈 class Stack(object): def __init__(self): self.deque = deque() # 你可以很容易替换为 python 内置的 collections.deque def push(self, value): self.deque.append(value) def pop(self): return self.deque.pop() class Stack2(object): def __init__(self): self._deque = deque() def push(self, value): return self._deque.append(value) def pop(self): return self._deque.pop() def empty(self): return len(self._deque) == 0 # 栈溢出 # 数组实现栈
false
d02622d0bfff0d9127e854982c594c4edd227da2
gaofan0906/Practise
/队列/队列.py
511
4.15625
4
# 单链表实现队列 # 队列的pop=链表的popleft # 队列的push=链表的append # 队列先进先出 class Queue(object): def __init__(self,maxsize): self.maxsize=maxsize self._item_link_list = LinkedList() def __len__(self): return len(self._item_link_list) def push(self,value): return self._item_link_list.append(value) def pop(self): if len(self)<=0: raise Exception('empty queue') return self._item_link_list.popleft()
false
8a14072c17b0610135b3d2579d7da31c120edf79
njfgyuq/6230403947-oop-labs
/sahapat-6230403947-lab3/Problem_11.py
890
4.25
4
while True: try: one = float(input("Enter the first number: ")) if one == "quit": break two = float(input("Enter the second number: ")) if two == "quit": break operator = str(input("Enter the operator: ")) except ValueError: break if operator == "+": print(f"{one} + {two} = " f"{one + two}") elif operator == "-": print(f"{one} - {two} = " f"{one - two}") elif operator == "*": print(f"{one} * {two} = " f"{one * two}") elif operator == "/": if one == 0 or two == 0: print("Cannot divide a number by 0") else: print(f"{one} / {two} = " f"{one / two}") elif operator == "quit": break else: print("Unknown operator")
false
f7abbea66d34fcda4b0a938fe329dd721365f6a9
Jsmie/L1Yr11PythonProject
/project.py
1,390
4.21875
4
#variables list_exe = [] #introduction print("Welcome to your digital clock simulator") answer = input("""Commands you may use are !time, !temperature, !day, !date, and !start_shopping_list """) #commands if ("!time") == answer : #Time function from datetime import datetime now = datetime.now() print("%s:%s:%s" % (now.hour,now.minute,now.second)) #date function elif ("!date") == answer : from datetime import datetime now = datetime.now() print("%s/%s/%s" % (now.day,now.month,now.year)) #List function elif ("!start_shopping_list") == answer : repeat=True #repeating function of list repeat = True while repeat == True: shopping_list = input("Please enter a item for the list or 'done' to end input: ").strip().lower() #Check if user has entered done so that loop can be stopped if so if shopping_list == 'done': repeat = False else: #Check if item is already in list count = list_exe.count(shopping_list) #If so, give user error message, otherwise add the item and give success message if count > 0: print("Sorry {} is already on the list!".format(shopping_list)) else: list_exe.append(shopping_list) print("{} has been added!".format(shopping_list)) #Once user is done, print out their list for them print("Your list contains : ") for shopping_list in list_exe: print(shopping_list.title())
true
68de6820561c4841b2bce19e450366c1a3fe6aff
lovingvalerie/filemanipulationcode
/manipulations.py
978
4.21875
4
#of times it happens in a file. #this functoin takes in the name of a file, #reads it and returns a file object.` def get_file_object(file_name): f = open(file_name, 'r') list_of_lines = f.readlines() return list_of_lines f.close() #print get_file_object('some_text.txt') #this function prompts the user for a string query #and returns that string def get_query(): query = raw_input('What word are you looking for?') return query #print get_query() def num_times(file_object, query): #make a list to later append # of times to list_of_locations = [] #iterate through each line #if query is in that line #append it to list_of_locations for line in file_object: if query in line: list_of_locations.append(line) #return the len or # of times the query #occured in file return len(list_of_locations) if __name__ is '__main__': print num_times(get_file_object('some_text.txt'), get_query())
true
d40dc08d71e0e3d9aa3a98f91ab59cee6928f45b
NiuYingchun/pythonBasic
/买家具.py
1,578
4.28125
4
# 创建房子类: # 房子的户型,面积,地址 class House: def __init__(self, info, area, addr): self.info = info self.area = area self.addr = addr self.furniture_lst = [] # 用来保存家具名称 '''添加家具的方法''' def add_furniture(self, furniture): '''furniturn 接收传进来的对象''' # house面积剩余面积=house当前面积-家具面积 self.area = self.area - furniture.area self.furniture_lst.append(furniture.name) # 蒋家具的名称添加到家具列表中 def __str__(self): msg = '剩余面积{},户型{},在{}买的房子,'.format(self.area, self.info, self.addr) msg1 = '新添的设备{}'.format(self.furniture_lst) return msg + msg1 # 创建床类: class Bad: def __init__(self, name, area): self.name = name self.area = area def __str__(self): msg = '{}面积是{}'.format(self.name, self.area) lst = [] return msg class Sofa: def __init__(self, name, area): self.name = name self.area = area def __str__(self): msg = '{}的面积是{}'.format(self.name, self.area) house = House('三室一厅', 130, '五方桥') # print(house) bad = Bad('上下铺', 2) # print(bad) house.add_furniture(bad) print(house) # 给房子再添家一个双人床 bad1 = Bad('双人床', 4) house.add_furniture(bad1) print(house) sofa = Sofa('沙发', 3) house.add_furniture(sofa) print(house)
false
70e8167e08a295565666599debcd919918b0f93f
sametcem/Python
/thenewboston3/tutorial_24.py
838
4.1875
4
# Dictionary Multiple Key Sort from operator import itemgetter #bunch of dictionary // first name and last name users = [ {'fname': 'Bucky', 'lname': 'Roberts'}, {'fname': 'Tom', 'lname': 'Roberts'}, {'fname': 'Bernie', 'lname': 'Zunks'}, {'fname': 'Jenna', 'lname': 'Hayes'}, {'fname': 'Sally', 'lname': 'Jones'}, {'fname': 'Amanda', 'lname': 'Roberts'}, {'fname': 'Tom', 'lname': 'Williams'}, {'fname': 'Dean', 'lname': 'Hayes'}, {'fname': 'Bernie', 'lname': 'Barbie'}, {'fname': 'Tom', 'lname': 'Jones'}, ] for x in sorted(users,key=itemgetter("fname")): print(x) print("----------------") # True alphebatical sorting for x in sorted(users,key=itemgetter("fname","lname")): #first sort them by their first name and then their last name print(x)
true
8a23e18a1f03122125b5b431a5cba697f577d0b2
MartaVinas/markov-chains
/markov.py
2,187
4.28125
4
"""Generate Markov text from text files.""" from random import choice import sys def open_and_read_file(file_path): """Take file path as string; return text as string. Takes a string that is a file path, opens the file, and turns the file's contents as one string of text. """ # your code goes here return open(file_path).read() def make_chains(text_string): """Take input text as string; return dictionary of Markov chains. A chain will be a key that consists of a tuple of (word1, word2) and the value would be a list of the word(s) that follow those two words in the input text. For example: >>> chains = make_chains("hi there mary hi there juanita") Each bigram (except the last) will be a key in chains: >>> sorted(chains.keys()) [('hi', 'there'), ('mary', 'hi'), ('there', 'mary')] Each item in chains is a list of all possible following words: >>> chains[('hi', 'there')] ['mary', 'juanita'] >>> chains[('there','juanita')] [None] """ chains = {} # your code goes here words = text_string.split() for i in range(len(words) - 2): current_key = tuple([words[i], words[i + 1]]) if current_key in chains: # by indexing into the key of the list we get the value which is a list, then we can append to that list chains[current_key].append(words[i +2]) else: chains[current_key] = [words[i + 2]] return chains def make_text(chains): """Return text from chains.""" words = [] random_key = choice(list(chains.keys())) random_value = choice(chains[random_key]) words.extend([random_key[0],random_key[1], random_value]) while True: new_key = tuple((words[-2], words[-1])) if new_key in chains: new_value = choice(chains[new_key]) words.append(new_value) else: break return " ".join(words) input_path = sys.argv[1] # Open the file and turn it into one long string input_text = open_and_read_file(input_path) # Get a Markov chain chains = make_chains(input_text) # Produce random text random_text = make_text(chains) print(random_text)
true
2d68e7c2de0890b9c1e7459464cdbd32c64405e1
Bardia95/daily-coding-problems
/code-wars-katas/python3/counting_duplicates.py
1,016
4.25
4
def duplicate_count(s): return len([c for c in set(s.lower()) if s.lower().count(c)>1]) def duplicate_count_2(text): freqs = {} duplicates = 0 text = text.lower() for char in text: if char in freqs: freqs[char] += 1 else: freqs[char] = 1 for freq in freqs: if freqs[freq] > 1: duplicates += 1 return duplicates """ Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits. Example "abcde" -> 0 # no characters repeats more than once "aabbcde" -> 2 # 'a' and 'b' "aabBcde" -> 2 # 'a' occurs twice and 'b' twice (`b` and `B`) "indivisibility" -> 1 # 'i' occurs six times "Indivisibilities" -> 2 # 'i' occurs seven times and 's' occurs twice "aA11" -> 2 # 'a' and '1' "ABBA" -> 2 # 'A' and 'B' each occur twice """
true
ff42de83ac5ba934853d4cf77b785eb360817b61
Bardia95/daily-coding-problems
/code-signal-arcade-universe/intro/python3/alphabetic_shift.py
656
4.375
4
def alphabetic_shift(s): return "".join(chr((ord(c) - 96) % 26 + 97) for c in s) """ Given a string, your task is to replace each of its characters by the next one in the English alphabet; i.e. replace a with b, replace b with c, etc (z would be replaced by a). Example For inputString = "crazy", the output should be alphabeticShift(inputString) = "dsbaz". Input/Output [execution time limit] 4 seconds (py3) [input] string inputString A non-empty string consisting of lowercase English characters. Guaranteed constraints: 1 ≤ inputString.length ≤ 1000. [output] string The resulting string after replacing each of its characters. """
true
522115bbf9c8ace6adb1d0d94c6a822385c31077
SaiRithvik/Mycaptain_AI
/datatypes.py
530
4.46875
4
#Q1 LIST list1 = ['hi', 'I', 'am', 'Rithvik'] ### assigning list list2 = [1, 2, 'Hello World!', "Goodbye"] ### assigning list print(list1[3]) ### List indexing. It goes from 0 to n-1 where n is the length of the list print(list2[2]) ### List indexing #Q2 TUPLE tuple1 = (1,2,"Mycaptain") ### Initialising a tuple print(tuple1[1]) ### Indexing a tuple #Q3 DICTIONARY dict1 = {'a':1, 'b':2.37, 'c': "Rithvik"} del dict1['a'] ### Deleting elements of a dictionary print(dict1)
false
f50094322cb43d842a90acd8a3b2c00912d0f47a
AakashOfficial/ChallengeTests
/challenge_21/python/slandau3/sortStack.py
377
4.21875
4
#!/usr/bin/env python3 # Reverse a stack using at most one other stack def sort_stack(stack): utility_stack = [] while len(stack) != 0: temp = stack.pop() while len(utility_stack) > 0 and utility_stack[-1] > temp: stack.append(utility_stack.pop()) utility_stack.append(temp) return utility_stack print(sort_stack([5,4,3,2,1]))
true
2f59a0592b76998f58fdbf83b0ec0a071050addb
AakashOfficial/ChallengeTests
/challenge_1/python/zooks97/src/reverseInput.py
265
4.21875
4
inText = input("Input some characters: ") #Get the text input listText = list(inText) #Convert the input string to a list listText.reverse() #Reverse the character list outText = ''.join(listText) #Revert list to string print(outText) #Print reversed string
true
3c42df1bdc36b9a5a421a09eca7613fa8e336654
AakashOfficial/ChallengeTests
/challenge_1/python/zanetti/challenge_0.py
205
4.46875
4
a=list(input("Insert the you want to invert :")) #input to user choose the characteres to invert - in a list form print('the choosen world: ', a) a.reverse() #invert the "a" list print('reversed: ', a)
true
17a224b4e6107bb7eee982542a867fb2763fcd77
AakashOfficial/ChallengeTests
/challenge_1/python/returnlove/src/reverse_a_string.py
473
4.4375
4
# read input string from user input_string = raw_input("enter any string") # solution 1 # create a variable to store the reversed string reversed_string = "" # loop through the input in reverse order and append each letter for l in xrange(len(input_string)-1, -1, -1): reversed_string += str(input_string[l]) print('Solution 1: ',reversed_string) # solutin 2 print('Solution 2: ',''.join(reversed(input_string))) # solution 3 print('Solution 3: ',input_string[::-1])
true
ec420b5b0a1645d9493b7d7d470b73d73abf6445
sbrown1948/PycharmProjects
/work/palindrone.py
799
4.3125
4
# A palindrome is something that reads the same backwards and forwards. The largest palindrome made from the product of any two numbers between 0 and 12 is 121 (11 * 11). # # # Find the largest palindrome made from the product of any two numbers between 0 and 1000. # 993 * 913 = 906609 # # # ecardin@cainc.com palindrones = [] def main(): for i in range(12): for j in range(12): result = i * j strResult = str(result) if strResult == strResult[::-1]: # print result palindrones.append(result) biggest = 0 for palindrone in palindrones: if palindrone > biggest: # print palindrone biggest = palindrone print "\nbiggest = " + str(biggest) if __name__ == "__main__": main()
true
c9f243212a531f61619dd9d766a9104cacc0a08a
skypearl85/python-datascience
/module1-slide2.py
666
4.25
4
#Solve it #1 number = input('Please insert a number: ') if (int(number) % 2 == 0): print('Number ' + number + ' is even') else: print('Number ' + number + ' is odd') #Solve it #2 #BMI = mass(kg) / height(meter) ^ 2 mass = int(input('Enter a mass (in kg): ')) height = int(input('Enter a height (in cm): ')) BMI = mass/((height/100) ** 2) message = '' if(BMI < 18.5): message = 'underweight' elif(BMI >= 18.5 and BMI < 25): message = 'ideal weight' elif(BMI >= 25 and BMI < 30): message = 'slightly overweight' elif(BMI >= 30 and BMI < 40): message = 'overweight' else: message = 'obesity' print('BMI is ' + str(BMI) + ', ' + message)
true
f5cb031439d7fb393cfe956cac6da71d85a0a771
D4NNONY/Hacktoberfest-2021
/exc 6.py
207
4.125
4
''' exc 6 Receber um nome do teclado e imprimí-lo de trás pra frente. ''' word = input('digite a palavra e veja o que acontece: ') word = list(word) word.reverse() word = ''.join(word) print(word) input()
false
3ff4bd0d5f8ea8cf1d44be5977819b7642077d4e
Quantum-Nox/python-coursera
/Ex7.py
390
4.40625
4
# Write a program that prompts for a file name, then opens that file and reads through the file, and print the contents of the file in upper case. Use the file words.txt to produce the output below. # You can download the sample data at http://www.py4e.com/code3/words.txt fname = raw_input("Enter file name: ") fh = open(fname) fh_upper = fh.read().upper() print(fh_upper.rstrip("\n"))
true
f3a64c55f34a7aab52939cf87fd00fe95cd578af
joaofoltran/python
/pep8.py
1,324
4.3125
4
""" PEP8 [1] Camel Case em nomes de classes; class Teste: pass class TesteDois: pass [2] Utilizar nomes em minúsculo, separado por underline para funções e variáveis; def teste(): pass def teste_dois(): pass teste = 4 teste_dois = 5 [3] Utilizar 4 espaços para identação (não tab) if 'a' in 'batata': print('existe') [4] Linhas em branco - Separar funções e definições de classe com duas linhas em branco; - Métodos dentro de uma classe devem ser separados com uma única linha em branco; [5] Imports - Imports devem ser sempre feitos em linhas separadas; import sys, os [X] import sys [Y] import os [Y] - Pode ser utilizado from types import StringType, ListType - Caso possuam muitos imports de um mesmo pacote, recomenda-se utilizar: from types import ( StringType, ListType, SetType, OutroType ) - Imports deve ser inseridos no topo do arquivo, após comentários ou docstrings (antes de constantes e variáveis globais) [6] Espaços em expressões e instruções - Incorreto function( smth[ 1 ], { other: 2 } ) smth (1) dict ['key'] = list [index] x = 1 y = 3 long_variable = 5 - Correto function(smth[1], {other: 2}) smth(1) dict['key'] = list[index] x = 1 y = 3 long_variable = 5 [7] Termine uma instrução com uma nova linha """
false
96dc3960d4b89da29128af592d25130b7356c5eb
zadca123/PythonExercises
/z026.py
1,096
4.21875
4
#!/usr/bin/env python import math as m class robot: def __init__(self): self.x = 0 self.y = 0 # self.x = x # self.y = y def position(self): print("os x: ", self.x) print("os y: ", self.y) def left(self, n): if type(n) is not type(int()): n = round(n) self.x -= n print("LEFT ", n) def right(self, n): if type(n) is not type(int()): n = round(n) self.x += n print("RIGHT", n) def up(self, n): if type(n) is not type(int()): n = round(n) self.y += n print("UP ", n) def down(self, n): if type(n) is not type(int()): n = round(n) self.y -= n print("DOWN ", n) def distance(self): print( "Distance from (0,0) to ({},{}) is: {}".format( self.x, self.y, m.sqrt(self.x ** 2 + self.y ** 2) ) ) # n = input("Type some number: ") r = robot() r.position() r.up(5) r.down(3) r.left(3) r.right(2) r.position() r.distance()
false
277755cfaceecc83f9bf54e29475035a02a511d5
Frankemiller/e0001-2019-03-Euler-Muliples-of-3-and-5
/muliples.py
496
4.375
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. def multiples(arg1, arg2, nrange): count = 0 for i in range(nrange): if (i % arg1) == 0 or ( i % arg2) == 0: count = count + i return(count) multi1 = int(3) multi2 = 5 numberrange = 1000 summ = multiples(multi1, multi2, numberrange) print("The sum is: ", summ)
true
94d71560a47c4efafacefa32848dadf9de2bb1d1
luhao2013/Algorithms
/sort_algorithm/selection_sort.py
506
4.25
4
""" 简单选择排序:每一趟找出最小的元素和前面进行交换 最好、最坏和平均的时间复杂度都为O(n^2) """ def selection_sort(array): for i in range(0, len(array)-1): small = i for j in range(i+1, len(array)): if array[j] < array[small]: small = j array[i], array[small] = array[small], array[i] if __name__ == "__main__": testList = [1, 3, 5, 7, 2, 6, 25, 18, 13] selection_sort(testList) print(testList)
false
0e4dd5dce86ea3e5a415bbdba8f8864140806098
luhao2013/Algorithms
/offer/06.重建二叉树.py
1,029
4.15625
4
""" 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。 """ class TreeNode: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def construct(pre_order, in_order): if (not pre_order) or (not in_order): return None return construct_tree(pre_order, in_order) def restruct_tree(pre_order, in_order): # 排出两种特殊情况 if len(pre_order) == 0: return None elif len(in_order) == 1: return TreeNode(in_order[0]) else: root = pre_order[0] depth = in_order.index(root) # 找到中序遍历该值的位置 temp = TreeNode(root) temp.left = restruct_tree(pre_order[1: depth + 1], in_order[: depth]) temp.right = restruct_tree(pre_order[depth + 1:], in_order[depth + 1:]) return temp # 用递归的都可以用栈来改造成迭代的
false
f26d35fce0fa2cb6921c7fe1c68ce69feb8a2bad
thomasperez37/cspp10
/unit5/mp_list1.py
990
4.1875
4
num_list = [] num_input = int(input("Enter a positive number to add it to the list and enter a zero to exit this app: ")) while num_input != 0: if num_input < 0 and -num_input in num_list: num_list.remove(-num_input) print(num_list) num_input = int(input("Enter a positive number to add it to the list, enter a negative number to remove it\'s positive counterpart and enter a zero to exit this app: ")) elif num_input < 0: print(num_list) print("{} doesn't exist in the list.".format(-num_input)) num_input = int(input("Enter a positive number to add it to the list, enter a negative number to remove it\'s positive counterpart and enter a zero to exit this app: ")) else: num_list.append(num_input) print(num_list) num_input = int(input("Enter a positive number to add it to the list, enter a negative number to remove it\'s positive counterpart and enter a zero to exit this app: ")) print("PROGRAM END")
true
f116959450dcb7aa55a083bec3f1962bdb1f9146
Dimonka111/geekbrains
/HomeWork03/3-2.py
1,054
4.25
4
# Реализовать функцию, принимающую несколько параметров, # описывающих данные пользователя: имя, фамилия, год рождения, # город проживания, email, телефон. Функция должна принимать # параметры как именованные аргументы. Реализовать вывод данных # о пользователе одной строкой. def anketa(name, surname, year, town, email, telephone): print('Для заполнения анкеты введите следующие данные: ') name = input('Ваше имя: ') surname = input('Ваша фамилия: ') year = input('Год рождения: ') town = input('Город проживания: ') email = input('email: ') telephone = input('Телефон: ') return ' '.join([name, surname, year, town, email, telephone]) print(anketa("", "", "", "", "", ""))
false
30d20f51d0ed7ed5ee12f80124757bbfb9e9d8ff
Ayyappa-BK/Python-assignments
/Tuple.py
320
4.25
4
#creating a new tuple tuple1=("cat","dog","elephant","horse","dog") #counting the number of times a word appeared x=tuple1.count("dog") print("The number of time dog appeared is: ",x) #getting the index of the particular element in the tuple x1=tuple1.index("horse") print("The position of horse is: ",x1)
true
fb732ae2e4e92987363ef770d5abfaa31d504927
momentum-team-7/house-hunting-with-python-GrantDM
/house_hunting.py
2,240
4.375
4
# Write your code here def current_savings1(): total_cost = int(input("What is the price of your dream home ? ")) annual_salary = int(input("What is your annual salary? ")) portion_down_payment = 0.25 current_savings = 0 r = 0.04 portion_saved = 0.1 months = 0 monthly_salary = (annual_salary / 12) monthly_saved = monthly_salary * portion_saved while current_savings < portion_down_payment * total_cost: print(current_savings) months += 1 interest_earned = ((current_savings * r) / 12) current_savings += monthly_saved + interest_earned print(current_savings) print(months) current_savings1() def current_savings2(): total_cost = int(input("What is the price of your dream home version 2? ")) annual_salary = int(input("What is your annual salary version 2? ")) portion_down_payment = 0.25 current_savings = 0 r = 0.04 portion_saved = 0.15 months = 0 monthly_salary = (annual_salary / 12) monthly_saved = monthly_salary * portion_saved while current_savings < portion_down_payment * total_cost: print(current_savings) months += 1 interest_earned = ((current_savings * r) / 12) current_savings += monthly_saved + interest_earned print(current_savings) print(months) current_savings2() def current_savings3(): total_cost = int(input("What is the price of your dream home version 3? ")) annual_salary = int(input("What is your annual salary version 3? ")) portion_down_payment = float(input("What percent do you need of the total cost? enter as decimal: ")) current_savings = 0 r = float(input("What is your annual rate of return? enter as decimal: ")) portion_saved = float(input("what percent do you want to save per month? enter as decimal: ")) months = 0 monthly_salary = (annual_salary / 12) monthly_saved = monthly_salary * portion_saved while current_savings < portion_down_payment * total_cost: print(current_savings) months += 1 interest_earned = ((current_savings * r) / 12) current_savings += monthly_saved + interest_earned print(current_savings) print(months) current_savings3()
true
50ca529ab18348b8951dc174125770499b3a2e5b
BeGifted/Youdao_crawler
/Day7.py
827
4.15625
4
""" 字符串和常用数据结构 version: 0.1 Author: gongyuandaye """ s1 = r'\'hello, world!\'' s2 = '\n\\hello, world!\\\n' print(s1, s2, end='') s1 = 'hello ' * 3 print(s1) # hello hello hello s2 = 'world' s1 += s2 print(s1) # hello hello hello world print('ll' in s1) # True print('good' in s1) # False str2 = 'abc123456' # 从字符串中取出指定位置的字符(下标运算) print(str2[2]) # c # 字符串切片(从指定的开始索引到指定的结束索引) print(str2[2:5]) # c12 print(str2[2:]) # c123456 print(str2[2::2]) # c246 print(str2[::2]) # ac246 print(str2[::-1]) # 654321cba print(str2[-3:-1]) # 45 len(s1) s1.find('') a, b = 1, 2 print(f'{a} * {b} = {a * b}') print('%d * %d = %d' % (a, b, a * b)) list1 = [5, 4, 3, 2, 1] list2 = sorted(list1) for i in range(len(list2)): print(list2[i])
false
e1bbbf8821812b47bea0562e2e3b4ee3813ede49
OwczarekP/Covid-19_NZ_report
/scripts/statistics_to_tables.py
1,434
4.15625
4
#!/usr/bin/env python # summary statistics to make tables by hand import pandas as pd def load_csv(path): """load_csv This function load the file from the path and save it as dataframe :param path: string to the csv file :return: df: the dataframe from the csv """ df = pd.read_csv(path) return df def get_data(df): """get_data This function get the data needed to write table 1 and table 3 in report Counts the number of covid-19 cases by gender and overseas travel :param df: the dataframe from the csv file :return: """ counts_all_sex = df["Sex"].count() counts_value_sex = df["Sex"].value_counts() per_female = round((1347/counts_value_sex)*100, 2) per_male = round((1296/counts_value_sex)*100, 2) counts_value_status = df["Case Status"].value_counts() counts_value_travel = df["Overseas travel"].value_counts() confirmed_Probable = 2287 + 356 per_travel = round((1466/confirmed_Probable)*100, 2) per_no_travel = round(((1171+6)/confirmed_Probable)*100, 2) number_confirmed = df['Case Status'].value_counts() population_NZL = 4917000 deaths = 26 caes_in_population = round((confirmed_Probable/population_NZL)*100, 2) deaths_in_population = round((deaths/population_NZL)*100, 2) def main(): df = load_csv('../data/covid_cases_2021-05-11.csv') get_data(df) if __name__=='__main__': main()
true
c43aa67053d31d8148fdecdf98c3e30193f58d75
BANSHEE-/practice
/tictac.py
1,269
4.46875
4
import numpy as np board={} for int in range(9): board.update({int:'_'}) xtaken = []#use x and otaken to confirm a win otaken =[] taken = [] def viewboard(): view = board.values() for i in xrange(0,len(view),3): print view[i:i+3] def xmove(): row = raw_input("Pick a row: ") col = raw_input("Pick a col: ") if row == "Top": x = 0 elif row == "Middle": x = 3 elif row == "Bottom": x = 6 if col == "Left": x += 0 elif col == "Center": x += 1 elif col == "Right": x += 2 if x not in taken: board.update({x:'X'}) xtaken.append(x) taken.append(x) print board else: x = np.random.randint #after two move comp stops working HELP def compwrite():#does this argument need to be here? board.update({pos:'O'}) otaken.append(pos) taken.append(pos) print board def compmove(): pos = np.random.randint(8) if pos not in taken: compwrite(pos) print board else:#how do we make it go back through random integer loop if already in take? call function again until integer that works? pos = np.random.randint(8) count = 0 while count < 10: xmove() compmove() viewboard() print otaken print xtaken count += 1 #board formating (turn to its won function to use after each turn
true
eb7aa68b9ca131c41705beb335bf7c0aba7824e8
CB721/coding-practice
/py/sep01.py
389
4.40625
4
# In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative? def make_negative( number ): if (number <= 0): print(number) else: print(number * -1) # test cases make_negative(42) # -42 make_negative(-1) # -2 make_negative(0) # 0 make_negative(-30012) # -30012 make_negative(40232123123) # -40232123123
true
8818b76ae51199690922fd439c11c8cadd5deade
SoyamDarshan/Python-Training
/Chapter 1/C1_20.py
758
4.21875
4
# -*- coding: utf-8 -*- """ Created on Sun Sep 30 22:00:45 2018 @author: soyam Python’s random module includes a function shuffle(data) that accepts a list of elements and randomly reorders the elements so that each possible order occurs with equal probability. The random module includes a more basic function randint(a, b) that returns a uniformly random integer from a to b (including both endpoints). Using only the randint function, implement your own version of the shuffle function. NOTE: Dont think this should be the final solution """ import random def suffler(data): b=set() i=0 while(i<data): b.add((random.randint(i,data))) i+=1 return b print (suffler(6))
true
25ba1fdf4437d715eb91ff15e9d97495d6a9ae6b
Suiam/coursera-python
/obj_memo.py
1,091
4.1875
4
#OBJETOS E REFERENCIAS: a= "banana" # a é como se fosse um apontador de memoria para verificar onde esta armazenado b="banana"" # tanto a quanto b apontaram para a mesma parte da memoria referente a banana. # em python string sao imutaveis c="maça" a is b # o comando is diz se ambas as referencias apontam para o mesmo objeto. No caso será true no caso de listas, que sao mutaveis: a=[81,82,83] b=[81,82,83] # nesse caso armazena em locais diferentes, apesar de mesmo conteudo a is b # nesse caso será False pois sao objetos diferentes a == b # será true pois o conteudo é identico #REPETIÇOES E REFERENCIAS: ex: list = [45,76,34,55] list*3 = [45,76,34,5,45,76,34,5,45,76,34,5] [list] * 3 = [[45,76,34,5], [45,76,34,5], [45,76,34,5]] #criou-se listas de listas newlist = [[45,76,34,5], [45,76,34,5], [45,76,34,5]] list = [45,76,34,55] list[1] = 99 list = [45,99,34,55] newlist = [[45,99,34,5], [45,99,34,5], [45,99,34,5]] # onde estava o 76 será alterado em ambas as listas.
false
e0031ae948d7cb0e5a85e5dd207436c0b3c690c7
davidandinom/david_andino_curso_python
/Tarea 1/Ejercicio_2.py
426
4.25
4
#Ejercicio 2 #Determina mentalmente (sin programar) el resultado que aparecerá por pantalla en las siguientes operaciones con variables: #Ejercicio a = 10 b = -5 c = "Hola " d = [1, 2, 3] print(a * 5) #Resultado: 50 print(a - b) #Resultado: 15 print(c + "Mundo") #Resultado: Hola Mundo print(c * 2) #Resultado Hola Hola print(d[-1]) #Resultado: 3 print(d[1:]) #Resultado: [2, 3] print(d + d) #Resultado: [1, 2, 3, 1, 2, 3]
false
379b442f71ca6ac82e47b2312e5e6455ee77fa59
surferJen/practice_problems
/Count_and_Say.py
1,925
4.28125
4
# define count and say # 1 , output would be 11 # 11, output would be 21 # 21, outputwould be 1211 # 1211, output would be 111221 # PSEUDOCODE: # iterating over the digits. the numbers i keep track of is numbers 1-9. i check to see how many times the numbers repeat themselves until a different number appears. there must be a counter to check for the repetition of numbers. once there is a change in number, then iterator starts again to account for different number. before the reiteration occurs, i want to push the counter number and the number that is counted into a list. in the end i will join that list into a string. # CODE: # num = 12 # def count_numbers(num): # new_list = [] # num = str(num) # counter = 0 # previous_value = 0 # for index, value in enumerate(num): # if index == 0: # counter += 1 # if index != 0: # previous_value = num[index - 1] # if value == previous_value: # counter += 1 # if value != previous_value: # new_list.append(counter) # counter = 0 # previous_value = int(previous_value) # new_list.append(previous_value) # # new_string = "".join(new_list) # return new_list # print(count_numbers(112)) def count_numbers(num): new_list = [] num = str(num) counter = 0 current_value = 0 for value in num: if current_value == 0: current_value = value counter += 1 elif current_value == value: counter += 1 elif value != current_value: new_list.append(counter) counter = 0 new_list.append(current_value) counter += 1 current_value = value new_list.append(counter) new_list.append(current_value) return new_list print(count_numbers(112233))
true
b5dcad605f7bc8f3e73ec2baa7ecd447db007cd7
joaocarlosmeloazevedo/Matriz.py
/exercicio2.py
989
4.25
4
# 2) Faça um programa em Python que realiza a soma de duas matrizes 2x2. # Importante: O usuário entrará com os valores (números inteiros) que preencherá as duas matrizes (a e b). # Mostrar na tela a terceira matriz (c) com a soma de a + b. matriz_a = [] matriz_b = [] matriz_c = [] for l in range(2): linha_a = [] linha_b = [] linha_c = [] for c in range(2): num = int(input("Digite um número: ")) num2= int(input("Digite um número: ")) linha_a.append(num) linha_b.append(num2) soma = num + num2 linha_c.append(soma) matriz_a.append(linha_a) matriz_b.append(linha_b) matriz_c.append(linha_c) print("\n") for lista in matriz_a: for linha in lista: print(linha, end=' ') print() print(" +") for lista in matriz_b: for linha in lista: print(linha, end=' ') print() print("=") for lista in matriz_c: for linha in lista: print(linha, end=' ') print()
false
28451955aeb3052c425d8e8f22cb0fd383ce4531
dev-gupta01/C-Programs
/python/for_loop.py
599
4.125
4
a=[1,2,3,"Devashish","Shubhashish"] print("printing elements of list:") for ele in a: print(ele) print() b=[1,2,3,4,5,6] s=0 for ele in b: s+=ele print("sum of elements of list:") print(s) print() b=list(range(1,100)) s=0 for ele in b: s+=ele print("sum of elements less than 100:") print(s) print() s=0 for i in range(1,10): if i%2==0: s+=i print("sum of even elements less than 20:") print(s) print() c=[] for i in range(1,100): if i%3==0: c.append(i) elif i%5==0: c.append(i) print("multiples of 3,5 that are less than 100:") print(c) print()
false
bb277a852b695f53accbe7c9bff949d77854c0bd
DoctorLuck/Learning_python
/exception.py
1,182
4.3125
4
#为了引发一个异常,可以使用一个类(Exception的子类)或者实力参数调用raise语句。 #创建自己的异常类时,要确保从Exception类继承。 #class MyException(Exception): # pass # try: # first_num=int(input("first number:")) # second_num=int(input("second number:")) # print(first_num/second_num) # except ZeroDivisionError: # print("The second num can't be zero") # try: # first_num=int(input("first number:")) # second_num=int(input("second number:")) # print(first_num/second_num) # except (ZeroDivisionError,TypeError,NameError): #可以一次捕捉多个异常 # print("The second num can't be zero") # try: # first_num=int(input("first number:")) # second_num=int(input("second number:")) # print(first_num/second_num) # except ZeroDivisionError as e: # print(e) #可以使用空的except子句来捕捉所有Exceptiom类的异常 # while True: # try: # first_num = int(input("first number:")) # second_num = int(input("second number:")) # print(first_num / second_num) # except ZeroDivisionError as e: # print(e) # else: # break
false
7ad7e626d3e53aa989976c1e9121b2dcbfed2169
drupell/Python
/ackermannfct.py
1,344
4.3125
4
''' Programmer: David Rupell Date: 11/16/2018 Description: Ackermann function example using recursion and an object oriented approach. **Warning: AckermanFct(3, 6) appears to be the highest calculatable value so far. ''' class AckermannFct: def __init__(self, m, n): if m > 0 and n > 0: ''' Mutator: ack(m,n) takes the two passed integers and computes the solution to the Ackermann function recursively. Preconditions: if one of the integers passed are negative, the function will never even be defined. Postconditions: computes and returns the solution recursively. ''' def ack(m, n): if m == 0: return n + 1 elif n == 0: return ack(m-1, 1); else: return ack(m-1, ack(m, n-1)) #self.m = int(m) #self.n = int(n) print("When the numbers " + str(m) + " and " + str(n) + " are plugged into the Ackermann Function,\n" + "We get: [" + str(ack(m, n)) + "]") else: print("Error: Integers entered must be positive.\n" +"Cannot compute solution to Ackermann function.") def main(): AckermannFct(1,6) main()
true
5780a60f0dc9d6ad083bea9a7ac8d2581c0398d2
hendrybones/python
/whileloop.py
206
4.125
4
password="" while password !='python123': password=input("enter your password") if password=='python123': print("you are logged in") else: print("enter the correct password")
true
280961b92c3be788569b2f99d7506f01d287a825
aalbiez/training
/demo3.py
420
4.25
4
#!/usr/bin/python # -*- coding: UTF8 -*- PrenomConnus = { 'ARNAUD': "Sympa comme prénom, tu dois être un garçon.", 'OLIVIER': "Tu dois être un mec génial.", 'CLAIRE': 'Tu es une fille.' } while True: prenom = input("Quel est ton prénom ? ").upper() if prenom in PrenomConnus: print(PrenomConnus[prenom]) else: print("Bonjour %s, je ne connais pas ton prénom." % prenom)
false
586cc2c53a54b4db4a5a946c8b2c20fabfe1bdef
NOSH2000/noshPortfolio
/gwc_labs/pythonshapes_starter.py
1,394
4.21875
4
from turtle import * import math # Name your Turtle. t = Turtle() # Set Up your screen and starting position. t.penup() setup(500,300) ###t.speed(3) to change the speed ### Write your code below: #SQUARE def square(): t.pendown() for sides in range(4): t.forward(50) t.right(90) #TRIANGLE def triangle(): t.pendown() for sides in range(3): t.forward(50) t.right(120) #RANDOM def random(): n = input('Number of Sides') t.pendown() for sides in range(n): t.forward(50) t.right(360/n) Size = 150 def triangles(): t.begin_fill() for sides in range(3): t.forward(Size) t.right(120) for sides in range(3): t.backward(Size) t.left(120) for sides in range(3): t.forward(Size) t.left(120) for sides in range(3): t.backward(Size) t.right(120) for sides in range(3): t.left(120) t.forward(Size) t.left(120) for sides in range(3): t.left(120) t.backward(Size) t.left(120) t.end_fill() Color = input('Pick your fill color') Pen = input('Pick your stroke color') t.fillcolor(Color) t.pencolor(Pen) width = Size t.goto(-450,0) for hexagons in range(7): t.pendown() triangles() t.goto(-450+width,0) width+=Size # Close window on click. exitonclick()
true
1ca47b7d95339a2362082cce1f0f6db22f79747b
coshkun/6.00.1x-MITx-Course-Training-Lab-Notes
/snippets/flatten-alist-function.midterm-exam-Problem9.py
733
4.40625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 14 14:23:39 2017 @author: coskun #MidtermExam > Problem 9 (15 points possible) Write a function to flatten a list. The list contains other lists, strings, or ints.For example, [[1,'a',['cat'],2],[[[3]],'dog'],4,5] is flattened into [1,'a','cat',2,3,'dog',4,5] """ #Problem Snippet def flatten(aList): ''' aList: a list Returns a copy of aList, which is a flattened version of aList ''' flt = lambda *n: (e for a in n for e in (flt(*a) if isinstance(a, list) else (a,))) return list(flt(aList)) #Test Case if __name__=="__main__": test_list = [[1,'a',['cat'],2],[[[3]],'dog'],4,5] flat = flatten(test_list) print(flat)
true
f185c37d8defe2b2083185d11dc95cb7033d90e8
coshkun/6.00.1x-MITx-Course-Training-Lab-Notes
/anaconda/6.00.1x.W2T3.Simple.Algorithms.E3.Secret.Number.Game.py
1,297
4.34375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Feb 18 02:46:54 2017 @author: coskun 6.00.1x.W2T3.Simple.Algorithms.E3.Secret.Number.Game Your Secret Number Game :) The program works as follows: you (the user) thinks of an integer between 0 (inclusive) and 100 (not inclusive). The computer makes guesses, and you give it input - is its guess too high or too low? Using bisection search, the computer will guess the user's secret number! """ # Paste your code into this box x = 99 low=0 height=x g=(low+height)/2 #change this with )//2 to pass the exam print("Please think of a number between 0 and 100!") while True: print("Is your secret number "+str(round(g))+"?") #change this with str(g) inp = input("(Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.): ") if (inp == str("l")) or (inp == str("h")) or (inp == str("c")): pass else: print("Sorry, I did not understand your input.") continue if inp == str("l"): low = g elif inp == str("h"): height = g elif inp == str("c"): break g = (low + height)/2 print("Game over. Your secret number was: ",str(round(g))) #change this with str(g)
true
18c772409e7353e35989f8fd4c434854adfd5e13
charlesfranciscodev/codingame
/clash-of-code/fastest/shopping-list/shopping_list.py
909
4.15625
4
def calculate_shopping_cost(): # Read the number of items on the shopping list N = int(input()) # Create a dictionary to store the items and their quantities shopping_list = {} # Read the items on the shopping list for _ in range(N): item = input() if item in shopping_list: shopping_list[item] += 1 else: shopping_list[item] = 1 # Read the number of items in the store C = int(input()) # Initialize the total cost total_cost = 0 # Read the items available in the store and calculate the total cost for _ in range(C): item, cost = input().split() if item in shopping_list: quantity = shopping_list[item] total_cost += int(cost) * quantity # Print the total cost print(total_cost) # Call the function to calculate the shopping cost calculate_shopping_cost()
true
ea02a11f09c0b6ce131f09d1cf2ac32370ce8c25
jainemarindasilva/SextaPythonica
/learning_the_basics/01/Exe03/Exe03_jai.py
606
4.3125
4
# ***Exe. 03 - Tip Calculator*** #Crie uma saudação para o seu programa. print('Bem vindo ao Tip Calculator! \n') #Pergunte quanto foi o total da conta. total = float(input('Informe o valor total da conta: \n')) #Pergunte quanta gorjeta será dada. gorgeta = float(input('Informe o valor desejado da gorjeta: \n')) #Pergunte quantas pessoas vão dividir a conta. pessoas_divisao = int(input('Informe a quantidade de pessoas para dividir: \n')) #Mostre quanto cada pessoa deve pagar. total_por_pessoa = (total + gorgeta) / pessoas_divisao print('Cada um deve pagar: R$ {:.2f}'.format(total_por_pessoa))
false
6c090098b6890da16038065dc105bb255c23e2d2
Yauhenija-Umet/LR0
/bmi_calculator.py
990
4.3125
4
name1 = 'Марина' height1 = 1.70 weight1 = 61 name2 = 'Саня' height2 = 1.70 weight2 = 70 name3 = 'Лена' height3 = 1.70 weight3 = 75 def calculate_bmi(height, weight): return weight / height**2 def show_person_bmi(name, height, weight): bmi = calculate_bmi(height, weight) print('%s: индекс массы тела = %.2f' % (name, bmi)) def get_advice_on_bmi(bmi): if bmi <= 25: return 'может скушать пончик' else: return 'пора садиться на диету' def show_advice_on_bmi(name, height, weight): bmi = calculate_bmi(height, weight) advice = get_advice_on_bmi(bmi) print(f"{name} {advice}") show_person_bmi(name1, height1, weight1) show_advice_on_bmi(name1, height1, weight1) show_person_bmi(name2, height2, weight2) show_advice_on_bmi(name2, height2, weight2) show_person_bmi(name3, height3, weight3) show_advice_on_bmi(name3, height3, weight3)
false
3ad59311d7ead7cb9135aa4bd92b14e5d49c16d7
zacharyloebs/Array
/main.py
1,036
4.21875
4
# This program demonstrates how the array data structure works in Python # O(n) complexity # Space O(n) # Insert O(n) # Get Item O(1) # Set Item O(1) # Delete Item O(n) # Iterate O(n) # An array holds elements in a specific order # Arrays are mutable meaning items can be added or removed after creation numbers = [5, 8, 4, 12, 27, 16, 7] # Print the contents of an array print(numbers) # Find the length of an array print(len(numbers)) # Access specific elements of an array # Prints the first element of the array print(numbers[0]) # Change an element in the array numbers[0] = 11 # The first element [0] has now been changed print(numbers[0]) # Add an element to the end of the array numbers.append(30) # The array now has a new element at the end print(numbers) # Delete an a element in the array (1st method) numbers.pop(1) # The element in the 2nd position in the array is removed print(numbers) # Delete an a element in the array (2nd method) numbers.remove(4) # The element with a value of 4 is removed print(numbers)
true
451eaff2c9164d3afb6913875a511c7582eec3a0
yn0927/Python-Data-structure
/栈.py
1,573
4.46875
4
#python实现常用的数据结构 #author by Liangwei #栈 class Stack(object): """栈""" # 初始化栈为空列表 def __init__(self): self.items = [] def clearstack(self): self.items.clear() # 判断栈是否为空,返回布尔值 def is_empty(self): return self.items == [] # 返回栈顶元素 def gettop(self): if self.is_empty(): #一定要进行此步骤,否则会出现数组越界报错,下Pop同 return '栈为空,无法进行你的操作' else: return self.items[-1] # 返回栈的大小 def size(self): return len(self.items) # 把新的元素堆进栈里面 def push(self, item): self.items.append(item) # 把栈顶元素丢出去,并且返回丢掉的数值 def Pop(self): if self.is_empty(): return '栈为空,无法进行你的操作' else: return self.items.pop() if __name__ == "__main__": # 初始化一个栈对象 my_stack = Stack() my_stack.push('p') my_stack.push('y') print (my_stack.size()) print (my_stack.gettop()) print (my_stack.Pop()) my_stack.clearstack() print (my_stack.gettop()) print (my_stack.is_empty()) my_stack.push('p') my_stack.push('y') my_stack.push('t') my_stack.push('h') my_stack.push('o') my_stack.push('n') print (my_stack.size()) print (my_stack.Pop()) print (my_stack.size()) print (my_stack.is_empty())
false
b8849411dec35dc0f2132f7314fec741d7bf9fc0
Reginald-Lee/biji-ben
/uoft/CSC108/Week 11/time_sorting.py
2,662
4.125
4
def bubble_sort(L): '''(list) -> list Sort the items in L into non-descending order and return the sorted list.''' for i in range(len(L)): for j in range(0, len(L) - 1 - i): if L[j] > L[j + 1]: L[j], L[j + 1] = L[j + 1], L[j] return L def find_min(L, i): '''(list, int) -> int Return the index of the smallest item in L[i:].''' smallest = i for j in range(i + 1, len(L)): if L[j] < L[smallest]: smallest = j return smallest def selection_sort(L): '''(list) -> list Sort the items in L into non-descending order and return the sorted list.''' i = 0 # L[:i] is sorted while i != len(L): smallest = find_min(L, i) L[smallest], L[i] = L[i], L[smallest] i += 1 return L def selection_sort2(L): '''(list) -> list Sort the items in L into non-descending order and return the sorted list.''' for i in range(len(L)): smallest = find_min(L, i) L[smallest], L[i] = L[i], L[smallest] return L def insert(L, i): '''(list, int) -> NoneType L[:i] is sorted. Move L[i] to where it belongs in L[:i].''' # the value to be inserted into the sorted part of the list value = L[i] # find the spot, i, where value should go while i > 0 and L[i - 1] > value: L[i] = L[i - 1] i -= 1 L[i] = value def insertion_sort(L): '''(list) -> list Sort the items in L into non-descending order and return the sorted list.''' i = 0 # L[:i] is sorted while i != len(L): insert(L, i) i += 1 return L def insertion_sort2(L): '''(list) -> list Sort the items in L into non-descending order and return the sorted list.''' for i in range(len(L)): insert(L, i) return L def merge(left, right): '''(list, list) -> list Return the list made by merging sorted lists left and right.''' result = [] i ,j = 0, 0 while i < len(left) and j < len(right): if left[i] <= right[j]: result.append(left[i]) i = i + 1 else: result.append(right[j]) j = j + 1 # One of the sublists has elements left over; the other is empty. Copying # both does no harm, since the empty one will add nothing. result += left[i:] result += right[j:] return result def merge_sort(L): '''(list) -> list Sort the items in L into non-descending order and return the sorted list.''' if len(L) < 2: return L else: middle = len(L) / 2 left = merge_sort(L[:middle]) right = merge_sort(L[middle:]) return merge(left, right)
false
3837d8e63b17fa992f3ba8c1113e1425b31a951c
Reginald-Lee/biji-ben
/uoft/CSC148H1F Intro to Comp Sci/@week2_exceptions_and_inheritance/@@Lecture4/lec04.py
1,879
4.28125
4
class Building: def __init__(self, address, rooms): """ (Building, str, list of Room) -> NoneType """ self.address = address self.rooms = rooms self.occupancy = 0 def __str__(self): """ (Building) -> str """ sum = 0 for room in self.rooms: sum += room.size return str(sum) def add_room(self, room): """ (Building, Room) -> NoneType """ self.rooms.append(room) def rent_room(self, person, room): # rent out the room print('Welcome, ' + person) class Room: def __init__(self, name, size): """ (Room, str, float) -> NoneType """ self.name = name self.size = size class House: # House is a subclass of Building # Building is a superclass of House #def __init__(self, address, rooms): # self.address = address # if len(rooms) > 10: # raise Exception # else: # self.rooms = rooms def __init__(self, address, rooms, family): Building._init__(self, address, rooms) # Now House has all of the attributes from its superclass self.occupancy = 10 # Can we change the attribute of superclass by # changing the subclass. # actually this does change it, because there is only one attribute, it # is the same attribute but said in two different places. self.family = family # Overriding a method def rent_room(self, person, room): if person == 'michael': print('Okay!') else: print('Get out!') # now if we rent room to michael, either from house or from building would be ok; # however, if we rent room to david, works from building, but rejected from house. # The execution order is: House -> Building.
true
6c61c8af075e518f86f4c9a5fa5598c87b491de4
Reginald-Lee/biji-ben
/uoft/CSC148H1F Intro to Comp Sci/@week6_trees/@@Exercise5/list_map.py
954
4.3125
4
# Exercise 5 - Recursive Linked Lists # # CSC148 Fall 2014, University of Toronto # Instructor: David Liu # --------------------------------------------- # STUDENT INFORMATION # # List your information below, in format # <full name>, <utorid> # Rui Qiu, qiurui2 # --------------------------------------------- from linkedlistrec import LinkedListRec def map_f(linked_list, f): """ (LinkedListRec, function) -> LinkedListRec Return a new recursive linked list whose items are obtained by applying f to the items in linked_list. Your implementation should access the attributes of the LinkedListRec class directly, and may not use any LinkedListRec methods other than the constructor and is_empty. """ new_list = LinkedListRec([]) if linked_list.is_empty(): return linked_list else: new_list.first = f(linked_list.first) new_list.rest = map_f(linked_list.rest, f) return new_list
true
0f8c2aa4703415266733218a46a4217ab23f461b
Reginald-Lee/biji-ben
/uoft/CSC108/FINAL/final.summer_2009/all_keys_values.py
376
4.21875
4
def all_keys_values (d): '''Return True if each key in d is also a value in d, and each value in d is also a key in d. For example, all_keys_values ({2:5, 4:4, 5:2}) returns True.''' all_good = True for k in d: if k not in d.values(): all_good = False for v in d.values(): if v not in d.keys(): all_good = False return all_good
false
214ba51ae173fd41c42f4c2e10d51457cc228e37
Reginald-Lee/biji-ben
/uoft/CSC148H1F Intro to Comp Sci/@week3_stacks/@@Lecture6/lec06.py
2,120
4.28125
4
class EmptyStackError(Exception): """Exception used when calling pop on empty stack.""" pass class Stack: """Stack implementation using a list, where the 'top' of the stack is the END of the list. """ def __init__(self): """ (Stack) -> NoneType """ self.items = [] def is_empty(self): """ (Stack) -> bool """ # return true if ... else false if ... #return not self.items # can convert a list to Boolean, for example, not [] == True, not [1, 2, 3] == False. #return self.items == [] return len(self.items) == 0 def push(self, item): """ (Stack, object) -> NoneType """ self.items.append(item) # it turns out that list in python has its own method 'list.pop()' def pop(self): """ (Stack) -> object """ try: return self.items.pop() except IndexError: raise EmptyStackError class Stack2: """Stack implementation using a list, where the 'top' of the stack is the FRONT of the list. """ def __init__(self): """ (Stack) -> NoneType """ self.items = [] # same def is_empty(self): """ (Stack) -> bool """ # return true if ... else false if ... return len(self.items) == 0 # same def push(self, item): """(Stack, object) -> NoneType Add a new element to the top of this stack. """ self.items.insert(0, item) # note that this does not return anything! # this doesn't work before it overwrite the first item! if items list has something at the beginning! #self.items[0] = item #self.items[0:0] = item def pop(self): """(Stack) -> object Remove and return the element at the top of this stack. Raise EmptyStackError if trying to pop from an empty list. """ try: item = self.items[0] self.items = self.items[1:] return item except IndexError: raise EmptyStackError #after time comparison, Stack1 looks more efficient!
true
0538ad374e4bd7cc37227c9279c43b678848bc45
vinaynayak2000/Number_Guessing_game
/Number Guessing/Beginner_level/beginner_number_guessing.py
732
4.3125
4
import random print("Welcome to Number Guessing game") #Computer randomly generates the number between the given range . c_no=random.randint(1,11) #Takes the user input and checks whether the given number entered by user is in given range or not. user_no=int(input("\nGuess the number between 1-10: ")) while(user_no > 10): print("Sorry :-( ...But Please guess the number between the given range....") user_no=int(input("Guess the number between 1-10: ")) if(user_no==c_no): print("Congo... You Guessed the number.") elif(user_no > c_no): print("Your number is greater....\nComputer's number is",c_no) elif(user_no < c_no): print("Your number is smaller....\nComputer's number is",c_no)
true
6ff1db340376bfe161afca243a628e7e938db0e8
dulyana/Python
/5.1.py
257
4.46875
4
RadiusValue = float(input("Enter the radius value of a circle:")) pi=22/7 Area = pi * RadiusValue * RadiusValue Circumference=2*pi*RadiusValue print("Area of the circle is:"+str(Area)) print("Circumference of the circle is:"+str(Circumference))
false
5f7533267055cc2db3e7d918d7d70335db8ef2c3
habbdt/python
/projects/apps/guess-the-number.py
1,358
4.40625
4
#!/usr/bin/env python3 '''guess the number''' # random library to generate random numbers # sys library to utilize sys.exit() import random import sys # guess a number between 1 to 10 - constant LOWER_THRESHOLD = 1 UPPER_THRESHOLD = 10 print ("Welcome to Guess the Number Game!!!\n") print ("You have to guess a number between 1 to 10\n") # function to find the high or low value def high_low(user_input_val, rand_number): diff_number = abs(int(rand_number) - int(user_input)) print (diff_number) if diff_number >= 5: print ("The number you have guessed is too high!!!") else: print ("The number you have guessed is too low!!!!") while True: try: user_input = input("Guess the number? ") rand_number = random.randint(LOWER_THRESHOLD, UPPER_THRESHOLD) if (int(user_input) <= 0): raise ValueError ("Please enter a number greater than zero") elif int(user_input) > 10: raise ValueError ("Please enter a number between 1 to 10") except ValueError as err: print ("ERROR!!!! {}".format(err)) else: user_input_main = int(user_input) if user_input_main == rand_number: print("You guessed right number\n") print("Exiting!!!") sys.exit() else: high_low(user_input_main, rand_number)
true
cccccb53f1779b56b6d73e79cc114f012d73a04b
radhakrishnan115/PythonScript
/hello_world.py
288
4.125
4
for x in range(8): if(x%2 == 0): Colm1 = 'BLACK' Colm2 = 'WHITE' else: Colm1 = 'WHITE' Colm2 = 'BLACK' for j in range(8): if(j%2 == 0): print(Colm1,end='|') else: print(Colm2,end='|') print('\n') print("End of Program")
false
85a5f5be61a62e89b32402d0d0a12e8887a7d91b
dlasing/udemy_python_class
/dailycode/SetMatrixZeroes.py
1,547
4.25
4
# Given a m x n matrix, if an element is 0, set its entire row and column to 0. # Do it in-place. # # Example 1: # #Input: # [ # [1,1,1], # [1,0,1], # [1,1,1] # ] # Output: # [ # [1,0,1], # [0,0,0], # [1,0,1] # ] class SetMatrixZeroes: def __init__(self,mylist): self.mylist = mylist def find_zero(self): zero_position = [] for m in range(len(self.mylist)): for n in range(len(self.mylist[0])): if self.mylist[m][n] == 0: zero_position.append([m,n]) print (zero_position) return zero_position def set_zeroes(self, zero_list): # Analysis # Based on the list returned from find_zero(), we have "position" of # all 0 found # For example: # # [[0, 0], [0, 3]] # A B C D # # convert the target row to 0 # pick the zero_list[row][0] which is A, C, then convert # the list to "0" # In this example, we convert row "0" to all 0 for convert_row in range(len(zero_list)): for row in range(len(self.mylist[0])): self.mylist[zero_list[convert_row][0]][row] = 0 # convert the target colum to 0 # pick the zero_list[column][1] which is B, D, the convert # the list to "0" for convert_column in range(len(zero_list[0])): for column in range(len(self.mylist)): self.mylist[column][zero_list[convert_column][1]] = 0 print (self.mylist) #matrix_list = [ [1,1,1], [1,0,1], [1,1,1]] matrix_list = [ [1,1,2,0], [3,4,0,2], [0,0,1,5]] case = SetMatrixZeroes(matrix_list) case.find_zero() #case.set_zeroes(case.find_zero())
true
7d2c9246788fe75f80ddfafdf0e40ddac5b266f9
dlasing/udemy_python_class
/dailycode/FindLargest.py
691
4.125
4
# Given a list of non negative integers, arrange them such that they form the largest number. # # Example 1: # # Input: [10,2] # Output: "210" # Example 2: # # Input: [3,30,34,5,9] # Output: "9534330" class Largest_num: def __init__(self, num_list): self.num_list = num_list def find_largest(self): for x in range (0, len(self.num_list)): for y in range (-1, -(len(self.num_list))-x, -1): temp = 0 # bubble sort if self.num_list [x] < self.num_list[y]: temp = self.num_list[x] self.num_list[x] = self.num_list[y] self.num_list[y] = temp print (self.num_list) case = Largest_num([32,30,34,50,91]) case.find_largest()
true
bba20fda3a5c3935188be0528e4fc06f21bedfd8
dlasing/udemy_python_class
/dailycode/ImplementStrStr.py
430
4.15625
4
# Return the index of the first occurrence of needle in haystack, or -1 if # needle is not part of haystack. # # Example 1: # # Input: haystack = "hello", needle = "ll" # Output: 2 # Example 2: # # Input: haystack = "aaaaa", needle = "bba" # Output: -1 haystack = "hello" needle = "aa" for x in range (0, len(haystack)): if haystack[x:(len(needle)+x)] == needle: print (f"position: {x}") print ("postion: -1")
true
77d2eb5a66953bfc672f081d1076dfde4bfed01b
melissapott/codefights
/checkPalindrome.py
410
4.125
4
"""Check to see if a given string is a palindrome""" def checkPalindrome(inputString): i = list(inputString) r = list(reversed(inputString)) p = True for x in range(0,len(inputString)): if i[x] != r[x]: p = False break return p # expected result = true print(checkPalindrome("tacocat")) # expected result = False print(checkPalindrome("not a palindrome"))
true
5bfe98ddfdb1dc64fa00abca9f6e62d9d5ed37b5
vick-hub/plc
/week6/problem3.py
404
4.25
4
import os import sys def string_reverse(s): # todo: add a docstring string_reversed = [] length = len(s) while length > 0: string_reversed += s[length - 1] length = length - 1 return string_reversed def main(): s = input("Enter string: ") print(''.join(string_reverse(s))) # very good! return os.EX_OK if __name__ == "__main__": sys.exit(main())
true
b58e8195e782f40d472f4307a88c98cc4f4ea822
binkesi/leetcode_easy
/python_cookbook/1-12Counter.py
399
4.34375
4
from collections import Counter words = [ 'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the', 'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into', 'my', 'eyes', "you're", 'under' ] if __name__ == "__main__": count = Counter(words) top_three = count.most_common(3) print(top_three)
false
e784615144ff8258af128b4c878d7562ad8c3cf5
riyanaje/python_programming
/pizzaOrder.py
502
4.125
4
# Pizza Order Homework def create_order(): crust = input("please enter what type of crust you would like: ") toppings = input("please enter what toppings you would like: ") sauce = input("please enter what sauce you would like: ") sides = input("please enter what sides you would like: ") pizza_order = { 'crust': crust, 'toppings': toppings, 'sauce': sauce, 'sides': sides } return pizza_order print(create_order())
true
63cf4f904903d0b3b6a32734e40fb98696122275
99ashr/PyCode
/Basics_of_python/File Handeling/file_handeling.py
1,395
4.46875
4
def user_input(): """This method takes the filename by the user which will be used later in other methods """ print("\t\tUser Input function!!") filename = input("Enter the name of the file here: ") return filename def open_file(filename): """This method is opening the file that has been passed by the user!!! Args: filename ([string]): [description] """ print("\t\t\topen_file function") m = input("Press 'w' to write or 'r' for read and 'a' to append into a file: ") file = open(filename, m) print("\t\tFile is opened by this function!!!") return (file, m) def user_input_write_file(): file_content = input("Enter the content to the file: ") return file_content def read_file(file): print(file.read()) def write_file(file): print("\t\tWrite file method!!!") file.write(user_input_write_file()) def close_file(file): """This function is called to close the file!!! """ file.close() def handel(): """This function contains all the file handeling operations!!! """ print("\t\t\tMain function") filename = user_input() r = open_file(filename) file = r[0] m = r[1] # print(m) if m == 'r': read_file(file) elif m == 'w' or 'a': write_file(file) close_file(file) handel()
true
e6ba17fd50b2c2c8b17d60f3d95d0ca7c25ae886
99ashr/PyCode
/Class and Object/class and object.py
1,521
4.53125
5
#!/usr/bin/env python3 #* ------------------------------- Introdunction ------------------------------ # # ! Entire program is defined as class and object. Everything that is similar is termed as class and every method,variable etc is an object. # ! A class is a logical grouping which can be reused. Can also be termed as Template. # & Syntax --> Class <class_name>: # ---------------------------------------------------------------------------- # #* ----------------------------------- Class ---------------------------------- # class Car(): def __init__(self, model, year, price): self.model = model self.year = year self.price = price def price_inc(self): self.price = int(self.price*1.15) #* ---------------------------------- Object ---------------------------------- # honda = Car("City", 2016, 10000789) #* ------------------------------ Display object ------------------------------ # print(honda.__dict__) # Everything that an object holds honda.cc = 1500 # New data to honda object print(honda.cc) # display a particular object detail print(honda.__dict__) # ---------------------------------- Output ---------------------------------- # {'model': 'City', 'year': 2016, 'price': 10000789} 1500 {'model': 'City', 'year': 2016, 'price': 10000789, 'cc': 1500} # ---------------------------------------------------------------------------- # #* ------------------------------------ EOF ----------------------------------- #
true
74ae3121b63e8c952e969a17428327e294d6a606
99ashr/PyCode
/Class and Object/Inheritance02.py
1,380
4.375
4
#!/usr/bin/env python3 #* -------------------------------- Inheritance ------------------------------- # class polygon(): def __init__(self, no_of_sides): self.n = no_of_sides self.sides = [0 for _ in range(no_of_sides)] def input_side(self): self.sides = [float(input("Enter the side "+str(i+1)+" : ")) for i in range(self.n)] def display_sides(self): print("#--------Sides--------#") for i in range(self.n): print("Side", i+1, "is", self.sides[i]) # #p = polygon(3) # #p.input_side() # #p.display_sides() class Triangle(polygon): def __init__(self): # polygon.__init__(self, 3) super().__init__(3) def Area(self): a, b, c = self.sides s = (a+b+c)/2 area = (s*(s-a)*(s-b)*(s-c))**0.5 print("The Area of Triangle is %0.2f Units sq" % area) # ---------------------------------------------------------------------------- # t = Triangle() t.input_side() t.display_sides() t.Area() # ---------------------------------------------------------------------------- # # print(isinstance(t, Triangle)) # print(isinstance(t, polygon)) # print(issubclass(Triangle, polygon)) # print(issubclass(polygon, Triangle)) #* ------------------------------------ EOF ----------------------------------- #
false
ab70b9b4085d65e91f8c300b1524656f470e4c97
99ashr/PyCode
/Infytq/Ass15.py
588
4.53125
5
#!/usr/bin/python3 """A python program to display the product of three numbers based upon following rules: if the value of one the integer is 7 then it should not be included and the values along its right should also be ignored In case there's 7 on the unit place display -1 as the output""" def find_product(num1,num2,num3): product=0 if num1==7: product=num2*num3 elif num2==7: product=num3 elif num3==7: product=-1 else: product=num1*num2*num3 return product product=find_product(7,6,2) print(product)
true
b82504ca7e524dac174acd289e7b8ce16d8fbd40
99ashr/PyCode
/Basics_of_python/Generators/fibonacci.py
493
4.28125
4
#!/usr/bin/env python3 #* ----------------------------- Fibonacci Series ----------------------------- # # ! A series of numbers where each number is a sum of previous two numbers. # & Syntax -->a=0,b=1,c=1,d=2 i.e (a=b and b=a+b) def fibonacci(): f, s = 0, 1 while True: yield f f, s = s, f+s for i in fibonacci(): if i > 50: break print(i, end=" ") #* ------------------------------------ EOF ----------------------------------- #
true
89617994b8929bcdd8f0842fa3cd7c88ec7627fe
pTricKg/python
/python_files/untitled/classes2.py
1,511
4.1875
4
#class ClassName(object): # class statements go here class Car(object): condition = "new" def __init__(self,model,color,mpg): self.model = model self.color = color self.mpg = mpg def display_car(self): return "This is a " + self.color + " " + self.model + " with " + str(self.mpg) + " MPG." def drive_car(self): self.condition = "used" #newObject = ClassName() my_car = Car("DeLorean", "silver", 88) ##print my_car.condition ##print my_car.model ##print my_car.color ##print my_car.mpg # using display_car method to return same as above print (my_car.display_car()) print ("My car is " + my_car.condition) my_car.drive_car() print ("I drove my car making it a " + my_car.condition + " car!") #newObject = ClassName() # Parents and Children ##class ChildClass(ParentClass): ## # new variables and functions go here class ElectricCar(Car): def __init__(self, model, color, mpg,battery_type): self.model = model self.color = color self.mpg = mpg self.battery_type = battery_type def drive_car(self): self.condition = "like new" my_car2 = ElectricCar("VW","green", 65, "molten salt") print (my_car2.battery_type) ## using representation class Point3D(object): def __init__(self,x,y,z): self.x = x self.y = y self.z = z def __repr__(self): return '(%d, %d, %d)' % (self.x, self.y, self.z) my_point = Point3D(1,2,3) print my_point
true
c1421f58688713642e26e8293f417e5a781fb4be
pTricKg/python
/python_files/untitled/testing8.18.py
589
4.15625
4
def median(lst): ''' takes a list, sorts list, and give median value''' lst.sort() if len(lst) % 2 == 0: # checks if even one = int(len(lst) / 2.0) # declares variable to hold first median two = int((len(lst) / 2.0) - 1) # delcares second variable return (lst[one] + lst[two]) / 2.0 # averages the two median values print (lst[one],lst[two]) # for testing else: three = int(len(lst) / 2.0) # for non-even lists, return 1st[three] # just half to get median value print (lst[three])
true
1d954663cbbd2a95db3f036e4848241faa07d101
pTricKg/python
/python_files/loop_index.py
830
4.1875
4
word = "supercalafragilous" index = 0 # print each letter: first to last while index < len(word): new_word = word[index] print (new_word) index = index + 1 # print each letter: last to first while index < len(word): new_word1 = word[index - 1] print (new_word1) index = index - 1 # IndexError # using for in even better for i in word: print (i) # prints word backwards while ~ while index < len(word): word1 = word[::-1] print (word1) index = index + 1 ##while index < len(word): word1 = word[index:-1:1] print (word1) index = index + 1 # output ##supercalafragilou ##upercalafragilou ##percalafragilou ##ercalafragilou ##rcalafragilou ##calafragilou ##alafragilou ##lafragilou ##afragilou ##fragilou ##ragilou ##agilou ##gilou ##ilou ##lou ##ou ##u
false
571c6c1e2b261f2c920509e3caaa2068f04d8b87
aau-hcl-p5/main
/code/object_detector/costfunction/mean_squared_error.py
1,182
4.125
4
"The Implementation of the Mean Squared Error cost function" import Vector import numpy as np from costfunction.generic_costfunction import GenericCostFunction from algorithms.utilities import NumberType class Mean_Squared_Error(GenericCostFunction): accumulated_error: NumberType """ Returns the direction of the vector (whether each axis is positive or negative) :return: a value between 0 and 1 indicating the cost, deviation from the expected. """ def compute_cost(data: np.ndarray[Vector], predictions: np.ndarray[Vector]) -> NumberType: data_length = len(data) predictions_length = len(predictions) if data_length != predictions_length: raise Exception('Prediction set and Data set must be of same length') if predictions_length == 0: raise Exception('Length of Prediction set must not be zero') accumulated_error = 0.0 for prediction, target in zip(predictions, data): accumulated_error += (prediction - target).length()**2 # Calculating mean and dividing by 2 cost = (1.0 / (2 * predictions_length)) * accumulated_error return cost
true
1469acf3b03146195ec0720c23c27927d75e2c47
nerones/PySOO
/extr_datos.py
2,320
4.125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- #sin implementar Heap class ColaFIFO: """ Clase q simula una cola FIFO """ def __init__(self): self.__elementos = [] def poner(self, elemento): self.__elementos.append(elemento) return elemento def sacar(self): return self.elemento.pop(0) def cabeza(self): return self.__elementos[0] def cola(self): return self.__elementos[-1] def __len__(self): return len(self.__elementos) tamanio = __len__ def pertenece(elemento): return elemento in self.__elementos class ColaLIFO(ColaFIFO): """ Clase q simula una cola de tipo LIFO """ def sacar(self): return self.elemento.pop() class Conjunto(ColaLIFO): def __init__(self): ColaFIFO.__init__(self) def sacar(self, obj): pass def sacar_ultimo(self): pass def pertenece(self, obj): pass def vacio(self): pass #toy pensando si implementar o no los siguientes metodos :S #ya q no se si valen la pena #error_llena() #error_vacia() #error_no_encontrado() #error_tamanio_minimo() #error_factor_ampliacion(factor) class NodoHeap: """ formato de registro de los Nodos Pertenecientes a la pila o Heap """ def __init__(self, obj=None, t=0.0): self.objecto = obj #apuntador a un objecto self.tiempo = t #por el momento no aseguro que esta clase funcione correrctamento #me esta costando entender la idea de esta clase :( class Heap: def __init__(self): self.__heap = [NodoHeap(t=-1e37)] def poner(self, r, datos): nodo = NodoHeap(datos, r) expl = len(self.__heap) - 1 def sacar(self, r): pass def vacio(self): """ devuelve el estado """ return not(self.__len__()) def altura(self): pass def imprime_arbol(self): #todavia no le entiendo la gracia a este metodo para mostrar el #arbol pass def __len__(self): """ sobrecarga del operador longitud, que permitira conocer externamente la cantidad de elementos de la Heap (Pila) """ return len(self.__heap)
false
58e54708161f12141855841ade2b01bbbb5e9d5f
sophiamahnke/LPTHW
/EX20/ex20.py
834
4.1875
4
from sys import argv #importing module script, input_file = argv #setting variables def print_all(f): #setting print_all function, is to read the whole file print f.read() def rewind(f): #setting rewind function f.seek(0) #starts at the beginning of file def print_a_line(line_count, f): #setting print_a_line function print line_count, f.readline() current_file = open(input_file) #current_file = open the file we put into argv print "First let's print the whole file:\n" print_all(current_file) #print whole file print "Now let's rewind, kind of like a tape." rewind(current_file) print "Let's print three lines:" current_line = 1 #1 print_a_line(current_line, current_file) current_line += 1 #1+1=2 print_a_line(current_line, current_file) current_line += 1 #2+1=3 print_a_line(current_line, current_file)
true
47d33570e688a0925c5e73faddfc522cbb0d7240
attawats/python3
/check_odd_even.py
305
4.1875
4
def is_even (n): return True if n % 2 == 0 else False #same language speak #if n % 2 == 0 : # return True #else: # return False def is_odd(n): return not(is_even(n)) #if n % 2 == 1 : # return True #else: # return False print(is_even(8)) print(is_odd(5))
false
46f3d15b52e51133c67c9e8fe3f4bd5ed5579912
aaryarajoju/cu-py
/Experiment-2/PRACTICAL/Exp-2_Task-5.py
843
4.125
4
# EXPERIMENT - 2 # TASK - 5 : Create a program wages.py that assumes people are paid double time for hours over 60. They get paid for at most 20 hours overtime at 1.5 times the normal rate. #wages.py import random def printSalary(hours, wage): if hours < 40: print("The salary cannot be generated") print('\a') elif hours >= 40 : print(salary(hours, wage)) def salary(hours, wage): if hours == 40: OTsalary = 40 * wage elif hours > 40 and hours < 60: OTsalary = 40 * wage + (hours-40)*(1.5*wage) elif hours > 60: OTsalary = 40 * wage + 20*(1.5*wage) + (hours-60)*(2*wage) return OTsalary #main numOfHours = random.randint(35,75) regularWage = int(input("Enter the regular wage: ")) print("The number of hours are:", numOfHours) printSalary(numOfHours, regularWage)
true
c4b913ba2bb2a1549321fd7ac7859595237b68fc
imkamali/pyclass
/s2_11_triangle.py
265
4.3125
4
num1 = int(input ("Enter num1 please \n")) num2 = int(input ("Enter num2 please \n")) num3 = int(input ("Enter num3 please \n")) if num1+num2 > num3 and num1 + num3 > num2 and num2+num3 > num1: print ("It's a triangle") else: print ("It's not a triangle")
false
014e43f7243a04eab6a9c38aa3cb75aae6238157
imkamali/pyclass
/s5h_2.py
833
4.375
4
''' لیستی از اعداد از کاربر بگیرد، به منفی که رسید متوقف شود و در نهایت اعداد، جمع و میانگین آنها را چاپ کند ''' numbers = list () while True: num=float(input("Enter number: \n")) if num < 0 : break numbers.append(num) listsum=sum(numbers) average=listsum/len(numbers) print("For", numbers, "Sum is:", listsum, "and", "Average is:", round(average,2)) ''' راه حل دوم: ''' numbers = list () listsum=0 while True: num=float(input("Enter number: \n")) if num < 0 : break else: numbers.append(num) listsum=listsum+num average=listsum/len(numbers) print("For", numbers, "Sum is:", listsum, "and", "Average is:", round(average,2))
false
35ba97cd41cd445086a3f9b3a1f5c852c3dd9367
122abhi/concepts-of-python-01
/Python Classes & Objects/Dog1.py
1,196
4.15625
4
# A Class is blueprint fora n entity while instance/object is a copy of the class with actual values # State: Defines attributes for an object # Behaviours: Defines possible behaviours of an object. # class variables: unique to a class, shared among all objects. Defined in the class. # instance attributes: Not unique to a class, each object have it's own actual values, Defined in __init__ constructor # or methods of the class # self is used to refer an object/instance itself in it's methods. It need not be passed but is taken automatically taken by python # while calling the function. Writing self/any-other-name is compulsory as 1st parameter while defining a method. class Dog(): # Class Variable animal= "Dog" # creating instance variable using __init__ constructor def __init__(self,breed): self.breed= breed # creating instance variable using a method constructor def setColor(self, color): self.color= color def getColor(self): return self.color # Driver code Rodger= Dog("Labrador") Rodger.setColor("Golden Brown") print(Rodger.getColor()) # https://medium.com/python-features/class-vs-instance-variables-8d452e9abcbd
true
31113ddc06c227508ac8c5312c955e5cb30df802
fandemisterling100/substrings_counter
/substring_counter.py
1,244
4.4375
4
# Python program to count every repeated substring # along a string of random characters and random # length def count_substrings(string): """ Parameters ---------- string : str String of random characters and random length. Returns ------- repeated : dict Data structure that contains the substrings that repeat and hoy many times they appear. """ # Initialize empty data structure substring_counts = {} # Iterate over the string to get the # substrings for i in range(len(string) - 3): substring = string[i:i+4] # validate if the substring exists in # the data structure to accumulate or # add it to it if substring not in substring_counts: substring_counts[substring] = 1 else: substring_counts[substring] += 1 # Get just the substrings that appear more # than once repeated = {k: v for k, v in substring_counts.items() if v > 1} return repeated if __name__ == "__main__": # Definition of the string s = "abcabcabcuioabcxcr" # Count substrings print(count_substrings(s))
true
39a0d696f5051ba1f9a9663614e16fdc99a6cbb1
StephanRaab/computer_fundamentals
/introduction_to_interactive_programming_in_python/week2/week2_guess_the_number.py
1,803
4.125
4
# "Guess the number" mini-project # input will come from buttons and an input field import math, random, simplegui # helper function to start and restart the game def new_game(): """ initialize global variables used in your code here """ global secret_number secret_number = random.randrange(0, 100) global guess_left guess_left = 7 return(secret_number, guess_left) def range100(): """ button that changes the range to [0,100) and starts a new game """ global secret_number secret_number = random.randrange(0, 100) global guess_left guess_left = 7 print("You're playing from 0 - 100!") def range1000(): """ button that changes the range to [0,1000) and starts a new game """ global secret_number secret_number = random.randrange(0, 1000) global guess_left guess_left = 10 print("You're playing from 0 - 1000!") def input_guess(guess): """ main game logic goes here """ global guess_left guess_left -= 1 print("") print("Guess was " + str(guess)) if(int(guess) < secret_number): print("Higher") print("You have " + str(guess_left) + " left!") elif(int(guess) > secret_number): print("Lower") print("You have " + str(guess_left) + " left!") else: print("Correct") print("You had " + str(guess_left) + " left!") # create frame frame = simplegui.create_frame("Guess The Number", 300, 300) frame.add_button("Range is [0,100)", range100, 150) frame.add_button("Range is [0,1000)", range1000, 150) frame.add_input("Input your guess", input_guess, 150) # register event handlers for control elements and start frame frame.start() # call new_game new_game()
true
150bb9825c55ee905de5b2d8f7121ed1ea9addb8
RaghavNitish/Unscramble-Computer-Science-Problems
/Task1.py
882
4.25
4
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 1: How many different telephone numbers are there in the records? Print a message: "There are <count> different telephone numbers in the records." """ phone_numbers = [] #Texts file for element in texts: for i in range(2): if element[i] not in phone_numbers: phone_numbers.append(element[i]) #Calls file for element1 in calls: for j in range(2): if element1[j] not in phone_numbers: phone_numbers.append(element1[j]) #Printing print("There are {} different telephone numbers in the records.".format(len(phone_numbers)))
true
415e3cc93c5424efe9c4927025cf7cbd674c8dcc
cseydlitz/practice
/LinkedLists/sum_lists.py
2,214
4.125
4
class Node: def __init__(self, data, next_node=False): self.data = data self.next_node = next_node class LinkedList: def __init__(self): self.head = None def insert_into_ll(self,data): new_node = Node(data) if self.head: cur_node = self.head while cur_node.next_node: cur_node = cur_node.next_node cur_node.next_node = new_node else: self.head = new_node def print_ll(self): cur_node = self.head while cur_node: print(cur_node.data) cur_node = cur_node.next_node def add_lists(LL1, LL2, rev=True): """Returns value of list integers Args: LL1: Linked List Object LL2: Linked List Object rev: boolean Returns: int """ ll1_int = process_list(LL1,rev=rev) ll2_int = process_list(LL2,rev=rev) final_val = ll1_int + ll2_int return final_val def process_list(LL,rev=True): """Returns integer made from nodes Args: LL: Linked List Object Returns: int integer is in reverse order as LL object """ cur_node = LL.head ll_list = [] while cur_node: ll_list.append(cur_node.data) cur_node = cur_node.next_node if rev: ll_list.reverse() strings = (str(i) for i in ll_list) string = "".join(strings) return int(string) def sum_lists(ll1=None, ll2=None, rev=True): """Prompt: Write a function that adds two numbers and returns the sum as a linked list Further details: Two numbers represented as a linked list, where each node contains a single digit. Args: ll1, ll2: LinkedList rev: boolen if revered is True, then the values or linked lists provided are assumed to be in reverse order of the digits of the integer. The returned Linked List Nodes will also be in reverse order of the sum """ if not ll1 and ll2: print("Plz gib values") LL_val = add_lists(ll1,ll2,rev=rev) LL_sum = process_list(LL_val,rev=rev) LL_sum.print_ll()
true
afb65d89a6a5a5baba23a8491562a192f4e3e7b9
AstiV/Harvard-cs50
/pset6/caesar/caesar.py
2,469
4.4375
4
from cs50 import get_string import sys def main(): # => argv = list of command-line arguments # In C: argc = number of command line arguments # A python list knows its length, so do len(sys.argv) # to get the number of elements in argv. # get the key from command line argument # argc must be 2 (caesar.py and key) if len(sys.argv) != 2: print("Please include your desired key to the command line argument!\n") elif len(sys.argv) == 2: print(f"The key you chose is: {sys.argv[1]}") # argv[1] = key is of datatype string # convert key string to integer # use atoi function # check which value it will return if the string passed in doesn't contain all numbers key = int(sys.argv[1]) # prompt for plaintext # output "plaintext: " (without a newline) and then # prompt the user for a string of plaintext (using get_string). plaintext = get_string("plaintext: ") # encipher # for each character in the plaintext string print("ciphertext: ", end="") # n = length of user input string n = len(plaintext) for i in range(n): # check if character is alphabetic (isalpha) # in python isalpha does not take any parameters # (in C isalpha(plaintext[i])) if (plaintext[i]).isalpha(): # preserve case - lower case characters if (plaintext[i]).islower(): # in python: # function ord() gets the int value of the char # to convert back afterwards, use function chr() # -97, as difference of ASCII value and alphabetical index (for lower case characters) # modulo 26 is used to wrap around the alphabet, e.g. x + 3 => a (26 = length of alphabet) # add 97 back again to access right ASCII value letter # store char value in variable as , end="" didn't work on calculation lowercasechar = chr(((((ord(plaintext[i]) - 97) + key) % 26) + 97)) print(lowercasechar, end="") # preserve case - upper case characters else: uppercasechar = chr(((((ord(plaintext[i]) - 65) + key) % 26) + 65)) print(uppercasechar, end="") # preserve all other non-alphabetical characters else: print(plaintext[i], end="") # print linebreak after string print() if __name__ == "__main__": main()
true
aa7a5cc2f2e66c8163de6ff995a391a6fededf12
atmanm/LeetCode
/Medium/rotateImage.py
1,404
4.125
4
#You are given an n x n 2D matrix representing an image. #Rotate the image by 90 degrees (clockwise). #Note: #You have to rotate the image in-place, which means you have to modify the #input 2D matrix directly. DO NOT allocate another 2D matrix and do the #rotation. class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ matrix = self.rotateHelper(matrix) print(matrix) return 0 def rotateHelper(self, matrix): if matrix: length = len(matrix[0]) for i in range(length-1): matrix[0][i],\ matrix[i][length-1],\ matrix[length-1][length-1-i],\ matrix[length-1-i][0] = \ matrix[length-1-i][0],\ matrix[0][i],\ matrix[i][length-1],\ matrix[length-1][length-1-i] newMatrix = matrix[1:-1] newMatrix = [x[1:-1] for x in newMatrix] rotMatrix = self.rotateHelper(newMatrix) if rotMatrix: for index,myList in enumerate(rotMatrix): matrix[index+1][1:-1] = myList return matrix if __name__ == "__main__": image = input().strip() matrix = eval(image) Solution().rotate(matrix)
true