blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
4aeb830f65676284ec85a523099b4bb18dad9db7
AbeForty/Dojo-Assignments
/Python/Python Fundamentals/mkrddict.py
262
4.40625
4
hello_dict = {"Name": "Aaron", "Age": "22", "Country of birth": "The United States", "Favorite language": "VB.NET"} def read_dict(my_dict): for key, value in my_dict.items(): print "My {} is {}".format(str(key).lower(), value) read_dict(hello_dict)
false
b3b83897b4359cffe25958eb2c23cd048eabe8ca
SivaIBT/Python-Training
/Day2/loop.py
995
4.1875
4
# prints Hello Geek 3 Times count = 0 while (count < 3): count = count+1 print("Hello Geek") # Iterating over a list print("List Iteration") l = ["geeks", "for", "geeks"] for i in l: print(i) # Iterating over a tuple (immutable) print("\nTuple Iteration") t = ("geeks", "for", "geeks") for i in t: print(i) # Iterating over a String print("\nString Iteration") s = "Geeks" for i in s : print(i) # Iterating over dictionary print("\nDictionary Iteration") d = dict() d['xyz'] = 123 d['abc'] = 345 for i in d : print("%s %d" %(i, d[i])) # Prints all letters except 'e' and 's' for letter in 'geeksforgeeks': if letter == 'e' or letter == 's': continue print 'Current Letter :', letter var = 10 for letter in 'geeksforgeeks': # break the loop as soon it sees 'e' # or 's' if letter == 'e' or letter == 's': break print 'Current Letter :', letter # An empty loop for letter in 'geeksforgeeks': pass print 'Last Letter :', letter
false
ef6a68902dc913298c6d3b7dbb21df988da5dd11
gillespilon/sql
/food.py
2,342
4.21875
4
#! /usr/bin/env python3 """ Example of an sqlite3 db - Create a dataframe - Save as a table in a database """ from sqlalchemy import create_engine import datasense as ds import pandas as pd import sqlite3 def main(): # engine = create_engine('sqlite://', echo=False) connection = sqlite3.connect('groceries.db') df = create_dataframe() print(df.head()) print(df.dtypes) df.to_sql( name='my_groceries', con=connection, if_exists='replace', index=False ) # list tables in database cursor = connection.cursor() cursor.execute( "SELECT name FROM sqlite_master\ WHERE type = 'table'\ ORDER BY name;" ) print(cursor.fetchall()) print() # open a database and read a table into a dataframe # list tables in database cursor.execute( "SELECT name FROM sqlite_master\ WHERE type = 'table'\ ORDER BY name;" ) print(cursor.fetchall()) print() # read table into dataframe query = "SELECT * FROM my_groceries;" df = pd.read_sql(query, connection) print(df.head()) print(df.dtypes) # cursor.execute("DROP table 'test'") # save dataframe to new database # df.to_sql('test', connection, if_exists='replace', index = False) def create_dataframe() -> pd.DataFrame: df = pd.DataFrame( { 'a': ds.random_data( distribution='uniform', size=42, loc=13, scale=70 ), 'b': ds.random_data(distribution='bool'), 'c': ds.random_data(distribution='categories'), 'd': ds.timedelta_data(), 'i': ds.random_data( distribution='uniform', size=42, loc=13, scale=70 ), 'r': ds.random_data( distribution='strings', strings=['0', '1'] ), 's': ds.random_data(distribution='strings'), 't': ds.datetime_data(), 'u': ds.datetime_data(), 'x': ds.random_data(distribution='norm'), 'y': ds.random_data(distribution='randint'), 'z': ds.random_data(distribution='uniform') } ) return df if __name__ == '__main__': main()
true
a0f011bed9d76b2dd839ee86cb409b7d236964c6
mohito1999/Miniprojects
/Projects/ATBS/col1.py
683
4.28125
4
from sys import exit def collatz(number): if number % 2 == 0: result = number // 2 elif number % 2 == 1: result = number * 3 + 1 while number != 1: number = result print(number) #the very first return statement executed will end the function thats why I was struggling for it to work when I was using a return statement for the print as well return collatz(number) #you are returning the function such that it runs again when this while condition is met if number == 1: print(number) exit() num = int(input("Enter an integer: ")) run = collatz(num) print(run)
true
fdc0930e953b6cde9c3ce7f9125b44f72da9f9d2
ResearchInMotion/TestProject
/Maximum.py
357
4.15625
4
print("Enter the first number") firstNumber=int(input()) print("Enter the second number") secondNumber=int(input()) def maximum(Number1 , Number2): if(Number1>Number2): print("Number one is greater") elif(Number1<Number2): print("Number two is greater") else: print("both are same") maximum(firstNumber ,secondNumber )
true
c5ac7b56e4c831d835080749c5ef09ab706069f5
ResearchInMotion/TestProject
/mutiple.py
452
4.21875
4
print("please enter a number : ") number = input() number2=int(number) if(number2%7==0): print("numbr is divisble by 7") if(number2%14==0): print("number is divisble by 14") else: print("number is divisble by 3 , but not with 7 ") #if number2 % 7 is 0: #print("number is divisble by 7") #if number2 % 14 is 0: #print("number is divisble by 14") #else: #print("number is divisble by 7 but not with 14")
true
fe1bc619dccda578cd13132e8fd25f36e98a106e
loosla/test_tasks
/test_tasks/search_insert_position_sorted_arr.py
983
4.1875
4
# Given a sorted array of distinct integers and a target value, # return the index if the target is found. # If not, return the index where it would be if it were inserted in order. # Code to check in main.py # nums = [1,3,5] # print(search_insert_position_sorted_arr(nums, 4)) def search_insert_position_sorted_arr(nums: [int], target: int) -> int: if not nums: return None if target in nums: return nums.index(target) else: if target > nums[len(nums)-1]: return len(nums) elif target < nums[0]: return 0 else: return binary_search_to_insert(nums, target) def binary_search_to_insert(arr, target): middle = int(round(len(arr) / 2)) for i in range(middle): if arr[i] < target and arr[i+1] > target: return i+1 elif i > target: binary_search_to_insert(arr[:middle], target) else: binary_search_to_insert(arr[middle:], target)
true
79d3c5f213673e352f9da283231cb7e4786237b9
jothiprakashv/Python
/OOPS/Abstraction/Vehicle.py
1,055
4.3125
4
from abc import ABC, abstractmethod class Vehicle(ABC): def __init__(self,model,no_of_wheels): self.__model=model self.__no_of_wheels=no_of_wheels def getModel(self): return self.__model def getNoOfWheels(self): return self.__no_of_wheels @abstractmethod def engine(self): return class Car(Vehicle): def __init__(self,model,no_of_wheels): super().__init__(model,no_of_wheels) def engine(self): return "4 stroke Engine" def __str__(self): return f"Car Model:{self.getModel()}\nWheels:{self.getNoOfWheels()}" class Bike(Vehicle): def __init__(self,model,no_of_wheels): super().__init__(model,no_of_wheels) def engine(self): return "2 stroke Engine" def __str__(self): return f"Bike Model:{self.getModel()}\nWheels:{self.getNoOfWheels()}" honda=Car("honda city",4) print(honda) print(honda.engine()) intruder=Bike("suzuki",2) print(intruder) print(intruder.engine()) v = Vehicle("mymodel",5)
false
6f30a37168be382f6f8fe541ab1dc9d86d130448
lilnop/pythonguess
/Guesser 2.0.py
616
4.15625
4
import random n = random.randint(1, 30) count = 10 print("Guess a random number from 1 to 30, you have 10 tries.") while count > 0: guess = int(input("\nEnter an integer from 1 to 30: ")) if (guess == n): print("You guessed the number correctly!") break elif (guess > n): print("Guessed number is high") elif (guess < n): print("Guessed number is low") count = count - 1 if (count <= 0): print("You ran out of tries. Game over!") print("The number was", n) else: print("Your tries remaining:", count)
true
c85269ae77a9e9a97a925c894531661addcd1623
1996hitesh/Pyhton-Problems
/Data Structures/List/program_4.py
346
4.15625
4
# Write a program to print the number of occurrences of a specified element in a list. def countX(lst, x): return lst.count(x) lst = [10,15,2,1,2,3,10,5,9,8,8] #defining the list x = int(input("Enter the element to check the occurenece : ")) result = countX(lst,x) print("Element {} occured in list {} times".format(x,result))
true
fd583e82077bf22717b8a70766639ec63d2de8d4
1996hitesh/Pyhton-Problems
/Data Structures/Tuple/problem_1.py
250
4.15625
4
# Write a program to print the 4th element from first #and 4th element from last in a tuple. t_1 = (1,2,3,4,5,6,7,8,9,10) #initializing a tuple print("4th element from the front = ",t_1[3]) print("4th element from the back = ",t_1[-4])
true
543d2750ed615de9d5c296925efd8d180b25ae63
1996hitesh/Pyhton-Problems
/Function/program_3.py
237
4.28125
4
#Write a function to calculate and return the factorial of a number #(a non-negative integer). def fact(n): if n == 1: return 1 f = n*fact(n-1) return f n = int(input("Enter number: ")) res = fact(n) print(res)
true
3fcaf8d563c66c0a4038e8ace50cb5e71aaac780
shiva-marupakula/Student-Management-System
/src/main/webapp/python/unit1/palindrome.py
252
4.25
4
#to check whether given number is or palindrome not. n=int(input("enter any number")) s=0 temp=n while(n!=0): r=n%10 s=(s*10)+r n=n//10 print(s,'is reverse of num') if(temp==s): print('number is palindrome') else: print('number is not palindrom')
true
c8df65ff8c008e84730660c08308aebd5c1f1f27
shiva-marupakula/Student-Management-System
/src/main/webapp/python/unit2/B171081/tupleass5.py
225
4.125
4
#a Python program to get the 4th element and 4th element from last of a tuple mytuple=(1,2,3,4,5,6,7,8,9,0,11,111,111,1111,1111) print(mytuple[4],'is fourth element of tuple') print(mytuple[-4],'is fourth element from last')
false
bf47d0e783970d89a5afcb14aeaa9ed36fd8e083
shiva-marupakula/Student-Management-System
/src/main/webapp/python/unit2/B171081/tupleass15.py
224
4.25
4
#Python program to count the elements in a list until an element is a tuple. mytuple=(11,12,23,34,(1,2,3,45),4) c=0 for i in mytuple: if(type(i)==tuple): print('sum is ',sum(i)) break else: c=c+1 print('count is',c)
true
a2089fa6465cba82302ebd5cb1a8eb4d3e0df124
shiva-marupakula/Student-Management-System
/src/main/webapp/python/unit2/B171081/tupleass6.py
288
4.4375
4
#a Python program to find the repeated items of a tuple mytuple=(1,2,3,4,5,6,7,8,9,0,11,111,111,1111,1111) new_tuple=[] for i in mytuple: if i not in new_tuple: if(mytuple.count(i)>1): new_tuple.append(i) duplicate_tuple=tuple(new_tuple) print("repeated items are",duplicate_tuple)
true
b6e5fb0255b58c6c6303b5003aa5b171469318cb
shiva-marupakula/Student-Management-System
/src/main/webapp/python/unit1/factorial.py
265
4.34375
4
#to print factorial of given number n=int(input('enter any number')) fact=1 if(n<0): print('please enter positive values only') elif(n==0): print('factorial of 0 is 1') else: for i in range(1,n+1): fact=fact*i print('factorial of {} is {}'.format(n,fact))
true
b1453285fd2613919ae320a09f44672d1d648a57
2727-ask/LinkCode-Projects
/secondmaximuminarray.py
355
4.125
4
print("Hello World") arr = [] n = int(input("Enter Number of Elements in array")) for i in range(n): no = int(input("Enter Number")) arr.append(no) first = 0 second = 0 for x in arr: if(first<x): second = first first = x elif(second<x and x!=first): second = x print('Second Largest Element in Array is',second)
true
e20dc0fe31f9f90a32856c53f635a9479242e367
xiaoqie007/pilot-student2-zby
/python botzhao.py
2,013
4.1875
4
#如果我们对交互的流程和样式不满意,就优化增强 Bot 父类的 run() 方法; #如果我们需要更多对话内容,就定义更多不一样的 Bot 子类; #如果想增加对话系统级的操作,比如提供系统帮助指令,可以修改 Garfield 和 Bot 类的 run() 方法来实现。 #1.公共父类 Bot import time class Bot: wait = 1 def __init__(self): self.q = '' self.a = '' def _think(self, s): return s def run(self): time.sleep(Bot.wait) print(self.q) self.a = input() time.sleep(Bot.wait) print(self._think(self.a)) #2.各个Bot子类 class HelloBot(Bot): def __init__(self): self.q = "Hi, what is your name?" def _think(self, s): return f"Hello{s}" class GreetingBot(Bot): def __init__(self): self.q = "How are you today?" def _think(self, s): if 'good' in s.lower() or 'fine' in s.lower(): return "I'm feeling good too" else: return "Sorry to hear that" import random class FavoriteColorBot(Bot): def __init__(self): self.q = "what's your favorite color?" def _think(self, s): colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'purple'] return f"You like {s.lower()}? My favorite color is {random.choice(colors)}" #3.一个主流程BotZhao把上面的这些 Bot 串起来 class BotZhao: def __init__(self, wait= 1): Bot.wait = wait self.bots = [] def add(self, bot): self.bots.append(bot) def _prompt(self, s): print(s) print() def run(self): self._prompt("This is BotZhao system. Let's talk.") for bot in self.bots: bot.run() #4.初始化一个 Garfield 实例来具体运行 botzhao = BotZhao(1) botzhao.add(HelloBot()) botzhao.add(GreetingBot()) botzhao.add(FavoriteColorBot()) botzhao.run()
false
bfa10f4a8888221ccbdac411c80f9b6bc5e66e87
oleglr/GB_Python_Algorithms
/lesson2/task1.py
679
4.375
4
# 2. Посчитать четные и нечетные цифры введенного натурального числа. Например, если введено число 34560, # то у него 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5). a = int(input("Введите натуральное число: ")) even = 0 odd = 0 while True: if a % 2 == 0: even += 1 else: odd += 1 a //= 10 if a == 0: break print(f'Количество четных цифры в введенном числе: {even}') print(f'Количество нечетных цифры в введенном числе: {odd}')
false
64dbb44a7739e29ed8748955cda42a585e04033d
oleglr/GB_Python_Algorithms
/lesson3/task3.py
793
4.1875
4
# 3. В массиве случайных целых чисел поменять местами минимальный и максимальный элементы. import random SIZE = 10 MIN_ITEM = 0 MAX_ITEM = 100 array = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)] print(f'Исходный массив: \n{array}') min_i = max_i = 0 for i in range(1, len(array)): if array[min_i] > array[i]: min_i = i elif array[max_i] < array[i]: max_i = i print(f'min = {array[min_i]} на {min_i} позиции') print(f'max = {array[max_i]} на {max_i} позиции') array[min_i], array[max_i] = array[max_i], array[min_i] print(f'Поменяли местами минимальный и максимальный элементы: \n{array}')
false
6fbe9938e78d98bd563c86ddf98879a729a4058b
zhanghuaisheng/mylearn
/Python基础/day006/04 深浅拷贝.py
2,894
4.15625
4
# 作用 # 后期开发代码时避免出现问题,不知道原因 # 面试几乎必问 # 什么是赋值 # 什么是浅拷贝 # 什么是深拷贝 # 赋值:多个变量名指向同一个内存地址 # a = 10 #不可变数据类型 # b = a # a,b 都指向10的内存地址 # a = 11 # print(a,b) # print(id(a),id(b)) # lst =[1,2,3] #可变数据类型 # lst1 = lst #lst,lst1 都指向列表的内存地址 # print(lst,lst1) # lst.append(4) # lst = [1,2,3,4] # print(lst,lst1) # print(id(lst),id(lst1)) # lst =[1,2,3] #可变数据类型 # lst1 = lst #lst,lst1 都指向列表的内存地址 # lst = lst.append(4) #返回值为None # print(lst,lst1) # dic = {"key":11,"key2":[1,2,3]} # dic1 = dic #dic,dic1都指向字典的内存地址,理解为新的引用 # dic["key2"].append(5) # del dic["key"] # print(dic,dic1) # print(id(dic) , id(dic1)) # 总结:多个变量指向同一个内存地址,如果这个内存地址的数据类型是 # 不可变的数据类型的时候,会新开空间(字符串,数字) # 可变的数据类型时,会在原地进行修改 # 浅拷贝: # lst = [1,2,3] # lst1 = lst.copy() #复制,新的列表 # print(lst,lst1) # lst1.append(4) # print(lst,lst1) # print(id(lst),id(lst1)) # print(id(lst[0]),id(lst1[0]),id(1)) # lst = [1,2,[3,4]] # lst1 = lst[:] #只拷贝第一层 # print(id(lst),id(lst1)) # print(id(lst[-1]),id(lst1[-1])) # lst1[-1].append(5) # print(lst,lst1) # print(id(lst[-1]),id(lst1[-1])) # lst = [1,2,[3,4]] # lst1 = lst.copy() # lst[0] = 5 # lst[-1] = 8 # # lst[-1].append(8) # print(id(lst[-1]),id(lst1[-1])) # print(lst,lst1) # lst = [2,3,[4,5],257] # lst1 = lst # lst2 = lst[:] # lst2[2].append(257) # print(lst) # print(lst1) # print(lst2) # print(id(lst[2][-1]),id(lst[-1])) #再看看地址 # print(id(lst1[2][-1]),id(lst1[-1])) # print(id(lst2[2][-1]),id(lst2[-1])) # print(id(257)) # lst = [2,3,[4,5],6] # lst1 = lst # lst2 = lst[:] # lst2[-1] = [8,9] # lst1[-1].append([0]) #报错 # 深拷贝 # import copy #导入copy模块 # lst = [-111,-111,[3,4]] # lst1 = copy.deepcopy(lst) #深拷贝 # print(id(lst),id(lst1)) #外壳不一样 # print(id(lst[0]),id(lst1[0])) #不可变数据 --共用 # print(id(lst[1]),id(lst1[1])) #不可变数据 --共用,开始定义过是不同地址,复制出来的是用相同地址 # print(id(lst[-1]),id(lst1[-1])) #可变数据--新开辟空间 # print(id(lst[-1][-1]),id(lst1[-1][-1])) #里面的不可变数据 --共用 # 总结: # 赋值:多个变量名指向同一个内存地址 # 浅拷贝:只拷贝第一层的内存地址,可变和不可变的数据都是共用的,能看到是因为通过内存地址去查找值然后显示的 # 深拷贝:不可变数据,元素共用内存地址;可变数据类型开辟新的空间,不管嵌套多少层都是这样的原理(理解为互相不会影响)
false
c7b6b4ebcc3e902765e66b3cc75e24c8ae77de0f
zhanghuaisheng/mylearn
/Python基础/day005/05 字典的其他操作.py
1,656
4.15625
4
# 解构 # dic = {"key":1,"key1":2} # print(dic.items()) # print(list(dic.items())) # 字典是无序的,显示时按照定义的顺序显示(python3.6版本以上) # dic = {"key1":1,"key2":2,"key3":3} # for i in dic.items(): # print(i[0],i[1]) # a,b = 10,20 # print(a) # print(b) # a,b,c = "你好啊" # print(a) # print(b) # a,b,c = [1,2,3] # print(a) # print(b) # a,b,c = {"key1":1,"key2":2,"key3":3} # print(a) # print(b) # a,b,a = 10,20,30 # print(a) # print(b) # a,b,*c = [1,2,3,4,5,6] # *聚合,将多余的数据打包为列表(无论多少) # print(a,b,c) # dic = {"key1":1,"key2":2,"key3":3} # for i in dic.items(): # k,v = i # print(k,v) # for k,v in dic.items(): # print(k,v) # for i in [1,2,3,4]: #a,b,c,d = [1,2,3,4] # keys 获取所有的键 # values 获取所有的值 # items 获取所有的键和值 # 字典的嵌套: # house = { # 101:{1:{"pp":{"mou":["xiao","cdd"],"zzz":["xingda","er"]}, # 2:{"ll":["moya"]}}}, # 102:{}, # 103:{}, # 104:{}, # 105:{}, # 106:{}, # } # print(house) # 字典和列表的区别: # 字典查找内容时方便 # 字典查找速度快 # 键:可哈希 # dic = {"key1":"cccc"} # print(hash("666")) #如果你对这个变量不关心,或者以后也不会用到那么就用_ #比如说我要取出列表的头尾,对其他我并不关心是什么 # a=[23,3,4,2,5,5,31,6,4,77,8] # h,*_,t=a # print(h) # print(_) # print(t) # #输出 # # # #比如在用for循环,我不会用到比如说i这个用来迭代下标的变量,那么我也可以使用_ # for _ in range(10): # print ("欢迎你10次") # print(_)
false
a58e6f56ce415e844e76d9dd3d0732a92ef89298
jmurraymcguirk17/5th-year-work
/emailchallenge.py
238
4.15625
4
firstname = input("Enter your first name") surname = input ("What is your surname") year = int(input("What year is it")) if year > 2000: print(firstname,surname,year-2000) elif year < 2000 >1900: print(firstname,surname,year-1900)
true
68382aefca50ef21e0ae0f06c9cf1b7a8361ff27
jasminenoack/learning-python
/merge.py
756
4.1875
4
def merge_sort(array): if len(array) == 1: return array middle_index = len(array)/2 left = array[0:middle_index] right = array[middle_index:] sorted_left = merge_sort(left) sorted_right = merge_sort(right) return merge(sorted_left, sorted_right) def merge(array1, array2): sorted_array = [] while array1 and array2: if array1[0] < array2[0]: sorted_array.append(array1.pop(0)) else: sorted_array.append(array2.pop(0)) if array1: sorted_array.extend(array1) else: sorted_array.extend(array2) return sorted_array print merge_sort([1, 2, 3, 4, 5]) print merge_sort([4,5,1,2,3]) print merge_sort([1,3,4,8,5]) print merge_sort([11,10,9,8,7])
true
173f34c3cfcc5a29a21e0ffbd6def363aaed77fd
symonsajib/PracticePython_P
/Exercise25_Guessing Game Two.py
238
4.15625
4
Number = float(input("What's your number: ")) Modulus = Number%2 Modulus_four = Number%4 if Modulus == 0: print("Even Number.") if Modulus_four == 0: print("It's also multiple of 4 !!") else: print("Odd")
true
bcaf20607f98fe03bfcb2cf8b3d90fc26a2783bd
symonsajib/PracticePython_P
/Exercise11_PrimeNumber.py
445
4.25
4
def get_the_interger(): return int(input("Enter the number: ")) Number = get_the_interger() list_divisors = [] for elements in range(1,Number+1): if Number % elements == 0: list_divisors.append(elements) else: pass print("Divisors of the numbers are " + str(list_divisors) + " and ") if len(list_divisors) > 2: print("it's not a prime") else: print("It is a prime number!!")
true
4f3ca1a47bf783d1e68fcd57710500a62285bd40
vaibhavpalve1234/hackerrank
/type.py
985
4.125
4
#Write the calculator program which will take input from users two numbers #And will ask them to type #0 for addition #1 for subtraction #2 for multiplication #3 for division #And will print the result a=int(input('enter a nu.')) b=int(input('enter 2nd nu.')) print(a+b) print(a-b) print(a*b) print(a/b) print(a//b) #Explain range in python with various examples .. #range(start,end ) #range (start,end,step) #range(start: int, stop: int, step: int=...) #range(stop) -> range object #range(start, stop[, step]) -> range object #Return an object that produces a sequence of integers from start (inclusive) #to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1. #start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3. #These are exactly the valid indices for a list of 4 elements. #When step is given, it specifies the increment (or decrement). #eg. #range(1,5,1) #ans :-1 2 3 4 #What will be the result of #int(6.6) + int(4.9) = ? #ans is 10
true
cdfb7239ccd0755aee27e5228150a948f45f0424
jyanar/Projects
/numbers/numbernames.py
2,337
4.28125
4
""" Number Names Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). To implement this, we split the given number n into trigrams, such that each trigram represents a magnitude within the given number. e.g., 152245235 turns to 235, 245, 152 We place each trigram into a stack, starting with the first tigram (235), and then construct the pronunciations for each one until we have the finished pronunciation. """ ones = {'0': '', '1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five','6': 'six', '7': 'seven', '8': 'eight', '9': 'nine'} teens = {'10': 'ten', '11': 'eleven', '12': 'twelve', '13': 'thirteen', '14': 'fourteen', '15': 'fifteen', '16': 'sixteen', '17': 'seventeen', '18': 'eighteen', '19': 'nineteen'} tens = {'0': '', '1': 'ten', '2': 'twenty','3': 'thirty', '4': 'forty', '5': 'fifty', '6': 'sixty', '7': 'seventy', '8': 'eighty', '9': 'ninety'} magnitudes = {1: '', 2: 'thousand', 3: 'million', 4: 'billion'} # Construct the pronunciation of a trigram, given its magnitude. def construct_trigram(gram, magnitude): pronounced_gram = "" if len(gram) is 3: pronounced_gram += ones[gram[0]] + ' hundred ' if magnitude is 1: pronounced_gram += teens[gram[1] + gram[2]] else: pronounced_gram += tens[gram[1]] + '-' + ones[gram[2]] + ' ' + magnitudes[magnitude] + ', ' else: if magnitude is 1: pronounced_gram += teens[gram[1] + gram[2]] else: pronounced_gram += tens[gram[0]] + '-' + ones[gram[1]] + ' ' + magnitudes[magnitude] + ', ' return pronounced_gram def number_name(n): pronunciation = "" reversed_num = str(n)[::-1] i = 0 stack = [] while i < len(reversed_num): stack.append(reversed_num[i : i+3][::-1]) i += 3 current_magnitude = len(stack) while current_magnitude > 0: current_trigram = stack.pop() pronunciation += construct_trigram(current_trigram, current_magnitude) current_magnitude -= 1 return pronunciation print(number_name(132777523312))
true
ced554a51c935cbef183f59a720b7ecc898ac58a
icculp/holbertonschool-machine_learning
/math/0x05-advanced_linear_algebra/1-minor.py
2,532
4.3125
4
#!/usr/bin/env python3 """ Advanced Linear Algebra not allowed to im-port any module must be done by hand! """ def determinant(matrix): """ Calculates the determinant of a matrix matrix is a square list of lists whose determinant should be calculated Returns: the determinant of matrix """ if matrix == [[]]: return 1 if type(matrix) is not list or len(matrix) < 1 or\ not all(isinstance(x, list) for x in matrix): raise TypeError("matrix must be a list of lists") if not all(len(matrix) == len(x) for x in matrix): raise ValueError("matrix must be a square matrix") copy = list(map(list, matrix)) dim = len(matrix) if dim == 1: return matrix[0][0] elif dim == 2: return matrix[0][0] * matrix[1][1] - matrix[1][0] * matrix[0][1] else: for cur in range(dim): for i in range(cur + 1, dim): if copy[cur][cur] == 0: copy[cur][cur] = 1.0e-10 curScaler = copy[i][cur] / copy[cur][cur] for j in range(dim): copy[i][j] = copy[i][j] - curScaler * copy[cur][j] det = 1 for i in range(dim): det *= copy[i][i] return round(det) def minor(matrix): """ Calculates the matrix of minors matrix is a square list of lists whose determinant should be calculated Returns: the matrix of minors """ if type(matrix) is not list or len(matrix) < 1 or\ not all(isinstance(x, list) for x in matrix): raise TypeError("matrix must be a list of lists") if not all(len(matrix) == len(x) for x in matrix) or matrix == [[]]: raise ValueError("matrix must be a non-empty square matrix") copy = list(map(list, matrix)) dim = len(matrix) if dim == 1: return [[1]] elif dim == 2: return [[matrix[1][1], matrix[1][0]], [matrix[0][1], matrix[0][0]]] else: minors = [] mins = [] for i in range(dim): for j in range(dim): minor = matrix[:i] + matrix[i + 1:] for k in range(len(minor)): minor[k] = minor[k][: j] + minor[k][j + 1:] minors.append(minor) mins.append(minor) mm = [] mmm = [] for m in range(len(minors)): mm.append(determinant(minors[m])) if (m + 1) % dim == 0: mmm.append(mm) mm = [] return mmm
true
a075f1a2eca8e525028e2cb5b300e25a55b38af2
PacktPublishing/Python-Object-Oriented-Programming-Cookbook
/Chapter05/C05R01_SimpleStacks.py
2,670
4.34375
4
#!/usr/bin/env python """ The complete code of Ch. 5, Recipe 1 -- Implementing a simple stack """ from random import randint def print_line( leader:str, line:(str,None)=None, indent:int=0, body_start:int=28 ) -> str: """ Prints a formatted line of text, with a dot-leader between the lead and the line supplied """ output = '' if indent: output = ' '*(3*(indent-1)) + '+- ' output += leader if line: output = ( (output + ' ').ljust(body_start - 1, '.') + ' ' + line ) print(output) # - Create a basic list to use as a stack my_stack = [] print_line('my_stack (initially)', str(my_stack)) # - "push" values into the stack with my_stack.append my_stack.append(1) my_stack.append(2) my_stack.append(3) print_line('my_stack (pushed 1,2,3)', str(my_stack)) # - pop a value from the stack value = my_stack.pop() print_line('value (popped)', str(value), 1) print_line('my_stack (after pop)', str(my_stack)) # - Push a couple random values new_value = randint(49,99) my_stack.append(new_value) print_line('my_stack (pushed %s)' % new_value, str(my_stack)) new_value = randint(1,49) my_stack.append(new_value) print_line('my_stack (pushed %s)' % new_value, str(my_stack)) # - Pop all values from the stack while len(my_stack): value = my_stack.pop() print_line('value (popped)', str(value), 1) print_line('my_stack (after pop)', str(my_stack), 1) # - Using a UserList to more tightly define a list-based # stack-implementation from collections import UserList class stack(UserList): def push(self, value): self.data.append(value) def pop(self): return self.data.pop() def sort(self, *args, **kwargs): raise AttributeError( '%s instances are not sortable' % self.__class__.__name__ ) def __setitem__(self, *args, **kwargs): raise RuntimeError( '%s instances cannot be altered except by ' 'using push' % self.__class__.__name__ ) empty_stack = stack() print_line('empty_stack', str(empty_stack)) my_stack = stack([9,8,7,6,5,4,3,2,1]) print_line('my_stack', str(my_stack)) try: my_stack.sort() except Exception as error: print_line( 'my_stack.sort', '%s: %s' % (error.__class__.__name__, error) ) try: my_stack[4] = 23 except Exception as error: print_line( 'my_stack[4] = ', '%s: %s' % (error.__class__.__name__, error) ) try: my_stack[4:5] = [99,98] except Exception as error: print_line( 'my_stack[4:5] = ', '%s: %s' % (error.__class__.__name__, error) )
true
38842b4b522c256d5f230772204f9c8250047b45
Ivaylo2017/hello-world
/ceasar_cypher.py
2,251
4.125
4
''' The program encrypts messages using Ceasar cypher with key length specified by the user When the same key with opposite sign is used it can decrypt messages as well. Ceaser cypher is the simplest and oldest known transpositional cypher. It adds the key to the numerical representation of each character in the original text and returns the new charater ''' def ceasarcypher(string,n): #Function takes two args - message to be encrypted as str and key as int cypheredString = "" for character in string: if ord(character) in range(97,123): #perform conversion for small letters ASCII char 97-123 charNum = ord(character) + n if charNum > 122: newChar = chr(charNum - 26) elif charNum < 97: newChar = chr(charNum + 26) else: newChar = chr(charNum) #translate punctuation as is cypheredString += newChar elif ord(character) in range(65,91): #perform same actions for capital letters - ASCII char 65-91 charNum = ord(character) + n if charNum > 90: newChar = chr(charNum - 26) elif charNum < 65: newChar = chr(charNum + 26) else: newChar = chr(charNum) cypheredString += newChar else: cypheredString += character return cypheredString #return the cyphertext def main(): string = input("Please provide your message:\n") #Take string input for message from the user and verify if type(string) != str: print("{} is not string.".format(string)) else: n = input("Please enter the encryption/decryption key as integer: ") try: int(n) print("\n{} when encrypted is equal to {}.\n".format(string,ceasarcypher(string,n))) #Print the result using format and calling ceasarcypher function on the user input #Take int input fromm user and verify except ValueError: print("{} is not an integer. Exiting...".format(n)) if __name__ == "__main__": #Make sure output is only printed if function called from this file main()
true
8f6966ad7908ba34021b24ca0fa9184e0e971d02
undrwatr/100daysofcode
/day4-rockpaperscissors/rockpaperscissors.py
1,659
4.25
4
#play rock paper scissors against the computer import random choices = ["paper", "rock", "scissors"] computer_choice = random.choice(choices) print("Welcome to the Rock Paper Scissors duel") human_choice = input("Please choose your weapon: rock, paper, or scissors \n") # ascii art for the computer choice rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ---.__(___) ''' #print the users choice print("You chose " + human_choice) if human_choice == "rock": print(rock) elif human_choice == "paper": print(paper) else: print(scissors) #print the computers choice print("The Computer chose " + str(computer_choice)) if computer_choice == "rock": print(rock) elif computer_choice == "paper": print(paper) else: print(scissors) #The different options and the logic to go through them if computer_choice == human_choice: print("it's a tie") elif computer_choice == "rock" and human_choice == "scissors": print("The computer won") elif computer_choice == "paper" and human_choice == "scissors": print("You won") elif computer_choice == "scissors" and human_choice == "paper": print("The computer won") elif computer_choice == "scissors" and human_choice == "rock": print("You won") elif computer_choice == "rock" and human_choice == "paper": print("You won") elif computer_choice == "paper" and human_choice == "rock": print("The Computer won")
false
9fd7f6f332033e08d34422b92397fa5cd23a9a89
saxena-rishabh/Python-OOP
/Level 1 - Exercise 3.py
642
4.59375
5
''' Exercise 3: Write a Python program to implement the class chosen with its attributes. Also, represent Jack and Jill as objects of the class chosen initialize their attributes and display their details Create a parameterless constructor in which create the attributes with None Note: Verification is done only for class structure ''' class Employee: def __init__(self): self.ismarried = None jack = Employee() jack.name = 'jack' jack.ismarried = 'Yes' print("name: {} and married: {}".format(jack.ismarried, jack.name)) jill = Employee() jill.name = 'jill' print("name: {} and married: {}".format(jill.ismarried, jill.name))
true
f801399f7fdd5176190ff14168a874b1ea62e34d
realThinhIT/python-bootcamp
/chapter-3/exercise-calculator.py
595
4.125
4
""" CALCULATOR PROGRAM """ print("CALCULATOR PROGRAM") firstNumber = int(input("Input a = ")); operator = input("Please choose your operator (+, -, *, /): "); secondNumber = int(input("Input b = ")); result = None if operator == '+': result = firstNumber + secondNumber elif operator == '-': result = firstNumber - secondNumber elif operator == '*': result = firstNumber * secondNumber elif operator == '/': result = firstNumber / secondNumber else: print("Invalid operator!") if result is not None: print("Result:", firstNumber, operator, secondNumber, "=", result);
true
90f1a5864f55bd21a75bb4532a23937add253431
hschoi1/TIL
/misc/unittest_example.py
1,897
4.15625
4
# examples from https://docs.python.org/3/library/unittest.html import unittest """ TestCase class provides assert methods to check for and report failures some include: assertEqual(a,b) assertNotEqual(a,b) assertTrue(x) assertFalse(x) assertIs(a,b) assertIsNot(a,b) assertIsNone(x) assertIsNotNone(x) assertIn(a,b) assertNotIn(a,b) assertIsInstance(a,b) assertNotIsInstance(a,b) assertRaises(exc, fun, *args, **kwds) assertRaisesRegex(exc, r, fun, *args, **kwds) assertWarns(warn, fun, *args, **kwds) assertWarnsRegex(warn, r, fun, *args, **kwds) assertLogs(logger, level) """ class TestStringMethods(unittest.TestCase): def test_upper(self): self.assertEqual('foo'.upper(), 'FOO') # checks for an expected result def test_isupper(self): self.assertTrue('FOO'.isupper()) #verify a condition self.assertFalse('Foo'.isupper()) def test_split(self): s = 'hello world' self.assertEqual(s.split(), [1, 'hello', 'world']) # check that s.split fails when the separator is not a string with self.assertRaises(TypeError): # verify that a specific exception gets raised s.split(2) # setup method allows you to define instructions that will be executed before/after each test method if __name__ == '__main__': unittest.main() """ .F. ====================================================================== FAIL: test_split (__main__.TestStringMethods) ---------------------------------------------------------------------- Traceback (most recent call last): File "unittest_example.py", line 15, in test_split self.assertEqual(s.split(), [1, 'hello', 'world']) AssertionError: Lists differ: ['hello', 'world'] != [1, 'hello', 'world'] First differing element 0: 'hello' 1 Second list contains 1 additional elements. First extra element 2: 'world' - ['hello', 'world'] + [1, 'hello', 'world'] ? +++ """
true
a2e83ca87c21142d0d3ee483fdf018ce6954d3a8
rvladimir001/hello_world_python
/lesson 09/file/02 lesson.py
899
4.125
4
#Программа должна подсчитать количество строк, слов и букв в переданном ей файле. #Имя файла должно передаваться в качестве первого аргумента после имени самого #скрипта. Например, вызов скрипта в Linux через командную оболочку выглядит #примерно так: python3 words.py text.txt f = open('text.txt','r') countStr = 0 str1 = "" for line in f: countStr=countStr+1 str1 = str1+line lstline = len(str1.split()) #letters = len(str1) letters = 0 for k in str1: if k==" ": continue elif k=="\n": continue else: letters=letters+1 f.close() print("Строк: {} Слов: {} Букв: {}".format(countStr, lstline, letters))
false
86d935c563bf8d580847d647efe02cc5a5a01a57
felix-ogutu/PYTHON-PROJECTS
/Hostel Management System/menu.py
552
4.15625
4
def menu(): print("[1] Option 1") print("[2] Option 2") print("[0] Exit the program") menu() option = int(input("Enter the option:")) while option != 0: if option == 1: print("Option 1 has been selected") elif option == 2: print("Option 2 has been selected") else: print("Invalid choice has been selected") print() menu() option = int(input("Enter your option:")) print("Thank you for using this program. Goodbye")
true
eb46cac051f275833b757b020dca6d78bbdde959
AmitCodes/PythonProgramming
/5_4_Son_Father_Grandfather.py
1,738
4.375
4
# Here we need to store name of son's father and grandfather. # Using tha name of the son, one should be able to access father and grafather #Notify the user for the options available print("Enter one of the below choices to proceed further") print("1 - Insert new data" , "2 - Get the data" , "3 - Delete the data","4 - Exit") choice = int(input("Enter your choice ")) #Creating a basic dictinary which basically maintains the data relationsDict = {"Raj" : ("Sunil","Param")} while(choice != 4): if(choice == 1): son = input("Enter sons name") father = input("Enter fathers name") grandfather = input("Enter grand fathers name") if(son not in relationsDict): relationsDict[son] = (father,grandfather) else: print("relationship already exist") elif(choice == 2): son = input("Enter the sons name whose relationship needs to be printed") if(son in relationsDict): father,grandfather = relationsDict[son] print(son ,"father's name is",father,"and grandfather's name is",grandfather) else: print("This name does not exist") elif(choice == 3): son = input("Enter the sons name which needs to be deleted") if(son in relationsDict): del relationsDict[son] else: print("Son's name does not exist") elif(choice == 4): print("exiting the game") else: print("wrong choice , please select again") print("Enter one of the below choices to proceed further") print("1 - Insert new data", "2 - Get the data", "3 - Delete the data", "4 - Exit") choice = int(input("Enter your choice "))
true
66b475b2d036cf23e329b107a534a3296ee73792
sean-blessing/100-doc-python
/sec-018/day-18-167-turtle-draw-shapes/main.py
748
4.40625
4
from turtle import Turtle, Screen import random timmy_the_turtle = Turtle() timmy_the_turtle.shape("turtle") colors = ["blue", "red", "black", "green", "orange", "pink", "purple", "indigo", "yellow", "cyan"] #draw some shapes # 360 degrees / # of sides # 3 sided shape to 10 sided shape # each side is 100 length #-triangle - 3 sides, 120 degrees #-square - 4 sides, 90 degrees #-pentagon - 5 sides, 72 degrees # etc for num_sides in range(3, 11): print(f"drawing a {num_sides} sided object...") angle = 360 / num_sides color = random.choice(colors) timmy_the_turtle.color(color) for n in range(0,num_sides): timmy_the_turtle.forward(100) timmy_the_turtle.right(angle) screen = Screen() screen.exitonclick()
true
f8a9f7ec2b6b30d19619c57cf411c578d4035fb1
floryken/Ch.04_Conditionals
/4.1_Number_Analysis.py
853
4.46875
4
''' NUMBER ANALYSIS PROGRAM ----------------------- Create a program that asks the user for a number and then analyzes it to determine if it is: 1.) odd or even 2.) positive, negative or zero 3.) inclusively between -100 and +100 A small report will then be printed. Use the following to test your program: In: 32 Out: Test 1: Even Test 2: Positive Test 3: Inclusive In: -123 Out: Test 1: Odd Test 2: Negative Test 3: Exclusive ''' print("Welcome to the Number Analyzer") N=int(input("Enter any Number")) if N%2==0: print("This number is even") else: print("This number is odd") if N>0: print("This number is Positive") elif N==0: print("This number is a 0") else: print("This number is Negative") if N<-100 or N>100: print("This number is Exclusive") else: print("This Number is Inclusicve")
true
805024ff3e4b9263f9c6b6ca24695450a7cf40b2
KenlyBerkowitz/casino
/Bank.py
2,913
4.125
4
################## ### Bank Class ### ################## class Bank: def __init__(self): self.balance = 0 # private variable self.fundsAdded = 0 # used to determine how much you made # adds money to the account def addFunds(self): if self.balance == 0: print("\nPlease add money to your account in order to gamble") flag = True while flag: print("Enter 0 if you would not like to buy any tokens.\n") try: money = int(input("Enter the amount of tokens you would like to buy: ")) if money < 0: print("Please enter a positive amount") else: flag = False except: print("Invalid number.\n\nPlease enter a whole number") else: break self.balance += money self.fundsAdded += money # check to see if there is enough money to make the bet def wagerBalanceCheck(self, wager): if wager > self.balance: print("\nInvalid balance. \nPlease enter more money into your account.") flag = True while flag: charInput = input("Would you like to enter more funds into your account? [Y/N]: ") charInput = charInput.upper() if charInput == 'Y' or charInput == 'N': if charInput == 'Y': self.addFunds() # calls the addfunds function if the user wants to add funds on the spot flag = False else: flag = False else: print("Invalid input. Re-enter:") # adds wager if won def addWinnings(self, wager): self.balance += wager # subtract wager if lost def subtractFunds(self, wager): self.balance -= wager # prints account balance def getAccountBalance(self): print("Account Balance: ", self.balance) print("––––––––––––––––––––––\n") # prints winnings def winningStats(self): print("Winnings: ", self.balance - self.fundsAdded) print("––––––––––––––\n") # outputs balance and winnings to .txt file def readTextData(self): tf = "textBalanceData.txt" textFile = open(tf, "r") textFile.seek(0) self.balance = int(textFile.readline()) self.fundsAdded = int(textFile.readline()) textFile.close() # inputs balance and winnings to .txt file def writeTextData(self): tf = "textBalanceData.txt" textFile = open(tf, "w") textFile.seek(0) textFile.write(str(self.balance) + "\n") textFile.write(str(self.fundsAdded) + "\n") textFile.close()
true
80fe136af56238956d99e1dabaa903601ae813ec
mgstabrani/code-test-eduka
/no1.py
513
4.1875
4
#Function to decide whether a number is palindrom def isPalindrom(number): #Set a variable palindrom True palindrom = True #Convert integer to string strNumber = str(number) #Check palindrom for i in range(len(strNumber)): palindrom = palindrom and (strNumber[i] == strNumber[len(strNumber)-(i+1)]) #Return result return palindrom #Input number number = int(input()) #Decide whether a number is palindrom if(isPalindrom(number)): print("YES") else: print("NO")
true
a139d1994fe5b0ac98e1ebc2d0efe16d6838d54f
ArthurSpillere/AtividadesPython
/Exercicios/atividade3.py
1,782
4.21875
4
####################################################################################################### # Faça um Programa que peça os 3 lados de um triângulo. # O programa deverá informar se os valores podem ser um triângulo. # Indique, caso os lados formem um triângulo, se o mesmo é: equilátero, isósceles ou escaleno. ####################################################################################################### lado1 = float(input("Digite o primeiro lado do triângulo: ")) lado2 = float(input("Digite o segundo lado do triângulo: ")) lado3 = float(input("Digite o terceiro lado do triângulo: ")) #Esta condição só funciona se o lado1 foi o maior lado. #Você pode resolver isso adicionando as outras condições (lado2 >= lado1 + lado3...) #Ou você pode organizar os inputs para que o lado1 seja sempre o maior lado. #Ex: #lado1 = 2 #lado2 = 30 #lado3 = 1 #Resultado = "Triângulo escaleno" #porém estas dimensões não formam triângulo. if (lado1 >= lado2 + lado3): print("Não forma triângulo") else: if lado1 == lado2 and lado1 == lado3: print("Triângulo equilátero") #Nesta condição abaixo, não é necessário falar que ladoX != ladoY, pois na condição anterior ele já verifica se são todos iguais #Não é errado deixar bem claro a condição que você quer, porém é possível fazer uma comparação apenas se 2 dos lados são iguais elif lado1 == lado2 and lado1 != lado3 or lado2 == lado3 and lado2 != lado1 or lado1 == lado3 and lado1 != lado2: print("Triângulo isósceles") elif lado1 != lado2 and lado1 != lado3: print("Triângulo escaleno") #Organização do código (antes de eu bagunçar) está muito boa. #Apenas se atentar às validações. De resto está show!
false
cf045d1e702e00c99a257621ce6ec7e10a7b31ba
CodingDojoDallas/python_aug_2018
/Sujata Singhal/FLASK/Hello Flask/sujata.py
1,668
4.15625
4
from flask import Flask # Import Flask to allow us to create our app. app = Flask(__name__) # Global variable __name__ tells Flask whether or not we are running the file # directly, or importing it as a module. print(__name__) # Just for fun, print __name__ to see what it is @app.route('/') def hello_world(): return 'Hello!' # Return the string 'Hello World!' as a response. @app.route('/dojo') def dojo(): return "Dojo3!" @app.route('/say/<name>') # for a route '/hello/____' anything after '/hello/' gets passed as a variable 'name' def say(name): print(name) return "hello "+name @app.route('/users/<username>/<id>') # for a route '/users/____/____', two parameters in the url get passed as username and id def show_user_profile(username, id): print(username) print(id) return "username: " + username + ", id: " + id if __name__=="__main__": app.run(debug=True) # localhost:5000/say/flask - have it say "Hi Flask". Have function say() handle this routing request. # localhost:5000/say/michael - have it say "Hi Michael" (have the same function say() handle this routing request) # localhost:5000/say/john - have it say "Hi John!" (have the same function say() handle this routing request) # localhost:5000/repeat/35/hello - have it say "hello" 35 times! - You will need to convert a string "35" to an integer 35. To do this use int(). For example int("35") returns 35. If the user request localhost:5000/repeat/80/hello, it should say "hello" 80 times. # localhost:5000/repeat/99/dogs - have it say "dogs" 99 times! (have this be handled by the same route function as #6)
true
8597c4746c954bee0f2e9a8912128bc22911ba5e
rahulmis/DataStructures-And-Algorithm-Using-Python
/16.BinaryTreeLevelOrderTraversal.py
2,623
4.125
4
""" # Depth First Traversal ] 1 = Inorder = (left root right) 2 = preorder = ( root left right) 3 = postorder = (left right root) # Breath First Traversal 1. Level ORder Traversal 1 first.left.left.data / \ queue = [] 2 3 print(1,2,3,4,5,6,7) / \ / \ 4 5 6 7 inorder = 4,2,5,1,6,3,7 preorder = 1,2,4,5,3,6,7 postorder = 4,5,2,6,7,3,1 levelorder = 1,2,3,4,5,6,7 """ class node: def __init__(self,data=None): self.data = data self.left_node = None self.right_node = None class BinaryTree: def __init__(self): self.root = None def inorder(self): if(self.root == None): print("Tree Is Empty....") else: self._inorder(self.root) def _inorder(self,current): if current: self._inorder(current.left_node) print(current.data,end=" ") self._inorder(current.right_node) def preorder(self): if(self.root == None): print("Tree Is Empty....") else: self._preorder(self.root) def _preorder(self,current): if current: print(current.data,end=" ") self._preorder(current.left_node) self._preorder(current.right_node) def postorder(self): if(self.root == None): print("Tree Is Empty....") else: self._postorder(self.root) def _postorder(self,current): if current: self._postorder(current.left_node) self._postorder(current.right_node) print(current.data,end=" ") def levelorder(self): if(self.root == None): print("Tree Is Empty....") else: self._levelorder(self.root) def _levelorder(self,current): queue = [] queue.append(current) while len(queue)>0: node1 = queue.pop(0) print(node1.data,end=" ") if(node1.left_node is not None): queue.append(node1.left_node) if(node1.right_node is not None): queue.append(node1.right_node) ob1 = BinaryTree() first = node(1) second = node(2) third = node(3) fourth = node(4) fifth = node(5) sixth = node(6) seventh = node(7) ob1.root = first first.left_node = second first.right_node = third second.left_node = fourth second.right_node = fifth third.left_node = sixth third.right_node = seventh print('Inorder : ',end=" ") ob1.inorder() print() print("Preorder : ",end=' ') ob1.preorder() print() print("Postorder : ",end=' ') ob1.postorder() print() print("Levelorder : ",end=' ') ob1.levelorder()
false
98f6598f62bdacb9f120ce2c5c280718bd6615dd
pauloALuis/LP
/SeriesDeProblemas2/pb1.py
1,873
4.4375
4
#!/usr/bin/env python3 """ Avaliação 1 pb1.py 18/08/2021 """ import random #1.a) def l1(n: int = 10, l: list = []): """ method that creates a list with random numbers "n" times @param n: number of the length of the list @param l: list to append @return list with "n" random integer numbers between 0 and 1 inclusive """ if len(l) < n: l.append(random.randint(0,100)) return l1(n,l) return l print(l1()) #1.b) def list_sum(n: int = 0, l: list = l1(), sum: int = 0): """ method that sum the odds numbers in the list @param n : variable to scroll throught the list elements @param l : the list @param sum : the sum of the odd numbers in the list @param print_manager: variable to manage the print type @return the sum variable """ if n < len(l): if l[n] % 2 == 1: sum += l[n] #print the sum print(l[n], " + ", end="", flush=True) # makes print ion the same line on terminal return list_sum(n + 1, l, sum) print(" = ", sum) return sum print("soma dos nº impares da lista = ", list_sum()) #1.c) def f1(n: int): """ method that subtract the argument by 1 @param n : an integer @return n minus 1 """ return n-1 sum = list_sum() print(sum, "- 1 = ", f1(sum)) def sub_odd_elements(lista: list = [], n : int = 0, l1: list = l1()): """ recursive method that substract the odd elements of a list by 1 @param lista : list to return @param n : counter @param l1 : list of integers @return new list with odd numbers of "l1" subtracted by 1 """ if n < len(l1): if l1[n] % 2 == 1: lista.append(f1(l1[n])) else: lista.append(l1[n]) return sub_odd_elements(lista, n+1, l1) return lista print(sub_odd_elements())
true
1f9dedc88f9c292126d67103e60ed74c422874a7
pauloALuis/LP
/SeriesDeProblemas1/questaoteste.py
1,721
4.28125
4
""" questão teste 18/08/2021 """ import math #1) def string_vocals(s: str): """ calculates the index of first and last vocal in a string @param s : the string given @return the tuple with indexes of first and last vocals in the string s """ first_checked = False vocals = ["a", "e", "i", "o", "u"] result = ['', ''] for i in range(len(s)): for vocal in vocals: if s[i] == vocal: if not(first_checked): result[0] = str(i) first_checked = True result[1] = str(i) return tuple(result) print(string_vocals("abcde")) #2) def cartesiano_to_polar(t: tuple): l = ['', ''] x= int(t[0]) y = int(t[1]) r = pitagoras(x, y) arctan = 0 if x > 0: arctan = math.atan(y/x) elif x < 0 and y >= 0: arctan = math.atan(y/x) + math.pi elif x < 0 and y < 0: arctan = math.atan(y/x) - math.pi elif x == 0 and y > 0: print("entrou") arctan = math.pi / 2 elif x == 0 and y < 0: arctan = - math.pi / 2 else: arctan = "undifened" return (r, arctan) def pitagoras(x: str, y: str): return math.sqrt(math.pow(int(x), 2) + math.pow(int(y), 2)) print(cartesiano_to_polar(string_vocals("abcde"))) #3 def calc_coordenates_circ(raio: float, phi: float): return (math.cos(phi) * raio, math.sin(phi) * raio) print(calc_coordenates_circ(5.0, 0.25 * math.pi)) #45 graus #4 def calc_lower_vocals(s: str): i = 0 vocals = ["a", "e", "i", "o", "u"] for char in s: for vocal in vocals: if char == vocal: i +=1 return i print(calc_lower_vocals("aAbeeiI"))
true
640ca6298b2fc5da9d2259017c0ec2ab06555370
prerakpatelca/related-arrays-numpy
/Assignment1A.py
2,809
4.15625
4
"""This assignment uses Python lists and sets along with related arrays in numpy. This program gets the input from the user for 5 player names and then stores it in a Python sets from which it randomly selects the users name asks that player to enter 10 times quickly, where program stores the time difference between the first enter & the second enter and stores it in and Python arrays. At the end program prints out some useful information dervied from the dataset. Prerak Patel, Student, Mohawk College, 2020""" import numpy as np,time print("Enter 5 player names:") """ names variable has type of Python set that is where all the players names are going to be stored. """ names = set() """ Looping to get 5 unique player names while checking for the empty space and duplicate entries. """ while len(names) != 5: players = input().title().strip() if players in names: print("Name already entered") elif players == "": print("Name can't be empty") else: names.add(players) """ Converting Python Set into numpy array using array function to use numpy functions. """ names = np.array(list(names)) """ count variable is used to keep track of the index of the player whose input we are taking so that we can use that index to store the input into an array""" count = 0 """ allTurns variable is used to hold the player's individual array. """ allTurns = [] """ Looping through each player to take their input of 10 quick enters to get the time difference """ for player in names: eachTurn = [] print(player+"'s turn. Press enter 10 times quickly.") input() time1 = time.time() for n in range(9): input() time2 = time.time() eachTurn.append(time2-time1) time1 = time2 allTurns.insert(count,eachTurn) count +=1 allTurns = np.array(allTurns) """ calculating mean of the allTurns array by player's row. """ meanScore = allTurns.mean(axis=1) """ getting the index array after sorting the names array alphabatically. """ sortSequence = names.argsort() print("Names " + str(names[sortSequence]) + "\n" + "Mean times: " + str(meanScore[sortSequence]) + "\n" + "Fastest Average Time: "+ str(np.around(meanScore.min(),decimals=3)) + " by " + names[int(np.where(meanScore == meanScore.min())[0])] + "\n" + "Slowest Average Time: " + str(np.around(meanScore.max(),decimals=3)) + " by " + names[int(np.where(meanScore == meanScore.max())[0])] + "\n" + "Fastest Single Time: " + str(allTurns.min()) + " by " + names[int(np.where(allTurns == allTurns.min())[0])] + "\n" + "Slowest Single Time: " + str(allTurns.max()) + " by " + names[int(np.where(allTurns == allTurns.max())[0])] + "\n\n" + str(names[sortSequence]) + "\n" + str(np.around(allTurns, decimals=3)[sortSequence]))
true
7f179729e8d795263d3eef4858af9f594b32830c
QPromise/DataStructure-UsingPython
/8.排序/CH08_06.py
2,118
4.21875
4
# 合并排序法(Merge Sort) #99999为数列1的结束数字不列入排序 list1 = [20,45,51,88,99999] #99999为数列2的结束数字不列入排序 list2 = [98,10,23,15,99999] list3 = [] def merge_sort(): global list1 global list2 global list3 # 先使用选择排序将两个数列排序,再进行合并 select_sort(list1, len(list1)-1) select_sort(list2, len(list2)-1) print('\n第1个数列的排序结果为: ', end = '') for i in range(len(list1)-1): print(list1[i], ' ', end = '') print('\n第2个数列的排序结果为: ', end = '') for i in range(len(list2)-1): print(list2[i], ' ', end = '') print() for i in range(60): print('=', end = '') print() My_Merge(len(list1)-1, len(list2)-1) for i in range(60): print('=', end = '') print() print('\n合并排序法的最终结果为: ', end = '') for i in range(len(list1)+len(list2)-2): print('%d ' % list3[i], end = '') def select_sort(data, size): for base in range(size-1): small = base for j in range(base+1, size): if data[j] < data[small]: small = j data[small], data[base] = data[base], data[small] def My_Merge(size1, size2): global list1 global list2 global list3 index1 = 0 index2 = 0 for index3 in range(len(list1)+len(list2)-2): if list1[index1] < list2[index2]: # 比较两个数列,数小的先存于合并后的数列 list3.append(list1[index1]) index1 += 1 print('此数字%d取自于第1个数列' % list3[index3]) else: list3.append(list2[index2]) index2 += 1 print('此数字%d取自于第2个数列' % list3[index3]) print('目前的合并排序结果为: ', end = '') for i in range(index3+1): print(list3[i], ' ', end = '') print('\n') #主程序开始 merge_sort() #调用所定义的合并排序法函数
false
a497d60feb752d5e367244971f7177d4f3598609
wwtang/code02
/in.py
578
4.34375
4
""" Inheritance with class and instance variable""" class P: """ base class""" #class variable z = "hello" def set_p(self): self.x = "class P" def print_p(self): print(self.x) class C(P): def set_c(self): self.x = "class C" def print_c(self): print(self.x) class Mine: """ another class to demostrate private variable and methods""" def __int__(self): self.x = 2 #private variable symboled by the leading double underscore self.__y =3 def print_y(self): print self.__y
true
d0718ae9939fd63b10d1d2707d5d6acd5f15a418
wwtang/code02
/greatheapsort.py
1,495
4.5
4
"""great heap sort functions used in heap sort: max_heapfy build a heap heap is a array, the essential algorithm here is the realtion between different elements """ def max_heapfy(array, k, last):#heapfy works among three elenment left = 2*k +1 right = 2*k +2 # find the largest element in the unit heap if left <=last and array[left] > array[k]: largest = left else: largest = k if right <= last and array[right] > array[largest]: largest = right if largest !=k: array[largest], array[k] = array[k], array[largest] max_heapfy(array, largest, last) def build_heap(array, last): n = last/2 for i in range(n, -1, -1): max_heapfy(array, i, last) return array def heap_sort(array): first = 0 last = len(array) -1 build_heap(array, last) print "heap: ", array #for i in range(0, last): for i in range(last, -1,-1):#swap from the end of the array, the end is the largest, i is the last array[first], array[i] = array[i], array[first] max_heapfy(array, first, i-1)# i-1 is the last element in the array that needs to be heapfied return array def main(): lst = [16,4,10,14,7,9,3,2,8,1] #print"build heap: ", build_heap(lst,0,len(lst)-1) #print "create_heap: ", create_heap(lst,0,len(lst)-1) #print "create_heap1: ", create_heap1(lst,0,len(lst)-1) print "sort:", heap_sort(lst) if __name__=="__main__": main()
true
11a9d0967867991f1693902b588629022b633a99
wwtang/code02
/sortAlgorithm/insertsort.py
675
4.1875
4
def insert_sort(list2):#compare the current element with its prior element, if smaller, insert it at the left of them for i in range(1,len(list2)):#begin from the second element save = list2[i] # save the current elem, use to compare with its prior elements j = i# j here used as helper index while j >0 and list2[j-1] > save:# chek the the current element with all the prior elements one by one list2[j] = list2[j-1]# j -=1#backloop to the beginng list2[j] = save#here j is the 0, the result of while loop return list2 list2 = [3, 7,4, 9, 5, 2, 6, 1] if __name__=="__main__": print insert_sort(list2)
true
c5c18b8138ca983cb10130d8cd6945e99ff1310e
wwtang/code02
/craking/106.py
1,559
4.125
4
""" write a method to find a given number in double sorted matrix arr = [[15, 20, 40,85],[20,35,80,95],[30,55,95,105],[40,80,100,120]] find 55 method 1: apply binary search to each row """ def binarySearch(arr, target, first ,last): if last < first or len(arr) <0 or target == None: return None mid = (first + last)/2 if arr[mid] == target: return mid elif target < arr[mid]: return binarySearch(arr, target, first, mid-1) else: return binarySearch(arr, target, mid+1, last) def findElem(arr, target, height, length): """ height is the number of list in arr, and the length is the length of list""" if arr == None or len(arr) <1 or target == None: return None for i in range(height+1):# height = len(arr) -1, and range(height) = len(arr)-1-1 j = binarySearch(arr[i], target, 0, length) if j: return (i,j) return none def findElem2(arr, target, row, col): """ row = len(arr) -1 col = len(arr[0]) -1 """ if arr == None or len(arr) < 1 or target == None: return None i= 0 j = col while i <=row and j >=0: if arr[i][j] == target: return (i,j) elif target > arr[i][j]: i +=1 else: j -=1 return None def main(): arr = [[15, 20, 40,85],[20,35,80,95],[30,55,95,105],[40,80,100,120]] height = len(arr)-1 length = len(arr[0]) -1 print findElem(arr, 55, height, length) print "The second method:" print findElem2(arr, 55, height, length) # arr1 = [15, 20, 40,85] # print binarySearch(arr1, 40, 0, len(arr1)-1) # print binarySearch(arr1, 85, 0, len(arr1)-1) if __name__=="__main__": main()
true
de78d0235a44e0733bd4c7ff50fd71cbc09a75fc
wwtang/code02
/insert_sort.py
985
4.21875
4
#used for heap sort def max_heapfy(array, k, last): left = 2*k +1 right = 2*k +2 if left<= last and array[left] > array[k]: largest = left else: largest = k if right <=last and array[right] > array[largest]: largest = right if largest != k: max_heapfy(array, largest, last) def build_heap(array): last = len(array)-1 n = last/2 for i in range(n, 0,-1): max_heapfy(array, i, last) def heap_sort(array): last = len(array) -1 build_heap(array) for i in range(last, -1, -1): array[0], array[i] = array[i], array[0] # swap the first with last element, max_heapfy(array, 0, i-1)# now reduce the heapfy size by 1 return array def main(): import random array = [random.randint(100,999) for i in range(8)] print array print "sorted_array: ", sorted(array) print "heap_sort: \n", heap_sort(array) if __name__=="__main__": main()
true
62e4bd0cbc8e8f1dc8cb0fbb9f7a9ae2700b5c54
wwtang/code02
/craking/eightqueens2.py
1,854
4.15625
4
""" Eight queens problem, In python there is no need to initialize an avari """ counter = 0 # def isValid(state,nextx): # """ # (list, int) --> boolean # state is list to represent the state history of the queens, the length represent the current row. # nextx is the position is the new row, from 0 to 8 # return True, if conflict, else False # """ # nexty = len(state) # for i in range(nexty): # if abs(nextx-state[i]) in (0, nexty-i): # return True # return False # the ith row, kth col def find(i,k,q): """ (int, int, list) -->boolean i is the ith row k is the kth col q is a list """ j = 0 while j <i: #if q[j] == k or (i-j) == abs(q[j]-k): #print "the current position is (%s, %s)"%(i,k) if abs(q[j] - k) in [0, i-j]: return False j +=1 #print "The valid position is (%s, %s)"%() return True def placeQ(r, n,q): """ r is the current row, n is the grid size. q is the state list result is a list to hold valid path """ #print "Current row is %s"%r if r == n: #print q printOut(q) #traceback to the 0th row, else: for i in range(n):#for every position in row, #print "Current checking position is (%s, %s)"%(r, i) if find(r,i,q): #print "Valid position (%s, %s)"%(r, i) q[r] = i #print "q is: %s" %q placeQ(r+1,n,q) def printOut(chessboard): chess = [] for x in range(len(chessboard)): row = [] for y in range(len(chessboard)): if chessboard[x] == y: row.append("Q") #print "Q" else: #print "X" row.append("X") chess.append(row) global counter counter +=1 print "the %s solution" %counter print "------------------------" print for r in chess: print r print print "------------------------" def main(): n = 4 q= [None]*n #paths = placeQ(0,n,q) placeQ(0,n,q) if __name__=="__main__": main()
false
91f6f93546e8240aff32445f1e68c11ccfe19d83
wwtang/code02
/tem.py
214
4.25
4
color = raw_input('please select the color: ') if color == "white" or color == "black": print "the color was black or white" elif color > "k" : print "the color start with letter after the 'K' in alphabet"
true
74bcfc187e93a5400fc008128e2ada59e97a3c83
wwtang/code02
/fibcache.py
872
4.125
4
"""fibonacci numbers: cache the intermediate result""" import time #Cached method def fib1(n): cache_dict = {0:0,1:1} if n == 0: return 0 if n == 1: return 1 if n in cache_dict: return cache_dict[n] cache_dict[n] = fib1(n-1) + fib1(n-2) return cache_dict[n] #Non Cached method def fib2(n): if n == 0: return 0 if n ==1: return 1 else: return fib2(n-1) +fib2(n-2) def main(): i = 30 start1 = time.clock() print fib1(i) end1 = time.clock() runtime1 = end1 - start1 print runtime1, "seconds" start2 = time.clock() print fib2(i) end2 = time.clock() runtime2 = end2 - start2 print runtime2, "seconds" print "The no cache method takes ", runtime2 - runtime1, " more seconds than the cached method." if __name__=="__main__": main()
true
b00ca8a133d0893365e9f5a26683e0475ea0d508
wwtang/code02
/findparentheses.py
2,691
4.21875
4
"""find all the valid parentheses input: number of pairs of parentheses output : a list of valid parenthese, left and right are separated. each function implement the most basic functionality The first algorithm takes o(n!) n' factorial, which is the b """ # i is the index of the open parentthese # string is a list def insertParenthese(string, i): return string[:i+1] +["("]+[")"]+string[i+1:] def findParenthese(num): parenthese = [] if num == 0: return [[]] if num == 1: parenthese = [["(",")"]] return parenthese else: pre_result = findParenthese(num-1) # item is a list for item in pre_result: # element of the list for i in range(len(item)): if item[i] =="(": new_result = insertParenthese(item,i) # remove the duplicated item if new_result not in parenthese: parenthese.append(new_result) # add the "()" at the beigning if "()" not there if ["(",")"] + item not in parenthese: parenthese.append(["(",")"]+item) return parenthese # more efficient method def addParen(result_list, pro_list, openParen, closeParen, count): # no result_list = [] here, every time call of addParen list set to empty #can not put str = [] here, every time str update to [] if openParen < 0 or closeParen > openParen: return False if openParen ==0 and closeParen ==0: result_list.append(pro_list) print result_list, "result list " return result_list else: # add left Paren if openParen > 0: pro_list.append( "(") print pro_list print"we are here ***" addParen(result_list, pro_list, openParen -1, closeParen, count +1) print openParen -1, closeParen," paren numbers" print count,"count" #add right Paren if closeParen > openParen: pro_list.append( ")") print "we are here *******" addParen(result_list, pro_list,openParen, closeParen-1, count+1) def generateParen(num): result_list = [] pro_list = [] addParen(result_list, pro_list, num,num,0) print "come here" return result_list def main(): print findParenthese(0) print findParenthese(1) print findParenthese(2) print "for 3" p = findParenthese(3) for elem in p: s = "".join(elem) print s print "test of the second methods" print generateParen(2) if __name__=="__main__": main()
true
435e27045634d138b3a888b727cc4687c0209327
wwtang/code02
/spellchecker.py
1,093
4.15625
4
""" Exercise problem: "given a word list and a text file, spell check the contents of the text file and print all (unique) words which aren't found in the word list." """ #function to generate a dict according the words from the dict file def dict_list(filename): dict_list = [] f = open(filename) data = f.readlines() for line in data: for word in line.strip().split(" "): dict_list.append(word) dict_set = set(dict_list) return dict_set #read the words from the spell_check needed file into words list, which is used for checking def words_list(words_filename): dict_list = [] f = open(words_filename) data = f.readlines() for line in data: for word in line.strip().split(" "): dict_list.append(word) return dict_list #unique words list def main(): uniqueWords = [] filename = "/Users/qitang/Desktop/dict.txt" dictionary = dict_list(filename) words_filename = "/Users/qitang/Desktop/words.txt" words = words_list(words_filename) for word in words: if word not in dictionary: uniqueWords.append(word) print uniqueWords if __name__=="__main__": main()
true
794f77df1b28dcac4af885f980e99619f0bec303
choidslab/PY4E
/ex_08/ex_08_02.py
312
4.125
4
filename = input("Enter a filename:") fhand = open(filename, 'rt') count = 0 words = list() for line in fhand: if line.startswith("From: "): count += 1 words.append(line.split()[1]) for word in words: print(word) print("There were", 27, "lines in the file with From as the first word")
true
17e59f50c4e02267a9347366ea0ca9e597cf01e1
13re/Python3_Assignments
/numberedlist.py
562
4.28125
4
# write a function that takes a list as an argument # and prints out all the values in the list along with the index # # Example: [apple, banana, organge] # #1 is apple # #2 is banana # # then try: # 1st element in the list is apple # 2nd element in the list is banana meals = ["breakfast", "lunch", "dinner", "dessert"] listlength = len(meals) i = 0 while i < listlength: a = i i = i+1 #counter print("#",i,"meal is", meals[a]) #|PRINT__________________ #| # 1 meal is breakfast #| # 2 meal is lunch #| # 3 meal is dinner #| # 4 meal is dessert
true
3163aefcb72042d0a1bbd54c6fe05eb780aab9bb
AidenLong/rgzn
/workspace/python-base/com/me/day2/string.py
1,195
4.28125
4
# 去除空格 s = ' abc de ' print(s.strip()) print(s.lstrip()) print(s.rstrip()) print(s) # 字符串连接 print('abc_' + 'defg') s = 'abcdefg' s += '\nlll' print(s) # 大小写 s = 'abc def' print(s.upper()) print(s.upper().lower()) print(s.capitalize()) # 位置和比较 s_1 = 'abcdef' s_2 = 'abdefg' print(s_1.index('bcd')) try: print(s_2.index('bcd')) except ValueError: print('ValueError: substring is not found') # cmp 函数被python3移除了 print(s_1 == s_2) print(s_1 < s_2) print(s_1 > s_2) # 分割和连接 s = 'a,b,c,d' print(s.split(',')) list2 = s.split(',') print('-'.join(list2)) # 常用判断 s = 'abcdef' print(s.startswith('ab')) print(s.endswith('ef')) print('abcd12'.isalnum()) print('\tabcd12'.isalnum()) print('abc'.isalpha()) print('abc123'.isalpha()) print(' '.isspace()) print('aaa111'.islower()) print('111AA'.isupper()) print('Avv Bdd'.istitle()) # 数字到字符串 print(str(5)) print(str(5.)) print(str(-5.23)) # 字符串到数字 print(int('122')) print(int('122', 8)) print(float('-122.23')) # 字符串到list s = 'aaa111' print(list(s)) # 格式化字符串 print('Hello %s!' % 'world') print('%d-%.2f-%s' % (4, -2.3, 'hello'))
false
f389c062cc7cd2b7d391118158543ef2be6c6cce
ultranaut/mathematics
/arithmetic/addition.py
829
4.125
4
"""Addition These will only work for the natural numbers. """ from utils import * def naive_r(augend, addend): """A recursive definition of addition. (http://en.wikipedia.org/wiki/Addition#Natural_numbers) """ if addend == 0: return augend return inc(naive_r(augend, dec(addend))) # in theory this is iterative, but Python lacks tail recursion def naive_i(augend, addend): if augend < addend: augend, addend = addend, augend if addend == 0: return augend return naive_i(inc(augend), dec(addend)) # gotta do it in a loop def naive_i2(augend, addend): if augend < addend: augend, addend = addend, augend while addend > 0: augend, addend = inc(augend), dec(addend) return augend def add(term1, term2): return naive_i2(term1, term2)
true
c85ee6d80f2ef97c2e4dacd2455b1e225c1f980b
BrianBalayon/projecteuler
/problem1.py
713
4.5
4
''' Problem 1: Multiples of 3 and 5 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 main(): threes = 0 fives = 0 for i in range(1, 1000): ''' Using else-if to avoid adding the same number twice. Ex. 15, 75, and 150 are multiples of 3 and 5. ''' if not i % 3: threes += i elif not i % 5: fives += i print("Sum of Multiples of 3: ", threes) print("Sum of Multiples of 5: ", fives) print("Combined sum of both: ", threes+fives) if __name__ == "__main__": main()
true
0423067280842795937912f7b95c98d7b162c217
becclest/206-repo
/lecture/Homework/ttt.py
2,962
4.3125
4
python ttt.py def generateBoard(board) #Generates 3 x 3 matrix of board that is passed # Uses a list of 9 strings print (' | | ') print ('' +board[6]+ ' | ' +board[7]+ ' | ' +board[8] ) print (' | | ') print ('-----------') print (' | | ') print ('' +board[3]+ ' | ' +board[4]+ ' | ' +board[5] ) print (' | | ') print ('-----------') print (' | | ') print ('' +board[0]+ ' | ' +board[1]+ ' |' +board[2] ) print (' | | ') board = [SW, SC, SE, CW, C, CE, NW, NC, NE] # The player decides whether to be X or O # Returns a list with the player's selection first, other as the second # Needs to be able to confirm player's selection using verification below def inputPlayerType letter = str(input("Would you like to be X or O? ")).upper() valid_letters = ['X', 'O'] if letter != 'X' or letter != 'O': letter = input("Please type the right symbol (X or O): ") if letter == 'X': return valid_letters else: return valid_letters[::-1] #Checks to see if list element is a valid move and if there's no one in that # place. # Given the board and player's moves, returns True if the player has won. def winning_moves(board, letter): #Across the top row (board[6] == letter and board[7] == letter and board[8] == letter) #Across the middle row (board[3] == letter and board[4] == letter and board[5] == letter) #Across the bottom row (board[0] == letter and board[1] == letter and board[2] == letter) #Down the left column (board[6] == letter and board[3] == letter and board[0] == letter) #Down the middle column (board[7] == letter and board[4] == letter and board[1] == letter) #Down the right column (board[8] == letter and board[5] == letter and board[2] == letter) #Across the left top corner to the bottom right (board[6] == letter and board[4] == letter and board[2] == letter) # Across the right top corner to the bottom left corner (board[8] == letter and board[4] == letter and board[0] == letter) # Make a duplicate of the board list and return it the duplicate. # Allows players to view the board as the game is being played def getBoardCopy(board): duplicateBoard = [] for i in board: duplicateBoard.append(i) print "CURRENT BOARD: " return duplicateBoard # User input to allow moves on the board def makeMove (Board, Coordinate, Letter): Board[Coordinate] = Letter # Checks if the matrix element is open or if there's a letter at that Coordinate def check_free_space(Board, Coordinate): return Board[Coordinate] == ' ' #Lets the player type in their move based on the coordiante def getPlayerMove(Board): Move = ' ' while Move not in board[].split() or not check_free_space(board, int(move)): print ("Please select your next move: ") Move = Input() return int(move)
true
73094afa611c90d92a0d9b4d4b99fd2f36b6dff0
DanielW1987/python-basics
/python_007_oop/Interfaces.py
1,501
4.25
4
from abc import abstractmethod, ABC # In Python, an interface is a class that has only abstract methods class Drivable(ABC): @abstractmethod def drive(self) -> None: pass class BMW(ABC, Drivable): def __int__(self, maker: str, model: str, year: int): self.__maker = maker self.__model = model self.__year = year @abstractmethod def start(self) -> None: pass @abstractmethod def stop(self) -> None: pass class ThreeSeries(BMW): def __init__(self, maker: str, model: str, year: int, cruise_control_enabled: bool): super().__int__(maker, model, year) # invoking super constructor self.__cruise_control_enabled = cruise_control_enabled def start(self) -> None: print("Three series start") def stop(self) -> None: print("Three series stop") def drive(self) -> None: print("Three series is being driven") class FiveSeries(BMW): def __init__(self, maker: str, model: str, year: int, parking_assist_enabled: bool): super().__int__(maker, model, year) # invoking super constructor self.__parking_assist_enabled = parking_assist_enabled def start(self) -> None: print("Five series start") def stop(self) -> None: print("Five series stop") def drive(self) -> None: print("Five Series is being driven") three_series: BMW = ThreeSeries("BMW", "328i", 2018, True) three_series.start() three_series.stop()
true
7501f61d1f3adf9b963818be06103dba086d0aa8
DanielW1987/python-basics
/python_007_oop/AbstractClasses.py
1,343
4.28125
4
from abc import ABC, abstractmethod # abstract classes have to inherit from ABC (ABstract Class) class BMW(ABC): def __int__(self, maker: str, model: str, year: int): self.__maker = maker self.__model = model self.__year = year def start(self) -> None: print("Starting the car") def stop(self) -> None: print("Stopping the car") # abstract method with decorator and pass keyword @abstractmethod def drive(self) -> None: pass class ThreeSeries(BMW): def __init__(self, maker: str, model: str, year: int, cruise_control_enabled: bool): super().__int__(maker, model, year) # invoking super constructor self.__cruise_control_enabled = cruise_control_enabled def start(self) -> None: super().start() print("Button start") def drive(self) -> None: print("Three Series is being driven") class FiveSeries(BMW): def __init__(self, maker: str, model: str, year: int, parking_assist_enabled: bool): super().__int__(maker, model, year) # invoking super constructor self.__parking_assist_enabled = parking_assist_enabled def drive(self) -> None: print("Five Series is being driven") three_series: BMW = ThreeSeries("BMW", "328i", 2018, True) three_series.start() three_series.stop()
false
7bd30bc15e44a0c2cb7bdf9d91d9e562e1553f1a
DanielW1987/python-basics
/python_exercises/GradingApplication.py
602
4.28125
4
mathsPoints: int = int(input("Enter the math points: ")) physicsPoints: int = int(input("Enter the physics points: ")) chemistryPoints: int = int(input("Enter the chemistry points: ")) if mathsPoints >= 35 and physicsPoints >= 35 and chemistryPoints >= 35: averageGrade: float = (mathsPoints + physicsPoints + chemistryPoints) / 3 finalGrade: str = "" if averageGrade <= 59: finalGrade = "C" elif averageGrade <= 69: finalGrade = "B" else: finalGrade = "A" print("The final grade is '{}'".format(finalGrade)) else: print("I'm afraid you failed.")
true
466c10fdd9a0e3a3cabf20b555ae91c5ae2f5589
Panda3D-public-projects-archive/pandacamp
/Handouts 2012/src/2-1 Reactive Programing/03-reactions.py
1,547
4.1875
4
from Panda import * # You attach a reaction to a model by giving the triggering event and the name of the reaction function. # exitScene is a built in reaction function # This tells the panda to exit the scene when the right mouse button is pressed (lbp). p = panda() p.react(rbp, exitScene) # This reaction function is used to respond to a mouse click by launching a soccer ball. # The first parameter is the model that is reacting - the now function is used to find the current # value of a signal like the position. The soccer ball moves up from the position of the model. # The value comes from the event that causes the reaction. lbp doesn't generate a value so we ignore it. def launch(model, value): pos = now(model.position) soccerBall(position = pos + integral(P3(0,0,4)), size = .05) p.react(lbp, launch) # Activities # Write a velocity controller that uses the arrow keys to move the panda left and right # Make the panda face left or right depending on which way he's going # Make the soccer ball come up from the top of the panda instead of the bottom # Launch a ball on left mouse or on the space key # Change the launch event to generate a color and use this to change the color of the soccer ball # Launch a blue ball with the space key and a red one with the left button # You can create reactions that are not attached to models. Create a reaction function # which launches a model into the scene that moves from left to right. # Launce this model when the space key is pressed. start()
true
75f34c99889810056721f0c316918dcdc306a99a
Panda3D-public-projects-archive/pandacamp
/Handouts/src/3-1 Interpolation and Collections/03-interpolation.py
567
4.21875
4
# Vectors and interpolation/03-interpolation.py from Panda import * # How do you interpolate between two points? # If the panda is at p0 at t = 0 and p1 at t = 1, # what equation would make it move from p0 to p1 smoothly? # what happens when t is not between 0 and 1? # What if you want to make it arrive at p1 when t = 2 instead of 1? p0 = P3(1,1, 1) p1 = P3(2, 0, -1) soccerBall(position = p0, size = .05, color = red) soccerBall(position = p1, size = .05, color = blue) t = slider(min = -1, max = 2, init = 0) text(t) p = text(p) panda(position = p) start()
true
2cb6f9a96a248fcce02372ea48612a112b8ee2c4
sean-attewell/Learn-Python-3-The-Hard-Way
/lpthw/ex14.py
1,174
4.4375
4
from sys import argv script, user_name, size = argv # Now if we want to make the prompt something else, we just change it in # this one spot and rerun the script. # We've used f-string to make the prompt to type tell you what the script # You're in is called and your username in brackets. Kind of like # Powershell does. prompt = f'{script} ({user_name})> ' print(f"Hi {size} {user_name}, I'm the {script} script.") print("I'd like to ask you a few questions.") print(f"Do you like me {user_name}?") likes = input(prompt) print(f"Where do you live {user_name}?") lives = input(prompt) print("What kind of computer do you have?") computer = input(prompt) print(f""" Alright, so you said {likes} about liking me. You live in {lives}. Not sure where that is. And you have a {computer} computer. nice. You're {size}. """) # Apparently nobody likes scripts that prompt you! So argv is more # common... # So you want command line arguments to be the main way people interact # with it rather than prompts # If you want to convert an input to an integer with int() # better to do it straight away, rather than within the f string braces
true
fdbc64dde1460d7f79a084e65a74ab9f065b4394
sean-attewell/Learn-Python-3-The-Hard-Way
/lpthw/ex40_modules.py
1,683
4.59375
5
# Modules, Classes, and Objects # Dictionaries map one thing to another: mystuff = {'apple': "I AM APPLES!"} print(mystuff['apple']) # Keep this idea of get X from Y in your head, and now think about modules. # You import a Python file with some functions or variables in it # And you can access the functions or variables in that module with the # . (dot) operator. ######################## # Imagine I have a module that I decide to name mystuff.py and I put a # function in it called apple, and a variable called tangerine. # This goes in mystuff.py def apple(): print("I AM APPLES!") tangerine = "Living reflection of a dream" # I can then use the module mystuff with import and then access the apple # function: # import mystuff mystuff.apple() # Have to reference where the apple function comes from # I think before you were importing 'thing as thing' to make it shorter print(mystuff.tangerine) # Let's compare syntax: mystuff['apple'] # get apple from dict mystuff.apple() # get function apple from the module mystuff.tangerine # same thing, it's just a variable # This means we have a very common pattern in Python: # 1. Take a key=value style container. # 2. Get something out of it by the key’s name. # In the case of the dictionary, the key is a string and the syntax is # [key]. # In the case of the module, the key is an identifier, and the syntax # is .key. Other than that they are nearly the same thing. container['key'] container.key() cointainer.key # You can think about a module as a specialized dictionary that can store # Python code so you can access it with the . operator
true
00bee0baa2e4c5cdca2eebeb157fd2b49bab4092
sean-attewell/Learn-Python-3-The-Hard-Way
/lpthw/ex9.py
1,224
4.40625
4
# Here's some strange stuff, remember to type it exactly days = "Mon Tue Wed Thu Fri Sat Sun" # So here \n makes the next bit start on a new line months = "Jan\nFeb\nMar\nApr\nMay\nJune\nJul\nAug" # It's an escape sequence. It's a way to add formatting in a way that # doesn't break python's processing of the string. # Special characters, tab, vertical space etc # After a backslash things are processed as either a special character # (like \n), or if it's not a special character, just the character like \" print("Here are the days:", days) print("Here are the months:", months) # using """ seems to put things on different lines automatically # If you code them that way. Also indents, all without escape sequences." print(""" There's something going on here. With the three double-quotes. We'll be able to type as much as we like. Even 4 lines if we want to, or 5, or 6. """) # You can put double and single quotes inside tripple quotes! # It will also take on any tabbed space automatically # (no need for \t) # If you open with two quotes, it just thinks an empty string has closed # And then goes into python mode, trying to interperet your string as # python
true
e78e69c91f5758be66de6103a0c0fab40d55b386
sean-attewell/Learn-Python-3-The-Hard-Way
/lpthw/ex34.py
1,245
4.5
4
# 1st second third are ”ordinal” numbers, # because they indicate an ordering of things # A cardinal number is a number such as 1, 3, or 10 that tells you # how many things there are in a group but not what order they are in # Programmers, however, can’t think this way because they can pick any # element out of a list at any point. To programmers, the list of animals # is more like a deck of cards. # This need to pull elements out of lists at random means that they need # a way to indicate elements consistently by an address, or an ”index”. # This kind of number is a "cardinal" number and means you can pick at # random, so there needs to be a 0 element. # you translate this "ordinal" number to a "cardinal" number by # subtracting 1. # The "third" animal is at index 2 and is the penguin # Famous OFF BY ONE error # Don't have to worry when doing a for loop. # for bug in bugs # Can do negative indexes to start from the end of the list # 0 and -0 are the same thing though. I guess because 0 can't be negative. hello = "Hello world how are you today" new_list = hello.split(' ') print(new_list[2]) # this prints how (the third word) print(new_list[-1]) # This prints "today"
true
28c88173d34a54b368ef2ada59480d76ba43a2e4
nasreldinas/-
/TA28.py
1,860
4.46875
4
#КОД ПРИМЕРА «Ветвления и оператор выбора» #номер версии: 1.0 #имя файла: TA28.py #автор и его учебная группа: A. nasreldin, ЭУ-135 #дата создания: 27.02.2021 #дата последней модификации: 04.03.2021 #описание: Ветвления и оператор выбора #версия Python:3.9.2 #Составить алгоритм и программу для реализации логических операций «И» и «ИЛИ» для двух переменных. import random time = ("morning", "noon", "evening", "night") TIME = random.choice(time) print("Time: " + str(TIME)) season = ("autumn" , "winter" , "spring" , "summer") SEASON = random.choice(season) print ("Season: " + str(SEASON) + '\n') print("WEATHER FORECAST:" + '\n') if (TIME == "night" and SEASON == "autumn") or (TIME == "night" and SEASON == "winter") or (TIME == "night" and SEASON == "spring") or (TIME == "evening" and SEASON == "winter"): print("It's very cold outside!!!") elif (TIME == "noon" and SEASON == "winter") or (TIME == "morning" and SEASON == "winter") or (TIME == "evening" and SEASON == "autumn") or (TIME == "noon" and SEASON == "autumn") or (TIME == "morning" and SEASON == "autumn") or (TIME == "evening" and SEASON == "spring") or (TIME == "noon" and SEASON == "spring") or (TIME == "morning" and SEASON == "spring"): print("It's not too cold outside!!!") elif (TIME == "night" and SEASON == "summer") or (TIME == "evening" and SEASON == "summer") or (TIME == "noon" and SEASON == "summer") or (TIME == "morning" and SEASON == "summer"): print("It's warm outside!!!") #результат Time: evening Season: winter WEATHER FORECAST: It's very cold outside!!!
false
9edbc10dc3e938c00324fb1be91a9712095f4b85
nasreldinas/-
/TA36.py
1,263
4.34375
4
#КОД ПРИМЕРА «Циклические алгоритмы. Обработка последовательностей и одномерных массивов» #номер версии: 1.0 #имя файла: TA36.py #автор и его учебная группа: A. nasreldin, ЭУ-135 #дата создания: 27.02.2021 #дата последней модификации: 04.03.2021 #описание: Циклические алгоритмы. Обработка последовательностей и одномерных массивов #версия Python:3.9.2 #Дан одномерный массив числовых значений, насчитывающий N элементов. Вставить группу из M новых элементов, начиная с позиции K. import array import random M = random.randint(1,10) K = random.randint(1,5) N = random.randint(1,10) arr = [random.randint(1,100) for i in range(N)] print("N= " + str(N)) print("K= " + str(K)) print("M= " + str(M)) print(arr) arr2 = [ random.randint(1,100) for i in range(M)] print(arr2) arr.insert(K, arr2) print(arr) #результат N= 4 K= 2 M= 2 [19, 66, 60, 55] [75, 49] [19, 66, [75, 49], 60, 55]
false
59506061fc7df6ca4e69329078ebb835bac30e49
Nishadansh47/LetsUpgrade-AI-ML
/Assignment_Day_7.py
1,004
4.15625
4
# --------------------------------------------Assignment Day 7 | 8th September 2020------------------------------------------------------- '''Question 1: Write a program to copy the contents of one file to another using a for loop.Do not use built-in copy function''' # Answer 1 ------------------ with open("input.txt", "r") as f: with open("output.txt", "a") as f1: for line in f: f1.write(line) # ____________________________________________________________________________________________________________________________________________ '''Question 2: Write a Python program to find maximum and minimum values in the dictionary. Do not use built-in min and max functions.''' # Answer 2 ------------ dic = {'a': 23, 'b': 16, 'c':52 , 'd': 14, 'e':5 } lst = [] for y in dic.values(): lst.append(y) lst = sorted(lst) print(f'The Minimum value of dictionary is {lst[0]}') print(f'The Maximum value of dictionary is {lst[-1]}')
true
327f5ddd68b4626aa8452976056db667d766cf96
joeypy/Python-scripts
/3.temperature_convertion_app.py
2,362
4.40625
4
print("Welcome to the Temperature Conversion App") def show_table(celsius, fahrenheit, kelvin): print(f"\nDegrees Celsius: {round(celsius, 2)}°C") print(f"Degrees Fahrenheit: {round(fahrenheit, 2)}°F") print(f"Degrees Kelvin: {round(kelvin, 2)}°K") # menu while True: print("\nMenú de selección de conversión") print("1. Fahrenheit to Celsius/Kelvin") print("2. Celsius to Fahrenheit/Kelvin") print("3. Kelvin to Celsius/Fahrenheit") print("4. Quit the program") selection = int( input("\nIntroduzca un número de acuerdo a la acción que desea ejecutar: ")) if selection == 1: try: fahrenheit = float( input("\nWhat is the given temperature in degrees Fahrenheit: ")) except ValueError: print( "Los valores ingresados son incorrectos, debe ingresar solo digitos numéricos.") continue # Formular de fahrenheit to celsius celsius = (fahrenheit - 32) * 5/9 # Formular de fahrenheit to kelvin kelvin = (fahrenheit - 32) * 5/9 + 273.15 show_table(celsius, fahrenheit, kelvin) break if selection == 2: try: celsius = float( input("\nWhat is the given temperature in degrees Celsius: ")) except ValueError: print( "Los valores ingresados son incorrectos, debe ingresar solo digitos numéricos.") continue # Formular de celsius to fahrenheit fahrenheit = (celsius * 9/5) + 32 # Formular de celsius to kelvin kelvin = celsius + 273.15 show_table(celsius, fahrenheit, kelvin) break if selection == 3: try: kelvin = float( input("\nWhat is the given temperature in degrees Kelvin: ")) except ValueError: print( "Los valores ingresados son incorrectos, debe ingresar solo digitos numéricos.") continue # Formular de kelvin to celsius celsius = kelvin - 273.15 # Formular de kelvin to fahrenheit fahrenheit = (kelvin - 273.15) * 9/5 + 32 show_table(celsius, fahrenheit, kelvin) break if selection == 4: break else: print(selection) print("You most choose a option in the menu")
false
48da242ee3defd120775dd065626bcbbac7a0df6
rockyshc/Python
/simples/basic/the_Set.py
864
4.34375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # set like dict, it a group of key # But not store value # Since every key should be unique # There should be no duplicated key in set # need to provide a list for set generation s = set([1, 2, 3]) print('The set named s should be:', s) # auto filter duplicate key s = set([1, 1, 1, 2, 2, 3, 3]) print('The set named s should be:', s) # add(key) s.add(4) print('The set named s should be:', s) # remove(key) s.remove(4) print('The set named s should be:', s) # for | and or & intersection and union s1 = set([1, 2, 3]) s2 = set([2, 3, 4]) print('s1 and s2 should be:', s1 & s2) print('s1 | s2 should be:', s1 | s2) # not changeable object # replace not replace the objects in a, just create a new list named b then return it a = 'abc' # b = a.replace('a', 'A') # print(b) print(a.replace('a', 'A')) print(a)
true
5f2f3e9203e267ba40e8e21e3ebec6f228c91024
rockyshc/Python
/simples/function/keyW_Args.py
1,397
4.4375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Keyword argument can extend the function of argument def person(name, age, **keyWord): print('Name:', name, 'Age:', age, 'Other:', keyWord) person('Tom', 4) person('Jack', 7, gender = 'M', job = 'Engineer') # Define a dict first # Then change the dict to keyword extra = { 'city': 'Beijing', 'job': 'Teacher' } person('Adam', 24, city = extra['city'], job = extra['job']) # Simplified # **extra means: # Use keyword argument all of the key-value in extra # Then send it to "**keyWord" # keyWord will receive a dict # Please notice the dict which keyWord received is a copy of extra # The change of keyWord will not impact extra extra = { 'city': 'Shanghai', 'job': 'Doctor' } person('Alex', 38, **extra) # Restriction of keyword argument name # Only the city and job can be the keyword argument # Need to use *, anything after * will be the keyword argument # 和关键字参数**kw不同,命名关键字参数需要一个特殊分隔符*,*后面的参数被视为命名关键字参数。 def person(name, age, *, city, job): print(name, age, city, job) # 调用方式如下 person('Mike', 33, city = 'Nanjing', job = 'Teacher') # 命名关键字参数可以有缺省值,从而简化调用 def person(name, age, *, city = 'Shanghai', job): print(name, age, city, job) person('Jack', 24, job = 'Engineer')
true
43b5c80a00fc4c799a2a7f621248d63ee3b63557
kamanazan/dailyprogrammer
/ch_137_e.py
1,641
4.3125
4
#challange 137 easy ''' http://www.reddit.com/r/dailyprogrammer/comments/1m1jam/081313_challenge_137_easy_string_transposition/ it can be helpful sometimes to rotate a string 90-degrees, like a big vertical "SALES" poster or your business name on vertical neon lights, like this image from Las Vegas. Your goal is to write a program that does this, but for multiples lines of text. This is very similar to a Matrix Transposition, since the order we want returned is not a true 90-degree rotation of text. Author: nint22 #Input Description You will first be given an integer N which is the number of strings that follows. N will range inclusively from 1 to 16. Each line of text will have at most 256 characters, including the new-line (so at most 255 printable-characters, with the last being the new-line or carriage-return). #Output Description Simply print the given lines top-to-bottom. The first given line should be the left-most vertical line. #Sample Input 1 1 Hello, World! #Sample Output 1 H e l l o , W o r l d ! #Sample Input 2 5 Kernel Microcontroller Register Memory Operator #Sample Output 2 KMRMO eieep rcgme nrior eosra lctyt oe o nr r t r o l l e r ''' import sys num = int(sys.stdin.next()) print num str_list = [] max_len = 0 for x in range(num): tmp = sys.stdin.next().replace('\n','') if len(tmp) > max_len: max_len = len(tmp) str_list.append(tmp) str_transpose = [[" " for x in xrange(num)] for x in xrange(max_len)] for x in range(num): lgt = len(str_list[x]) for y in range(max_len): if y < lgt: str_transpose[y][x] = str_list[x][y] for a in str_transpose: print ''.join(a)
true
63f2315f8fea58785156e866d98aaabb86c7419f
RainingWish/Python-Learning
/Day2/variable.py
398
4.125
4
#this code will intro the variable in python #give a a number a = 123 print ('a = 123 print a',a) #give a a string, remenber 'string' a = 'ABC' print ('a = ABC print a',a) print ('''x = 10 x = x + 2''') x = 10 x = x + 2 print ('print new x value',x) print ('\n\n') #print 2 variable print ('''a = ABC let b = a then a = XYZ''') b=a a='XYZ' print ('print new a =',a) print ('final print b =',b)
false
18a712e0599f6c7b83372330cc581a57cd011dfa
RainingWish/Python-Learning
/Day4/if.py
893
4.5
4
#input a birth year decide u are a adult, teenager or a kid #let user input theire birth year birth = input('Your birth year is:') #input function will save the number in string #in this case, we need change the string to intiger for comparing birth = int(birth) #calculate your age age = 2019-birth print ('your age is', age) #start comparing #elif = else if # warning: dont forget ':' if age >= 18: print('adult') elif age >= 6: print('teenager') else: print('kid') #practice, given hight and weight find BMI and give the health statement height = input('Your height in meter:') weight = input('Your weight in kg:') height = float(height) weight = float(weight) BMI = weight/(height*height) print ('your BMI is', BMI) if BMI >= 32: print('really fat') elif BMI >= 28: print('fat') elif BMI >= 25: print('over weight') elif BMI >= 18.5: print('normal') else: print('too light')
true
b44b8e936e6388eb7d5113fa596efae6cecb7d0a
RainingWish/Python-Learning
/Day7/slice.py
626
4.125
4
# slice is use to get some specific things in a list or tuple L = ['Mick','Sam','Tracy','Bob','Jack'] print (L[:3]) print(L[1:3]) print(L[-2:]) print(L[-2:-1]) l = list(range(100)) #print(l) print (l[:10]) print(l[-10:]) print(l[:10:2]) # 0 to 10 skip 1 each print(l[::5]) # every 5 pick 1 #print(l[:]) #print a same list # tuple print((0,1,2,3,4,5)[:3]) #output also tuple #remove all empty from a string def trim(s): i=len(s) while i>1: if s[0]==' ': s = s[1:] elif s[-1] == ' ': s = s[:-1] i-=1 return s A = ' hello ' print(A) print(trim(A)) B = ' EMMMMMM ' print(B) print(trim(B))
false
325ce962d7f6e3834c22b96693639673a1874adb
ukirderohit/2017Challenges
/challenge_13/python/ning/challenge_13.py
1,373
4.15625
4
def get_int_len(_int): '''Find the number of digits of an int Given an integer, finds the number of digits in that integer in base 10 ''' power = 1 while True: if _int == 0: return 0 elif _int < 10**power: return power power += 1 def check_palindrome(_int): ones = 0 digits = get_int_len(_int) while digits > 1: if _int % 10 != 0: # not end with 0 ones += 1 _int -= 1 else: _int -= ones * 10**(digits-1) _int /= 10 new_digits = get_int_len(_int) diff_digits = digits - new_digits if diff_digits == 1 or _int < 0: # e.g. 514, 510, 110, 10 # e.g. 415, 410, -90, -9 return False elif diff_digits > 2: # e.g. 10101, 10100, 0010 extra_zeroes = diff_digits - 2 _int /= 10**(extra_zeroes) if _int % 1 != 0: return False digits = get_int_len(_int) ones = 0 return True def check_palindrome_str(_str): return check_palindrome(int(_str)) if __name__ == '__main__': while True: print(check_palindrome_str(input(' >>> '))) ''' # FOR REPL.IT while True: print(check_palindrome_str(input(' >>> '))) '''
true
326a09c5067545f2b79dbf9174057e243fe18e4c
amirlevis/varonis_interview_questions
/diagonal_square.py
1,246
4.625
5
# Python3 program to change value of # diagonal elements of a matrix to 0. # method to replace the diagonal # matrix with zeros def diagonalMat(row, col, m): # l is the left iterator which is # iterationg from 0 to col-1[4] here # k is the right iterator which is # iterating from col-1 to 0 i, l, k = 0, 0, col - 1; # i used to iterate over rows of the matrix while(i < row): j = 0; # condition to check if it is # the centre of the matrix if(l == k): m[l][k] = 0; l += 1; k -= 1; # otherwize the diagonal will be equivalaent to l or k # increment l because l is traversing from left # to right and decrement k for vice-cersa else: m[i][l] = 0; l += 1; m[i][k] = 0; k -= 1; # print every element # after replacing from the column while(j < col): print(" ", m[i][j], end = ""); j += 1; i += 1; print(""); # Driver Code if __name__ == '__main__': m = [[2, 1, 7 ], [ 3, 7, 2 ], [ 5, 4, 9 ]]; row, col = 3, 3; diagonalMat(row, col, m);
true
9a32d06c0a41912fffff2192c80ee11355249dc4
pushoo-sharma/Python_File
/Median.py
790
4.3125
4
def median(numbers): """" median, returns the median value of an input list. """ numbers.sort() #The sort method sorts a list directly, rather than returning a new sorted list if (len(numbers) % 2 == 0): middle_index = int(len(numbers)/2) - 1 next_middle_index = middle_index + 1 return float(float((numbers[middle_index]) + float(numbers[next_middle_index]))/2) middle_index = int(len(numbers)/2) return numbers[middle_index] test1 = median([1,2,3]) print("expected result: 2, actual result: {}".format(test1)) test2 = median([1,2,3,4]) print("expected result: 2.5, actual result: {}".format(test2)) test3 = median([53, 12, 65, 7, 420, 317, 88]) print("expected result: 65, actual result: {}".format(test3))
true
529f8e15895df08270a9d7ec4e46e8a713d57c6e
hrawson79/Algorithms
/LinkedLists/queue.py
1,266
4.21875
4
# Queue Class from LinkedLists.list_node import ListNode class Queue(object): # Constructor def __init__(self): self.front = None self.end = None self.size = 0 # Method to return the size of the queue def __len__(self): return self.size # Method to add item to the queue def enqueue(self, item): if (self.size == 0): self.front = ListNode(item) self.end = self.front else: node = ListNode(item) self.end.set_link(node) self.end = node self.size += 1 # Method to remove next item from the queue def dequeue(self): node = None if (self.size > 0): node = self.front self.front = node.get_link() self.size -= 1 return node # Method to retrieve the front item without removing it def get_front(self): return self.front # Method to retrieve the size of the queue def get_size(self): return self.size # Method to iterate the queue def __iter__(self): current_node = self.front while current_node is not None: yield current_node.get_item() current_node = current_node.get_link()
true
10528e6cfd77dc9ca73a14d4dd782cd14c5e84d4
makshev1/Labs_IFMO
/1st_course/Informatics/2nd_Lab/src/lab_02_01.py
2,688
4.125
4
""" Условия """ # if..else num = int(input("How many times have you been to the Hermitage? ")) if num > 0: print("Wonderful!") print("I hope you liked this museum!") else: print("You should definitely visit the Hermitage!") # if..elif..else course = int(input("What is your course number?")) if course == 1: print("You are just at the beginning!") elif course == 2: print("You learned many things, but not all of them!") elif course == 3: print("The basic course is over, it's time for professional disciplines!") else: print("Oh! You need to hurry! June is the month of thesis defense") x = 5 y = 12 if y % x > 0: print("%d cannot be evenly divided by %d" % (y, x)) z = 3 x = "{} is a divider of {}".format(z, y) if y % z == 0 else "{} is not a divider of {}".format(z, y) print(x) print("\n\n") # Создайте переменную p, в которую будет записано значение количества выполненных за год лабораторных по различным # дисциплинам. Осуществите вывод значения переменной в терминал, если значение больше 10. Оператор ветвления запишите # двумя способами: в одну строку и в несколько строк. p = int(input("Введите количество выполненных за год лабораторных по различным дисциплинам")) if p > 10: print("Количество выполненных за год лабораторных по различным дисциплинам:", p) if p > 10: print("Количество выполненных за год лабораторных по различным дисциплинам:", p) a = 157 # Создате переменные a со значением 157 и b со значением 525. b = 525 # Осуществите проверку следующих условий и выполнение соответствующих действий: if a > b: # если a>b, рассчитайте остаток от деления a на b и выведите значение на экран; print("a>b -> a%b =", (a % b)) elif a < b: # если a<b, рассчитайте остаток от деления b на a и выведите значение на экран; print("a<b -> b%a =", (b % a)) else: # если a==b, рассчитайте произведение чисел a и b и выведите значение на экран. print("a=b -> a*b =", (a ** 2))
true
e38e2ea0882bfad0cee87d37bee63d4ab5d31225
srsagehorn/codeWars100Days
/1-10/day10.py
1,030
4.28125
4
# Removing Elements # 8kyu # https://www.codewars.com/kata/5769b3802ae6f8e4890009d2/train/python # Take an array and remove every second element out of that array. Always keep the first element and start removing with the next element. # Example: # my_list = ['Keep', 'Remove', 'Keep', 'Remove', 'Keep', ...] # None of the arrays will be empty, so you don't have to worry about that! def remove_every_other(arr): newArr = [] #new array for i in range(len(arr)): if i % 2 == 0: #if it is an even number element newArr.append(arr[i]) #push to array return newArr #return new array # test.assert_equals(remove_every_other(['Hello', 'Goodbye', 'Hello Again']), # ['Hello', 'Hello Again']) # test.assert_equals(remove_every_other([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), # [1, 3, 5, 7, 9]) # test.assert_equals(remove_every_other([[1, 2]]), [[1, 2]]) # test.assert_equals(remove_every_other([['Goodbye'], {'Great': 'Job'}]), # [['Goodbye']])
true
5f869ff770ba02b93d104ec7ba73d34f796a77cc
srsagehorn/codeWars100Days
/21-30/day24.py
1,474
4.1875
4
# Tip Calculator # 8kyu # https://www.codewars.com/kata/56598d8076ee7a0759000087/train/python # Complete the function, which calculates how much you need to tip based on the total amount of the bill and the service. # You need to consider the following ratings: # Terrible: tip 0% # Poor: tip 5% # Good: tip 10% # Great: tip 15% # Excellent: tip 20% # The rating is case insensitive (so "great" = "GREAT"). If an unrecognised rating is received, then you need to return: # "Rating not recognised" in Javascript, Python and Ruby... # ...or null in Java # ...or -1 in C# # Because you're a nice person, you always round up the tip, regardless of the service. import math #import math def calculate_tip(amount, rating): rating = rating.lower() #convert the rating to lower case #use the correct rating t round up the appropriate tip if rating == "excellent": return math.ceil(amount * .20 ) if rating == "great": return math.ceil(amount * .15) if rating == "good": return math.ceil(amount * .10) if rating == "poor": return math.ceil(amount * .05) if rating == "terrible": return 0 return "Rating not recognised"#if not a rating # Test.assert_equals(calculate_tip(30, "poor"), 2) # Test.assert_equals(calculate_tip(20, "Excellent"), 4) # Test.assert_equals(calculate_tip(20, "hi"), 'Rating not recognised') # Test.assert_equals(calculate_tip(107.65, "GReat"), 17) # Test.assert_equals(calculate_tip(20, "great!"), 'Rating not recognised')
true
3a21182c743199db0d23d66bbeda1cdc20ed3d79
srsagehorn/codeWars100Days
/additional/squareEveryDigit.py
679
4.15625
4
# 7kyu # Square Every Digit # https://www.codewars.com/kata/546e2562b03326a88e000020/train/python # Welcome. In this kata, you are asked to square every digit of a number. # For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1. # Note: The function accepts an integer and returns an integer def square_digits(num): # create a variable res = '' # iterate over the num by converting it to a string for i in str(num): # add the square of each integer in num to res res += str(int(i)**2) # convert answer back to an int return int(ans) # test.assert_equals(square_digits(9119), 811181)
true
86d7e77637626e81f6c65a704bc2dfa58c1a65f5
lukegriffith/CodeExamples
/Python/CBT Tutorials/ErrorHandling.py
667
4.1875
4
while True: try: print("Let us solve the equation (x/2) / (x-y) ") print("Please enter 0 to Exit") x = int(input("Please enter x: ")) y = int(input("Please enter y: ")) if x==0 or y==0: break z = (x/2) / (x-y) except ZeroDivisionError as e: print("There was an error with the code") print("You tried to divide by zero!") except NameError as e: print("There was an error with the code") print("You keyed in a text input when it expected a ") except Exception as e: print("There was an error with the code") print("Error: ", str(e)) else: print("Solving (x/2) / (x-y) for values x = ", x," and y = ",y, "we get the result", z)
true
f1be1475fb0a88ae435b3c7d2db492fda162a2c6
lukegriffith/CodeExamples
/Python/CBT Tutorials/Dictionaries.py
509
4.59375
5
ages = {"Luke":23,"Jess":20,"Mark":47,"Caroline":47} print(ages) for age in ages: print('The age of',age,'is',ages[age]) ###This has to be done with dictionaries, as it doesn't have an order. You can get the value by specifying ages - the collection and [age] the key to get the value #.keys() is a function to get a list of keys. this is useful - this does not work in py3 x = ages.keys() print(x) #Adding new keys to a dictionary is the same as lists, but to delete you need to use del ages[remKey]
true
30fd0bf10de116fc4b01eef59d24ff7936f454d0
KKosukeee/AlgorithmsMediumSeries
/classes/queue.py
1,290
4.5625
5
""" Implement a queue class here using LinkedList class """ from classes import LinkedList class Queue: """ Queue class implementation """ def __init__(self, node=None): """ Initialization method for a queue object Args: node: Node object as the first element in the queue """ # Create a linked-list object with FIFO structure self.list = LinkedList(node) def enqueue(self, node): """ This method will add an element into the queue Args: node: Node object to add into the queue Returns: """ # Append the element at the tail of the list self.list.append_right(node) def dequeue(self): """ This method will get an element from the queue in FIFO manner Returns: """ # Temporary get the head element head_element = self.list.head # Remove the head element self.list.remove(head_element) # Simply return the node object return head_element def peek(self): """ This method will return an integer value of the first element Returns: """ # Return the head element in the queue return self.list.head.value
true
0422617d86c175c1e43463a5373bf367a27e804f
KKosukeee/AlgorithmsMediumSeries
/part7/quick_sort.py
2,575
4.25
4
""" This file contains a content for the part 7 of the data structures and algorithms series """ import numpy as np from classes import BigO from classes import Plotter def main(): """ Main function of this file. It runs a quick sort several times Returns: None: """ # Initialize quick sort operation to see the runtime quick_sort_op = BigO('Quick Sort') plotter = Plotter() plotter.add_object(quick_sort_op) # Create an array with different length N times for i in range(1000): # Create an arbitrary array unsorted_array = np.random.randint(0, i+1, size=i+1) # Sort an array by calling quick_sort function quick_sort_op.time_function(quick_sort, array=unsorted_array, low=0, high=i) # Plot the runtime plotter.to_plot() def quick_sort(array, low, high): """ This function sorts an array via quick sort. This function calls itself (recursion) with the pivot pointer returned by the partition function Args: array(list[int]): list of integers to sort low(int): int value representing the left-most index where the elements in the range are unsorted high(int): int value representing the right-most index as opposed to the left-most (low) Returns: None: """ if not low < high: return # After this function call, array[pivot] will be in the right position pivot = partition(array, low, high) # Recursively call for the left-half of the array quick_sort(array, low, pivot-1) # Recursively call for the right-half of the array quick_sort(array, pivot+1, high) def partition(array, low, high): """ This function partitions an array in memory, such that Args: array(list[int]): list of integers to partition with low(int): a pointer which points the left-most element that isn't in-place yet high(int): a pointer which points the right-most element that isn't in-place yet Returns: int: int value representing the pivot number where array[pivot] is in the right position """ i = low pivot = array[high] # Loop for each number in the range [low, high) for j in range(low, high): # If current number is smaller than the pivot, then swap them if array[j] < pivot: array[i], array[j] = array[j], array[i] i += 1 # After the loop, I know where the pivot should go, just swap them array[i], array[high] = array[high], array[i] return i if __name__ == '__main__': main()
true
d7e3706f50b7cdbca5875983c93577403065d79f
KKosukeee/AlgorithmsMediumSeries
/tests/classes_queue.py
2,255
4.25
4
""" Unit-test file for Queue object """ from unittest import TestCase from classes import Queue from classes import Node class TestQueue(TestCase): """ TestQueue object implementation """ def setUp(self): """ Setup method for unit-testing. This method will be called for each test case in this file Returns: """ # Initialize a couple nodes to test the queue class self.first_node = Node(3) self.second_node = Node(2) self.third_node = Node(1) # Create a queue with elements created above self.queue = Queue() self.queue.enqueue(self.first_node) self.queue.enqueue(self.second_node) self.queue.enqueue(self.third_node) def test_enqueue(self): """ Unit-test for queue.enqueue method which is supposed to add an element in the linked-list Returns: """ # Enqueue a node into self.queue: 1->2->3->4 new_node = Node(4) self.queue.enqueue(new_node) self.assertEqual(self.queue.peek(), self.first_node.value) def test_dequeue(self): """ Unit-test for queue.dequeue method which is supposed to remove an element from the list in FIFO manner Returns: """ # Dequeue a node from self.queue: 2->3 self.assertEqual(self.queue.peek(), self.first_node.value) node = self.queue.dequeue() self.assertEqual(node.value, self.first_node.value) # Dequeue a node from self.queue: 3 self.assertEqual(self.queue.peek(), self.second_node.value) node = self.queue.dequeue() self.assertEqual(node.value, self.second_node.value) # Dequeue the last element from self.queue: None self.assertEqual(self.queue.peek(), self.third_node.value) node = self.queue.dequeue() self.assertEqual(node.value, self.third_node.value) def test_peek(self): """ Unit-test for queue.peek method which is supposed to get an element that will be the next element you get by calling enqueue method Returns: """ # Check if its initially right self.assertEqual(self.first_node.value, self.queue.peek())
true
ba5ed9d2618cad3f6e6a0f70578f9bab6521dfeb
abhishekthukaram/Course-python
/Practice-Problems/firstnonrepeatingcharacter.py
1,622
4.3125
4
""" Create a function that accepts a string as an argument and returns the first non-repeated character. Examples first_non_repeated_character("it was then the frothy word met the round night") "a" first_non_repeated_character("the quick brown fox jumps then quickly blows air") "f" first_non_repeated_character("g") "g" first_non_repeated_character("") False first_non_repeated_character("hheelloo")False Notes An empty string should return False. If every character repeats, return False. Don't worry about case sensitivity or non-alphanumeric characters. """ """ def checknonrepeating(str): counter = {} charcter = [] for c in str: if c in charcter: counter[c] += 1 else: counter[c] = 1 charcter.append(c) print counter print charcter for i in charcter: if counter[i] == 1: return i return False """ def check_non_repeating1(string): char_dict = {} for char in string: char_dict[char] += 1 print(char_dict) for i, char in enumerate(string): if char_dict[char] == 1: return char return False def check_non_repeating(string): char_dict = {} for char in string: if char in char_dict: char_dict[char] += 1 elif char not in char_dict: char_dict[char] = 1 print char_dict for i, char in enumerate(string): print i,char if char_dict[char] == 1: return char return False print check_non_repeating("hheelloo") print check_non_repeating("it was then the frothy word met the round night")
true
79f263ead3f75922dab8b43ed1dff388efa29105
abhishekthukaram/Course-python
/Practice-Set1/permutation-palindrome.py
1,156
4.1875
4
""" Write an efficient function that checks whether any permutation ↴ of an input string is a palindrome. ↴ """ def has_palindrome_permutation(the_string): result = {} count = 0 final_result = 0 if (len(the_string) == 0): return True for key in the_string: if key in result: result[key] += 1 else: result[key] = 1 for sum_value in result.keys(): if result[sum_value] == 1: final_result += 1 if len(the_string) % 2 == 0: if final_result == 0: return True else: if final_result == 1: return True return False print(has_palindrome_permutation("civic")) """ def has_palindrome_permutation(the_string): # Track characters we've seen an odd number of times unpaired_characters = set() for char in the_string: if char in unpaired_characters: unpaired_characters.remove(char) else: unpaired_characters.add(char) # The string has a palindrome permutation if it # has one or zero characters without a pair return len(unpaired_characters) <= 1 """
true