blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
4f2487efd3bb2d56cb4e502bf08783ff5ef3f2a4
Nigirimeshi/leetcode
/0021_merge-two-sorted-lists.py
2,635
4.1875
4
""" 合并两个有序链表 链接:https://leetcode-cn.com/problems/merge-two-sorted-lists 将两个升序链表合并为一个新的升序链表并返回。 新链表是通过拼接给定的两个链表的所有节点组成的。 示例: 输入:1 -> 2 -> 4, 1 -> 3 -> 4 输出:1 -> 1 -> 2 -> 3 -> 4 -> 4 官方解法: 1. 迭代法。 当两个链表都不为空时,判断哪个链表的头节点的值更小,将较小值添加到结果里,之后将链表中的节点向后移动一位。 时间复杂度:O(n+m),n 和 m 分别是两个链表的长度,因为每次迭代循环时,只会放入一个链表元素,因此 while 循环次数不会超过两个链表之和。 空间复杂度:O(1). """ import unittest from typing import List # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class OfficialSolution: def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode: """迭代""" pre_head = ListNode(-1) prev = pre_head while l1 and l2: if l1.val <= l2.val: prev.next = l1 l1 = l1.next else: prev.next = l2 l2 = l2.next prev = prev.next # 合并后的 l1 和 l2 最多只有还未合并完,直接将链表末尾指向未合并完的链表即可。 prev.next = l1 if l1 is not None else l2 return pre_head.next def merge_two_lists_2(self, l1: ListNode, l2: ListNode) -> ListNode: """递归""" if not l1: return l2 if not l2: return l1 if l1.val <= l2.val: l1.next = self.merge_two_lists_2(l1.next, l2) return l1 else: l2.next = self.merge_two_lists_2(l1, l2.next) return l2 class TestOfficialSolution(unittest.TestCase): @staticmethod def list_to_list_node(l: List) -> ListNode: dummy = ListNode(0) n = dummy for v in l: n.next = ListNode(v) n = n.next return dummy.next def setUp(self) -> None: self.node1 = self.list_to_list_node([1, 2, 4]) self.node2 = self.list_to_list_node([1, 3, 4]) self.s = OfficialSolution() def test_merge_two_lists(self) -> None: node = self.s.merge_two_lists_2(self.node1, self.node2) values = list() while node is not None: values.append(node.val) node = node.next print(values) if __name__ == '__main__': unittest.main()
false
439445e18cb8260567be42e0e8df9eade0b3c9b5
Nigirimeshi/leetcode
/1249_minimum-remove-to-make-valid-parentheses.py
2,593
4.125
4
""" 移出无效的括号 链接:https://leetcode-cn.com/problems/minimum-remove-to-make-valid-parentheses 给你一个由 '('、')' 和小写字母组成的字符串 s。 你需要从字符串中删除最少数目的 '(' 或者 ')'(可以删除任意位置的括号),使得剩下的「括号字符串」有效。 请返回任意一个合法字符串。 有效「括号字符串」应当符合以下任意一条要求: 空字符串或只包含小写字母的字符串 可以被写作 AB(A 连接 B)的字符串,其中 A 和 B 都是有效「括号字符串」 可以被写作 (A) 的字符串,其中 A 是一个有效的「括号字符串」 示例 1: 输入:s = "lee(t(c)o)de)" 输出:"lee(t(c)o)de" 解释:"lee(t(co)de)" , "lee(t(c)ode)" 也是一个可行答案。 示例 2: 输入:s = "a)b(c)d" 输出:"ab(c)d" 示例 3: 输入:s = "))((" 输出:"" 解释:空字符串也是有效的 示例 4: 输入:s = "(a(b(c)d)" 输出:"a(b(c)d)" 提示: 1 <= s.length <= 10^5 s[i] 可能是 '('、')' 或英文小写字母 解法: 1. 栈。 """ import unittest from collections import defaultdict from typing import List, Tuple, Union class Solution: def min_remove_to_make_valid(self, s: str) -> str: """ 栈。 """ stack: List[Tuple[str, int]] = [] ans: List[str] = [] for i, c in enumerate(s): if c == "(": stack.append((c, i)) if c == ")": # 栈为空,说明 ")" 是多余的,用空字符代替 ")"。 if len(stack) == 0: ans.append("") continue stack.pop() ans.append(c) # 栈不为空,说明存在多于的 "(",依次出栈,并替换为空字符。 while stack: c, i = stack.pop() ans[i] = "" return "".join(ans) class TestSolution(unittest.TestCase): def setUp(self) -> None: self.s = Solution() def test_min_remove_to_make_valid(self) -> None: self.assertEqual( "lee(t(c)o)de", self.s.min_remove_to_make_valid("lee(t(c)o)de)"), ) self.assertEqual( "", self.s.min_remove_to_make_valid("))(("), ) self.assertEqual( "abc", self.s.min_remove_to_make_valid("))a(b(c"), ) self.assertEqual( "a(b(c)d)", self.s.min_remove_to_make_valid("(a(b(c)d)"), ) if __name__ == "__main__": unittest.main()
false
606fe3d50350078588bbbf2a1f07e3c46b9c66e9
Padma-1/100_days-coding
/Abundant_number.py
332
4.1875
4
#A number is abundant if sum of the proper factors of the number is greater than the given number eg:12-->1+2+3+4+6=16-->16>12 i.e., 12 is Abundant number n=int(input()) sum=0 for i in range(1,n//2+1): if n%i==0: sum+=i if sum>n: print("Abundant number") else: print("not Abundant number")
true
b63c5ad4a138de403ef34297f1e05d4668c20339
Padma-1/100_days-coding
/sastry_and_zukerman.py
674
4.15625
4
###Sastry number:A number N is a Sastry Number if N concatenated with N + 1 gives a perfect square.eg:183 ##from math import sqrt ##def is_sastry(n): ## m=n+1 ## result=str(n)+str(m) ## result=int(result) ## if sqrt(result)==int(sqrt(result)): ## return True ## return False ##n=int(input()) ##print(is_sastry(n)) #Zukarman numbers:Zuckerman Number is a number which is divisible by the product of its digits eg:115 def is_Zukerman(n): mul=1 while n: r=n%10 n=n//10 mul*=r #print(mul) if temp%mul==0: return True return False n=int(input()) temp=n print(is_Zukerman(n))
true
96af38fcaf676e67b50112b713af0b4d4fa08022
aswanthkoleri/Competitive-codes
/Codeforces/Contests/Codeforces_Global_Round_3/Quicksort.py
2,073
4.34375
4
def partition(arr,low,high): i = ( low-1 ) # index of smaller element pivot = arr[high] # pivot # print("Pivot 1 = ",pivot) # What we are basically doing in the next few steps : # 1. Whenever we find an element less than the pivot element we swap it with the element starting from the 0th index. # 2. Point to note is that there can be unnecessary swapping as the 0th index element can itself be less than the pivot. # 3. Finally when we arrange all the elements less than pivot in one side, the index right after that is the exact position for the pivot # 4. Swap the pivot with that position.This way we can get the correct position of an element in the sorted array. # 5. After that we will find the correct position for the pivot in the elements before and after the current pivot got. for j in range(low , high): # If current element is smaller than or # equal to pivot # print(arr[j],pivot,arr[j]+pivot) if arr[j] < pivot: # increment index of smaller element i = i+1 arr[i],arr[j] = arr[j],arr[i] # print("Pivot 2 = ",pivot,arr[high]) # if (arr[i+1]+arr[high])%2!=0: arr[i+1],arr[high] = arr[high],arr[i+1] return ( i+1 ) # The main function that implements QuickSort # arr[] --> Array to be sorted, # low --> Starting index, # high --> Ending index # Function to do Quick sort def quickSort(arr,low,high): if low < high: # pi is partitioning index, arr[p] is now # at right place pi = partition(arr,low,high) # print("array=",arr,"i+1= ",pi) # Separately sort elements before # partition and after partition quickSort(arr, low, pi-1) quickSort(arr, pi+1, high) if __name__=="__main__": # Write the main function here n=int(input()) ar=list(map(int,input().split())) # print(ar) quickSort(ar,0,len(ar)-1) # print(ar) for i in ar: print(i,end=" ") # # Find the minimum number and the index # minimum=min(ar)
true
44e4a22c1318e44f75e74af86558246f9acecd83
lavish205/hackerrank
/time_conversion.py
913
4.3125
4
"""PROBLEM STATEMENT Given a time in AM/PM format, convert it to military (24-hour) time. Note: Midnight is 12:00:00AM on a 12-hour clock and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock and 12:00:00 on a 24-hour clock. Input Format A time in 12-hour clock format (i.e.: hh:mm:ssAM or hh:mm:ssPM), where 01≤hh≤12. Output Format Convert and print the given time in 24-hour format, where 00≤hh≤23. Sample Input 07:05:45PM Sample Output 19:05:45 Explanation 7 PM is after noon, so you need to add 12 hours to it during conversion. 12 + 7 = 19. Minutes and seconds do not change in 12-24 hour time conversions, so the answer is 19:05:45. """ time = raw_input() h,m,s = time.split(':') sec = s[:-2] form = s[-2:] if form =='AM': if h == '12': h = '00' print h+':'+m+':'+sec elif h == '12': print h+':'+m+':'+sec else: h = str(int(h) + 12) print h+':'+m+':'+sec
true
336462673f1eccec9e6b8cd938c8d9c5af4c8018
alihasan01/CodingInterview_Python
/Chapter2/removeDuplicates.py
1,503
4.3125
4
class Node: def __init__(self, data, next=None): self.data = data self.next = next # Time Complexity O(n) # Space complexity Complexity O(n) class linkedList: def __init__(self): self.head = None def insertAtStart(self,data): node = Node(data , self.head) self.head = node def insertAtEnd(self,data): if self.head is None: self.head = Node(data , None) return else: itr = self.head while itr.next: itr = itr.next itr.next = Node(data, None) return self.head def print(self): if self.head == Node: print ("Linked list is Empty") return itr = self.head while(itr): print(str(itr.data) + " ",end='') itr = itr.next def removeDuplicates(self ): mySet = set() if self.head is None: print("linked List is empty") return itr = self.head mySet.add(self.head.data) while itr and itr.next: if itr.next.data in mySet: itr.next = itr.next.next else: mySet.add(itr.next.data) itr = itr.next return self.head if __name__ == '__main__': obj = linkedList() obj.insertAtEnd(3) obj.insertAtEnd(3) obj.insertAtEnd(31) obj.insertAtEnd(3) obj.print() print() head = obj.removeDuplicates() obj.print()
false
c7b26dd29739edb1e8aa671f1b7a41e03ad1134a
alihasan01/CodingInterview_Python
/Chapter2/Intersection.py
1,855
4.1875
4
class Node: def __init__(self, data, next=None): self.data = data self.next = next # Time Complexity O(n) # Space complexity Complexity O(1) class linkedList: def __init__(self): self.head = None def insertAtStart(self,data): node = Node(data , self.head) self.head = node def insertAtEnd(self,data): if self.head is None: self.head = Node(data , None) return else: itr = self.head while itr.next: itr = itr.next itr.next = Node(data, None) return self.head def print(self): if self.head == Node: print ("Linked list is Empty") return itr = self.head while(itr): print(str(itr.data) + " ",end='') itr = itr.next def IntersectionOptimal(self , l1, l2): p1 = l1 p2 = l2 l1switch = False l2switch = False while (p1 or not l1switch) and (p2 or not l2switch): if (p1 == p2): return True p1 = p1.next p2 = p2.next if p1 is None and not l1switch: p1 = l2 l1switch = True if p2 is None and not l2switch: p2 = l1 l2switch = True return False if __name__ == '__main__': obj = linkedList() obj1 = linkedList() obj.insertAtEnd(1) obj.insertAtEnd(2) obj.insertAtEnd(3) obj.insertAtEnd(4) head = obj.insertAtEnd(5) obj.print() print() obj1.insertAtEnd(21) obj1.insertAtEnd(32) obj1.insertAtEnd(42) obj1.insertAtEnd(52) # obj1.head.next.next.next = obj.head.next.next head1 = obj1.insertAtEnd(62) obj1.print() print() print(obj.IntersectionOptimal(head , head1))
false
2f4d5d2c4a37041f53c26f8bb0cce084028b4183
tpraks/python-2.7
/recur_reverse.py
223
4.21875
4
def reverse(str): if len(str)==1: return str else: return reverse(str[1::]) + str[0] def main(): str1 = raw_input("Enter String: ") print str1 print reverse(str1) if __name__ == '__main__': main()
false
255a630ce8ac960c214b6758e771233d36f0a6bc
Mo-Shakib/DSA
/Data-Structures/Array/right_rotate.py
565
4.53125
5
# Python program to right rotate a list by n # Returns the rotated list def rightRotate(lists, num): output_list = [] # Will add values from n to the new list for item in range(len(lists) - num, len(lists)): output_list.append(lists[item]) # Will add the values before # n to the end of new list for item in range(0, len(lists) - num): output_list.append(lists[item]) return output_list # Driver Code rotate_num = 3 list_1 = [1, 2, 3, 4, 5, 6] print(rightRotate(list_1, rotate_num))
true
7471c5beb138b6a39583083b4ea4173fa98e65b6
Misha-create/MK_MIPT_Python
/черепашка/12(1).py
291
4.15625
4
import turtle turtle.shape('turtle') def polygon (angle, l): for i in range(angle//2): turtle.forward(l) turtle.right(360/angle) big = int(input()) small = int(input()) n = int(input()) turtle.left(90) for i in range(n): polygon(big, 1) polygon(small, 1)
false
124bbb8ba9da101c72ffae44f897a2b8d71a4261
G00398792/pforcs-problem-sheet
/bmi.py
674
4.5625
5
# bmi.py # This program calculates your Body Mass Index (BMI). # author: Barry Gardiner #User is prompted to enter height and weight as a float # (real number i.e. 1.0) number. The users weight is divided # by the height in metres to the power of 2. The output # is printed to the screen. The code "{:.2f}'.format(BMI)" # specifies the format of the string. "2f" represents a floating # point number to a precision of 2 decimal places. height = float(input("Please Enter Your Height In Centimetres:")) weight = float(input("Please Enter Your Weight in kilograms:")) bmi = ((weight) / ((height/100))**2)#Formula: weight (kg) / [height (m)]2 print('BMI is {:.2f}.'.format(bmi))
true
f70c9a371369cb3ec1cd1f484c877704fa30b799
mre9798/Python
/lab 9.1.py
233
4.3125
4
# lab 9.1 # Write a recursive function to find factorial of a number. def fact(n): if n==1: return 1 else: return n*fact(n-1) n=int(input("Enter the nnumber : ")) print("Factorial is ",fact(n))
true
65abd6e3940706315542de8ba291bdd93b2c1dab
bajram-a/Basic-Programing-Examples
/Conditionals/Exercise2.4.py
505
4.25
4
"""Write a program that requires from the user to input coordinates x and y for the circle center and the radius of that circle, then another set of coordinates for point A. The program then calculates whether A is within the circle""" from math import sqrt Cir_x = float(input()) Cir_y = float(input()) r = float(input()) Ax = float(input()) Ay = float(input()) d = sqrt((Ax - Cir_x)**2 + (Ay - Cir_y)**2) if d <= r: print("A is within the circle") else: print("A isn't within the circle")
true
c5ff2f18e9728e2e015be69bf7389b11c54f55ba
fantods/python-design-patterns
/creational/builder.py
1,258
4.4375
4
# decouples creation of a complex object and its representation # helpful for abstractions # Pros: # code is more maintainable # object creation is less error-prone # increases robustness of application # Cons: # verbose and requires a lot of code duplication # Abstract Building class Building(object): def __init__(self): self.build_floor() self.build_size() def build_floor(self): raise NotImplementedError def build_size(self): raise NotImplementedError def __repr__(self): return 'Floor: {0.floor}, Size: {0.size}'.format(self) # Concrete Buildings class House(Building): def build_floor(self): self.floor = 'One' def build_size(self): self.size = 'Big' class Flat(Building): def build_floor(self): self.floor = 'More than One' def build_size(self): self.size = 'Small' def construct_building(cls): building = cls() building.build_floor() building.build_size() return building house = House() print(house) # Floor: One, Size: Big flat = Flat() print(flat) # Floor: More than One, Size: Small # use external constructor complex_house = construct_building(House) print(complex_house) # Floor: One, Size: Big
true
77f8837147e6516faa44883791fc94cfe6f4e02b
BloodiestChapel/Personal-Projects
/Python/HelloWorld.py
461
4.1875
4
# This is a standard HelloWorld program. # It is meant for practice. import datetime print('Hello World!') print('What is your name?') myName = input() myNameLen = len(myName) print('It is good to meet you, ' + myName) print('Your name is ' + str(myNameLen) + ' characters long.') print('What is your age?') date = datetime.datetime.now() myAge = input() birthYear = int(date.year) - int(myAge) - 1 print('You were born, at least, in ' + str(birthYear))
true
5a821cf368d6aac40b3e13a7ee6d3f9e3b73df24
miked49er/com.mikedeiters.learningpython
/12 Classes/classes.py
1,625
4.1875
4
#!/usr/bin/python3 # classes.py by Bill Weinman [http://bw.org/] # This is an exercise file from Python 3 Essential Training on lynda.com # Copyright 2010 The BearHeart Group, LLC class Animal: def talk(self):print('I have something to say') def walk(self):print("Hey I'm walking here") def clothes(self):print('I have nice close') class Duck(Animal): def __init__(self, **kwargs): self._variables = kwargs def quack(self): print('Quaaack!') def walk(self): # super().walk() print('Walks like a duck.') def bark(self):print('A Duck cannot bark') def fur(self):print('A Duck has feathers') # def get_color(self): # return self.variables.get('color', None) # # def set_color(self, color): # self.variables['color'] = color def set_variable(self, key, value): self._variables[key] = value def get_variable(self, key): return self._variables.get(key) class Dog(Animal): def fur(self):print('I have brown and white fur') def bark(self):print('Woof!') def walk(self):print('Walks like a dog') def quack(self):print('A dog cannot quack') def in_the_forest(dog): dog.bark() dog.fur() def in_the_pond(duck): duck.quack() duck.walk() def main(): donald = Duck() donald.set_variable('feet', 2) donald.set_variable('color', 'blue') # print('Color', donald.get_variable('color')) # print('# of Feet', donald.get_variable('feet')) fido = Dog() for o in (donald, fido): in_the_forest(o) in_the_pond(o) if __name__ == "__main__": main()
false
7d6e84349dcb9c8ca76a35192e1bbbc5a6301142
TheRockStarDBA/PythonClass01
/program/python_0050_flow_control_nested_for_loop.py
1,158
4.1875
4
''' Requirement: There are 4 numbers: 1/2/3/4. List out all 3 digits numbers using these 4 numbers. You cannot use the same number twice in the 3 digits numbers. ''' #Step 1) How to generate 1 digit number? for i in range(1,5): print(i, end=' ') print('\n-------------------------------------') #Step 2) How to generate 2 digits number? # Nested loop: for/while loop inside another for/while loop. for i in range(1,5): for j in range(1, 5): num = i * 10 + j print(num, end=' ') print('\n-------------------------------------') #Step 3) How to generate 3 digits number? # Nested loop: for/while loop inside another for/while loop, inside another for/while loop. for i in range(1,5): for j in range(1,5): for k in range(1,5): num = i * 100 + j * 10 + k print(num, end=' ') print('\n-------------------------------------') #Step 4) It has another condition - the 3 numbers should be different. for i in range(1,5): for j in range(1,5): for k in range(1,5): if i != j and i != k and j != k: num = i * 100 + j * 10 + k print(num, end=' ')
true
ad3979824471e652f79e74cf93ca18366b922436
TheRockStarDBA/PythonClass01
/program/python_0020_flow_control_if.py
1,262
4.28125
4
# Every python program we've seen so far is sequential exection. # Code is executed strictly line after line, from top to bottom. # Flow Control can help you skip over some lines of the code. # if statement today = input("What day is today?") print('I get up at 7 am.') print('I have my breakfast at 8 am.') # IMPORTANCE !!! -------------------------------------------------- # # if <boolean expression>: # <statement> # <statement> # <statement> # # 1) ":" at the end of the if clause # 2) All code under if section are indented 4 spaces. # 3) Treat the 3 print statements as a 'block', because they are indented 4 spaces. # The 'block' will be executed if today == 'Sunday' is True, otherwise, the 'block' won't get executed. # ----------------------------------------------------------------- if today == 'Sunday': # today == 'Sunday' is a boolean expression. The boolean expression will always have a bool value - True / False print("I attend Mr Fan's Python lesson at 9 am.") print("I start working on my homework at 10:30 am.") print("Homework is done at 11:30 am.") print("I have my lunch at 12 pm.") print("I play football with my friends at 5 pm.") print("I have my dinner at 7 pm.") print("I go to bed at 10 pm.")
true
e9fcd04639d97eef36e0891c5a4e8ad7513bd9c1
TheRockStarDBA/PythonClass01
/program/python_0048_practice_number_guessing_name.py
1,575
4.40625
4
''' Requirement: Build a Number guessing game, in which the user selects a range, for example: 1, 100. And your program will generate some random number in the range, for example: 42. And the user needs to guess the number. If his answer is 50, then you need to tell him. “Try Again! You guessed too high” If his answer is 20, then you need to tell him. “Try Again! You guessed too low” When he finally guesses it, you need to tell him, how many times he guesses. ''' ''' Solution: Step 1) Get lower bound / upper bound from console Step 2) Use random module to generate a number in the range as the answer Step 3) Loop to ask the user "what's the correct answer?", and tell him/her higher or lower. If it is correct, exit. ''' import random # Step 1) Get lower bound / upper bound from console lower = int(input("Enter positive lower bound: ")) upper = int(input("Enter positive upper bound: ")) # Step 2) Use random module to generate a number in the range as the answer answer = random.randint(lower, upper) count = 0 # Step 3) Loop to ask the user "what's the correct answer?", and tell him/her higher or lower. If it is correct, exit. while True: # Step 3.1) Get user guess guess_result = int(input("Guess a number: ")) # Step 3.2) update the count count += 1 # Step 3.3) check user guess if answer == guess_result: print(f"Congrats! You did it {count} try.") break elif answer > guess_result: print("Try again! You guessed too low.") else: print("Try again! You guessed too high.")
true
45d32d880019054cbcc22f71c5cf0b62bc605ecf
TheRockStarDBA/PythonClass01
/program/python_0006_data_type_str.py
613
4.15625
4
# str - 字符串 str1 = "Hello Python!" str2 = 'I am str value, "surrounded" by single quote.' str3 = "I am another str value, 'surrounded' by doulbe quotes." print('variable str1 type is:', type(str1), 'str1=', str1) print('variable str2 type is:', type(str2), 'str2=', str2) print('variable str3 type is:', type(str3), 'str3=', str3) # '+' sign joins str variables and get a new str first_name = 'Tom' last_name = 'Hanks' full_name = first_name + " " + last_name print("My favourite actor is", full_name) # '*' sign duplicates str variable and get a new str separate_line = "*" * 50 print(separate_line)
true
caf77761eb946bc292c8f0c9802bc0bfd75160a4
TheRockStarDBA/PythonClass01
/program/python_0031_practice_input_if_elif_else_bmi_calculator.py
1,132
4.53125
5
# Requirement: get input from the user about height in meters and weight in kg. # Calculate his bmi based on this formula: # bmi = weight / (height ** 2) # Print information based on user's bmi value # bmi in (0, 16) : You are severely underweight # bmi in [16, 18.5) : You are underweight # bmi in [18.5, 25) : You are healthy # bmi in [25, 30) : You are overweight # bmi in [30, max) : You are severely overweight height = float(input("Enter height in meters: ")) weight = float(input("Enter weight in kg: ")) bmi = weight / (height ** 2) print(f"Your BMI is {bmi:.3f}") # IMPORTANT !!! ------------------------------------------- # There are 2 ways to express bmi in a range [16, 18.5) # [Solution 1] elif bmi >= 16 and bmi < 18.5: # [Solution 2] elif 16 <= bmi < 18.5: # --------------------------------------------------------- if bmi < 16: print("You are severely underweight") elif 16 <= bmi < 18.5: print("You are underweight") elif bmi >= 18.5 and bmi < 25: print("You are healthy") elif 25 <= bmi < 30: print("You are overweight") else: print("You are severely overweight")
true
e9a945d21935f5bb2e66d9323eeb5e26b5a97ec6
TheRockStarDBA/PythonClass01
/program/python_0039_library_random.py
1,221
4.5625
5
# IMPORTANT !!! ---------------------------------- # Import the random module into your python file # ------------------------------------------------ import random # IMPORTANT !!! ---------------------------------- # random.randint(1, 10) is composed of 4 parts. # # 1) random : module name # 2) . : separate module name and function name # 3) randint : randint is a function # it is under random module # it will return a random number in range [1, 10] # 4) (1, 10) : both 1 and 10 are parameters. # What is parameter? Parameter is some value you pass to a function. # ------------------------------------------------ # Util method / Util class - 工具类 i = 0 while i < 100: random_int = random.randint(1, 100) # random.randint(1, 3) returns a random int in range[1,3] print(random_int) i += 1 i = 0 while i < 100: random_number = random.random() # random.random() return a random float in range [0, 1) print(random_number) i += 1 i = 0 while i < 100: random_number = random.uniform(1.2, 7.8) # random.uniform(1.2, 7.8) returns a random float in range[1.2, 7.8) print(random_number) i += 1
true
587e9f60c46a7db78e6e1f78885eb0b405f16239
Alamin11/JavaScript-and-Python
/lecture02/sequeces.py
652
4.15625
4
from typing import OrderedDict, Sequence # Mutable and Ordered # Mutable means can be changed the Sequence # Orderd means can not be changed the sequence because order matters #string = oredered name = "Farjana" print(name[0]) print(name[6]) print(name) #Lists=mutable and ordered listName = ["Farjana", "Toma", "Nuntu", "Tuntun pakhi", "Jhunjhun pakhi"] print(listName) print(listName[0]) print(listName[1]) print(listName[2]) print(listName[3]) print(listName[4]) # Add a new name to the list: listName.append("Ami") print(listName[5]) # Delete a name from the list listName.remove(listName[5]) print(listName) # Sort the list listName.sort() print(listName)
true
71cdaa322abe4a1f266d5ce9704c11f3a759892c
alisaffak/GlobalAIHubPythonHomework
/proje.py
2,720
4.1875
4
student_name = "Ali".upper() student_surname = "Şaffak".upper() all_courses = ["Calculus","Lineer Algebra","Computer Science","DSP","Embeded Systems"] selected_courses = set() student_grades = {} def select_courses(): j = 1 for i in all_courses: print("{}-{}".format(j,i)) j +=1 print("6-No course selection") print("Please select at least 3 courses. ") selected = input("Enter the course's number:") if selected == "1": selected_courses.add(all_courses[0]) elif selected == "2": selected_courses.add(all_courses[1]) elif selected == "3": selected_courses.add(all_courses[2]) elif selected == "4": selected_courses.add(all_courses[3]) elif selected == "5": selected_courses.add(all_courses[4]) else: print("ınvalid input") def exam(): for i in selected_courses: print(i) select = input("choose the course you will take the exam: ") if select in selected_courses: midterm = input("Enter the midterm notes: ") final = input("Enter the final notes: ") project = input("Enter the project notes: ") student_grades["midterm"] = int(midterm) student_grades["final"] = int(final) student_grades["project"] = int(project) else: print("Invalid input") exam() def calculate_notes(): grade = student_grades["midterm"]*0.3 + student_grades["final"]*0.5 + student_grades["project"]*0.2 if grade >= 90 : print("AA") elif 70 <= grade < 90 : print("BB") elif 50 <= grade < 70 : print("BB") elif 30 <= grade < 50 : print("BB") else: print("FF") print("You failed the lesson") tries = 3 while (tries > 0): name = input("Please enter your name: ").upper() surname = input("Please enter your surname: ").upper() if name == student_name and surname == student_surname: print("WELCOME!") while len(selected_courses) < 3 : select_courses() exam() calculate_notes() elif name != student_name and surname == student_surname: tries -= 1 print("Opps! You have last {} entries".format(tries)) elif name == student_name and surname != student_surname: tries -= 1 print("Opps! You have last {} entries".format(tries)) elif name != student_name and surname != student_surname: tries -= 1 print("Opps! You have last {} entries".format(tries)) else: print("Please try again later!") break
true
224f1cb5e79f927af38bffa0629d03d0eddbfe86
Surgeom/geekbrains
/algoritms/dz2/1.py
858
4.25
4
def calcul(): operation = input('Введите операцию (+, -, *, / или 0 для выхода):') if operation == "0": return 'bye' elif operation == "-" or operation == '+' or operation == '*' or operation == '/': num1 = int(input('Введите первое число')) num2 = int(input('Введите второе число')) if operation == '+': print(f' {num1 + num2}') elif operation == '-': print(f'{num1 - num2}') elif operation == '*': print(f'{num1 * num2}') elif operation == '/': try: print(f'{num1 / num2}') except ZeroDivisionError: print('Делить на 0 нельзя') else: print('неверный ввод') print(calcul()) print(calcul())
false
6a8f962aebd5ddd10742d907de30819d82ae5d1e
LaRenegaws/wiki_crawl
/lru_cache.py
2,955
4.125
4
import datetime class Cache: """ Basic LRU cache that is made using a dictionary The value stores a date field that is used to maintain the elements in the cache Date field is used to compare expire an element in the cache Persisted field is a boolean that determines whether it can be deleted """ def __init__(self, size): self.cache_size_limit = size self.__cache = {} def update(self, key, value=None, persisted=False): """ if inputs are key and value then adds the key and value to the cache if inputs are only key, then only updates the access date for the element in the cache """ if value == None: if not self.exists(key): raise LookupError("The element does not exist in the cache") self.__cache[key]["date"] = datetime.datetime.utcnow() else: date = datetime.datetime.utcnow() if self.size() == self.cache_size_limit: self.delete_oldest_entry() self.__cache[key] = { "date": date, "value": value, "persisted": persisted } def delete_oldest_entry(self): # Deletes the dictionary element that was the last element to be updated oldest = datetime.datetime.utcnow() oldest_key = None for key in self.__cache: if self.__cache[key]["date"] < oldest and not self.__cache[key]["persisted"]: oldest = self.__cache[key]["date"] oldest_key = key del self.__cache[oldest_key] def find(self, key): # Returns the value that is associated with the key # Otherwise returns False if not self.exists(key): # raise LookupError("The element does not exist in the cache") return False else: return self.__cache[key]["value"] def size(self): return len(self.__cache) def exists(self, key): # Returns a boolean whether the key exists in the cache return key in self.__cache class WikiCache(Cache): """ For the purpose of the wiki_crawl, the key represents the article title and the value is the number of links until philosophy There is a pattern of certain wiki links appearing frequently prior to reaching Philosophy. As a result, I will initiallly seed the cache with the most common links that I've noticed to improve performance. The seeded entries would then not be expirable in the cache """ def __init__(self, size=100): Cache.__init__(self, size) self.seed_wiki_cache() def seed_wiki_cache(self): common_links = { "Critical thinking - Wikipedia": 6, "Polity - Wikipedia": 4, "Geometry - Wikipedia": 4, "Fact - Wikipedia": 5, "Mathematics - Wikipedia": 3, "Ontology - Wikipedia": 2, "Premise - Wikipedia": 3, "Logic - Wikipedia": 2, "Quantity - Wikipedia": 2, "Argument - Wikipedia": 1, "Property (philosophy) - Wikipedia": 1, "Psychology - Wikipedia": 12 } for key in common_links: self.update(key, common_links[key], True)
true
448aa1aead420c84febe08b1d5dcecff30b28d85
canlasd/Python-Projects
/Assignment3.py
450
4.1875
4
wind=eval(input("Enter Wind Speed")) if wind>=74 and wind <=95: print ("This is a category 1 hurricane") elif wind<=96 and wind <=110: print ("This is a category 2 hurricane") elif wind<=111 and wind <=130: print ("This is a category 3 hurricane") elif wind<=131 and wind <=155: print ("This is a category 4 hurricane") elif wind>=156: print ("This is a category 5 hurricane")
true
bec4400de442d424a2594b4b76e1a3c72a713bd8
kailash-manasarovar/A-Level-CS-code
/algorithms/merge_sort.py
1,069
4.15625
4
def merge(a_list): print("Splitting ", a_list) if len(a_list)>1: mid = len(a_list) // 2 left_half = a_list[:mid] right_half = a_list[mid:] merge(left_half) merge(right_half) i=j=k=0 # while all lists have more than one element while i < len(left_half) and j < len(right_half): # check the order and add to new list identified by k depending on order if left_half[i] < right_half[j]: a_list[k]=left_half[i] i=i+1 else: a_list[k]=right_half[j] j=j+1 k=k+1 # check for the situations in which only one half has more than one element / in the case of odd numbers while i < len(left_half): a_list[k]=left_half[i] i=i+1 k=k+1 while j < len(right_half): a_list[k]=right_half[j] j=j+1 k=k+1 print("Merging ", a_list) my_list = [14,46,43,27,57,41,45,21,70] merge(my_list) print(my_list)
false
ac9a7f7dc8d38922d664e20b379d14109e0c7b0e
kailash-manasarovar/A-Level-CS-code
/challenges/number_table.py
317
4.1875
4
operator = input("Please input an operator, +,-,*,/ ") number = int(input("Please input a number ")) list_of_numbers = [i for i in range(number+1)] print(operator + " | " + str(list_of_numbers[:])) print("- - - - - - - - - -") for i in range(number+1): print(str(i) + " | " + str(list_of_numbers[i:])) pass
false
1b25840045d4858f9eec3deeda08f2373376ee25
osanseviero/Python-Notebook
/ex31.py
626
4.375
4
#Program 31. Using while loops def create_list(size, increment): """Creates a list and prints it""" i = 0 numbers = [] while i < size: print "New run! " print "At the top i is %d" % i numbers.append(i) i = i + increment print "Numbers now: ", numbers print "At the bottom i is %d\n \n" % i print "The numbers: " for num in numbers: print num #Some testing print "Test 1" create_list(6, 1) print "\n\n\nTest 2" create_list(3, 1) print "\n\n\nTest 3" create_list(20,3) #User interface size = int(raw_input("Enter the top: ")) jump = int(raw_input("Enter the increment: ")) create_list(size, jump)
true
006a4070da536f4d42c65d93e0e5eb67db3b06b6
mirgags/pear_shaped
/fruit_script.py
1,896
4.21875
4
# An interactive script that prompts the user to accept or reject fruit # offerings and then asks if they want any other fruit that wasn't offered. # Responses are stored in the fruitlist.txt file for later reading. yeses = ['YES', 'OK', 'SURE', 'YEAH', 'OKAY', 'SI'] nos = ['NO', 'NOPE', 'NAH', 'UH-UH'] fruits = [] # imports list of fruits fro text file with open('fruitlist.txt', 'r') as fruitlist: for line in fruitlist: fruits.append(line.rstrip()) # checks response input against list of approved responses. def wants_fruit(answer, yeses, nos): more_fruit = "" for yes in yeses: if answer.upper() == yes: more_fruit = 'yes_fruit' for no in nos: if answer.upper() == no: more_fruit = 'no_fruit' if not (more_fruit == 'yes_fruit' or more_fruit =='no_fruit'): more_fruit = wants_fruit(raw_input("I'm sorry I didn't catch that, do you want some other fruit? > "), yeses, nos) return more_fruit # adds requested fruit to list def add_fruit(fruits): fruits.append(raw_input("What is it? > ")) print "Oh ok, I'll bring some %s next time." % fruits[-1] return fruits # beginning of interactivw program for fruit in fruits: answer = raw_input("Would you like some %s? (yes/no) > " % fruit).upper() for yes in yeses: if answer == yes: print "Here you go." answer = raw_input("Is there any fruit you like that I didn't offer? > ") more_fruit = "" while more_fruit != 'no_fruit': more_fruit = wants_fruit(answer, yeses, nos) if more_fruit == 'yes_fruit': fruits = add_fruit(fruits) more_fruit = "" answer = raw_input("Is there any fruit you like that I didn't offer? > ") fruits.sort() # opens and writes list to text file writefile = open('fruitlist.txt', 'w') for fruit in fruits: writefile.write("%s\n" % fruit) writefile.close()
true
1864a160dec53b2c9585bf05928daeafc23ff066
andrewdaoust/project-euler
/problem004.py
825
4.1875
4
""" A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. """ def palindrome_check(n): s = str(n) length = len(s) for i in range(int(len(s)/2)): j = -i - 1 if s[i] != s[j]: return False return True def run(): palindrome_numbers = [] for i in range(999, 99, -1): palindrome = False for j in range(i, 99, -1): num = i * j palindrome = palindrome_check(num) # print(i, j, num, palindrome) if palindrome: palindrome_numbers.append(num) return max(palindrome_numbers) if __name__ == '__main__': sol = run() print(sol)
true
c6ecdc710116054197d6d8f14f50f7af44700829
andrewdaoust/project-euler
/problem001.py
487
4.3125
4
""" If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ import numpy as np def run(): mult_3_5 = [] for i in range(1, 1000): if i % 3 == 0: mult_3_5.append(i) elif i % 5 == 0: mult_3_5.append(i) sol = np.sum(mult_3_5) return sol if __name__ == '__main__': sol = run() print(sol)
true
688b44387560371c3262dd115f377c87f06eabb5
nickmallare/Leet-Code-Practice
/35-search-insert-position.py
851
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. You must write an algorithm with O(log n) runtime complexity. """ class Solution(object): def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ head = 0 tail = len(nums) - 1 while(head <= tail): index = (head + tail) //2 val = nums[index] if val == target: return index #take the "middle" value and take the left or right side based on the middle number if val > target: tail = index - 1 else: head = index + 1 return head
true
f911c2170e7dcb50d4d0eef0eebe550926af2c87
Frank-LSY/Foundations-of-AI
/HW1/Puzzle8/bfs.py
1,650
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Sep 3 17:01:00 2019 vanilla breadth first search - relies on Puzzle8.py module @author: Milos Hauskrecht (milos) """ from Puzzle8 import * #### ++++++++++++++++++++++++++++++++++++++++++++++++++++ #### breadth first search def breadth_first_search(problem): queue =deque([]) root=TreeNode(problem,problem.initial_state) queue.append(root) while len(queue)>0: next=queue.popleft() if next.goalp(): del(queue) return next.path() else: new_nodes=next.generate_new_tree_nodes() for new_node in new_nodes: queue.append(new_node) print('No solution') return NULL problem=Puzzle8_Problem(Example1) output= breadth_first_search(problem) print('Solution Example 1:') print_path(output) wait = input("PRESS ENTER TO CONTINUE.") problem=Puzzle8_Problem(Example2) output= breadth_first_search(problem) print('Solution Example 2:') print_path(output) wait = input("PRESS ENTER TO CONTINUE.") problem=Puzzle8_Problem(Example3) output= breadth_first_search(problem) print('Solution Example 3:') print_path(output) wait = input("PRESS ENTER TO CONTINUE.") problem=Puzzle8_Problem(Example4) output= breadth_first_search(problem) print('Solution Example 4:') print_path(output) # Solution to Example 5 may take too long to calculate using vanilla bfs # problem=Puzzle8_Problem(Example5) # output= breadth_first_search(problem) # print('Solution Example 5:') # print_path(output)
true
4ad120e7f53162c10541c354acd1a30bc30cbeae
Nihila/python_programs
/begginer/positiveornegative.py
797
4.25
4
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: Administrator # # Created: 04/02/2018 # Copyright: (c) Administrator 2018 # Licence: <your licence> #------------------------------------------------------------------------------- def main(): pass stringVar.count('x') - counts the number of occurrences of 'x' in stringVar stringVar.find('x') - returns the position of character 'x' stringVar.lower() - returns the stringVar in lowercase (this is temporary) stringVar.upper() - returns the stringVar in uppercase(this is temporary) stringVar.replace('a', 'b') - replaces all occurrences of a with b in the string stringVar.strip() - removes leading/trailing white space from string
true
3cb7608386af892df8d2a09000e5461ff7abed11
essenceD/Python_algorythmes
/Lesson_2(Cycles, recursion, functions)/task_2.py
628
4.15625
4
# 2. # Посчитать четные и нечетные цифры введенного натурального числа. # Например, если введено число 34560, в нем 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5). num = input('Enter number to check its digits on parity: ') even = '' n_even = 0 odd = '' n_odd = 0 for i in num: if int(i) % 2 == 0: even += f'{i};' n_even += 1 else: odd += f'{i};' n_odd += 1 print(f'In number {num}:\n' f'{n_even} evens: {even[:-1]}\n' f'{n_odd} odds: {odd[:-1]}')
false
0e0b2a636417c19d1c9f728b727e48ce7aeab4bb
essenceD/Python_algorythmes
/Lesson_2(Cycles, recursion, functions)/task_8.py
876
4.25
4
# 8. # Посчитать, сколько раз встречается определенная цифра в введенной последовательности чисел. # Количество вводимых чисел и цифра, которую необходимо посчитать, задаются вводом с клавиатуры. match, line = 0, '' print('This program will count the digit you\'ll enter in numbers yo\'ll enter.') tries = int(input('Enter number of numbers to count digits: ')) dig = int(input('Enter digit which need to find: ')) for i in range(tries): num = int(input(f'Enter number where needed to find digit "{dig}": ')) line += f'{num}\n' while num != 0: if num % 10 == dig: match += 1 num //= 10 print(f'There are {match} digits "{dig}" in following numbers:\n{line}')
false
327720b380ef7d2fa891f67c916ba51f91c74769
pandey-ankur-au17/Python
/coding-challenges/week03/Assignment/AssignmentQ2while.py
540
4.125
4
def by_while_loop(): print("by using while loop ") n = int(input("Enter the number of lines : ")) line = 1 while (line <= n): print(" " * (n - line), end="") digit = 1 while digit <= line: print(digit, end="") if line == digit: rev_digit = line-1 while rev_digit >= 1: print(rev_digit, end="") rev_digit = rev_digit-1 digit = digit+1 print() line = line+1 by_while_loop()
true
158bdd6828bc4a720f962b5d329b5b8f8f5a045f
pandey-ankur-au17/Python
/coding-challenges/week04/day01/ccQ2.py
366
4.46875
4
# Write a function fibonacci(n) which returns the nth fibonacci number. This # should be calcuated using the while loop. The default value of n should be 10. def fibonacci(n=10): n1=0 n2=1 count=0 while count<n: print(n1) nth=n1+n2 n1=n2 n2=nth count=count+1 #n=int(input("Enter the numbers:")) fibonacci()
true
c830897d5aa2bd691af45ccb59f3bcaa22307d75
pandey-ankur-au17/Python
/coding-challenges/week07/AssignmentQ1.py
991
4.15625
4
# Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). # Note: # Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned. # In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 3, the input represents the signed integer. -3. # Example 1: # Input: n = 00000000000000000000000000001011 # Output: 3 # Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits. class Solution(object): def hammingWeight(self, n): count = 0 while(n): count+=1; n = n&(n-1); return count n=int(input("Binary only:")) print(hammingWeight(1,n))
true
58bfff25bede8b43e9e236d83d9326a8f0b4b125
pandey-ankur-au17/Python
/coding-challenges/week07/day04/ccQ3.py
591
4.25
4
# Given an array with NO Duplicates . Write a program to find PEAK # ELEMENT # Return value corresponding to the element of the peak element. # Example : # Input : - arr = [2,5,3,7,9,13,8] # Output : - 5 or 13 (anyone) # HINT : - Peak element is the element which is greater than both # neighhbours. def Peak_value(arr): s=arr.sort() for i in range(len(arr)): if arr[-1]>0: print(arr[-1]) return arr[-1] elif arr[i] >arr [i-1] and arr[i] >arr[i+1]: print(arr[i]) return arr[i] arr = [2,5,3,7,9,13,8] Peak_value(arr)
true
d727b7c08eab9667089f1dd1fb10f31cf694e880
pandey-ankur-au17/Python
/coding-challenges/week08/day04/ccQ2.py
724
4.125
4
# 2) Write a program to print sum of border elements of a square Matrix # (5 marks) # Border elements: # 1 2 3 4 # 4 5 6 5 # 7 8 9 6 # 4 9 8 7 # Sum of border elements = 1+2+3+4+5+6+7+8+9+4+7+4 = 60 def Border_element(a, m, n): sum = 0 for i in range(m): for j in range(n): if (i == 0): sum += a[i][j] elif (i == m-1): sum += a[i][j] elif (j == 0): sum += a[i][j] elif (j == n-1): sum += a[i][j] return sum m=int(input("Row:")) n=int(input("Column:")) a=[] for i in range(m): arr=list(map(int,input("Elements:").split())) a.append(arr) total = Border_element(a, m, n) print (total)
false
632564d4d1d0ed5f9c4cc1a8d9a36b67ab263810
alishalabi/binary-search-tree
/binary_search_tree.py
2,888
4.25
4
""" Step 1: Build a binary search tree, with add, remove and in methods. Step 2: Perform DFS's and BFS """ class BinaryTreeNode: def __init__(self, data, left_child=None, right_child=None): self.data = data self.left_child = left_child self.right_child = right_child self.is_leaf = True class BinarySearchTree: def __init__(self, root=None): self.root = root def add(self, node, current_node=None): # Base case: empty binary tree, add as root if self.root == None: self.root = node print("Adding root") return self # else: if current_node == None: current_node = self.root # Item already exists, return nothing if node.data == current_node.data: print("Node data already in Binary Search Tree") return self # Begin traversal at root node # See if data belongs on left or right of current node # Left: # print(f"Node.data: {node.data}") # print(f"Current_node.data: {current_node.data}") if node.data < current_node.data: # No left value, add node if current_node.left_child == None: current_node.left_child = node # Left value exists, recursively call add # with left child as current else: print(f"Current node's left child: {current_node.left_child.data}") return self.add(node, current_node.left_child) # Right: elif node.data > current_node.data: # No right value, add node if current_node.right_child == None: current_node.right_child = node # Right value exists, recursively call add # with right child as current else: print(f"Current node's right child: {current_node.right_child.data}") return self.add(node, current_node.right_child) nodeA = BinaryTreeNode(4) nodeB = BinaryTreeNode(2) # print(nodeB) nodeC = BinaryTreeNode(5) nodeD = BinaryTreeNode(1) nodeE = BinaryTreeNode(3) test_tree = BinarySearchTree() test_tree.add(nodeA) # print(f"Tree Root's data (should be 4): {test_tree.root.data}") test_tree.add(nodeB) # print(nodeA.left_child) print(f"Root's left child (should be 2): {test_tree.root.left_child.data}") # print(f"Left's left's data (should be None): {test_tree.root.left_child.left_child}") test_tree.add(nodeC) print(f"Root's right child (should be 5): {test_tree.root.right_child.data}") print(f"Root's right's right (should be None): {test_tree.root.right_child.right_child}") test_tree.add(nodeD) test_tree.add(nodeE) print(f"Root's left's left (should be 1): {test_tree.root.left_child.left_child.data}") print(f"Root's left's right (should be 3): {test_tree.root.left_child.right_child.data}")
true
f8c78f310b51c3af0ff82744fa7ac9a9118ce165
Hinal-Sonkusre/Python-Internship
/day4python.py
2,561
4.1875
4
# function # def myfunction(): # print("Hello world") # # # myfunction() # # # def myfunction1(name): # print("Name is:", name) # # # myfunction1("Hinal") # def myfunction2(name): # return name # # # name = myfunction2("Hinal") # print("Value is ", name) # def myfunction(): # name = "Hinal" # a = 1 # return name, a # # # name, a = myfunction() # print("Name is: ", name) # print("Value is: ", a) # default argument # def sum(a=50, b=50): # print(a + b) # sum(10, 20) # sum() # a = int(input("a: ")) # b = int(input("b: ")) # sum(a, b) # keyword argument # def sum(a, b): # print(a + b) # # # sum(b=20, a=30) # variable length argument # non keyword arguments # def sum(*a): # sum = 0 # # for i in a: # sum += i # # print("Ans is: ", sum) # # # sum(10, 20) # sum(10, 20, 30) # sum(10, 10, 10, 10) # keyword arguments # def function(**arg): # for i,j in arg.items(): # print(i,j) # # function(name = 'Hinal', name2 = 'Rudra') # variable scope # def func(): # x = 5 # print("x: ", x) # # x = 10 # func() # print("x: ", x) # modules in python # import demo # # demo.function() # import demo # # name = demo.function("Hinal") # print("Name is: ", name) # operators # arithmetic operators # a = 5 # b = 5 # # print("a + b : ", a + b) # print("a - b : ", a - b) # print("a * b : ", a * b) # print("a / b : ", a / b) # print("a % b : ", a % b) # print("a // b : ", a // b) # print("a ** b : ", a ** b) # comparison operators # a = 5 # b = 5 # # print("a > b : ", a > b) # print("a < b : ", a < b) # print("a == b : ", a == b) # print("a != b : ", a != b) # print("a >= b : ", a >= b) # print("a <= b : ", a <= b) # logical operators # and # a = 10 # b = 20 # c = 30 # # if a > b and a > c: # print("A is greatest") # # elif b > a and b > c: # print("B is greatest") # # else: # print("C is greatest") # or # ch = input("Enter a character: ") # # if(ch == 'A' or ch == 'a' or ch == 'E' or ch == 'e' or ch == 'I' or ch == 'i' or ch == 'O' or ch == 'o' or ch == 'U' or ch == 'u'): # print(ch, "is a vowel") # # else: # print(ch, "is a consonant") # membership operator # list = [10, 20, 30, 40] # x = int(input("x ")) # y = int(input("y ")) # # print(x in list) # print((x not in list)) # print(y in list) # print(y not in list) # identity operator a = 10 b = 10 print(a is b) print(a is not b)
false
2871bbaccc81e158cd4f7ae714af0a1c53ef2fce
brunohprada/Python-para-zumbis
/lista-2/01_triangulo.py
903
4.25
4
''' Lista 2 - Exercicio 1. Faça um Programa que peça os três 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('Informe o valor do primeiro lado: ')) lado2 = float(input('Informe o valor do segundo lado: ')) lado3 = float(input('Informe o valor do terceiro lado: ')) if (lado1 + lado2) >= lado3 and (lado2 + lado3) >= lado1 and (lado3 + lado1) >= lado2: if lado1 == lado2 and lado2 == lado3: print ('E um triangulo equilatero, pois todos os lados sao iguais') elif lado1 == lado2 or lado2 == lado3: print ('E um triangulo isosceles, pois possui dois lados iguais') else: print ('E um triangulo escaleno, pois todos os lados sao diferentes') else: print ('Nao e um triangulo')
false
f3fd05cd8a7ac17a0809891fd7fb7fcb338c6972
brunohprada/Python-para-zumbis
/lista-1/09_aluguel.py
539
4.125
4
''' Lista 1 - Exercício 9 Escreva um programa que pergunte a quantidade de km percorridos por um carro alugado pelo usuário, assim como a quantidade de dias pelos quais o carro foi alugado. Calcule o preço a pagar, sabendo que o carro custa R$ 60,00 por dia e R$ 0,15 por km rodado. Felipe Nogueira de Souza @_outrofelipe ''' km = float(input("Informe a quantidade de km's percorridos: ")) diarias = int(input("Informe a quantidade de diarias: ")) valor = (km * 0.15) + (diarias * 60.0) print ('O valor a pagar e: R$ %.2f' %valor)
false
0bb123d4261f05d1c3b1654c10cff9300a408135
pancakewaffles/Stuff-I-learnt
/Python Refresher/Python for Security Developers/Module 2 Apprentice Python/Activities/Apprentice_Final_Activity.py
1,475
4.125
4
import operator saved_string = '' def remove_letter(): #Remove a selected letter from a string base_string = str(raw_input("Enter String: ")); letter = str(raw_input("Letter to remove: ")); i = len(base_string) -1 ; while(i < len(base_string) and i >= 0): if(base_string[i] == letter): base_string = base_string[:i] + base_string[i+1::]; i -= 1; print base_string; def num_compare(): #Compare 2 numbers to determine the larger a = int(raw_input("First number: ")); b = int(raw_input("Second number: ")); if(a>b): return "%d is larger than %d." % (a,b); elif(a<b): return "%d is larger than %d." % (b,a); else: return "%d is equal to %d." %(a,b); def print_string(): #Print the previously stored string print saved_string; return def calculator(): #Basic Calculator (addition, subtraction, multiplication, division) return def accept_and_store(): #Accept and store a string input_string = raw_input("Enter your string: "); global saved_string; saved_string = str(input_string); return def main(): #menu goes here opt_list = [accept_and_store, calculator, print_string, num_compare, remove_letter]; while(True): choice = int(raw_input(" Enter your choice : ")); opt_list[choice](); main()
true
cb48aff62616fd3fe4888d6a4fde3aef185d99c1
pancakewaffles/Stuff-I-learnt
/Python Refresher/Python Math/1 Numbers, Fractions, Complex, Factors, Roots, Unit Conversion/quadraticRootsCalc.py
517
4.15625
4
#! quadraticRootCalc.py # Finds roots of quadratic equations, including even complex roots! def roots(a,b,c): # a,b,c are the coefficients D = (b*b - 4*a*c)**0.5; x_1 = (-b+D)/(2*a); x_2 = (-b-D)/(2*a); print("x1: {0}".format(x_1)); print("x2: {0}".format(x_2)); #print("x1: %f"%(x_1)); Doesn't work for complex #print("x2: %f"%(x_2)); if(__name__=="__main__"): a = input("Enter a: "); b = input("Enter b: "); c = input("Enter c: "); roots(float(a),float(b),float(c));
true
38f8b6498b4d756f7f2255109323fa4112f48e8f
pancakewaffles/Stuff-I-learnt
/Python Refresher/Python Basics/collatz.py
280
4.1875
4
#Collatz Conjecture def collatz(number): if(number%2==0): print(number//2); return number//2; else: print(3*number + 1); return 3*number + 1; print("Enter number:"); number = int(input()); while(number > 1): number = collatz(number);
false
4e8a52d1b2563727ac655e2c84ad0b80af626e29
fpert041/experiments_in_ML_17
/LB_02_TestEx.py
1,274
4.21875
4
#PRESS <Ctrl>+<Enter> to execute this cell #%matplotlib inline #In this cell, we load the iris/flower dataset we talked about in class from sklearn import datasets import matplotlib.pyplot as plt iris = datasets.load_iris() # view a description of the dataset print(iris.DESCR) %matplotlib inline #above: directive to plot inline #PRESS <Ctrl>+<Enter> to execute this cell #This populates info regarding the dataset. Amongst others, we can see that the 'features' used are sepal length and width and petal length and width #Lets plot sepal length against sepal width, using the target labels (which flower) X=iris.data Y=iris.target plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired) #first two features are sepal length and sepal width plt.show() %matplotlib inline #here's also how to plot in 3d: from mpl_toolkits.mplot3d import Axes3D # #create a new figure fig = plt.figure(figsize=(5,5)) #this creates a 1x1 grid (just one figure), and now we are plotting subfigure 1 (this is what 111 means) ax = fig.add_subplot(111, projection='3d') #plot first three features in a 3d Plot. Using : means that we take all elements in the correspond array dimension ax.scatter(X[:, 0], X[:, 1], X[:, 2],c=Y)
true
1adb144238abf3ad518e644c680a44e7b66cca15
ianjosephjones/Python-Pc-Professor
/8_11_21_Python_Classs/Exercise_5-11.py
723
4.5625
5
""" 5-11: Ordinal Numbers --------------------- Ordinal numbers indicate their position in a list, such as 1st or 2nd. Most ordinal numbers end in th, except 1, 2, and 3. Store the numbers 1 through 9 in a list. Loop through the list. Use an if-elif-else chain inside the loop to print the proper ordinal ending for each number. Your output should read "1st 2nd 3rd 4th 5th 6th 7th 8th 9th" , and each result should be on a separate line. """ numbers = list(range(1, 10)) for number in numbers: if number == 1: print("1st") elif number == 2: print("2nd") elif number == 3: print("3rd") else: print(f"{number}th") """ Output: ------- 1st 2nd 3rd 4th 5th 6th 7th 8th 9th """
true
cd7df41cd3b77c163d2ce1eda9dc4500e1b038c9
Mooshoopork/Uh
/multiplcationtable1-10.py
777
4.25
4
#Mutiplication table from 1-10 while True: num = input("What number would you like to multiply? ") try: num = int(num) break except: print("Please input an integer.") print("Here is the multiplication table:") awn = num * 1 print(str(num) + " x 1 = " + str(awn)) awn = num * 2 print(str(num) + " x 2 = " + str(awn)) awn = num * 3 print(str(num) + " x 3 = " + str(awn)) awn = num * 4 print(str(num) + " x 4 = " + str(awn)) awn = num * 5 print(str(num) + " x 5 = " + str(awn)) awn = num * 6 print(str(num) + " x 6 = " + str(awn)) awn = num * 7 print(str(num) + " x 7 = " + str(awn)) awn = num * 8 print(str(num) + " x 8 = " + str(awn)) awn = num * 9 print(str(num) + " x 9 = " + str(awn)) awn = num * 10 print(str(num) + " x 10 = " + str(awn))
false
15a517a5443e03e322d9c2fbfcdbb31c9418cf25
awesomeleoding1995/Python_Learning_Process
/python_crash_course/chapter-9/user.py
1,773
4.125
4
class User(): """this class is used to create user-related profile""" def __init__(self, first_name, last_name): self.f_name = first_name self.l_name = last_name self.login_attempts = 0 def describe_user(self): formatted_name = self.f_name + " " + self.l_name return formatted_name.title() def greet_user(self): print("Thanks for logging in!") def increment_login_attempts(self): self.login_attempts += 1 def rest_login_attempts(self): self.login_attempts = 0 class Admin(User): """ This is a child class of User""" def __init__(self, first_name, last_name): """initialise parent class""" super().__init__(first_name, last_name) self.privilege = Privileges() class Privileges(): """describe tha attribute of admin""" def __init__( self, privileges = [ 'can add post', 'can delete post', 'can ban user', 'can manage post' ] ): self.privileges = privileges def show_privileges(self): for privilege in self.privileges: print("\nYou " + privilege) admin = Admin('eggy', 'zhang') admin_name = admin.describe_user() print("Welcome " + admin_name) admin.privilege.show_privileges() admin.greet_user() # user_1 = User('william', 'wu') # user_2 = User('gerard', 'bai') # user_3 = User('eggy', 'zhang') # user_1_name = user_1.describe_user() # print("\nWelcome " + user_1_name) # user_1.greet_user() # # counter = 0 # for counter in range(0, 5): # user_1.increment_login_attempts() # print(str(user_1.login_attempts)) # counter += 1 # user_1.rest_login_attempts() # print(str(user_1.login_attempts)) # user_2_name = user_2.describe_user() # print("\nWelcome " + user_2_name) # user_2.greet_user() # user_3_name = user_3.describe_user() # print("\nWelcome " + user_3_name) # user_3.greet_user()
true
27dc85dad52a603c8df7ca93ef2f35da27ed262d
danielvillanoh/conditionals
/secondary.py
2,425
4.59375
5
# author: Daniel Villano-Herrera # date: 7/23/2021 # --------------- # Section 2 # --------------- # # ---------- # Part 1 # ---------- # print('----- Section 2 -----'.center(25)) print('--- Part 1 ---'.center(25)) # 2 - Palindrome print('\n' + 'Task 1' + '\n') # # Background: A palindrome is a word that is the same if read forwards and backwards. Examples of palindromes include: # - mom # - dad # - radar # - deified # # Instructions # a. Prompt input from the user in the form of a word. # b. Determine if the word is a palindrome. # a. If so, print that the word is a palindrome. # b. Otherwise, print that the word is not a palindrome. word = input('Please enter a word: ') # Creating a function called palindrome with words as parameter. def palindrome(words): # Creating a variable called reserve which will take the parameter and reserve it. reverse = words[::-1] # If the parameter and reserve are the same, then we print out that they are the same, not if otherwise. if words == reverse: print('The word is a palindrome.') else: print('The word is not a palindrome') palindrome(word) # 2 - for Loop Patterns print('\n' + 'Task 2' + '\n') # # # Instructions # a. Create at least two of the following patterns using for loops and conditionals. One has been done for you as an # example. You still have to do two more. You are free to choose which ones you do. # b. Use the symbol specified by the user. # $$$$$ | i = 0 # $ | i = 1 # $ | i = 2 # $$$$$ | i = 3 # $ | i = 4 # $ | i = 5 # $$$$$ | i = 6 # When i is evenly divisible by 3 --> 5 symbols. Otherwise, 1 symbol. s = input('>> symbol | ') for i in range(7): if i % 3 == 0: print(s * 5) else: print(s) print() # **** | i = 0 # * * | i = 1 # * * | i = 2 # * * | i = 3 # * * | i = 4 # * * | i = 5 # **** | i = 6 d = input('Enter a symbol: ') for i in range(7): if i % 6 == 0: print(d * 4) else: print(d + ' ' * 3 + d) print() # & | i = 0 # & | i = 1 # & | i = 2 # & | i = 3 # & | i = 4 # &&&&& | i = 5 el = input('Enter a symbol: ') for i in range(6): if i == 5: print(el * 5) else: print(el) print() # @ @ | i = 0 # @ @ | i = 1 # @ @ | i = 2 # @ | i = 3 # @ @ | i = 4 # @ @ | i = 5 # @ @ | i = 6 # ------- # - # - # - # - # - # -------
true
7473187eb899dfaf8f409aae4424c0fbc4ccb6f1
interviewprep/InterviewQuestions
/trees/python/column_order_traversal.py
1,028
4.3125
4
# Column Order Traversal # Write a traversal method for Binary Tree that prints nodes that fall on a # line from leftmost to rightmost. # Example: For following Binary Tree, # # 4 # / \ # 2 5 # / \ \ # 1 3 7 # # Column order traversal = [1, 2, 4, 3, 5, 7] # # Explanation: If we draw lines vertically, then we will see that # # | | 4 | | # | | | | | # | 2 | 5 | # | | | | | # 1 | 3 | 7 # # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None def column_order(root): columns = {} preorder(root, 0, columns) return [columns[k] for k in sorted(columns)] def preorder(node, distance, columns): if node: if distance in columns: columns[distance].append(node.val) else: columns[distance] = [node.val] preorder(node.left, distance - 1, columns) preorder(node.right, distance + 1, columns)
false
b74184838111476129625eb2f3b1f26e6f189b4f
interviewprep/InterviewQuestions
/stacksandqueues/python/reverse_parentheses.py
1,304
4.15625
4
# You are given a string s that consists of lower case English letters and brackets. # Reverse the strings in each pair of matching parentheses, starting from the innermost one. # Your result should not contain any brackets. # Example 1: # # Input: s = "(abcd)" # Output: "dcba" # # Example 2: # # Input: s = "(u(love)i)" # Output: "iloveu" # Explanation: The substring "love" is reversed first, then the whole string is reversed. # # Example 3: # # Input: s = "(es(iv(re))nU)" # Output: "Universe" # Explanation: First, we reverse the substring "oc", then "etco", and finally, the whole string. # # Example 4: # # Input: s = "a(bcdefghijkl(mno)p)q" # Output: "apmnolkjihgfedcbq" def reverse_parentheses(s): stack = [] for x in s: if x != ')': stack.append(x) else: temp = get_reverse(stack) for c in temp: stack.append(c) return ''.join(stack) def get_reverse(stack): result = [] x = len(stack) - 1 while stack[x] != '(': result.append(stack.pop()) x -= 1 stack.pop() # Get rid of '(' return result if __name__ == '__main__': tests = ["(abcd)", "(u(love)i)", "(es(iv(re))nU)", "a(bcdefghijkl(mno)p)q"] for t in tests: print(reverse_parentheses(t))
true
86196f2b2663b2b5a5da6a1a0ed3c5f5686c6654
ivo-pontes/Python3
/ed/Queue.py
1,035
4.375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -* ''' Classe Fila FIFO = FIRST IN FIRST OUT ''' class Queue: #Fila def __init__(self): self.queue = [] self.size = 0 ''' Insere ao fim da fila ''' def push(self, item): self.queue.append(item) self.size += 1 ''' Remove o primeiro item da fila ''' def pop(self): if not self.empty(): self.queue.pop(0) self.size -= 1 else: print("Fila Vazia!") ''' Verifica se a fila está vazia ''' def empty(self): return True if self.size == 0 else False ''' Retorna o tamanho da fila ''' def length(self): return self.size ''' Retorna o primeiro Item da fila ''' def front(self): if not self.empty(): return self.queue[0] #Fila ''' print("Fila") q = Queue() q.push(10) q.push(2) q.push(4) print("Vazia: {}".format(q.empty())) print("Tamanho: {}".format(q.length())) print("Frente: {}".format(q.front())) q.pop() print("Frente: {}".format(q.front())) q.pop() print("Frente: {}".format(q.front())) q.pop() print("Vazia: {}".format(q.empty())) '''
false
d6ab5e83c842579911b3e6504ec2f9aa288604d6
natacadiz/Nata
/Ejercicios Unidad 1/1.4.py
299
4.125
4
# Escribe un programa que le pida al usuario una temperatura en grados Celsius, la convierta a grados Fahrenheit e imprima por pantalla la # temperatura convertida. celsius=float(input("Cuantos grados celsius hace?: ")) fahrenheit= (celsius*9/5)+32 print ("Hace",fahrenheit,"grados Fahrenheit")
false
66af55819c15092e3431065410c26c302cf2e279
Tayyab-Ilahi12/Python-Programs-for-practice
/FlashCard Game.py
1,900
4.46875
4
""" This flashcard program allows the user to ask for a glossary entry. In response,if user select show flash card the program randomly picks an entry from all glossary entries. It shows the entry. After the user presses return, the program shows the definition of that particular entry. If user select show_definition the program randomly picks a definition fro the glossary. It shows the definition and if user presses return, the program displays the key of the random definition displayed. The user can repeatedly ask for an entry , or the definition also has the option to quit the program instead of seeing another entry or definition. """ from random import * def show_flashcard(): """ Show the user a random key and ask them to define it. Show the definition when the user presses return. """ random_key = choice(list(glossary)) print('Define: ', random_key) input('Press return to see the definition') print(glossary[random_key]) def show_definition(): """Show the user a random definiton. Show the key which is associated with the random definition printed above""" random_key = choice(glossary.values()) print(random_key) input('Press return to see the word') key = glossary.keys()[glossary.values().index(random_key)] print key # Set up the glossary glossary = {'word1':'definition1', 'word2':'definition2', 'word3':'definition3'} # The interactive loop exit = False while not exit: user_input = sinput('Enter s to show a flashcard,Enter d to see a definition and q to quit: ') if user_input == 'q': exit = True elif user_input == 's': show_flashcard() elif user_input == 'd': show_definition() else: print('You need to enter either q or s.')
true
4f58cdbfa6c6e24a07ad1305632cca0e50dfb70b
Ananya31-tkm/PROGRAMMING_LAB_PYTHON
/CO2/CO2-Q1.py
213
4.1875
4
n=int(input("enter number:")) fact=1 if n<0: print("cannot find factorial") elif n==0: print("Factorial is 0") else: for i in range(1,n+1): fact=fact*i print("Fctorial of ",n," is",fact)
true
a22fca2b62384a297e2feea5dbfa57a3dc509313
ArtHouse5/python_progs
/simple_tasks.py
2,303
4.21875
4
#1 print('Create list of 6 numbers and sort it in ascending order') l=[4,23,15,42,16,8] print('The initial list is ',l) l.sort() print(l) print() #2 print('Create dictionary with 5 items int:str and print it pairwise') d = {1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four', 5 : 'five'} print('The initial dictionaty is ',d) for key in d: print(key,d[key]) print() #3 print('Create tuple with 5 fractions and find min and max in it') from fractions import Fraction t=(Fraction(1,2),Fraction(2,3),Fraction(5,7),Fraction(1,4),Fraction(7,8)) print('The initial tuple is ',t) print('The maximum in this tuple is {}, the minimum is {}'.format(max(t),min(t))) print() #4 print('Create list of three words and concatenate it to get "word1->word2->word3"') l2=['Earth','Spain','Madrid'] print('The initial list is ',l2) sep='->' print(sep.join(l2)) print() #5 print(' Split the string "/bin:/usr/bin:/usr/local/bin" into list by symbol ":" ') s = '/bin:/usr/bin:/usr/local/bin' print(s.split(':')) print() #6 print('print which numbers from 1 to 100 are devided by 7 and which are not') for i in range(1,101): if i%7==0: print(i, ' devided by 7') else: print(i, ' is not devided by 7') print() #7 print('Create matrix 3x4 and print firstly all the rows then all the columns') multi=[[1,2,3,4], [5,6,7,8], [9,10,11,12] ] print('The initial matrix is ',multi) print('Rows are :') for row in multi: print(row) print('Columns are:') for column in range(0,4): print() for i in range(0,3): print(multi[i][column]) print() """ also we can do it with the help of numpy: import numpy as np A = np.array([[1,2,3,4],[5,6,7,8]]) array([[1, 2, 3, 4], [5, 6, 7, 8]]) A[:,2] # returns the third columm """ #8 print('Create a list and in the loop write the object and its index') l3=['booom', 84, None, 'python', True, False, 90, 33] print(l3) for object in l3: print('Object {} has index {}'.format(object,l3.index(object))) #9 print('Create a list with tree values "to_delete" among the others and delete them') l4=['to_delete','Good!','better','to_delete','to_delete','the_best'] print(l4) while 'to_delete' in l4: l4.remove('to_delete') print('Clear list : ',l4) #10 print('Print numbers from 10 to 1') for i in range(10,-1,-1): print(i)
true
d16fca91d7550b7a22417b6730d2d92cde1b217b
annamaryjacob/Python
/OOP/Polymorphism/2str.py
508
4.25
4
class Person(): def setPerson(self,age,name): self.age=age self.name=name def __str__(self): return self.name+str(self.age) ob=Person() ob.setPerson(25,"name") print(ob) #When we give print(ob) we get '<__main__.Person object at 0x7f92fee45ba8>'. This is the method called 2string method in the parent class #'Object' which is a parent class for every class we make. We overide this method in our child class (def __str__(self) so that when #we print ob we get only 'name'
true
6c048cc77e200c6e6a379addf34afc63bf910e5a
mherr77m/pg2014_herrera
/HW2/HW2_q1.py
1,280
4.3125
4
# !env python # Michael Herrera # 10/18/14 # HW2, Problem 1 # Pass the function two arrays of x,y points and returns # the distance between all the points between the two arrays. import numpy as np def distance(array1,array2): """ Calculates the distance between all points in two arrays. The arrays don't have to be the same size. Each array has the form [[x1,y1],[x2,y2],...,[xn,yn]] """ # Use array broadcasting in the distance formula to # allow for arrays of different sizes dist = np.sqrt((array1[:,0,np.newaxis] - array2[:,0])**2 + \ (array1[:,1,np.newaxis] - array2[:,1])**2) return dist if __name__ == '__main__': array1 = np.array([[1,2],[3,4],[5,6],[7,8]]) array2 = np.array([[1,2],[3,4]]) dist = distance(array1,array2) print "Problem 1:\n" print "Points from array1" for p in array1: print ' (%.0f,%.0f)' % (p[0],p[1]) print "Points from array2" for p in array2: print ' (%.0f,%.0f)' % (p[0],p[1]) print "\nPoint 1 Point 2 Distance" ic = 0 for i in array1: jc = 0 for j in array2: print " (%.0f,%.0f) (%.0f,%.0f) %.2f" % \ (i[0],i[1],j[0],j[1],dist[ic,jc]) jc += 1 ic += 1
true
ac8d4d04a1118995b2aba680aa09472a85a7d92d
nikhitha1997/studentproctor
/proct.py
1,817
4.25
4
#Student procter class Student(): def studentdetails(self): #adding the student details """ Attributes: self.student_name --- name of the student self.usn ---- usn of that perticutar student self.ph_no self.branch----branch of the student_details self.marks---student internal and externa marks """ #dictoinary to store all the personaldatails of the student self.student_details = {} self.student_name=input('Enter the student\'s name:') self.usn=input('Enter the USN of the student: ') self.ph_no=int(input('Enter the phone number of the student: ')) self.branch=input('Enter the branch in which the student is studying in: ') stud_dict = {} stud_dict["student_name"] = self.student_name stud_dict['ph_no']=self.ph_no stud_dict['branch']=self.branch self.student_details[self.usn]= stud_dict #using usn as a key def display_student_details(self): #display all the personal details of the student for i, val in self.student_details.items(): print(i ,val) def enter_marks(self): #entering the student marks a=[] i = 0 #usn is used as pin usn = input("Enter the USN of the student whose marks you want to enter: ") while i < 3: print(i) internal=int(input('enter the marks:'))#to enter the internal marks if internal<=20: a.append(internal) print(a) i += 1 else: print('invalid') print(i) self.student_details[usn]['internal_marks']=a external=int(input('external marks:')) #external marks if external<=80: self.student_details[usn]['external_marks']=external else: print('invalid') if __name__ == "__main__": student=Student() student.studentdetails() student.display_student_details() student.enter_marks()
false
ca7c7c91bf638b4e18660677fe8fb4f7630c4c01
Neenu1995/CHPC-PYTHON
/bisection_cuberoot.py
322
4.125
4
number = input('Enter the number : ' ) number = float(number) change = 0.00001 low =0.0 high = max(1.0,number) mid = (low+high)/2.0 while (abs(mid**3-number)>=change): if mid**3<number: low = mid else: high = mid mid =(low+high)/2.0 print 'The cube root of ', number ,' is ', mid
true
236a2cea8c179cb2ce1d4a8c9fe1c53c22ff1226
ggoolsby/CS-101-HW
/graysongoolsby_HW5.py
1,496
4.125
4
# -*- coding: utf-8 -*- """ Created on Tue Mar 14 09:44:07 2017 @author: graygoolsby Name: Grayson Goolsby Date: 03-22-17 Lab: X """ import turtle def binary2decimal(bs): """converts a binary string to a decimal number""" if bs=='': return 0 else: return binary2decimal(bs[:-1])*2+(int(bs[-1])) def decimal2binary(n): """turns a decimal number into a binary string""" if n==0: return '' else: return decimal2binary(n//2)+str(n%2) def GCD(a, b): """uses remainders to determine the greatest common divisor of two numbers, when a and b are positive integers""" rem=a%b if rem==0: return b else: return GCD(b,rem) def stairs(l, g): """draws recursive boxes in the pattern of stairs""" if g>0: turtle.forward(l) turtle.right(90) turtle.forward(l) turtle.left(90) stairs(l/2, g-1) turtle.backward(l) turtle.right(90) turtle.backward(l) turtle.left(90) def drawStairsScene(): """ Moves the turtle to the top left of the screen and draws a staircase. """ # pick up the pen and move the turtle so it starts at the left edge of the canvas turtle.penup() turtle.goto(-turtle.window_width()/2 + 20, turtle.window_height()/2 - 20) turtle.pendown() # draw the tree by calling your function stairs(300,7) # finished turtle.done()
false
185abd0b12115a2cf3f91ac799fccc664c403a14
LessonsWithAri/textadv
/next.py
1,803
4.15625
4
#!/usr/bin/env python3 INVENTORY = [] room_learning_took_soda = False def room_learning(): global room_learning_took_soda print("You are in room #312. You see a Kellan, a Maria, and a Brooke.") if not room_learning_took_soda: print("There is a can of soda on the table.") print("Exits: DOOR") command = input("> ").lower() if command == "door": print("You have gone through the door.") room_hallway() elif command == "kellan": print("Kellan says, 'Hi!'") room_learning() elif command == "maria": print("Maria is busy doing coding") room_learning() elif command == "brooke": print("Brooke is writing a story") room_learning() elif command == "take the soda" and not room_learning_took_soda: print("You pick up the soda. It's nice and cold.") room_learning_took_soda = True INVENTORY.append('soda') room_learning() else: print("INVALID COMMAND!!!") room_learning() room_hallway_gave_matt_soda = False def room_hallway(): global room_hallway_gave_matt_soda print("You are in the hallway. It's very spoooooky.") if not room_hallway_gave_matt_soda: print("Matt is here, he's very thirsty.") print("Exits: LEARNING") command = input("> ").lower() if command == "learning": print("You are going back to the learning room.") room_learning() elif command == "give matt the soda" and not room_hallway_gave_matt_soda and 'soda' in INVENTORY: print("You give Matt the soda. He says thanks, gulps it down, and leaves.") INVENTORY.remove('soda') room_hallway_gave_matt_soda = True room_hallway() else: print("INVALID COMMAND!!!") room_hallway() room_learning()
true
6a8b4dab5c7639a003dc530cb9d4bf6c5fb5c552
Michaeloye/python-journey
/simp-py-code/Password_Validation_sololearn.py
1,044
4.40625
4
# Password Validation : You are interviewing to join a security team. They want to see you build a password evaluator for your technical interview to validate #the input. #task: Write a program that takes in a string as input and evaluates it as a valid password. The password is valid if it has a minimum 2 numbers, 2 of #the following special characters('!', '@', '#', '$', '%', '%', '*'), and a length of at least 7 characters. if the password passes the check, output 'Strong' #else output 'Weak'. #Input Format: A string representing the password to evaluate. #Output Format: A string that says 'Strong' if the input meets the requirements, or 'Weak', if not. #Sample Input: Hello@$World19 #Sample Output: Strong import string password = input("Enter password \n") numbers = 0 sym = string.punctuation no_of_sym = 0 for char in password: if char.isnumeric(): numbers += 1 elif char in sym: no_of_sym += 1 if no_of_sym >= 2 and numbers >= 2 and len(password) >= 7: print("Strong") else: print("Weak")
true
9940f0e66b71ed701e9ee4440772a39b4f0d8726
Michaeloye/python-journey
/simp-py-code/Tkinter_trial_DL.py
2,046
4.5625
5
from tkinter import * # Import all definitions from tkinter window = Tk() # Create a window label = Label(window, text = "Welcome to Python") # Create a label button = Button(window, text = "Click Me") # Create a button label.pack() # Place the label in the window button.pack() # Place the button in the window window.mainloop() window = Tk() label = Label(window, text = "Welcome to Python", cursor = "plus", justify = LEFT) button = Button(window, text = "Click") button.pack() # pack manager packs it row by row therefore the button comes before the label label.pack() window.mainloop() # This creates an event loop which processes the events until you close the main window # so therefore you have to create a window again using window = Tk() else it would give an error def pressbutton(): label["text"] = "Hi" # to change the text written... from "thank you" to "Hi" window = Tk() label = Label(window, text = "Hello there") button = Button(window, text = "Thank you", bg = "skyblue",command = pressbutton) label.pack() button.pack() window.mainloop() window = Tk() frame1 = Frame(window) frame1.pack() label = Label(frame1, text = "Hello") button = Button(frame1, text = "okay") label.grid(row = 1, column = 1) button.grid(row = 1, column = 2) window.mainloop() window = Tk() # Create a window window.title("Grid Manager Demo") # Set title message = Message(window, text ="This Message widget occupies three rows and two columns") message.grid(row = 1, column = 1, rowspan = 3, columnspan = 2) Label(window, text = "First Name:").grid(row = 1, column = 3) Entry(window).grid(row = 1, column = 4, padx = 5, pady = 5) Label(window, text = "Last Name:").grid(row = 2, column = 3) Entry(window).grid(row = 2, column = 4) Button(window, text = "Get Name").grid(row = 3, padx = 5, pady = 5, column = 4, sticky = E) image_1 = PhotoImage(file = "download.gif") canvas = Canvas(window, width = 300, height = 400) canvas.create_image(70,90, image = image_1) canvas.grid(row = 4, column = 7) window.mainloop() # Create an event loop
true
338d446f53b76308220122fdd2b1115eaf3906db
Michaeloye/python-journey
/simp-py-code/raise_to_power.py
588
4.40625
4
#raise to power base_num = int(input("Enter the base number: ")) pow_num = int(input("Enter the power number: ")) def raise_to_power(base_num, pow_num): result = 1 for num in range(pow_num): '''since the pow_num is what the base_num will multiply itself by. so pow_num if 3 will cause the code loop 3 times that means 1*4 for pow_num 1 then pow_num 2 the result will be stored as 4 for pow_num 1 then run again present result 4 4*4 for pow_num 3 16*4''' result = result * base_num return result print(raise_to_power(base_num, pow_num))
true
a68f609d435c84d30dc569699894df16d8db9354
Michaeloye/python-journey
/simp-py-code/New_driver's_license_sololearn.py
1,372
4.1875
4
# New Driver's License #You have to get a new driver's license and you show up at the office at the same time as 4 other people. The office says that they will see everyone in #alphabetical order and it takes 20 minutes for them to process each new license. All of the agents are available now and they can each see one customer at a #time. How long will it take for you to walk out of the office with your new license? # Task: Given everyon's name that showed up at the same time, determine how long it will take to get your new license. # Input Format: Your input will be a string of your name, then an integer of the number of available agents, and lastly a string of the other four names #seperated by spaces. # Output Format: You will output an integer of the number of minutes that it will take to get your license. # Sample Input: # "Eric" # 2 # "Adam Caroline Rebecca Frank" # Sample Output: # 40 Explanation it will take 40 minutes to get your license because you are in the second group of two to be seen by one of the two available agents. name = input("Please enter your name: ") no_of_agents = int(input("Please enter the number of agents: ")) others = input("Please enter the names of the rest people: ") list1 = [] others_split = others.split() list1.extend(others_split) list1.append(name) list1.sort() answer = int(((list1.index(name)/no_of_agents)*20) + 20) print(answer)
true
24f8a43e73503662cd2a930ad44a5fe1cb29e16f
Michaeloye/python-journey
/simp-py-code/task21.py
658
4.125
4
# Bob has a strange counter. At the first second t=1, it displays the number 3. At each subsequent second, the number displayed by the counter decrements by 1. # the counter counts down in cycles. In the second after the counter counts down to 1, the number becomes 2 times the initial number for that countdown cycle # and then continues counting down from the new initial number in a cycle. # Given a time, t. Find and print the value displayed by the counter at time t. v = 3 t = 1 time = int(input("Enter the time at which you want to know the value: ")) while time < t : if v == 1: break t += 1 v -= 1 t = t * 2 print(t)
true
25b83260765a26cab0ba821ad5b69b5161ffc171
Michaeloye/python-journey
/simp-py-code/task7.py
672
4.1875
4
# Given a string input count all lower case, upper case, digits, and special symbols def findingchars(string): ucharcount = 0 lcharcount = 0 intcount = 0 symcount = 0 for char in string: if char.isupper(): ucharcount+=1 elif char.islower(): lcharcount+=1 elif char.isnumeric(): intcount+=1 else: symcount+=1 print("Number of lowercase characters is ", lcharcount, " Number of uppercase characters is ", ucharcount, " Number of integers is ", intcount, " Number of symbols is ", symcount,) findingchars("GUioKJio*$%#124")
true
a802e0447e69c9e42b353305575d0762fcbc3f86
fish-py/PythonImpl
/collections/dict.py
237
4.125
4
dict1 = { "firstName": "Jon", "lastName": "Snow", "age": 33 } """ 遍历dict """ for key in dict1.keys(): print(key) for value in dict1.values(): print(value) for key, value in dict1.items(): print(key, value)
true
45df33b916bb8d19ac17790fb182f14166480437
fish-py/PythonImpl
/collections/sorted_list.py
449
4.1875
4
""" sorted函数可以将一个iterable进行排序 使用的时候我们需要传递一个函数作为排序规则 https://www.runoob.com/python/python-func-sorted.html """ # 自定义排序规则: 按照字符串的长度来排序 def key(item): return len(item) if __name__ == "__main__": list1 = ["Java", "Python", "C", "Go", "C++"] list2 = sorted(list1, key=key) print(list2) # ['C', 'Go', 'C++', 'Java', 'Python']
false
376948215d3a318897c6f836e31ef5b75a7a87e3
kangic/study
/ds_algo/sorting/insertion.py
374
4.1875
4
# -*- coding: utf-8 -*- def insertion_sort(ar): for i in range(1, len(ar)): idx = i - 1 value = ar[i] while (idx >= 0 and ar[idx] > value): ar[idx + 1] = ar[idx] idx = idx - 1 ar[idx + 1] = value return ar if __name__ == "__main__": changed_ar = insertion_sort([3,6,1,8,5,9,4,2,7]) print(changed_ar)
false
e58d6c0bc2831729f65f722de7e4bb30b7291a4b
DanielSouzaBertoldi/codewars-solutions
/Python/7kyu/Isograms/solution.py
508
4.15625
4
# Calculates the ocurrence of every letter of the word. # If it can't find more than one ocurrence for every letter, # then it's an isogram. def is_isogram(string): string = string.lower() for char in string: if string.count(char) > 1: return False return True # That was my first try at this challenge. Then ocurred to me # you could use the set() function and just compare the # lengths, like so: def is_isogram(string): return len(string) == len(set(string.lower()))
true
b20046be773df17575d2c87213cc2c55aa70e186
n8951577/scrapy
/factorial.py
253
4.1875
4
def factorial(x): if x == 1: return 1 else: return x * factorial(x - 1) try: n = int(input("enter a number to find the factorial of a digit")) print ("The factorial of n is %d" % factorial(n)) except: print("Invalid")
true
dc0d64d1c54a204ecebbb0a589f354f13447c876
priyanshi1996/Advanced_Python_Course
/Ex_Files_Adv_Python/Exercise Files/04 Collections/defaultdict_finished.py
1,272
4.5
4
# Demonstrate the usage of defaultdict objects from collections import defaultdict def main(): # define a list of items that we want to count fruits = ['apple', 'pear', 'orange', 'banana', 'apple', 'grape', 'banana', 'banana'] fruitCount = {} # Count the elements in the list # This code will give error because we are trying to modify the value # of this key, before its been initialy added to the dictionary for fruit in fruits: fruitCount[fruit] += 1 # To avoid the above error we could write something like this for fruit in fruits: if fruit in fruitCount.keys(): fruitCount[fruit] += 1 else: fruitCount[fruit] = 1 # use a dictionary to count each element # this code says that if I am trying to access a key which # does not exists, create a default value for me fruitCounter = defaultdict(int) # We can also use lambda here, here each key will start from 100 # fruitCounter = defaultdict(lambda:100) # Count the elements in the list for fruit in fruits: fruitCounter[fruit] += 1 # print the result for (k, v) in fruitCounter.items(): print(k + ": " + str(v)) if __name__ == "__main__": main()
true
5af4158a8ff3d270b35e6b6b02332ca3cb82ce43
IfthikarAliA/python
/Beginner/3.py
261
4.125
4
#User input no. of Element a=int(input("Enter the number of Element: ")) #Empty List l=[] #Function to get list of input for i in range(a): l.append(int(input(f"Enter the {i+1} item: "))) #Iterator over a list for i in l: if(i%2==0): print(i)
true
f707d8fc6cf42c70d569c187792d1fa674f17bc0
austindrenski/GEGM-Programming-Meetings
/ProgrammingMeeting1_Python/Example.py
428
4.125
4
class Example: """Represents an example.""" def __init__(self, value): self.value = value def increase_value(self, amount): """Increases the value by the specified amount.""" self.value = self.value + amount return self.value > 0 def __repr__(self): """Returns a string that represents the current object.""" return "The value of this example is %i" % self.value
true
663c8604ccf16d20dd92c597ba4b5f33fd26bb39
austinrhode/SI-Practical-3
/shortest_word.py
488
4.4375
4
""" Write a function that given a list of word, will return a dictionary of the shortest word that begins will each letter of the alphabet. For example, if the list is ["Hello", "hi", "Goodbye", "ant", "apple"] your dictionary would be { h: "Hi", g: "Goodbye", a: "ant" } because those are the shortest words that start with h, g, and a (which are the only starting letters present) Notice that the function is not case sensitive. """ def shortest_word(a_list): pass
true
0ea757ff04c81a1a53a6cba0275cc12433cc0c36
ikhlestov/computational_geometry
/algorithms/predicates.py
783
4.125
4
from algorithms.primitives import Point, LineSegment def cross_product(u, v): return u.x * v.y - u.y * v.x def points_turn_value(a: Point, b: Point, c: Point) -> float: return cross_product(b - a, c - a) def line_segments_turn_value(l1: LineSegment, l2: LineSegment) -> float: return cross_product(l1.p2 - l1.p1, l2.p2 - l2.p1) def turn(a: Point, b: Point, c: Point) -> int: """Return correspondence of three points. 1 - left turn (`c` lies left from ab) -1 - right turn (`c` lies right from ab) 0 - collinear References: https://habr.com/ru/post/138168/ """ turn_value = points_turn_value(a, b, c) if turn_value > 0: return 1 # left elif turn_value < 0: return -1 # right else: return 0
false
3f63aac86bed8b98276e9850fbb00421121d6eae
BridgitA/Week10
/mod3.py
713
4.125
4
maximum_order = 150.00 minimum_order = 5.00 def cheese_program(order_amount): if order_amount.isdigit() == False: print("Enter a numeric value") elif float(order_amount) > maximum_order: print(order_amount, "is more than currently available stock") elif float(order_amount) < minimum_order: print(order_amount, "is less than currently available stock") elif (float(order_amount)<= maximum_order) and (float(order_amount)>= minimum_order): print(order_amount, "pounds costs", int(order_amount) * 5) else: print("Enter numeric value") weight = input("Enter cheese order weight (pounds numeric value): ") function = cheese_program(weight)
true
f8293c7294cc10da6dab7dfedf7328c865f899fe
michellesanchez-lpsr/class-sampless
/4-2WritingFiles/haikuGenerator.py
794
4.3125
4
# we are writing a program that ask a user for each line of haiku print("Welcome to the Haiku generator!") print("Provide the first line of your haiku:") # create a list to write to my file firstL = raw_input() print(" ") print("Provide the second line of your haiku:") secondL = raw_input() print(" ") print("Provide the third line of your haiku:") thirdL = raw_input() print(" ") print("What file would you like to write your haiku to?") # ask the user for raw_input x = raw_input() myProgram = open( x , "w") myProgram.write(firstL) myProgram.write(secondL) myProgram.write(thirdL) print("Done! To view your haiku, type 'cat' and the name of your file at the command line.") print("When you run cat and the file name at the terminal, you should get your haiku!") myProgram.close()
true
9e20d9bab577aba6e39590e3365b56b9325dd32a
michellesanchez-lpsr/class-sampless
/msanchez/university.py
584
4.1875
4
# print statements print(" How many miles away do you live from richmond state?") miles = raw_input() miles = int(miles) #if else and print statements if miles <=30: print("You need atleast 2.5 gpa to get in") else: print("You need atleast 2.0 gpa to get in") print(" What is your gpa?") gpa = float(raw_input()) gpa = int(gpa) if miles <=30 <= 2.0: print("Great you have been accepted") else: print("What is your act score?") act = (input()) act = int(act) if miles >30 and gpa >= 2.5 and act >=18: print("Sorry you need all 3 to get in") else: print("Accepted")
true
5ff742b0b2ec95157cc738b9668d911db3ee6e7e
ceden95/self.py
/temperature.py
445
4.46875
4
#the program convert degrees from F to C and the opposite. temp = input("Insert the temperature you would like to convert(with a 'C' or 'F' mark):") temp_type = temp[-1].upper() temp_number = float(temp[:-1]) C_to_F = str(((9*temp_number)+(160))/5) F_to_C = str((5*temp_number-160)/9) if (temp_type == "C"): print(C_to_F + "F") elif (temp_type == "F"): print (F_to_C + "C") else: print("told you to mark the temperature")
true
76f0e060b29af72dd5420918b10a0b2034073891
ceden95/self.py
/9.3.1.fileFor_listOfSongs.py
2,791
4.34375
4
#the program uses the data of file made from a list of songs details in the following structure: #song name;artist\band name;song length. #the function my_mp3_playlist in the program returns a tuple of the next items: #(name of the longest song, number of songs in the file, the most played artist) def main(): file_path = "C:\python course\9.3.1\9.3.1.listOfSongs.txt" playlist_tuple = my_mp3_playlist(file_path) print(playlist_tuple) def my_mp3_playlist(file_path): """the function creates a tuple of 3 item from a date in file_path. :param file_path: file path to a file of playlist. :file_path type: str :return: (first_in_tuple, second_in_tuple, third_in_tuple). :rtype: tuple""" opened_file_path = open(file_path, "r") readed_file_path = opened_file_path.read() opened_file_path.close() #the longest song first_in_tuple = find_the_longest_song(readed_file_path) #number of songs in the file second_in_tuple = len(song_details_in_list(readed_file_path)) #the most played artist third_in_tuple = find_most_played_artist(readed_file_path) ourTuple = (first_in_tuple, second_in_tuple, third_in_tuple) return ourTuple def song_details_in_list(readed_file_path): splited_lines_file = readed_file_path.split("\n") song_details = [] for item in splited_lines_file: splited_item = item.split(";") song_details.append(splited_item) return song_details def find_the_longest_song(readed_file_path): song_details = song_details_in_list(readed_file_path) listOfSongsStr = [] for item in song_details: listOfSongsStr.append(item[2]) listOfSongsFloat = [] for item in listOfSongsStr: a = item.replace(":", ".") strToFloat = float(a) listOfSongsFloat.append(strToFloat) listOfSongsFloat.sort() longestSong = str(listOfSongsFloat[-1]).replace(".", ":") for item in song_details: if longestSong in item: longest_song = item[0] return longest_song def find_most_played_artist(readed_file_path): song_details = song_details_in_list(readed_file_path) listOfArtist = [] for item in song_details: listOfArtist.append(item[1]) times_played_dict = {} for item in listOfArtist: if item in times_played_dict.keys(): times_played_dict[item] = int(times_played_dict[item]) + 1 else: times_played_dict[item] = 1 maxValue = max(times_played_dict.values()) ourArtist = "" for key in times_played_dict.keys(): if(times_played_dict[key] == maxValue): ourArtist = key break return ourArtist main()
true
266f1eef9643832e942c30fec52406331b26b8ae
ceden95/self.py
/for_loop.py
816
4.3125
4
#the program creates a new list(from the list the user created) of numbers bigger then the number the user choosed. def main(): list1 = input('type a sequence of random numbers devided by the sign ",": ') my_list = list1.split(",") n = int(input("type a number which represent the smallest number in your new list: ")) is_greater(my_list, n) def is_greater(my_list, n): """the fuction creates a list of numbers from my_list from numbers bigger them number n. :param my_list: list of numbers :my_list type: list :param n: number from user :n type: int""" my_new_list = [] for num in my_list: num = int(num) if num > n: my_new_list.append(num) else: continue print(my_new_list) main()
true
f55a6562de4c30e76723c61ef0a3a60ef178bec2
ceden95/self.py
/shift_left.py
713
4.4375
4
#the program prints the new list of the user when the first item moving to the last on the list. def shift_left(my_list): """the func receives a list, replace the items on the list with the item on the left :param my_list: list from user. :type my_list: list. :return: my_shift_list :rtype: list with str items""" my_list.append("") my_list[-1] = my_list[0] my_shift_list = my_list[1:-1] + [my_list[-1]] print(my_shift_list) list = input('please type a group of numbers\\words devided by "," (without space):') print("your list is: ") print(list) list = list.split(",") print("your new updated list with the first item to the last is:") shift_left(list)
true
a840b3093757889fb34c8aaf13df449ea52dc3d0
ceden95/self.py
/dates_to_days.py
559
4.4375
4
#the program prints back the day of the date the user choosed. date = input(" please write a date which contains dd/mm/yyyy:") dd = int(date[:2]) mm = int(date[3:5]) yyyy = int(date[-4:]) import calendar what_day = calendar.weekday(yyyy, mm, dd) if what_day == 0: print("monday") elif what_day == 1: print("tuesday") elif what_day == 2: print("wednesday") elif what_day == 3: print("Thursday") elif what_day == 4: print("Friday") elif what_day == 5: print("Saturday") elif what_day == 6: print("Sunday")
false
c32e466c8f7004bc5e9b8fd23cfe9714d39cad09
Andrewctrl/Final_project
/Visting_Mom.py
744
4.25
4
import Visting_mom_ending import Getting_help def choice(): print("You get dressed up quicky as you rush out to visit your mom in the hospital. " + "You visit your mom in the hospital, she is doing well. But you have a pile of bills. You get a job working at In-and-Out. Balancing work and school is hard, your grades are dropping.") answer = input("Do you quit school and work full time, or do you try to get help with school, therefore maintaining your job and school." + "Type \"Quit School\" to quit school, \"Get help\" to get help with school.") # question for dropping out or getting help with school if answer == "Quit School": Visting_mom_ending.final() if answer == "Get Help": Getting_help.got_help()
true
ea5a201812b6f4ad9ba49505a53e99bcbf207a42
ar021/control-flow-lab
/exercise-2.py
305
4.15625
4
# exercise-02 Length of Phrase while True: phrase = input('Please enter a word or phrase or "quite" to Exit:') if phrase == 'quite': print('Goodbye') break else: phrase_length = len(phrase) print(f'What you entered is {phrase_length} characters long')
true
d2cc0691e0e05128e98144d19206b7a6f2df3f70
EVgates/VSAproject
/proj02/proj02_02.py
1,100
4.3125
4
# Name: # Date: # proj02_02: Fibonaci Sequence """ Asks a user how many Fibonacci numbers to generate and generates them. The Fibonacci sequence is a sequence of numbers where the next number in the sequence is the sum of the previous two numbers in the sequence. The sequence looks like this: 1, 1, 2, 3, 5, 8, 13... """ amount = int(raw_input("How many numbers do you wish to generate?")) x=0 y=1 print y while amount-1> 0: z = x + y print z x= y y= z amount= amount-1 print "Generation complete." c = raw_input("Do you want to generate any more numbers?") if c=="yes" or c=="Yes" or c=="Yeah" or c== "Yep" or c=="YES" or c=="yep" or c=="yeah" or c=="y" or c=="Y": dog = int(raw_input("How many numbers do you wish to generate this time?")) x=0 y=1 print y for number in range (1,dog): z = x+ y print z x= y y= z dog= dog + 1 "Program complete." elif c=="no" or c=="No" or c=="NO" or c=="Nope" or c=="nope": print "Program complete." else: print "That is an unacceptable answer. Program incomplete."
true
0c6f697432c64e2ff1dfd39192c3e2d5d7938ba9
H0bbyist/hero-rpg
/hero_rpg.py
2,112
4.1875
4
from math import * #!/usr/bin/env python # In this simple RPG game, the hero fights the goblin. He has the options to: # 1. fight goblin # 2. do nothing - in which case the goblin will attack him anyway # 3. flee class Character: def alive(self): if self.health > 0: return True def attack(self, enemy): enemy.health -= self.power def print_status(self): print("The {} has {} health and {} power.".format(self.name, self.health, self.power)) class Hero(Character): def __init__(self, name, health, power): self.name = name self.health = health self.power = power class Goblin(Character): def __init__(self, name, health, power): self.name = name self.health = health self.power = power class Zombie(Character): def __init__(self, name, health, power): self.name = name self.health = health self.power = power hero = Hero("Hero", 10, 5) goblin = Goblin("Goblin", 6, 2) zombie = Zombie("Zombie", float(inf), 100) en = zombie while en.alive() and hero.alive(): print() hero.print_status() en.print_status() print() print("What do you want to do?") print("1. fight {}".format(en.name)) print("2. do nothing") print("3. flee") print("> ", end=' ') raw_input = input() if raw_input == "1": # Hero attacks goblin hero.attack(goblin) print("You do {} damage to the {}.".format(hero.power,en.name)) if en.health <= 0: print("The {} is dead.".format(en.name)) elif raw_input == "2": pass elif raw_input == "3": print("What kind of hero runs?") break else: print("Invalid input {}".format(raw_input)) if en.health > 0: # Goblin attacks hero en.attack(hero) print("The {} does {} damage to you.".format(en.name, en.power)) if hero.health <= 0: print("You are dead.")
true
e2af114dca2a51f5802980c84b596e2e794ae15e
Percapio/Algorithms-and-Data-Structures
/lib/algorithms/quick_sort.py
1,957
4.15625
4
# Quick Sort: # Sort an unsorted array/list by first indexing an element as the pivot point, # check if this index is our target. If not, then check if target is more than # the indexed point. If it is then we check the right half of the list, otherwise # we check the left half. ###################################################### # Recursive Quick Sort # Time Complexity: O( nlogn ) def recursive( array ): size = len( array ) # Recursive requires base case if size <= 1: return array # Partition the array for sorting left, right, pivot = partition( array, size ) # Recursive call this function on left and right and concat # results together return recursive( left ) + [ pivot ] + recursive( right ) def partition( array, size ): # Pivot point to compare elements too pivot = array[ 0 ] # Left and right list to plug the elements in for sorting left = [] right = [] # Iterate: placing lower than in left list and higher in right for i in range( 1, size ): if array[ i ] < pivot: left.append( array[ i ] ) else: right.append( array[ i ] ) return left, right, pivot ###################################################### ###################################################### # Iterative Quick Sort # Time Complexity: O( n^2 ) def iterative( array ): # push the array onto a stack stack = array[:] size = len( stack ) # iterate until stack is empty while size > 0: # decrease stack size, and use size as index for pivot size -= 1 pivot = stack[ size ] # partition the given array around the pivot point array = partition_iter( array, pivot ) return array def partition_iter( array, pivot ): left = [] right = [] # step through the array, and partition based on for i in range( len(array) ): if array[ i ] < pivot: left.append( array[ i ] ) else: right.append( array[ i ] ) # concat return left + right
true
b8591c8775413e7a26139e3f362bb8338c6c6a4a
bhandarisudip/learn_python_the_hard_way_book_exercises
/ex7-studydrills.py
1,640
4.46875
4
#exercise 7--study drills #prints a string: 'Mary had a little lamb.' print("Mary had a little lamb.") #prints a string: 'Its fleece was white as snow.' print("Its fleece was white as %s." %'snow') #prints a string: 'And everything that Mary went.' print("And everything that Mary went.") #prints "." ten times print("." * 10) #what'd that do? -- '*' operator for strings used to repeat a character for certain times #assign a string character 'C' to variable end1 end1 = "C" #assign a string character 'h' to variable end2 end2 = "h" #assign a string character 'e' to variable end3 end3 = "e" #assign a string character 'e' to variable end4 end4 = "e" #assign a string character 's' to variable end5 end5 = "s" #assign a string character 'e' to variable end6 end6 = "e" #assign a string 'B' to variable end7 end7 = "B" #assign a string 'u' to variable end8 end8 = "u" #assign a string 'r' to variable end9 end9 = "r" #assign a string 'g' to variable end10 end10 = "g" #assign a string 'e' to variable end11 end11 = "e" #assign a string 'r' to variable end12 end12 = "r" #print a concatenation of strings end1 through end6, create a space using a comma ',' #then print a concatenation of strings end7 through end12 in the same line. print(end1+end2+end3+end4+end5+end6, end7+end8+end9+end10+end11+end12) #this also prints 'Cheese Burger' but instead of concatenating all the variables in one #line, it concatenates the end1-end6, then using a statement end = ' ' concatenates #the remaining variables end7-end12 from another line print(end1+end2+end3+end4+end5+end6, end = " ") print(end7+end8+end9+end10+end11+end12)
false
48ff5efd50d6150ab8bf1b0e5e30fb7f0bd6e585
bhandarisudip/learn_python_the_hard_way_book_exercises
/ex6-studydrills.py
1,535
4.6875
5
#ex06-study drills #assign a string to x that includes a formatting character, which is then replaced by 10 x = "There are %d types of people."%10 #create a variable, binary, and assign the string "binary" to it binary = 'binary' #assign a new variable a string "don't" to a variable 'do_not' do_not = "don't" #create a string called y, replace the formatting characters with variables "binary" and # "do_not". Example of two strings inside a string. y = "Those who know %s and those who %s."%(binary, do_not) #print x, i.e., "There are 10 types of people" print(x) #print y, i.e., "There are those who know binary and those who don't" print(y) #print "I said: There are 10 types of people". #Example of an integer (10) within a string (x), within a string "I said:" print('I said: %r'%x) #print "I also said: Those who know binary and those who do not". #Example of two strings (binary and do_not) within a string (y) within a string "I also said:" print("I also said: '%s'"%y) #assign boolean False to a variable hilarious hilarious = False #assign a string "Isn't that joke so funny?!" to a variable, joke_evaluation joke_evaluation = "Isn't that joke so funny?! %r" #assign a string "This is the left side of the string..." to variable w. w = 'This is the left side of the string...' #assign "a string with a right side" to a variable e e = 'a string with a right side' #print "This is the left side of the string...a string with a right side" #example of concatenating two strings with an operator '+' print(w+e)
true