blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
5002780e53c2f1ec05cb60da27530afc69c5dd32
jeffreybyrne/0222-assn2-inheritance1
/people.py
1,713
4.53125
5
# 1. Let's start by creating two classes: one called Student and another # called Instructor. # 2. The student class has an instance method called learn that returns # "I get it!". # 3. The instructor class has an instance method called teach that returns # "An object is an instance of a class". # 4. Both the instructor and the student have names. We know that instructors # and students are both people. Create a parent Person class that contains the # attribute name and an __init__() method to set the name. # 5. Both the instructor and the student should also be able to do a greeting, # like "Hi, my name is so-and-so". Where's the best place to put this # common method? # 6. Create an instance of instructor whose name is "Nadia" and call # their greeting. # 7. Create an instance of student whose name is "Chris" and call # their greeting. # 8. Call the teach method on your instructor instance and call the learn # method on your student. Next, call the teach method on your student instance. # What happens? Why doesn't that work? Leave a comment in your program # explaining why. class People: def __init__(self, new_name): self.name = new_name def greet(self): return "Hi, my name is {}.".format(self.name) class Student(People): def learn(self): return "I get it!" class Instructor(People): def teach(self): return "An object is an instance of a class." nadia = Instructor("Nadia") print(nadia.greet()) chris = Student("Chris") print(chris.greet()) print(nadia.teach()) print(chris.learn()) # print(chris.teach()) This won't work because the Student inherits from the # People class, but the teach method is for the Instructor class only
true
e28057c18699009e2d0c2b141ce1c42d29f79d9e
diganthdr/python_bootcamp_september
/week2/classes/class_demo.py
1,252
4.15625
4
# Structure class Bottle: x = 0 y= 1 def __init__(self, turn_direction): print("Bottle.. initializing.... ") self.turn_cap = turn_direction def open_cap(self): #member func print("Address of self:", id(self)) print("Opening cap..") print("Turn cap to: ",self.turn_cap) def shape(self): raise NotImplementedError bottle_pepsi = Bottle("right") bottle_pepsi.open_cap() #bottle_pepsi.shape() #bottle_pepsi.new_var = 89 #print(dir(bottle_pepsi)) bottle_cola = Bottle("left") bottle_cola.open_cap() #print(dir(bottle_cola)) #print("Address of bottle_pepsi:", id(bottle_pepsi)) # member functions # the 'self' object, id(self) and the id(obj) # Inheritance class GlassBottle(Bottle): #inheritance def __init__(self, turn_direction): super().__init__(turn_direction) self.turn_cap = turn_direction print("GlassBottle, opens ", self.turn_cap) def open_cap(self): #member func print("Upside..") def shape(self): print("Shape is oval") g = GlassBottle("right") print("------") print(dir(g), type(g)) g.open_cap() g.shape() # Polymorphism # Encapsulation # Abstraction
true
6ceeb9b861ba183a489bcc69c964f61f32153ba1
abdulsamad786/Python-for-programmers
/ExamTodaySamad/day1/Ex3/CreateAnArray.py
921
4.34375
4
#!/usr/bin/env python """ Create a new directory name "Ex3" copy "Ex1" in this folder. Create a new python file named "CreateAnArray.py". Call the function named AppendTheString created in the previous exercise. Append two strings from the pervious Samples Strings. Sample String Input 1: I am going to Sample String Input 2: Lahore Result: I am going to Lahore. HINT: Import the Module from pervious Ex1. """ from Ex1.string_addition import * """ What I have done is that I have imported the whole Ex1 dir in Ex3 dir.""" """Created a '__init__.py' using touch in linux. """ def calling_function(): """ In this function I am calling function AppendTheString(s1,s2), passing values to them""" calling = AppendTheString('I am going to',' Lahore') print calling def main(): calling_function() if __name__ == '__main__': main()
true
61339b3c7b766d16a104268125385e32c942652c
Excellentc/HILLEL_LES
/Lesson 6/DZ_14_Dva_spiska.py
603
4.28125
4
""" Даны два списка чисел (можно сгенерировать при помощи генератора случайных чисел). Посчитайте, сколько уникальных чисел содержится одновременно как в первом списке, так и во втором. Примечание. Эту задачу можно решить в одну строчку.""" import random x1 = {random.randint(1, 100) for _ in range(6)} print(x1) x2 = {random.randint(1, 100) for _ in range(6)} print(x2) print(len(set(x1.union(x2))))
false
b86aefff876a3f2aaa1cfe3977f5edc5cf3d2c80
Excellentc/HILLEL_LES
/Lesson 7/DZ_15_arithmetic.py
1,139
4.3125
4
""" Написать функцию arithmetic, принимающую 3 аргумента: первые 2 - числа, третий - операция, которая должна быть произведена над ними. Функция должна вернуть результат вычислений зависящий от третьего аргумент +, сложить их; если -, то вычесть; * — умножить; / — разделить (первое на второе). В остальных случаях вернуть строку "Неизвестная операция". """ def arithmetic(x1, y1, ar1): if ar1 == "+": return x1 + y1 elif ar1 == "-": return x1 - y1 elif ar1 == "*": return x1*y1 elif ar1 == "/": return x1/y1 else: print("Неизвестная операция") x = int(input("Введите первое число : ")) y = int(input("Введите второе число : ")) ar = str(input("Введите мат.операцию для этих чисел : ")) print(arithmetic(x, y, ar))
false
8697bd841d31112b709d141f98dfba63bac2dc17
rajagoah/LeetCodeChallenge
/Week-1 challenge 2 -Happy numbers.py
981
4.15625
4
#Write an algorithm to determine if a number is "happy". #A happy number is a number defined by the following process: #Starting with any positive integer, replace the number by the sum of the squares of its digits, #and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in #a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers num = 345 # coverting to string to iterate through it num_Str = str(num) # declaring variables happy_num = 0 #Using while loop to make the loop continue performing calculations till the Happy number result is reached while happy_num != 1: #declaring variables happy_num = 0 lst_num = [] #iterating through the string for i in range(len(num_Str)): lst_num.append(int(num_Str[i])) for i in lst_num: happy_num = (i*i) + happy_num num_Str = str(happy_num) if happy_num == 1: print('True') else: print('False')
true
9df6d0fafacb9ddd03ce996fe6065371405de79e
richardbarkr/MITx-6.00.2x
/PSET 4/Problem 2.py
510
4.15625
4
import numpy as np def r_squared(y, estimated): """ Calculate the R-squared error term. Args: y: list with length N, representing the y-coords of N sample points estimated: a list of values estimated by the regression model Returns: a float for the R-squared error term """ # TODO y, estimated = np.array(y), np.array(estimated) SEE = ((estimated - y)**2).sum() mMean = y.sum()/float(len(y)) MV = ((mMean - y)**2).sum() return 1 - SEE/MV
true
ac58ae44c880b45a5a2e8b70802dd53ec3707a47
ochoag90/Refresher_Python
/Farenheit_to_Celcius
541
4.375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jul 4 13:39:54 2020 @author: gabrielochoa """ # inputFarenheit = int(input("What is the temperature you want to convert into? \n >>>")) # celcius = ((inputFarenheit-32)*(5/9)) # print(str(inputFarenheit) + " Farenheit is equivalent to " + str(celcius) + " Celcius.") #Better way of writing it in my opinion far = float(input("Please, enter the temperature in farenheit: \n >>>")) cel = (far - 32) * (5/9) print(far, " farenheit is equivalent to ", cel, " celcius")
true
ea84c722e61d705c4f4f5baeabdf1167b999c460
YMChen95/CMPUT174-Introduction-to-the-Foundations-of-Computation-I
/lab5/lab5-3.py
380
4.15625
4
user_input=input("Type in a line of text:") punctuation = ['(', ')', '?', ':', ';', ',', '.', '!', '/', '"', "'", " "] list1=[] for x in user_input: if x not in punctuation: list1.append(x) result="".join(list1) Fresult=result.lower() FFresult=Fresult[::-1] print(FFresult) if Fresult==FFresult: print("Palindrome? True") else: print("Palindrome? False")
true
2e4240840ad706946ac64cd432bbcfff0f3e69fd
TJBrynach/studious-guacamole
/projects/findpi.py
220
4.15625
4
#Find PI to the Nth Digit** - Enter a number and have the program generate π (pi) up to that many decimal places. # Keep a limit to how far the program will go. import math def find_pi(n): return math.pi
true
2addf95e579808b930186bd94e93090259a5254c
vikasb30/sample
/question_01.py
724
4.28125
4
question_01 = """ Given a query string s and a list of all possible words, return all words that have s as a prefix. Example 1: Input: s = “de” words = [“dog”, “deal”, “deer”] Output: [“deal”, “deer”] Explanation: Only deal and deer begin with de. Example 2: Input: s = “b” words = [“banana”, “binary”, “carrot”, “bit”, “boar”] Output: [“banana”, “binary”, “bit”, “boar”] Explanation: All these words start with b, except for “carrot”. Write your code bellow """ s=input("Enter the prefix") str=input("Enter a list element separated by space ") words=str.split() news=[] for j in words: if j.startswith(s): news.append(j) print(news)
true
0c013ac16d699d2f23d029840366ec53aca47810
xyktl/python-study
/00_笔记/special_funtion.py
1,624
4.25
4
# python 的特殊函数的功能 class Person(object): """docstring for Person""" def __init__(self, name, age): '''创建实例对象时自动调用''' super(Person, self).__init__() self.name = name self.age = age def __new__(cls, name, age): '''在__init__() 之前自动调用 为对象分配空间,返回对象的引用 ''' print("有地方住了") return super().__new__(cls) # 必须要有返回值 def __str__(self): return "%s出生了" % self.name # 返回字符串 def __del__(self): '''垃圾回收前被自动调用 垃圾:创建的对象没有被引用''' print("%s去世了" % self.name) def __bool__(self): '''用于实例对象的bool判断''' return True # 如果对象不为空,返回True def __len__(self): '''返回实例的长度''' return len(self.name) def __repr__(self): '''指定对象在 交互 模式中直接输出结果''' return "Hello" #__lt__(self,other) 小于 < #__le__(self,other) 小于等于 <= #__eq__(self,other) 等于 = #__ne__(self,other) 不等于 != #__gt__(self,other) 大于 > #__ge__(self,other) 大于等于 >= def __lt__(self, other): '''比较两个实例的年龄 age''' return self.age < other.age sunwukong = Person("孙悟空", 25) zhubajie = Person("猪八戒", 36) print(sunwukong) print(bool(sunwukong)) print(len(sunwukong)) print(sunwukong < zhubajie)#调用了 __lt__ 函数 返回 true print(zhubajie)
false
096e49cc4777b91eaeb09ec02bca5ce96490e8e3
jholczinger/euler-project
/009_pythagorean.py
462
4.375
4
'''A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product a*b*c.''' def pyth(n): while True: for a in range(1,n): for b in range(1,n): c = n - a - b if (a**2+b**2) == c**2: return a*b*c, [a,b,c] print(pyth(1000))
true
276152b9dd82c594f5d96e1bf4c71b0c67eecc20
alex-garcia12/space-invaders
/bullet.py
1,682
4.21875
4
import pygame from pygame.sprite import Sprite class Bullet(Sprite): #Sprite is imported from pygame def __init__(self, ai_settings, screen, ship): #here we create a bullet object at the ship's current position super(Bullet, self).__init__() #super is used to inherit properly from Sprite self.screen = screen #create a bullet rect at (0,0) and then set the current position self.rect = pygame.Rect(0, 0, ai_settings.bullet_width, ai_settings.bullet_height) #this creates bullet's rect attribute self.rect.centerx = ship.rect.centerx #we determine the bullet's centerx at the ship's centerx self.rect.top = ship.rect.top #the bullet emerges from the top so it looks like it's getting fired #store the bullet's position as a decimal value self.y = float(self.rect.y) #make it a decimal to fine tune the bullet's speed self.color = ai_settings.bullet_color #stores the bullet's color self.speed_factor = ai_settings.bullet_speed_factor def update(self): #move the bullet up the screen #update the decimal position of the bullet self.y -= self.speed_factor #subtract the amount stored in self.speed_factor from self.y #update the rect position self.rect.y = self.y #bullet position/speed updates def draw_bullet(self): #draw the bullet to the screen pygame.draw.rect(self.screen, self.color, self.rect)
true
f7f4970df7e08c4b3f0c78773b515b002ad8e458
ronandunphy/MDF-Lab2
/Sandbox/hashcalc.py
2,268
4.25
4
import sys import hashlib from sha3 import sha3_256, sha3_512 import string ans=True while ans: print (""" Please choose one of the following options? 1.Get Hash values of a String 2.Get Hash values of a File 3.Exit """) ans=raw_input(">") if ans=="1": mystring = raw_input ('Please enter a string: ') hash_object1 = hashlib.sha1(mystring.encode()) hash_object2 = hashlib.sha256(mystring.encode()) hash_object3 = hashlib.sha512(mystring.encode()) hash_object4 = hashlib.sha3_256(mystring.encode()) hash_object5 = hashlib.sha3_512(mystring.encode()) print ("SHA-1:" + hash_object1.hexdigest()) print ("SHA-256:" + hash_object2.hexdigest()) print ("SHA-512:" + hash_object3.hexdigest()) print ("SHA-3(256):" + hash_object4.hexdigest()) print ("SHA-3(512):" + hash_object5.hexdigest()) print ("The string entered is: %s" % mystring) print ("SHA-1: " + hash_object1.hexdigest()) print ("SHA-256: " + hash_object2.hexdigest()) print ("SHA-512: " + hash_object3.hexdigest()) print ("SHA-3(256): " + hash_object4.hexdigest()) print ("SHA-3(512): " + hash_object5.hexdigest()) elif ans=="2": inputFile = raw_input("Please enter the name of a file:") openedFile = open(inputFile) readFile = openedFile.read() hash_object1 = hashlib.sha1(readFile) hash_object1_final = hash_object1.hexdigest() hash_object2 = hashlib.sha256(readFile) hash_object2_final = hash_object2.hexdigest() hash_object3 = hashlib.sha512(readFile) hash_object3_final = hash_object3.hexdigest() hash_object4 = hashlib.sha3_256(readFile) hash_object4_final = hash_object4.hexdigest() hash_object5 = hashlib.sha3_512(readFile) hash_object5_final = hash_object5.hexdigest() print ("The filename is: %s" % inputFile) print ("SHA-1: " + hash_object1_final) print ("SHA-256: " + hash_object2_final) print ("SHA-512: " + hash_object3_final) print ("SHA-3(256): " + hash_object4_final) print ("SHA-3(512): " + hash_object5_final) elif ans=="3": sys.exit() elif ans !="": print("\n Not a valid selection. Please try again.")
false
d2b57040cc3bd294ed0343bc513d1ed8f074ed84
nightmare307/Python-Learning
/Python_Crash_Course/Part_1/Chapter_7.py
2,258
4.15625
4
# -*- coding: utf-8 -* #7.1汽车租赁 car=input('What\'s car do you want ?\n') print('Let me see if I can find you a %s.'%(car)) #7.2餐馆定位 count=int(input('How many peoples will have dinner ?\n')) if count > 8: print('There is not have a big enough table !') else: print('All of you welcome here!') #7.3 10的整数倍 num = int(input('Please input a number:\n')) if num == 0: print('The number must bigger than 0,input again') num = int(input('Please input a number:\n')) elif num%10=='0': print('The number is correct!') else: print('The number is wrong') #7.4食物配料 prompt= '\nPlease select something to add into your burger :\nEnter \'quit\' when you are ready:\n' food='' while food != 'quit': food = input(prompt) if food != 'quit': print('Ok , We will add %s into your burger!'%(food)) #7.5电影票 age='' price='' while age != 'quit': age = input('\nPlease input your age :\nEnter \'quit\' when you need quit\n') if len(age) >3: break elif int(age) < 3: price='free' print('Your ticket price is %s' % (price)) elif int(age)<=12: price='10$' print('Your ticket price is %s' % (price)) elif int(age) >12: price='15$' print('Your ticket price is %s' % (price)) #7.8熟食店 sandwich_order=['tuna','beef','chicken'] finish_sadnwiches=[] while len(sandwich_order)>0: sandwich = sandwich_order.pop() print('We made your %s sandwich'%(sandwich)) finish_sadnwiches.append(sandwich) print(finish_sadnwiches) #7.9五香烟熏牛肉卖完了 sandwich_order = ['tuna', 'beef', 'chicken','pastrami','pastrami'] print('Our pastrami is sold out') while 'pastrami' in sandwich_order: sandwich_order.remove('pastrami') print(sandwich_order) #7.10 梦想的度假胜地 active=True investgate = {} while active: name=input('Please input your name:\n') place = input('If you could visit one place in the world, where would you go?\n') investgate[name]=place next=input('Would you like to let another respond?(y/n)\n') if next=='n': active=False for name,place in investgate.items(): print('%s would like to go to %s'%(name,place))
true
20ac2879f3a25597e2059f3d6eac68d5918cb282
daydaychallenge/leetcode-python
/01233/remove_sub_folders_from_the_filesystem.py
2,534
4.1875
4
from typing import List class TrieNode: def __init__(self): self.children = {} self.is_end = False class Trie: def __init__(self): self.root = TrieNode() def insert(self, pathes): node = self.root for p in pathes: if p not in node.children: node.children[p] = TrieNode() node = node.children[p] node.is_end = True def find(self): ans = [] def dfs(pathes, node): if node.is_end: ans.append("/" + "/".join(pathes)) return for p in node.children: dfs(pathes+[p], node.children[p]) dfs([], self.root) return ans class Solution: def removeSubfolders(self, folder: List[str]) -> List[str]: """ ### [1233. Remove Sub-Folders from the Filesystem](https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/) Given a list of folders, remove all sub-folders in those folders and return in **any order** the folders after removing. If a `folder[i]` is located within another `folder[j]`, it is called a sub-folder of it. The format of a path is one or more concatenated strings of the form: `/` followed by one or more lowercase English letters. For example, `/leetcode` and `/leetcode/problems` are valid paths while an empty string and `/` are not. **Example 1:** ``` Input: folder = ["/a","/a/b","/c/d","/c/d/e","/c/f"] Output: ["/a","/c/d","/c/f"] Explanation: Folders "/a/b/" is a subfolder of "/a" and "/c/d/e" is inside of folder "/c/d" in our filesystem. ``` **Example 2:** ``` Input: folder = ["/a","/a/b/c","/a/b/d"] Output: ["/a"] Explanation: Folders "/a/b/c" and "/a/b/d/" will be removed because they are subfolders of "/a". ``` **Example 3:** ``` Input: folder = ["/a/b/c","/a/b/ca","/a/b/d"] Output: ["/a/b/c","/a/b/ca","/a/b/d"] ``` **Constraints:** - `1 <= folder.length <= 4 * 10^4` - `2 <= folder[i].length <= 100` - `folder[i]` contains only lowercase letters and '/' - `folder[i]` always starts with character '/' - Each folder name is unique. Notes ----- References --------- """ trie = Trie() for pathes in folder: trie.insert(pathes.split("/")[1:]) return trie.find()
true
2e9b4f5b78de6770486e8dc76609adf9858dc813
daydaychallenge/leetcode-python
/00186/reverse_words_in_a_string_ii.py
1,437
4.125
4
from typing import List class Solution: def reverseWords(self, s: List[str]) -> None: """ ### [186. Reverse Words in a String II](https://leetcode.com/problems/reverse-words-in-a-string-ii/) Given an input string , reverse the string word by word. **Example:** ``` Input: ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"] Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"] ``` **Note:** - A word is defined as a sequence of non-space characters. - The input string does not contain leading or trailing spaces. - The words are always separated by a single space. **Follow up:** Could you do it *in-place* without allocating extra space? Parameters ---------- s: List[str] Returns ------- None Examples -------- Notes ----- References --------- """ def reverse(s, start, end): while start < end: s[start], s[end] = s[end], s[start] start += 1 end -= 1 reverse(s, 0, len(s)-1) start = 0 for end in range(len(s)): if s[end] == ' ': reverse(s, start, end-1) start = end+1 elif end == len(s)-1: reverse(s, start, end)
true
8ce00eac0a4266738e0c5d3750e0ffb364bfaabb
darkaxelcodes/randompython
/fibbonacci.py
427
4.21875
4
def calculate_fib(n): array = [0,1,1] for i in range(3,n+1): length = len(array) next = array[length-1] + array[length-2] array.append(next) if n == 0: return 0 elif n == 1: return [0,1] else: return array n = int(input("Enter the number of terms you want in the fibbonacci sequence: ")) #result = calculateFib(n) print(calculate_fib(n))
true
e55c7ef22c440b0a1235c988e575836c7e11ba2f
darkaxelcodes/randompython
/LinearSearch.py
602
4.34375
4
''' Program to implement Linear Search. The time complexity of above algorithm is O(n). ''' def linear_search(list_of_numbers,digit_to_find): while list_of_numbers is not None: for i in range(len(list_of_numbers)): if digit_to_find == list_of_numbers[i]: return i+1 break else: return None list_of_numbers = [1,2,3,4,5,6,7,8,9,10] digit_to_find = int(input("Enter the digit to search: ")) position = linear_search(list_of_numbers,digit_to_find) print("The digit is found at position: {}".format(position))
true
f8b4d09ee3294fd6eb62699d2755fdcff47be9da
ivvve/my-python
/basic_lecture/03_control&code_structure/none.py
345
4.15625
4
# print(help((None))) is_empty = None # 파이썬에서는 None을 판별할 때는 ==, != 가 아닌 # is, is not 을 사용한다. if is_empty is None: print("hello") else: print("world") ## print(1 == True) # 값 비교 print(1 is True) # object 끼리 비교 l = [1, 2] l2 = [1, 2] print(l == l2) # True print(l is l2) # False
false
3620718793532221a1738375a068cd99f616faf5
Danithak/CS101
/Exam Questions/removehtmltags.py
1,925
4.375
4
#!/usr/bin/python # Question 4: Remove Tags # When we add our words to the index, we don't really want to include # html tags such as <body>, <head>, <table>, <a href="..."> and so on. # Write a procedure, remove_tags, that takes as input a string and returns # a list of words, in order, with the tags removed. Tags are defined to be # strings surrounded by < >. Words are separated by whitespace or tags. # You may assume the input does not include any unclosed tags, that is, # there will be no '<' without a following '>'. # My solution: def remove_tags(b): for i in b: if i == '<': # Loops through string searching for start of tag ('<'). c = b.index(i) # Locates position of start tag. d = b.index('>') # Locates position of end tag. b = b[:c] + ' ' + b[d + 1:] # Modifies b to include portion of string without tag. return b.split() # Splits b to separate all words. print remove_tags('''Title</h1> <p>This is a<a href="http://www.udacity.com">link</a>.<p>''') #>>> ['Title','This','is','a','link','.'] print remove_tags('''<table cellpadding='3'> <tr><td>Hello</td><td>World!</td></tr> </table>''') #>>> ['Hello','World!'] print remove_tags("<hello><goodbye>") #>>> [] print remove_tags("This is plain text.") #>>> ['This', 'is', 'plain', 'text.'] # Professor's solution: def remove_tags_prof(string): start = string.find('<') # Finds first tag. while start != -1: # Continues looping until no more '<' are found. end = string.find('>', start) # Locates nearest closing tag. string = string[:start] + ' ' + string[end + 1:] # Modifies string variable to not include start and end of tag. start = string.find('<') # Modifies start to locate the next tag. return string
true
9ee08ff661739dbf6564aec7b9e1dda4f988a726
Danithak/CS101
/Chapter 5/rotate_string.py
1,476
4.125
4
#!/usr/bin/python # Write a procedure, rotate which takes as its input a string of lower case # letters, a-z, and spaces, and an integer n, and returns the string constructed # by shifting each of the letters n steps, and leaving the spaces unchanged. # Note that 'a' follows 'z'. You can use an additional procedure if you # choose to as long as rotate returns the correct string. # Note that n can be positive, negative or zero. def rotate(x, n): new_string = '' # Creates a new string for the rotation procedure. alphabet = 'abcdefghijklmnopqrstuvwxyz' for i in x: # Loops through input string. if i == ' ': new_string += i # Adds empty space to new string if present. else: t = alphabet.find(i) # Finds position of character in string. y = t + n if y >= 25 or y < 0: new_string += (alphabet[(y) % 26]) # Modulo of 26 if y is larger than alphabet length. else: new_string += (alphabet[(y) % 25]) # Modulo of 25 if y is within alphabet length. return new_string # Returns newly constructed (rotated) string. print rotate ('sarah', 13) #>>> 'fnenu' print rotate('fnenu',13) #>>> 'sarah' print rotate('dave',5) #>>>'ifaj' print rotate('ifaj',-5) #>>>'dave' print rotate(("zw pfli tfuv nfibj tfiivtkcp pfl jyflcu " "sv rscv kf ivru kyzj"),-17) #>>> ???
true
dfd808151efbeb074773d8432666c6c0960d96c0
Danithak/CS101
/Chapter 5/hashtable_all.py
2,888
4.59375
5
#!/usr/bin/python # NOTE: This is a collection of all hash functions using lists throughout the video lectures in Chapter 5. # The whole purpose of the lesson was to take a deep dive into how dictionaries function, as all of the # functions created here are more or less inherent properties of dictionaries. def hashtable_add(htable,key,value): position = hash_string(key,len(htable)) # This function uses the same method to look up where htable[position].append([key, value]) # a keyword would fit into a bucket, and places it inside return htable def hashtable_get_bucket(htable,keyword): # This function derives the hash value and returns return htable[hash_string(keyword,len(htable))] # the appropriate bucket (list inside the list) def hashtable_lookup(htable,key): bucket = hashtable_get_bucket(htable, key) # This function finds the bucket that a key would be in for i in bucket: # using the above function and then checks each key inside if key in i: # the bucket to see if it exists. It returns the value return i[1] # associated with the key if it exists, and returns None if not. else: None def hashtable_update(htable,key,value): bucket = hashtable_get_bucket(htable,key) # This function is very similar to the one above, for entry in bucket: # except that it will add the key with the value if key in entry: # if it does not exist, or update the entry[1] = value # value if the key already exists. return htable hashtable_add(htable, key, value) def hash_string(keyword,buckets): # This function hashes keys into specific buckets by out = 0 # looping through each character, adding the ordinal value to out, for s in keyword: # then taking the modulo of out, and returning out after it terminates. out = (out + ord(s)) % buckets return out def make_hashtable(nbuckets): # This functiona simply creates a list with n number of lists table = [] # inside. for unused in range(0,nbuckets): table.append([]) return table table = make_hashtable(5) hashtable_add(table,'Bill', 17) hashtable_add(table,'Coach', 4) hashtable_add(table,'Ellis', 11) hashtable_add(table,'Francis', 13) hashtable_add(table,'Louis', 29) hashtable_add(table,'Nick', 2) hashtable_add(table,'Rochelle', 4) hashtable_add(table,'Zoe', 14) print table #>>> [[['Ellis', 11], ['Francis', 13]], [], [['Bill', 17], ['Zoe', 14]], #>>> [['Coach', 4]], [['Louis', 29], ['Nick', 2], ['Rochelle', 4]]]
true
25ebfb8052fdb447c914acad22179adb145104da
prayagparmar/intro-to-data-science
/data_wrangling/16_reform_subway_dates.py
1,292
4.21875
4
import datetime import pandas def reformat_subway_dates(date): ''' The dates in our subway data are formatted in the format month-day-year. The dates in our weather underground data are formatted year-month-date. In order to join these two data sets together, we'll want the dates formatted the same way. Write a function that takes as its input a date in the MTA Subway data format, and returns a date in the weather underground format. Hint: There is a useful function in the datetime library called strptime. More info can be seen here: http://docs.python.org/2/library/datetime.html#datetime.datetime.strptime %m - month (01 to 12) %d - day of the month (01 to 31) %y - year without a century (range 00 to 99) %Y - year including the century ''' date_formatted = datetime.datetime.strptime(date, '%m-%d-%y').strftime('%Y-%m-%d') return date_formatted if __name__ == "__main__": input_filename = "turnstile_data_master_subset_time_to_hours.csv" output_filename = "output.csv" turnstile_master = pandas.read_csv(input_filename) student_df = turnstile_master.copy(deep=True) student_df['DATEn'] = student_df['DATEn'].map(reformat_subway_dates) student_df.to_csv(output_filename)
true
7ff44988e9ed6dee5c9a11dd15f707b8305e509f
rehmanalira/Python-Programming
/4)python list and list function.py
625
4.1875
4
#arr=["helo","Where","Pakistan","Study"] #print(arr) num1=[2,34,43,23,211,44] print(num1) print(max(num1)) print(min(num1)) #num1.sort() #print(num1)#give in small and then order #num1.reverse() #print(num1)#gives in high order #num1.append(3)#it will add this number in the end0 #print(num1) a=60 b=77 print("before swaping",a,b) a,b=b,a print("after swaping",a,b) num1.remove(44) #print(num1)#it will remove the number #num1.clear() print(num1)#it will remove all the numbers in list num1.copy() print(num1)#it give the copy of the list num1.pop(3) print(num1)#remove the element at given position
true
21160e457bab0c03245a6ab1c079eccec7e3980c
rehmanalira/Python-Programming
/15 try except.py
703
4.15625
4
""" try and except are two keywords which are used when our program is run and give error but we want get error and want to print the next statment """ try: #which will run this if it throw erroe then it will give only error message but it will not exit the program print("Enter the number") num1=int(input()) print("Enter Second Number") num2=int(input()) sum= num1+num2 print(sum) #if we put the value which is integer and then the value of string it will throw error except Exception as e: print(e) print("MA Print hu gya ") # if we use try and except and then it will not throw error it gives location of error and also print this value
true
a2470de34fe4424e1a1dbeb4408cc0ccccdc11a0
rehmanalira/Python-Programming
/22 Module Random Number.py
781
4.15625
4
""" there are module in python which means they are already written there is no need to write them for example if we have to find a random nunmber then there ie no need to write a random number function we just have to use this already written function in python to use this we write import module name<---> if there is no module in this you can download it by writting pip install (module name ) """ import random#it is imporatant to use built in moudule r1=random.randint(1,30)#it will use the random number from 1 to 30 print(r1) r2=random.random() *10#when we multiply it by number it give random number to that number print(r2) list=["Rehman","Ahsan","Jani","Tayyab"] r3=random.choice(list)#it will give the random list name by writting choice print(r3)
true
98221b7ef9c6ce5cad81d069021883535b247525
rehmanalira/Python-Programming
/34 OOP class methods.py
942
4.28125
4
""" we using class method when we create a function in the class also take the value of as self but we not want that it take sthe value as self so we use class method also if we want the change the value of the gloabal value of the class so we can similary change with the class methods """ class Employe: variable=50 #This is constructor def __init__(self,rname,rage,rstudy): self.name=rname self.age=rage self.study=rstudy def show(self):#here self is an argument which take any of obejct which given and the the function name print(f"My name is {self.name} , My age is {self.age} and i am studying in{self.study}") @classmethod #using class method def new_variable(cls,new_v):#creat function and pass the new value which we want to change cls.variable=new_v RA= Employe("Rehman Ali","19","GUCF") RA.new_variable(99999999) print(RA.variable)
true
5a3f147292fcb89432431688578d58362a41ee32
xiaokexiang/start_python
/basic/_type_.py
950
4.34375
4
""" 基本数据类型: string,number(整数&浮点数) """ def _string_(): message = "hello world" print(message) print(message.title()) # 每个单词都首字母大写 print(message.lower()) print(message.upper()) def _add_string_(): first_name = 'hello' second_name = 'world' print(first_name + ' ' + second_name) print('\t' + first_name) # tab制表符 print(first_name + '\n' + second_name) # 换行符 blank_str = ' hello world ' print(blank_str.strip()) # 去除开头和末尾空格(不是修改原字符串) print(blank_str.lstrip()) # 去除开头空格(不是修改原字符串) print(blank_str.rstrip()) # 去除末尾空格(不是修改原字符串) def _add_number_(): age = 12 print('Happy ' + str(age) + 'rd birthday!') def _add_float_(): print(0.1 + 0.2) # 0.30000000000000004 _string_() _add_string_() _add_number_() _add_float_()
false
2bee16dbbdbe0f74ad6554e2d568420de8861f94
jmlapicola/Python_Puzzles
/Problem50.py
941
4.125
4
def listPrimes(n): composites = {2} primes = list() for i in range(3, n + 1, 2): if i not in composites: primes.append(i) composites = composites.union(set(range(2*i, n + 1, i))) return primes def isPrime(n): if n == 2 or n == 3: return True if n%2 == 0 or n%3 == 0 or n < 2: return False max = n**(1/2) i = 5 while i <= max: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True primes = listPrimes(100000) maxLen = 0 maxSum = 0 start = 0 startsum = 0 while startsum < 1000000: length = maxLen startsum = sum(primes[start:start + length]) total = startsum while total < 1000000: if isPrime(total): maxSum = total maxLen = length print(length, total) length += 1 total = sum(primes[start:start + length]) start += 1 print(maxSum)
true
b7e22ef7e011056cbe130900c8e7be5a7db7cc64
saulquispe/My-Solutions-to-The-Python-Workbook-By-Ben-Stephenson-122-of-174-
/Function Exercises/ex91.py
1,556
4.4375
4
''' Exercise 91: Operator Precedence Write a function named precedence that returns an integer representing the precedence of a mathematical operator. A string containing the operator will be passed to the function as its only parameter. Your function should return 1 for + and -, 2 for * and /, and 3 for ˆ. If the string passed to the function is not one of these operators then the function should return -1. Include a main program that reads an operator from the user and either displays the operator’s precedence or an error message indicating that the input was not an operator. Your main program should only run when the file containing your solution has not been imported into another program. In this exercise, along with others that appear later in the book, we will use ˆ to represent exponentiation. Using ˆ instead of Python’s choice of ** will make these exercises easier because an operator will always be a single character. ''' def precedence(s): if s == '+' or s == '-': return 1 elif s == '*' or s == '/': return 2 elif s == '^': return 3 else: return -1 def main(): s = input('Input an mathematical operator: ') if precedence(s) == 1: print('{} has a precedence of {}'. format(s, precedence(s))) elif precedence(s) == 2: print('{} has a predecdence of {}'. format(s, precedence(s))) elif precedence(s) == -1: print('{} is not a mathematical operator'. format(s)) if __name__ == '__main__': main()
true
80259105ba297ba546871ec26c35550a44f01168
saulquispe/My-Solutions-to-The-Python-Workbook-By-Ben-Stephenson-122-of-174-
/Introduction to Programming Exercises/ex23.py
725
4.28125
4
''' Exercise 23: Area of a Regular Polygon A polygon is regular if its sides are all the same length and the angles between all of the adjacent sides are equal. The area of a regular polygon can be computed using the following formula, where s is the length of a side and n is the number of sides: area = n × s^2/4 × tan (πn) Write a program that reads s and n from the user and then displays the area of a regular polygon constructed from these values ''' import math n = int(input('How many sides does the polygon have: ')) s = int(input('How long are the sides of the polygon: ')) area = n * s**2 / 4 * math.tan(math.pi / n) print('The area of the polygon is: {:.2f} metered squared'. format(area))
true
fe63771d718f078641bddbafa07a94ac0a54126a
saulquispe/My-Solutions-to-The-Python-Workbook-By-Ben-Stephenson-122-of-174-
/Function Exercises/ex94.py
1,112
4.46875
4
''' Exercise 94: Random Password Write a function that generates a random password. The password should have a random length of between 7 and 10 characters. Each character should be randomly selected from positions 33 to 126 in the ASCII table. Your function will not take any parameters. It will return the randomly generated password as its only result. Display the randomly generated password in your file’s main program. Your main program should only run when your solution has not been imported into another file. Hint: You will probably find the chr function helpful when completing this exercise. Detailed information about this function is available online. ''' def randompassword(): from random import randint maximum = 10 minimum = 7 password_range = randint(minimum, maximum) generated = '' for i in range(password_range): randomchar = chr(randint(33,126)) generated += randomchar return generated def main(): print('{} is your randomized passoword'. format(randompassword())) if __name__ == '__main__': main()
true
524be6b4b5f222127f865ec424eb91b5c37cc68f
saulquispe/My-Solutions-to-The-Python-Workbook-By-Ben-Stephenson-122-of-174-
/If Statement Exercises/ex34.py
348
4.3125
4
''' Exercise 34: Even or Odd? Write a program that reads an integer from the user. Then your program should display a message indicating whether the integer is even or odd. ''' num = int(input('Enter an integer: ')) if num % 2 == 0: print('The integer {} is even'. format(num)) else: print('The integer {} is odd'. format(num))
true
1f3402b688d1ecd09a001411e0db7aece78481cc
saulquispe/My-Solutions-to-The-Python-Workbook-By-Ben-Stephenson-122-of-174-
/List Exercises/ex107.py
708
4.1875
4
''' Exercise 107: Avoiding Duplicates In this exercise, you will create a program that reads words from the user until the user enters a blank line. After the user enters a blank line your program should display each word entered by the user exactly once. The words should be displayed in the same order that they were entered. For example, if the user enters: first second first third second then your program should display: first second third ''' words = [] word = input('Enter a word (blank line to quit): ') while word != '': if word not in words: words.append(word) word = input('Enter a word (blank line to quit): ') for word in words: print(word)
true
1cc8456090b34ef674296d953797938e26d2dca4
saulquispe/My-Solutions-to-The-Python-Workbook-By-Ben-Stephenson-122-of-174-
/Function Exercises/ex103.py
1,413
4.34375
4
''' Exercise 103: Magic Dates A magic date is a date where the day multiplied by the month is equal to the two digit year. For example, June 10, 1960 is a magic date because June is the sixth month, and 6 times 10 is 60, which is equal to the two digit year. Write a function that determines whether or not a date is a magic date. Use your function to create a main program that finds and displays all of the magic dates in the 20th century. You will probably find your solution to Exercise 100 helpful when completing this exercise. ''' # Days in a month(ex100) def days(month, year): if year % 400 == 0 or year % 4 == 0: leap = True elif year % 100 == 0: leap = False else: leap = False days_30 = [9,4,6,11] days_31 = [1,3,5,7,8,10] if leap == True and month == 2: return 29 elif leap == False and month == 2: return 28 elif month in days_30: return 30 elif month in days_31: return 31 def magicdate(day, month, year): if day * month == year % 100: return True return False def main(): for year in range(1900, 2000): for month in range(1, 13): for day in range(1, days(month, year) + 1): if magicdate(day, month, year): print('{}/{}/{} is a magic year'. format(day, month, year)) main()
true
6fbffd10ae6fb9132060cceb3892e101fb5ffa96
saulquispe/My-Solutions-to-The-Python-Workbook-By-Ben-Stephenson-122-of-174-
/Introduction to Programming Exercises/ex1.py
748
4.625
5
''' Exercise 1: Mailing Address Create a program that displays your name and complete mailing address formatted in the manner that you would usually see it on the outside of an envelope. Your program does not need to read any input from the user. ''' name = 'Ifeoluwa Oyelakin' department = 'Dept of Electronic and Electricial Engineering' univerisity = 'Obafemi Awolowo Univerisity' address = 'P.M.B. 13, Ile-Ife, Osun' country = 'Nigeria' print('{} \n{} \n{} \n{} \n{}'. format(name,department,univerisity,address,country)) ''' or print('Ifeoluwa Oyelakin') print('Department of Electronic and Electricial Engineering') print('Obafemi Awolowo Univerisity') print('P.M.B. 13, Ile-Ife, Osun') print(''Nigeria'') '''
true
10e57ff5a5e744d3ed13d1359989bf7ade6d849e
saulquispe/My-Solutions-to-The-Python-Workbook-By-Ben-Stephenson-122-of-174-
/Introduction to Programming Exercises/ex16.py
621
4.53125
5
''' Exercise 16: Area and Volume Write a program that begins by reading a radius, r, from the user. The program will continue by computing and displaying the area of a circle with radius r and the volume of a sphere with radius r. Use the pi constant in the math module in your calculations. ''' import math radius = float(input('Enter your radius: ')) circle = math.pi * (radius) ** 2 sphere = math.pi * 4/3 * (radius) ** 3 print('The Area of the circle with radius {} is {} meter squared'.format(radius,circle)) print('The Volume of the sphere with radius {} is {} meter cube'.format(radius,sphere))
true
f0441b97e8fa2e83cf7a1f368e507b6f5f44f03b
saulquispe/My-Solutions-to-The-Python-Workbook-By-Ben-Stephenson-122-of-174-
/If Statement Exercises/ex58.py
2,102
4.1875
4
''' Exercise 58: Next Day Write a program that reads a date from the user and computes its immediates uccessor. For example, if the user enters values that represent 2013-11-18 then your program should display a message indicating that the day immediately after 2013-11-18 is 2013-11-19. If the user enters values that represent 2013-11-30 then the program should indicate that the next day is 2013-12-01. If the user enters values that represent 2013-12-31 then the program should indicate that the next day is 2014-01-01. The date will be entered in numeric form with three separate input statements; one for the year, one for the month, and one for the day. Ensure that your program works correctly for leap years. ''' date = input('Enter a date in the format (Year-Month-Day): ' ) date = date.split('-') year, month, day = int(date[0]), int(date[1]), int(date[2]) days_30 = [9,4,6,11] days_31 = [1,3,5,7,8,10] if year % 400 == 0 or year % 4 == 0: leap = True feb = 29 elif year % 100 == 0: leap = False feb = 28 else: leap = False if month == 2 and leap: if 1 <= day <= 28: day += 1 month = month year = year elif day == 29: day = 1 month += 1 year = year elif month == 2 and not leap: if 1 <= day < 28: day += 1 month = month year = year elif day == 28: day = 1 month += 1 year = year elif month == 12: if 1 <= day < 31: day += 1 month = month year = year elif day == 31: day = 1 month = 1 year += 1 elif month in days_30: if 1 <= day < 30: day += 1 month = month year = year elif day == 30: day = 1 month += 1 year = year elif month in days_31: if 1 <= day < 31: day += 1 month = month year = year elif day == 31: day = 1 month += 1 year = year print('{}-{:0>2d}-{:0>2d}'. format(year, month, day))
true
195626068070242cc1bf3009403cc83d67147fc6
saulquispe/My-Solutions-to-The-Python-Workbook-By-Ben-Stephenson-122-of-174-
/If Statement Exercises/ex38.py
733
4.5
4
''' Exercise 38: Month Name to Number of Days The length of a month varies from 28 to 31 days. In this exercise you will create a program that reads the name of a month from the user as a string. Then your program should display the number of days in that month. Display “28 or 29 days” for February so that leap years are addressed. ''' month = input('Enter the current month: ').lower() days_30 = ['september','april','june','november'] days_31 = ['january','march','may','july','august','october','december'] if month in days_30: print('You have 30 days in', month) elif month in days_31: print('You have 31 days in', month) elif month == 'february': print('You have 28 or 29 days in', month)
true
055f05719a3457833e82ba08afb9f0989c682fb9
saulquispe/My-Solutions-to-The-Python-Workbook-By-Ben-Stephenson-122-of-174-
/Function Exercises/ex93.py
945
4.53125
5
''' Exercise 93: Next Prime In this exercise you will create a function named nextPrime that finds and returns the first prime number larger than some integer, n. The value of n will be passed to the function as its only parameter. Include a main program that reads an integer from the user and displays the first prime number larger than the entered value. Import and use your solution to Exercise 92 while completing this exercise. ''' # Previous Function (ex92.py) def prime(n): if n > 1: for i in range(2, n): if n % i == 0: return False return True def nextprime(n): found = False while (not found): n += 1 if prime(n): found = True return n def main(): n = int(input('Enter an integer: ')) print('{} is the next prime after the integer {}'. format(nextprime(n), n)) if __name__ == '__main__': main()
true
26929f7d7cf6a96440990f1da13e3fe5706576a2
saulquispe/My-Solutions-to-The-Python-Workbook-By-Ben-Stephenson-122-of-174-
/Function Exercises/ex101.py
1,172
4.125
4
''' Exercise 101: Reduce a Fraction to Lowest Terms Write a function that takes two positive integers that represent the numerator and denominator of a fraction as its only two parameters. The body of the function should reduce the fraction to lowest terms and then return both the numerator and denominator of the reduced fraction as its result. For example, if the parameters passed to the function are 6 and 63 then the function should return 2 and 21. Include a main program that allows the user to enter a numerator and denominator. Then your program should display the reduced fraction. Hint: In Exercise 75 you wrote a program for computing the greatest common divisor of two positive integers. You may find that code useful when completing this exercise. ''' def reduce_fraction(a, b): a = int(a) b = int(b) c = min(a,b) while a % c != 0 or b % c != 0: c -= 1 new_a = int(a/c) new_b = int(b/c) print('{}/{}'. format(new_a, new_b)) def main(): a = input('Enter the numerator: ') b = input('Enter the denominator: ') reduce_fraction(a,b) if __name__ == '__main__': main()
true
6694d33cbd7a58f1d07e7af79d7307fa06b322da
zhangkunjie/python_basic
/com.python/com/python/thread/threadtest2.py
1,386
4.375
4
#打印当前线程的名字 """ Python通过两个标准库thread和threading提供对线程的支持。thread提供了低级别的、原始的线程以及一个简单的锁。 thread 模块提供的其他方法: threading.currentThread(): 返回当前的线程变量。 threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。 threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。 除了使用方法外,线程模块同样提供了Thread类来处理线程,Thread类提供了以下方法: run(): 用以表示线程活动的方法。 start():启动线程活动。 join([time]): 等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。 isAlive(): 返回线程是否活动的。 getName(): 返回线程名。 setName(): 设置线程名 """ from threading import Thread import threading import time def z(x): for i in range(1,5): print("线程名:"+threading.current_thread().getName()+"#######"+str(i)) time.sleep(x) t1=threading.Thread(target=z,name="线程1",args=(1,)) t2=threading.Thread(target=z,name="线程2",args=(3,)) t1.start() t2.start()
false
f6ff9a24dadbbd92deacbeebc7776fde5fd82670
Kavya-YS/Sept_Testing_Intern_2020
/nonlocal.py
1,328
4.28125
4
""" Scope 1. Create an outer function and define the nolocal variables 2. create an inner function to modify nonlocal variables with the use of nonlocal keyword 3. Modify the nonlocal variables and also define the local variables within the function 4. Call the inner functions with respective print statements 5. Call the outer function """ #defining a function to declare nonlocal variables def vehicles(): #Defining global variables wheel_base=1200 ground_clearance=120 #Defining a function activa def activa(): nonlocal wheel_base wheel_base= 1260 nonlocal ground_clearance ground_clearance= 165 fuel_tank_capacity=5.3 #local variable of activa() finction print("Activa's fuel_tank_capacity is: ", fuel_tank_capacity) def dio(): nonlocal wheel_base wheel_base= 1270 nonlocal ground_clearance ground_clearance= 171 fuel_tank_capacity=4.5 #local variable of dio() finction print("Dio's fuel_tank_capacity is: ", fuel_tank_capacity) dio() print("Dio's wheel base is: ", wheel_base) print("Dio's ground clearance is: ", ground_clearance) activa() print("Activa's wheel base is: ", wheel_base) print("Activa's ground clearance is: ", ground_clearance) vehicles()
true
356bae9009701be601abe717dbc59e796354ad23
FabianOrecchia/curso_python
/generators.py
917
4.125
4
# def my_gen(): # print("hello world") # n = 0 # yield n # print("hello heaven") # n = 1 # yield n # print("bye people") # n = 2 # yield 2 # a = my_gen() # print(next(a)) # print(next(a)) # print(next(a)) # print(next(a)) #ACA CREAMOS UN GENERADOR PARA RECORRER LA SERIE DE FIBONACCI HASTA UN MAXIMO QUE INDIQUE UN USUARIO import time def fibo_gen(max=None): n1 = 0 n2 = 1 counter = 0 while counter < max: if counter == 0: counter+=1 yield n1 elif counter == 1: counter+=1 yield n2 else: aux = n1+n2 n1,n2 = n2, aux counter+=1 yield aux if __name__ == "__main__": max = int(input("Ingresa un numero: ")) fibonacci = fibo_gen(max) for element in fibonacci: print(element) time.sleep(1)
false
fb3369425af9794dae9848fe8435fe494ca27e62
crysclitheroe/Rosalind
/Bioinf_Stronghold/FIBD.py
2,457
4.125
4
"""This script calculates numbers of mortal rabbits in a population using dynamic programming to implement a recurrence relation as part of the Rosalind Bioinformatics Stronghold problem set FIBD Ive essentially just modified the code from the FIB (rrr.py) problem """ #First get input values n and m. n = int(input("Please input generation number n: ")) m = int(input("Please input life expectancy, in months: ")) #The problem does not stipulate the numbers of pairs produced so I'm assuming one pair generated per adult pair k = 1 #create recursive function breed, which takes integers from the sample dataset, i.e. generations, fecundity and life expectany (mortality) def breed(gen, juv, mort): #this first step is the base case, because a recursive function, or, a function that calls itself needs some way to stop. The first month there is only one pair of bunnies (juvenile), so state that if gen == 1: return 1 #the number of pairs in month 2 is still 1 (the first juvenile pair matures), the number of pairs in month 3 is = that in month 1 plus the juvies produced in month 2 elif gen == 2: return juv #now our function continues to call itself until it hits on of the base cases f1 = breed(gen-1, juv, mort) f2 = breed(gen-2, juv, mort) #from month 3, up to month "mort" and if gen = mort, population size is predicted by adding previous two generations, i.e. we only need to call the function once to get to the base cases if gen <= mort: print('sanity') return (f1+(f2*juv)) #However if we have a generation time greater than life expectancy, we need to modify f1 and f2 to reflect the population "mort" months previously. Not really sure how this works (but it does!), and thinking recursively about how modified f1 and f2 actually go back to the f1 and f2 of the original function really hurts my brain (hence the commented out 'sanity' print statements). This is crazy though. The time-step doubles with every generation, it takes too long to solve within the rosalind's 5min time limit. 1m14s to solve a 37gen, 20mort case. It needs to be able to solve a 100min20mort case in 5mins. How to speed this up? elif gen > mort: print('insanity') #f1 = breed(gen-mort+1, juv, mort) #f2 = breed(gen-mort, juv, mort) #a different approach. both approaches are actually failing hard =( mortality = breed(gen-mort, juv, mort) return f1+(f2*juv) - mortality print(breed(n,k,m))
true
7d31b4361c61c45bd7ac9ec11bbef1c4cf3eee57
crysclitheroe/Rosalind
/Textbook_Track/minskew_ba1f.py
810
4.15625
4
#solution to problem BA1F in rosalind's textbook track set find the position in a genome minimizing the "skew" of a DNA string Genome, denoted Skew(Genome), which is the difference between the total number of occurrences of 'G' and 'C' in Genome def minskewpos(genome): #first set variables to 0 c = 0 g = 0 minskew = 0 index = 0 poslist = [] for i in genome: index += 1 if i == 'C': c += 1 if i == 'G': g += 1 #calculate current skew skew = g-c #i.e. if a new minimum, reset the poslist if skew < minskew: poslist = [index] minskew = skew if skew == minskew and index not in poslist: poslist.append(index) return poslist with open('rosalind_ba1f.txt', 'r') as inputfile: sequence = inputfile.readline() for pos in minskewpos(sequence): print(pos, end=' ')
true
6856d769e35954823acfdd7fe7e17ad4b47e7a26
hvescovi/programar2020
/99-fundamentos/python/dicionarios.py
1,771
4.21875
4
# https://www.w3schools.com/python/python_dictionaries.asp # guardando dados de uma pessoa nome = "Joao da Silva", email = "josilva@gmail.com" telefone = "47 9 9233 1234" # guardar dados em um dicionário; a atribuição lembra formato json pessoa = { "nome" : "Joao da Silva", "email" : "josilva@gmail.com", "telefone" : "47 9 9233 1234" } print('* mostrar a pessoa em forma de dicionário') print(pessoa) # note as aspas simples print('* percorrer e exibir dados do dicionário') for info in pessoa: print(info) print('* mostrando só o email e o telefone da pessoa (aspas duplas ou simples)') print(pessoa["email"],pessoa['telefone']) print('* adequando o dicionário para que seu conteúdo fique 100% json') import json print(json.dumps(pessoa)) # conteúdo 100% json com aspas duplas! # passando um dicionário como parâmetro pra uma função # dois asteriscos permitem passar quaisquer número de parâmetros def mostra_tudo(**parametros): # CASO 1 print("mostrando tudo...") # percorrer a lista de parametros no formato chave=valor for p in parametros: # mostra o nome do parâmetro e o valor print(p, "é igual a", parametros[p]) print('* usando a função que mostra tudo: mostrando nomes e valores') mostra_tudo(nome = "Paulo Tarso", cor_da_escova_de_dentes = "azul") print('* passando dic pra mostra_tudo, desempacotar dic com dois asteriscos') mostra_tudo(**pessoa) # CASO 2 class Pessoa: def __init__(self, nome, email, telefone): self.nome = nome self.email = email self.telefone = telefone def __str__(self): return self.nome+", "+self.email+", "+self.telefone p1 = Pessoa("Tiago", "tibah@gmail.com", "92231-1232") print(p1) p2 = Pessoa(**pessoa) # criando objeto com dados do dicionário print(p2)
false
551cea6ac115eaf51815c4e54c04489d33ae7266
japankid-code/projects
/Python/Udacity/lesson3/sliceyboy.py
425
4.25
4
def word_triangle(word): length = len(word) for n in range(length): # prints out a right side up triangle print(word[:n + 1]) for n in range(length): # prints out an upside down triangle. print(word[:length - n]) for n in range(length): # prints out a column with all the letties :) print(word[:n + 1], word[:length - n]) word_triangle(input("what word would u like to slice up??? "))
true
33c0ea3d9acf31a83f487c148c0d270541c27473
thekioskman/Algorithms
/Sorting_Algorithms.py
2,065
4.3125
4
#Sorting algorithms: Bubble, Selection, Insertion, Merge #Bubble sort list_1 = [1,23,32,4523,4,2345,23,4213,4,143] def bubble_sort(list_1): ''' Sorts a given list param: list return: list ''' for i in range(len(list_1)): for j in range(len(list_1)-1): if list_1[j] > list_1[j+1]: temp = list_1[j] list_1[j] = list_1[j+1] list_1[j+1] = temp return list_1 #Insertion Sort list_1 = [1,23,32,4523,4,2345,23,4213,4,143] def insertio_sort(list_1): ''' Sorts a given list peram: list return: list ''' for i in range(len(list_1)): j = i #saves value of i while list_1[j] < list_1[j-1] and j > 0: temp = list_1[j-1] list_1[j-1] = list_1[j] list_1[j] = temp j -= 1 return list_1 #Selection Sort list_1 = [1,23,32,4523,4,2345,23,4213,4,143] def selectio_sort(list_1): ''' Sorts a given list param: list return: list ''' return_list = [] for loops in range(len(list_1)): return_list.append(min(list_1)) list_1.remove(min(list_1)) return return_list #Merge Sort def merge(right_list, left_list): ''' Combines two lists in sorted order param: list return: list ''' return_list = [] while right_list and left_list: if right_list[0] < left_list[0]: temp = right_list.pop(0) return_list.append(temp) else: temp = left_list.pop(0) return_list.append(temp) if not(right_list): return_list += left_list else: return_list += right_list return return_list list_1 = [1,23,32,4523,4,2345,23,4213,4,143] def merge_sort(list_1): ''' Sorts a given list param: list return: list ''' if len(list_1) <= 1: return list_1 else: right_list = [] left_list = [] for i in range(len(list_1)): if i < len(list_1)//2: left_list.append(list_1[i]) else: right_list.append(list_1[i]) left_list = merge_sort(left_list) right_list = merge_sort(right_list) return merge(right_list, left_list) print(merge_sort(list_1)) print(list_1)
false
e7aba4f5f843ae97542585d2f527c19e6bed955f
adrianoforcellini/ciencia-da-computaco
/35 - Algoritimos/35.2 - Recursividade e Estratégias para solução de problemas.py/2 - Iterativo vs Recursivo.py
599
4.25
4
def iterative_reverse(list): reversed_list = [] for item in list: reversed_list.insert(0, item) return reversed_list def reverse(list): if len(list) < 2: return list else: return reverse(list[1:]) + [list[0]] def iterative_countdown(n): while n > 0: print(n) n = n - 1 print("FIM!") return n def iterative_factorial(n): fact = 1 for i in range(1, n + 1): fact = fact * i return fact iterative_factorial(5) # NOTA : APESAR DE MAIS ELEGANTE, RARAMENTE # A PERFORMANCE É MELHOR. # DE PREFERENCIA Á ITERATIVIDADE!!
false
c8f42a4d880d03b214825a9107b8a805d9fa9618
adrianoforcellini/ciencia-da-computaco
/32 - Introduçao a Python/33.1 - Introduçao/1-Listas.py
567
4.15625
4
fruits = ["orange", "apple", "grape", "pineapple"] # elementos são definidos separados por vírgula, envolvidos por colchetes fruits[0] # o acesso é feito por indices iniciados em 0 fruits[-1] # o acesso também pode ser negativo fruits.append("banana") # adicionando uma nova fruta fruits.remove("pineapple") # removendo uma fruta fruits.extend(["pear", "melon", "kiwi"]) # acrescenta uma lista de frutas a lista original fruits.index("apple") # retorna o índice onde a fruta está localizada, neste caso 1 fruits.sort() # ordena a lista de frutas
false
ee161f2497d8c2903f0ea0147cc85a007b2fc0bd
kimi0230/leetcodePractice
/invertBinaryTree/invertBinaryTree.py
2,109
4.46875
4
# Invert a binary tree. # Example: # Input: # 4 # / \ # 2 7 # / \ / \ # 1 3 6 9 # Output: # 4 # / \ # 7 2 # / \ / \ # 9 6 3 1 # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class TreeNode(object): def __init__(self, data): self.val = data self.left = None self.right = None def insert(self, data): # Compare the new value with the parent node if self.val: if data < self.val: if self.left is None: self.left = TreeNode(data) else: self.left.insert(data) elif data > self.val: if self.right is None: self.right = TreeNode(data) else: self.right.insert(data) else: self.val = data # 前序走訪 def preOrder(self): if self == None: return print(self.val) if self.left: self.left.preOrder() if self.right: self.right.preOrder() class Solution(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ # 節點為null或沒有子節點,不用反轉,終止遞迴 if root == None or (root.right == None and root.left == None): return root root.left, root.right = self.invertTree(root.right), self.invertTree(root.left) return root if __name__ == '__main__': sol = Solution() test_object = TreeNode(10) test_object.insert(8) test_object.insert(20) test_object.insert(15) test_object.insert(9) test_object.insert(7) print(test_object.preOrder()) print('---') print(sol.invertTree(test_object).preOrder()) # 10 # / \ # 8 20 # / \ / # 7 9 15 # 10 # / \ # 20 8 # / \ / \ # 15 9 7 # 10 8 7 9 20 15 None # 10 20 15 8 9 7 None
false
62ca41e5ffdbfc59a550fba7bd357b1be7ea5428
remember-5/python-demo
/com/remember/basic/calculator.py
1,395
4.15625
4
# @see https://mofanpy.com/tutorials/python-basic/interactive-python/useless-calculator/ # 嗯,计算器,那就该有计算器该有的样子。我先定位一下这个产品出来以后能怎么用? # # 计算两个数的加减乘除等一些常用方法 # 一次性计算一批数据的运算结果 # 好,就这么简单两项,能为我的生活创造出很多价值了,特别是第二个功能,让我能一次性处理一批数据。这个需求很常见,比如我在 excel 里面有一批数据, 都要处理,那么批处理就十分有用了。 class Calculator: def subtract(self, a, b): return a - b def batch_subtract(self, a_list, b_list): res_list = [] for i in range(len(a_list)): res_list.append(self.subtract(a_list[i], b_list[i])) return res_list c = Calculator() print(c.subtract(2, 1)) print(c.batch_subtract([3, 2, 1], [2, 3, 4])) print("================================================") class Calculator: def add(self, a, b): return a + b def subtract(self, a, b): return a - b def multiply(self, a, b): return a * b def divide(self, a, b): # 处理异常 if b == 0: print("b cannot be 0") else: return a / b # 生产一个实例 c = Calculator() print(c.add(1, 2)) print(c.divide(1, 2)) c.divide(1, 0)
false
5766d763f31637e5c2584b75023a8b0f5f89b2de
marcusgalvin/python_hang-man
/hangman.py
749
4.125
4
import random possible_answers = ["cat", "dog", "pig", "car", "run", "grab", "pub", "man", "women"] letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] guess = "" def main(): # the cimputer will select a random word to have user guess computer_pick = random.choice(possible_answers) print("computer chose word: ", computer_pick) first_pick = raw_input("Hello, Please select your first letter: ") # for marble in computer_pick: # print(marble) def findLetters(first_pick, computer_pick): return all(letter in computer_pick for letter in first_pick) if __name__ == '__main__': main()
true
3d8b4a30b459945ccd4e3524f598a75900b66a14
piyushagarwal08/Adhoc-Python
/problem6.py
834
4.21875
4
#!/usr/bin/python3 print(''' 1. to show contents of single file 2. to show contents of multiple file 3. insert using cat 4. display line numbers in file -n ''') option = input('Select an option: ') if option == '1': file_name = input('Enter file name: ') fhand = open(file_name) print(fhand.read()) fhand.close() elif option == '2': file_name = input('Enter file names: ').split() for i in file_name: fhand = open(i) print(fhand.read()) fhand.close() elif option == '3': file_name = input('Enter file name: ') fhand = open(file_name,'a') text = input('Enter what you want to write: ') fhand.write(text) fhand.close() elif option == '4': file_name = input('Enter file name: ') fhand = open(file_name) text = fhand.readlines() for i in range(1,len(text)+1): print(i,text[i-1]) else: print('command not found')
true
1f5e4de6fadcdc27d2511de4946a8d21044494ed
dellaub/Files
/Python_Projects/check_circle_area_by_radius.py
441
4.46875
4
#Area of the circle = pi*radius**2 Pr^2 print("\n[Check for the Area of a circle by its radius]\n") #Import pi from math module from math import pi #ask for and set radius radius = float(input("Circle Radius (cm) ? : ")) #area calculation circle_area = pi * radius ** 2 #print string r = radius print("Radius = " + str(radius) + "cm") #print string Area = circle_area print("Circle Area = " + str("%.2f" % circle_area) + "cm²") # #
true
822e4ac84d0f97441a566e967fc368f1419bc854
sseaver/number_guesser
/main.py
779
4.15625
4
import random guesses = 0 computer_number = random.randint(1, 100) my_guess = input("Guess the computer's number.") my_guess = int(my_guess) guesses += 1 while guesses < 5 and my_guess != computer_number: if my_guess > computer_number: print ("Too big. Try again.") elif my_guess < computer_number: print ("Too small. Try again.") if abs((my_guess - computer_number)) < 10: print ("You are within 10!") if abs((my_guess - computer_number)) < 3: print ("You are within 3!") my_guess = input("Guess again") my_guess = int(my_guess) guesses += 1 if guesses == 5 and my_guess != computer_number: print ("You are out of tries. Play again.") print ("My number was", computer_number) else: print ("Way to go!")
true
c8d036524af484f8f3da0485c31d53a6508a630a
sahilee26/Python-Programming
/regex_cs384_prog_003.py
289
4.21875
4
# Matching words with patterns: # # Consider an input string where you have to match certain words with the string. To elaborate, check out the following example code: # import re Str = "Sat, hat, mat, pat" allStr = re.findall("[shmp]at", Str) for i in allStr: print(i)
true
5a39ab12501d511370172cbf3817e3f28e03b620
Lynijahhhhhhhhh/input_casting
/tertiary.py
807
4.375
4
# The distance from one point to another on a 2 Dimensional Plane is defined by the following equation: # # d = sqrt((x2 - x1) ^ 2 + (y2 - y1) ^ 2) # where d = distance; sqrt() represent square root, or to the power of (1/2) # Write a program that accepts two coordinates from the user and then calculates distance between the points. # Example Output: # x1 = 5 # y1 = 10 # # x2 = 35 # y2 = -85 # # distance from (5, 10) to (35, -85) is 99.6423 def distance(x1,y1,x2,y2): d = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** (1/2) #ITTTT WORKSSSSSSSSSSSSSSSSSSSSS print("distance from (",x1,",",y1,") to (",x2,",",y2,") is" , d) from1=int(input("What is x1? ")) from2=int(input("What is y1? ")) to1=int(input("What is x2? ")) to2=int(input("What is y2? ")) distance(from1,from2,to1,to2)
true
7e06648698a53857c8723d6fe04961ac0b02e604
maciej-m/my-first-blog
/cwiczenia/kolejny.py
1,143
4.3125
4
# zrobić z tego funkcję, która: # po poprawnym wykoanniu funkcji, osoba zotaje zapisana na liście gości na blogu # dodatkowo, niech np. dodaje jakiś randomowy przydomek ze słownika (trza utworzyć) # def hello_user(): "Powinien wyświetlać to, co sobie user wpisze jako string" name = input("Your name is: ") surname = input("Your surname is: ") if name == "" and surname == "": # zrobić z tego funkcję dla wszystkich przypadków print ("You didn't tell your name and surname! Want to try again? Y/N") no_name() elif name == "": print ("You didn't tell your name! Want to try again? Y/N ") no_name() elif surname == "": no_name_surname = input ("You didn't tell your surname! Want to try again? Y/N ") no_name() else: print ("Hello, " + name + " " + surname + "!") def no_name(): #jak zaimplementować tę funkcję do hello_user? no_name_surname = input() no_name_surname = no_name_surname.upper() if no_name_surname == "Y": print ("OK. TRYING AGAIN") hello_user() else: print ("BYE THEN!") hello_user()
false
a3b0ffc1f7e88f9de83df6b280f50bda1c5696b4
RodneyDong/python
/src/comparison.py
479
4.40625
4
""" Comparison Operators == Equal != NotEqual > Greater than < Less than >= Greater than or equal to <= Less than or equal to comparison operator always return True or False bool type. """ a, b = 10, 20 f=a==b # comparison operator has higher priority than assignment operator print(type(f)) print(f) print(a == b) print(a != b) print(a <= b) print(a >= b) print(a > b) print(a < b) print() if a < b: print("a is less than b.") else: print("a is greater than b.")
true
8457a7fe000f9bd0bc487dae142935422695ffec
RodneyDong/python
/src/function/collision.py
385
4.15625
4
""" TypeError: foo() got multiple values for argument 'name' """ def foo(name, **kwds): return 'name' in kwds # ask if there is key named 'name' in the dictionary def foo1(name, /, **kwds): # In other words, the names of positional-only parameters can be used in **kwds without ambiguity. return 'name' in kwds x = foo(1, **{'name': 2}) #x = foo1(1, **{'name': 2}) print(x)
true
642bcdb79fe7273a8e186aba6db4a058a8038fa3
Vanamman/LP3THW
/ex5.py
702
4.125
4
name = "Tim D. Ott" age = 29 height = 72 #inches weight = 225 # lbs eyes = "Hazel" teeth = 'White' hair = 'Brown' centimeters = round(height * 2.54) kilograms = round(weight * 0.45359237) print(f"\nLet's talk about {name}") print(f"He's {height} inches tall.") print(f"He's {weight} pounds heavy") print("Actually that's not too heavy.") print(f"He's got {eyes} eyes and {hair} hair.") print(f"His teeth are usually {teeth} depending on the coffee.") # this line is tricky, try to get it exactly right total = age + height + weight print(f"If I add {age}, {height}, and {weight} I get {total}.") print(f"His height is centimeters is {centimeters}.") print(f"His weight in kilograms is {kilograms}. \n")
true
062f6f64c27baedccec154f16887ca51338f715b
Vanamman/LP3THW
/ex9.py
723
4.125
4
# Here's some new strange stuff, remember type it exactly. # Setting days equal to abbrevaitions of the days of the week days = "Mon Tue Wed Thu Fri Sat Sun" # Setting months to abbreviated months with a newline character between each. months = "\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug" # Printing the days variable. Using older syntax instead of an f-string print("Here are the days: ", days) # Printing the months variable. Using older syntax instead of an f-string print("Here are the months: ", months) # Printing multiple lines inside of a single string. print(""" There's something going on here. With the three double-quotes. We'll be able to type as much as we like. Even 4 lines if we want, or 5, or 6. """)
true
4e9f331d932613958da5d709542414ecbc5901b4
isakura313/15_05_3
/lamb_da.py
251
4.1875
4
func = lambda x, y: x + y func_multiply = lambda x, y: x * y print(func(2, 2)) print(func_multiply(3, 2)) def krat_3(x): if x%3 == 0: return("кратное 3") else: return "no" func = lambda x: x**2 print(krat_3(func(2)))
false
bb84cb063102dd1771e7535df6c9584e13ddabd0
aa-ag/dmwp
/1. Working with Numbers/measurement_units.py
1,042
4.3125
4
def print_menu(): print('Enter 1 to convert kilometers to miles\n2 to convert miles to kilometers\n"q" to quit\exit') def kilometer_to_miles(): kilometers = input('Enter number of kilometers:\n') return f"\n{kilometers} kilometers equals {round(int(kilometers) / 1.609, 2)} miles." def miles_to_kilometers(): miles = input('Enter number of miles:\n') return f"\n{miles} miles equals {round(int(miles) * 1.609, 2)} kilometers." if __name__ == '__main__': print_menu() while True: option = input('\nWhich conversion would you like to do?\n') if option == 'q': print('\nbye.') break if option == '1': print(kilometer_to_miles()) if option == '2': print(miles_to_kilometers()) # inches to meters # (n * 2.54) / 100 # example: # print((5 * 2.54) / 100) # 0.127 # farenheit to celsius # (F - 32) * (5/9) # print((10 - 32) * (5/9)) # -12.222222222222223 # celsius to farenheit # C * (9/5) + 32 # print(10 * (9/5) + 32) # 50.0
false
bc113b54fa86d8011a45d37d70d417f2e948a9db
diesarrollador/Python-JavaScript--Cuso-Polotic
/num-en-lista.py
267
4.15625
4
#Escribe un programa en Python que reciba 5 números enteros del usuario y los guarde en una lista. #Luego recorrer la lista y mostrar los números por pantalla. numeros = [] for i in range(5): numeros.append(int(input(f"Ingrese numero {i+1}: "))) print(numeros)
false
882ec3fbd39f3a736bcea343060b6cffebca4570
RawSharkYu/UdaDataAnalyst
/MostFrequentWord/MostFrequentWord.py
1,355
4.3125
4
"""Quiz: Most Frequent Word""" def most_frequent(s): """Return the most frequently occuring word in s.""" # HINT: Use the built-in split() function to transform the string s into an # array # HINT: Sort the new array by using the built-in sorted() function or # .sort() list method # HINT: Iterate through the array and count each occurance of every word # using the .count() list method # HINT: Find the number of times the most common word appears using max() # HINT: Locate the index of the most frequently seen word # HINT: Return the most frequent word. Remember that if there is a tie, # return the first (tied) word in alphabetical order. words = s.split() words.sort() single_word = [] length = [] i = 0 while i < len(words): single_word.append(words[i]) length.append(words.count(words[i])) i = i + words.count(words[i]) result = single_word[length.index(max(length))] return result def test_run(): """Test most_frequent() with some inputs.""" print(most_frequent("cat bat mat cat bat cat")) # output: 'cat' print(most_frequent("betty bought a bit of butter but the butter was bitter")) # output: 'butter' if __name__ == '__main__': test_run()
true
1985079d1c1bbe9a90323ce41e809e90da56fb52
Igoren007/CODEWARS
/duplicate.py
942
4.4375
4
#Count the number of Duplicates #Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits. # #Example #"abcde" -> 0 # no characters repeats more than once #"aabbcde" -> 2 # 'a' and 'b' #"indivisibility" -> 1 # 'i' occurs six times #"Indivisibilities" -> 2 # 'i' occurs seven times and 's' occurs twice #"aA11" -> 2 # 'a' and '1' #"ABBA" -> 2 # 'A' and 'B' each occur twice def duplicate_count(text): count = 0 list_sym = [] text = text.lower() for pos, sym in enumerate(text): c1 = text[0:pos] c2 = text[pos+1:] if (sym in c1 or sym in c2) and (sym not in list_sym): count += 1 list_sym.append(sym) return count print(duplicate_count("aabBcde"))
true
2884558406b7edc41b3a01cf2d41410caa7c331e
Saiyam539/GeeksForGeeks-Python-Practice-Problem
/Program_9/main.py
398
4.125
4
# This program will read content from file_1.txt and then will # print this content in the file_2.txt with the # help of python. def copy_content(): with open('file_1.txt', 'r') as file_1: content = file_1.read() with open('file_2.txt', 'w') as file_2: file_2.write(content) print("The content has been copyed from file_1.txt\nto file_2.txt.") copy_content()
true
15eafd1c03f8679f61a2a378c5242c929096233f
JaxonDimes/Python
/dixon_TIY7.1/dixon_TIY7.3.py
203
4.1875
4
number = int(input("Please render a number that may or may not be a multiple of ten: ")) if number % 10 == 0: print(f"Looks like {number} is a multiple of ten.") else: print("Not a multiple...")
true
73fee61b6459f8f192d03f48c8c7cc9a58b8edf0
fahmidamc/codedady_testcodes
/simple_calculator.py
1,399
4.1875
4
#create a simple calculator #addition #substraction #multiplication #division #refer : try, except #code should not break unless the user decide def addition(x,y): return x + y def subtraction(x,y): return x - y def multiplication(x,y): return x * y def division(x,y): return x / y while True: print("=================================================") print("select your operation.") print("1.Addition") print("2.Subtraction") print("3.Multiplication") print("4.Division") print("5.exit") choice = input("enter the choice 1/2/3/4/5") try: if choice in ('1','2','3','4') : a = float(input("enter the first number")) b = float(input("enter the second number")) if choice == '1': print(a,"+",b,"=",addition(a,b)) elif choice == '2': print(a,"-",b,"=",subtraction(a,b)) elif choice == '3' : print(a,"*",b,"=",multiplication(a,b)) elif choice == '4' : print(a,"/",b,"=",division(a,b)) elif choice == '5': print("program exiting") break else: print("invalid choice") except Exception as e: print(e) # # except ValueError: # print("invalid",'value error!') # # # except ZeroDivisionError: # print(a, '/', b, ':', 'Division by zero!')
true
06f37afa538fd3ee8961c8ab7188543881a0bf3b
j-walrath/autonomous-turtle
/utils/rvo/rvo_math.py
2,703
4.125
4
""" Contains functions and constants used in multiple classes. """ import math """ A sufficiently small positive number. """ EPSILON = 0.00001 def abs_sq(vector): """ Computes the squared length of a specified two-dimensional vector. Args: vector (Vector2): The two-dimensional vector whose squared length is to be computed. Returns: float: The squared length of the two-dimensional vector. """ return vector @ vector def normalize(vector): """ Computes the normalization of the specified two-dimensional vector. Args: vector (Vector2): The two-dimensional vector whose normalization is to be computed. Returns: Vector2: The normalization of the two-dimensional vector. """ return vector / abs(vector) def det(vector1, vector2): """ Computes the determinant of a two-dimensional square matrix with rows consisting of the specified two-dimensional vectors. Args: vector1 (Vector2): The top row of the two-dimensional square matrix. vector2 (Vector2): The bottom row of the two-dimensional square matrix. Returns: float: The determinant of the two-dimensional square matrix. """ return vector1.x_ * vector2.y_ - vector1.y_ * vector2.x_ def dist_sq_point_line_segment(vector1, vector2, vector3): """ Computes the squared distance from a line segment with the specified endpoints to a specified point. Args: vector1 (Vector2): The first endpoint of the line segment. vector2 (Vector2): The second endpoint of the line segment. vector3 (Vector2): The point to which the squared distance is to be calculated. Returns: float: The squared distance from the line segment to the point. """ r = ((vector3 - vector1) @ (vector2 - vector1)) / abs_sq(vector2 - vector1) if r < 0.0: return abs_sq(vector3 - vector1) if r > 1.0: return abs_sq(vector3 - vector2) return abs_sq(vector3 - (vector1 + r * (vector2 - vector1))) def left_of(a, b, c): """ Computes the signed distance from a line connecting the specified points to a specified point. Args: a (Vector2): The first point on the line. b (Vector2): The second point on the line. c (Vector2): The point to which the signed distance is to be calculated. Returns: float: Positive when the point c lies to the left of the line ab. """ return det(a - c, b - a) def square(scalar): """ Computes the square of a float. Args: scalar (float): The float to be squared. Returns: float: The square of the float. """ return scalar * scalar
true
7d29bc308fb0d3758f6ea2085328a11226f239ba
syuuhei-yama/Python_202105
/Day29-6.py
1,023
4.125
4
#特殊メソッド class Human: def __init__(self, name, age, phone_number): self.name = name self.age = age self.phone_number = phone_number def __str__(self): return self.name + ',' + str(self.age) + ',' + self.phone_number def __eq__(self, other): return (self.name == other.name) and (self.phone_number == other.phone_number) def __hash__(self): return hash(self.name + self.phone_number) def __bool__(self): return True if self.age >= 20 else False def __len__(self): return len(self.name) man = Human('Toro',20, '09003530554') man2 = Human('Toro', 18, '09003530554' ) man3 = Human('jiro2', 18, '08003530554' ) man_str = str(man) print(man_str) print(man == man2) set_men = {man,man2,man3} for x in set_men: print(x) if man: print('manはTrue') if man2: print('man2はTru e') print(len(man)) print(len(man3)) # print(hash('Toro')) # print(hash('Toro')) # print(hash('jiro'))
false
ea14cf16d8ef42339890d7f16d4777d9841fe1db
syuuhei-yama/Python_202105
/Day25-3.py
803
4.34375
4
#練習問題 #1 num = 10 #2 print(type(num)) #3 num_s = str(num) print(type(num_s)) #4 num_list = [num_s, '20','30'] print(num_list) #5 num_list.append('40') print(num_list) #6 num_tuple = tuple(num_list) print(type(num_tuple)) #7 val = input() num_tuple += (val,) print(num_tuple) #8 num_set = {"40","50","60"} # print(type(num_set)) print("num_tuple={}".format(num_tuple)) print("num_set={}".format(num_set)) #9 print(set(num_tuple).union(num_set)) #10 num_dict = { num_tuple: num_s } #11 print(len(num_list)) #12 print(num_dict.get("Mykey","Does Not exitst")) #13 num_list.extend(["50","60"]) print("num_list={}".format(num_list)) #14 val = input() is_under_50 = int(val) < 50 print("is_under_50={}".format(is_under_50)) #15 print(f'num_s = {num_s}') #16 print(dir(num_dict))
false
348747ab2fad4a6929ff34f54b8f79d1bd0340ad
Crackfever/Grade-Sorter-App
/main.py
921
4.28125
4
print("Welcome to the Grade Sorter App") #Start list and get user input grades = [] grade = (input("\nWhat is your first grade (0-100): ")) grades.append(grade) grade = (input("What is your second grade (0-100): ")) grades.append(grade) grade = (input("What is your third grade (0-100): ")) grades.append(grade) grade = (input("What is your forth grade (0-100): ")) grades.append(grade) print("\nYour grades are: " + str(grades)) #Sort list high to low grades.sort(reverse=True) print("\nYour grades from highest to lowest are: " + str(grades)) #Removing lowest 2 grades print("\nThe lowest two grades will now be dropped.") removed_grade = grades.pop() print("Removed grade: " + str(removed_grade)) removed_grade = grades.pop() print("Removed grade: " + str(removed_grade)) #Recap remaining grades print("\nYour remaining grades are: " + str(grades)) print("Nice work! Your highest grade is " + str(grades[0])+ ".")
true
83d58da6bbb90030a810d6d9e9ad6072ba0686d4
Nishith170217/Coursera-Python-3-Programming-Specialization
/num_words_list.py
387
4.1875
4
#Write code to create a list of word lengths for the words in original_str using the accumulation pattern and assign #the answer to a variable num_words_list. (You should use the len function) original_str = "The quick brown rhino jumped over the extremely lazy fox" list=original_str.split() num_words_list = [] for i in list: num_words_list.append(len(i)) print(num_words_list)
true
aa73ed9ef256d0c251ff6ac49e6b7909a6c2fd35
raghav855/Python-programs
/exercise8.py
716
4.3125
4
# Write a Code for checking the speed of drivers. This code should take one value: speed. # If speed is less than 70, it should print “Ok”. # Otherwise, for every 5km above the speed limit (70), it should give the driver one demerit point and print the total # number of demerit points. For example, if the speed is 80, it should print: “Points: 2”. # If the driver gets more than 12 points, the function should print: “License suspended speed=int(input("Enter the maximum speed : ")) demerit_points=0 if speed<=70: print("Ok") elif speed>70 : a=(speed-70)//5 demerit_points+=a print(demerit_points) if demerit_points>=12: print("License Expired")
true
17e7884d8928ef39426ac4487880ba3fdfad849d
TitusSmith33/scs_numerical_data
/source/determine-even-odd.py
1,086
4.46875
4
def determine_even_odd(value: int) -> str: """Determine if a number is even or odd.""" # use modular arithmetic to determine if the number is even if value % 2 == 0: return "even" # since the number is not even, conclude that it is odd else: return "odd" print("Determining whether integer values are even or odd") # perform the computation with the value of zero number = 0 response = determine_even_odd(number) print(f"The number of {number} is {response}!") # perform the computation with the value of ten number = 10 response = determine_even_odd(number) print(f"The number of {number} is {response}!") # perform the computation with the value of eleven number = 11 response = determine_even_odd(number) print(f"The number of {number} is {response}!") # use a negative value for the computation number = -10 response = determine_even_odd(number) print(f"The number of {number} is {response}!") # use a negative value for the computation number = -11 response = determine_even_odd(number) print(f"The number of {number} is {response}!")
true
57b31897bb295bbe944f7ba39b03e54714b43237
Tom-Goring/Sorting-And-Searching-Algorithms
/Sorting Algorithms/SelectionSort.py
850
4.15625
4
""" Selection Sort picks the smallest element in the list and swaps it to the first position, then the second smallest into the second position, etc. Selection sort is an in-place sort. """ import random def selection_sort(alist): for i in range(len(alist)): min_position = i for j in range (i + 1, len(alist)): if alist[min_position] > alist[j]: min_position = j alist[i], alist[min_position] = alist[min_position], alist[i] unordered_list = [] for i in range(100): unordered_list.append(i) random.shuffle(unordered_list) selection_sort(unordered_list) print(unordered_list) success = True for index in range(len(unordered_list) - 1): if unordered_list[index] > unordered_list[index + 1]: success = False if success: print("Selection Sort successful!")
true
38562fb7abc006f1545695d514445f5486eb553a
VaniaNatalie/Exercise
/Discussion Forum Week 4/question 2.py
381
4.21875
4
print("Weight in Planet Calculations") def calc_weight_on_planet(weight, gravity=23.1): mass = float(weight)/9.8 q = float(mass)*float(gravity) return q #input the numbers in the calc_weight_on_planet(), the gravity is optional print("Your weight in this planet ", calc_weight_on_planet(120)) print("(If you didn't input any gravity, by default it's Jupiter)")
true
bc8c8daeb0e8c763f3e955b247ea9b9a3d1804bd
VaniaNatalie/Exercise
/Discussion Week 5/question 13.py
617
4.1875
4
def makeForming(word): vowels = ('a', 'e', 'i', 'o', 'u') if word.endswith('ie'): if True: word = word[:-2] a = word + "ying" return a if word.endswith('e'): if True: word = word[:-1] b = word + "ing" return b if word[-1] not in vowels: if word[-2] in vowels: if word[-3] not in vowels: c = word + str(word[-1]) + "ing" return c return word += 'ing' def main(): word = input("Input word: ") print(makeForming(word)) main()
false
bf71f6d7cb83e8749815f7bf4b9e47d3cdcf70b9
shirshirzong/MIS3640
/session09/For Testing.py
1,074
4.25
4
def is_abecedarian(word): """ returns True if the letters in a word appear in alphabetical order (double letters are ok). """ before = word[0] for letter in word: if letter < before: return False before = letter return True # def find_abecedarian_words(): # fin = open('session 9/words.txt') # counter = 0 # current_longest_word = '' # for line in fin: # word = line.strip() # if is_abecedarian(word): # # print(word) # counter += 1 # if len(word) > len(current_longest_word): # current_longest_word = word # return counter, current_longest_word # print(find_abecedarian_words()) def is_abecedarian_using_recursion(word): """ returns True if the letters in a word appear in alphabetical order (double letters are ok). """ if len(word) <= 1: return True if word[0] > word[1]: return False return is_abecedarian_using_recursion(word[1:]) print(is_abecedarian_using_recursion('b'))
true
e92c28cb51d0ab47af599b65c91a5fe044fa9984
shirshirzong/MIS3640
/session10/demo.py
832
4.125
4
AFC_east = ['New England Patriots', 'Buffalo Bills', 'Miami Dolphins', 'New York Jets'] numbers = [42, 123] empty = [] # print(AFC_east, numbers, empty) # print(numbers[1]) AFC_east[3] = 'New York Giants' # print(AFC_east) AFC_east = ['New England Patriots', 'Buffalo Bills', 'Miami Dolphins', 'New York Jets'] # print('Buffalo' in AFC_east) '''Exercise 1''' L = [ ['Apple', 'Google', 'Microsoft'], ['Java', 'Python', ['Ruby','On Rail'], 'PHP'], ['Adam', 'Bart', 'Lisa'] ] # Index of 'Apple' print(L[0][0]) # Index of 'Lisa' print(L[2][2]) # Index of 'On Rail' print(L[1][2][1]) '''Traversing A list''' numbers = [2, 0, 1, 6, 9] for i in range(len(numbers)): numbers[i] = numbers[i] * 2 print(numbers) '''Exercise 2 play around''' '''List Slices''' t = ['a','b','c','d','e','f'] print(t[1:3])
false
36e95e308d703821399a9413dfd15242e1bccf94
AndresEscobarDev/holbertonschool-higher_level_programming
/0x06-python-classes/102-square.py
1,367
4.25
4
#!/usr/bin/python3 """Square Module""" class Square(): """Square. Private instance attribute: size: property def size(self). property setter def size(self, value). Instantiation with optional size. Public instance method: def area(self). """ def __init__(self, size=0): """Constructor""" self.size = size def area(self): """returns the current square area""" return self.__size ** 2 @property def size(self): """retrieves the size""" return self.__size @size.setter def size(self, value): """sets the size""" if type(value) != int: raise TypeError("size must be an integer") if value < 0: raise ValueError("size must be >= 0") self.__size = value def __eq__(self, next): """Equal.""" return self.__size == next def __ne__(self, next): """Diferent.""" return self.__size != next def __lt__(self, next): """Less than.""" return self.__size < next def __le__(self, next): """Less or equal than.""" return self.__size <= next def __gt__(self, next): """Greater than.""" return self.__size > next def __ge__(self, next): """Greater or equal than.""" return self.__size >= next
true
0ee1f18dfffe143ddc2b07d19a56b365b9663072
AggieNate/may4
/find_largest.py
212
4.21875
4
array = [5,7,24,80,95] max = array[0] for num in range(0,len(array)): if array[num] > max: max = array[num] print(max) # Assignment: Write a program which finds the largest element in the array
true
8d28be7508a6445914067c93d207323c1d2e9263
vkbiotech841/basics_python
/credit_card_eligibiity.py
970
4.28125
4
print("Welcome to the credit card eligibility analyzer") print("*"*50) try: age = int(input("Enter your age ")) is_valid_age = bool(age >= 18 and age <=65) if is_valid_age == False: while is_valid_age == False: print("Please provide the correct age") age = int(input("Enter your age ")) is_valid_age = bool(age >= 18 and age <=65) except NameError: print("You did not enter the valid age.") except ValueError: print("You did not enter the valid age") monthly_income = int(input("Enter your monthy income ")) annual_income = monthly_income*12 print(f"your annual income is {annual_income}") high_income = annual_income >= 300000 credit_score = True student = False if is_valid_age and high_income and credit_score and not student: print("You are eligible for credit card") else: print("You are not eligible for credit card") print("Thank you for analyzing you credit card eligibility")
true
bf16946eddf014d8aea5f0529b60f9309a4958fd
VasiliosX/100-Days-of-code
/day-19/day-19.py
1,011
4.21875
4
from turtle import Turtle, Screen import random colors = ['red', 'yellow', 'blue', 'orange', 'green','purple'] is_on=False screen = Screen() screen.setup(width=500,height=400) user_bet=screen.textinput(title='Turtle race', prompt='Which turtle is going to be triumphant? pick a color: ') turtles=[] if user_bet: is_on=True turtles=[] for i in range(6): timmy=Turtle(shape='turtle') timmy.speed(2) timmy.color(colors[i]) timmy.penup() timmy.goto(-230,-130+i*60) turtles.append(timmy) while is_on: for current_turtle in turtles: if current_turtle.xcor()>230: winner=current_turtle.pencolor() print(f'The {winner} turtle is the champion!!!!!') is_on=False dist = random.randint(0, 10) current_turtle.forward(dist) if winner==user_bet: print('You won the bet') else: print(f'You lost the bet, you said {user_bet} turtle is going to win, but eventually the {winner} turtle won') screen.exitonclick()
true
7e6b98790f3bfa1dfde2f943bac88d661dd846a6
do-ryan/athena
/PEG/longest_increasing_subsequence.py
1,380
4.40625
4
""" Given an array of integers, find the longest increasing subsequence. A subsequence is just a collection of numbers from the array - however, they must be in order. For example: Array: 1 2 5 4 3 6 The longest increasing subsequence here is 1 2 5 6 (or 1 2 4 6, or 1 2 3 6). The numbers must be strictly increasing - no two numbers can be equal. Input N <= 5000, the number of integers. N lines, each with a value in the array. Output The length of the longest increasing subsequence of the array. Sample input: 6 1 2 5 4 3 6 """ import datetime def inp(): """Return list of integers from problem input""" n = int(input()) ret = [int(input()) for _ in range(n)] # ret = [] # marker = datetime.datetime.now() # for _ in range(n): # print(datetime.datetime.now() - marker) # marker = datetime.datetime.now() # ret.append(int(input())) return ret, n def longest_increasing_subsequence(integers, n): """Return integer length of longest increasing subsequence from an ordered list of integers. Dynamic programming. """ if n < 1: return 0 lis = [1 for _ in integers] for i in range(1, n): for j in range(i): if integers[i] > integers[j] and lis[i] < lis[j] + 1: lis[i] = lis[j] + 1 return max(lis) ret, n = inp() print(longest_increasing_subsequence(ret, n))
true
281dfc9f41540ed25aa874e6decfc7f303e4cb09
loetcodes/100-Days-of-Code--PythonChallenge-02
/Day_114_GoalMatchBestMatch.py
2,012
4.15625
4
""" Day 114 - Best Match Codewars "AL-AHLY" and "Zamalek" are the best teams in Egypt, but "AL-AHLY" always wins the matches between them. "Zamalek" managers want to know what is the best match they've played so far. The best match is the match they lost with the minimum goal difference. If there is more than one match with the same difference, choose the one "Zamalek" scored more goals in. Given the information about all matches they played, return the index of the best match (0-based). If more than one valid result, return the smallest index. Example: For ALAHLYGoals = [6,4] and zamalekGoals = [1,2], the output should be 1. Because 4 - 2 is less than 6 - 1 For ALAHLYGoals = [1,2,3,4,5] and zamalekGoals = [0,1,2,3,4], the output should be 4. The goal difference of all matches are 1, but at 4th match "Zamalek" scored more goals in. So the result is 4. Input/Output: [input] integer array ALAHLYGoals: The number of goals "AL-AHLY" scored in each match. [input] integer array zamalekGoals: The number of goals "Zamalek" scored in each match. It is guaranteed that zamalekGoals[i] < ALAHLYGoals[i] for each element. [output] an integer: Index of the best match. """ #!/bin/python3 from math import gcd def best_match(goals1, goals2): min_diff = goals1[0] - goals2[0] best_idx = 0 for idx in range(len(goals1)): diff = goals1[idx] - goals2[idx] if diff < min_diff: min_diff = diff best_idx = idx elif diff == min_diff and goals2[idx] > goals2[best_idx]: best_idx = idx return best_idx if __name__ == "__main__": assert best_match([6, 4],[1, 2]) == 1, "Invalid result: Should return 1" assert best_match([1],[0]) == 1 "Invalid result: Should return 1" assert best_match([1, 2, 3, 4, 5],[0, 1, 2, 3, 4]), "Invalid result: Should return 1" assert best_match([3, 4, 3],[1, 1, 2]), "Invalid result: Should return 1" assert best_match([4, 3, 4],[1, 1, 1]), "Invalid result: Should return 1"
true
1a4aa8d7abee9a3e5fe2b7664a9d80b8cf974b2c
andrew-kavas/pyPhys
/pyPhys/euler/E_371.py
1,136
4.21875
4
''' Oregon licence plates consist of three letters followed by a three digit number (each digit can be from [0..9]). While driving to work Seth plays the following game: Whenever the numbers of two licence plates seen on his trip add to 1000 that's a win. E.g. MIC-012 and HAN-988 is a win and RYU-500 and SET-500 too. (as long as he sees them in the same trip). Find the expected number of plates he needs to see for a win. Give your answer rounded to 8 decimal places behind the decimal point. Note: We assume that each licence plate seen is equally likely to have any three digit number on it. ''' # Second Attempt Using Monte Carlo Tree # First Attempt Using Bernoulli Random Numbers ''' # 1000 unique plates (000-999) # (1/1000) = Prob of getting the unmatched number, 000 # Prob of getting a car with a winning counterpart matched = (999/1000) # Prob of getting the winning counterpart after winner_winner = (1/1000) def chicken_dinner(): # Prob of getting two that add up in a row p_win = matched * winner_winner * .5 gauss = 1 expected = gauss/p_win return expected print(chicken_dinner()) '''
true
9a5889624de1bffbb51efbe1f843504023b75ede
sammanthp007/sticky_problems
/generate_uniform_random_number.py
1,039
4.28125
4
# Generate Uniform Random Numbers '''How would you implement a random number generator that generates a random integer i in [a,b], given a random number generator that produces either zero of one with equal probability? All generated values should have equal probability. What is the run time of your algorithm? ''' # input = a, b (the two margins inclusive) # output = res, which is a random number in between a and b # working: import random def zero_one_random(): return random.randint(0,1) # top = b - a + 1 # how to create a number from bits # 0 to 8 # we need to repetedly range(0, top) -> create a bit -> add it to our result in the range -> 0 , top def randomly_select(a, b): top = b - a + 1 res = top + 1 while res >= top: res = 0 iterator = 1 while iterator < top: bit = zero_one_random() res = res << 1 res = res | bit iterator = iterator << 1 return res + a # res = {000, 001, 010, 011, 100, 101} print (randomly_select(12, 19))
true
7d25ed5817d14e996797a59ea402fa20ec760907
sammanthp007/sticky_problems
/reverse_word.py
1,130
4.40625
4
# Given a word containing a set of words separated by white space, we would like to transform it to a string in which the words appear in the reverse order. For example, "Alice likes Bob" transforms to "Bob likes Alice". We do not need to keep the original string. # Implement a function for reversing the words in a string s. Your function should use O(1) space. def reverse_word(sentence): # Phase1: traverse to get where the words are letter_ptr = 0 word_starts = [0] word_length =[] word_begin = 0 while letter_ptr < len(sentence): while letter_ptr < len(sentence) and sentence[letter_ptr] != ' ': letter_ptr += 1 temp_length = letter_ptr - word_begin word_length.append(temp_length) letter_ptr += 1 word_starts.append(letter_ptr) word_begin = letter_ptr # Phase2: reverse the sentence based on words, words are determined by spaces in between res = '' for i in range(len(word_length)): res = sentence[word_starts[i]: word_starts[i] + word_length[i]] + ' ' + res return res sen = "Bob likes alice" print(reverse_word(sen))
true
652ad4292a140676bd74a6ef13231f0a275d39d2
gillespilon/github_gists
/capitalize_string.py
442
4.28125
4
#! /usr/bin/env python3 """ Function to capitalize a string. """ def capital_case(x: str) -> str: return x.capitalize() def main(): print(capital_case('gilles')) print(capital_case('GILLES')) print(capital_case('gIlLeS')) print(capital_case('good morning')) print(capital_case('good Morning')) print(capital_case('Good Morning')) print(capital_case('Good morning')) if __name__ == '__main__': main()
false
a17859299358ea8ade2de4b66aee0f82f29c132c
Manish-kumar-Thakur/Lab-exercises-of-python
/pallindrome by string if-else statement.py
213
4.34375
4
number=int(input("enter a number:")) string=str(number) rev_string=string[::-1] print("reversed:",rev_string) if string==rev_string: print("number is pallindrome") else: print("number is not pallindrome")
false
ec6bcbf94e24beacae90cee0bf16a063041b1753
anhtr525/coding-summer2020
/Javascript/1.py
813
4.1875
4
for x in range (1, 101): #loop through 1 to 100 if x%15 == 0: print("FizzBuzz") #the output will be FizzBuzz when the number devisable by 15 elif x%5 == 0: print("Buzz") #the output will be Buzz when the number devisable by 5 elif x%3 == 0: print("Fizz") #the output will be Fizz when the number devisable by 3 else: print(x) #the output will be the number when it isn't devisable by 3, 5 and 15 def linearSearch(fruit, targetvalue): #to check if the target value matches the fruit in the fruit list for y in fruit: if y == targetvalue: return fruit.index(y) fruit = ["apple", "banana", "cherry", "dragonfruit", "elderberry"] #list of the fruit targetvalue = "cherry" foundFruit = linearSearch(fruit, targetvalue) print(foundFruit)
true
eb418641463a263b54d2db8db078803cebaaa99a
shwetaatgit/Python-Language-Tasks
/Task3.py
393
4.21875
4
list = [] # number of elemetns as input n = int(input("Enter number of elements : ")) for i in range(0, n): ele = str(input()) list.append(ele) # adding the element print(list) l = [] for i in list: length = 0 for j in i: length += 1 l.append(length) l.sort() # arranging lengths in ascending order print(l[-1]) # finding maximum in the list
true
2a13b45ce3ac19585ded402e3939a75150733e7a
JeffKnowlesJr/python_fundamentals
/functions_intermediate_1.py
1,581
4.25
4
""" # Create beCheerful(). Within it, print string "good morning!" 98 times. print("*"*80) def beCheerful(name='', repeat=1): print(f"good morning {name}\n"*repeat) beCheerful() beCheerful(name="john") beCheerful(name="michael", repeat=5) beCheerful(repeat=5, name="kb") beCheerful(name="aa") # helpful tips for the next assignment import random print(random.random()) # returns a random floating number between 0.000 to 1.000 print(random.random()*50) # returns a float between 0.000 to 50.000 int( 3.654 ) # returns 3 round( 3.654 ) # returns 4 As part of this assignment, please create a function randInt() where randInt() returns a random integer between 0 to 100 randInt(max=50) returns a random integer between 0 to 50 randInt(min=50) returns a random integer between 50 to 100 randInt(min=50, max=500) returns a random integer between 50 and 500 Create this function without using random.randInt() but you are allowed to use random.random(). """ def randInt(): import random rand = round(random.random()*100) print("\nRandom 1 - 100:") return rand print(randInt()) def randInt(max): import random rand = round(random.random()*max) print("Random 1 -", max, ":") return rand print(randInt(max=50)) def randInt(min): import random rand = round(random.random()*min + min) print("Random ", min, " - ", 2*min, ":") return rand print(randInt(min=50)) def randInt(min, max): import random rand = round(random.uniform(min, max)) print("Random ", min, " -", max, ":") return rand print(randInt(min=50, max=500))
true