blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
bfa4cd171831f50848856dd016fb4fdf0461bc47
davidjeet/Learning-Python
/PythonHelloWorld/MoreLists 2/MoreLists_2.py
948
4.125
4
z = 'Demetrius Harris' for i in z: print(i,end = '*') print() eggs = ('hello', 323, 0.5) print(eggs[2]) #eggs[1] = 400 # illegal #converting tuple to list a = list(eggs) a[1] = 500 b = tuple(a) print(b) spam = 42 cheese = 100 print(spam) print(cheese) #different than spam, because by-value spam = [0,1,2,3,4,5] cheese = spam cheese[1] = 'Hello!' print(spam) print(cheese) #should be identical, because lists are reference types x = [[3,4,5,6],[7,8,9,10],9.1] y = x.copy() # z = x.deepcopy() y[1] = 'blah' print(x) print(y) # things to learn #1. lists are mutable, strings are not. So z[2] = 'g' is illegal #2. Tuples are like lists but use parens() not square brackets. #3. Tuples are also immutable. (line 7) #4. Use tuples to signal you don't want data changed, # also it optimzes Python for speed working with these. #5. convert to tuples/lists using list() and tuple(). See 10, 12 #6. variables are by-value, but lists are by reference
true
1c7472684b1621d64c77426d62733997f027b60d
LFValio/aprendendo-vetores
/vetores-aprendendo/ex-03.py
625
4.125
4
# Exercício 3: ler vários nomes mas só armazenar aqueles que começam com C. nome = [] cNome = 0 # contagem nome sNome = [] # string nome for x in range(1, 6): nome.append(str(input(f"{x}º Nome: "))) for x in nome: # varrerá o vetor nome, verificando todas as palavras que contém nele if x[0].lower() == "c": # x[0].lower() --> pega o primeiro caractere e o converte em minúsculo cNome += 1 sNome.append(x) # as strings que tiverem "C" ficarão armazenadas no vetor sNome print(f"{cNome} nomes começam com C, sendo eles: {sNome}")
false
aa1d86e1bd876632b1db4d2d5f9381a162db051f
wavecrasher/Turtle-Events
/main.py
416
4.21875
4
import turtle turtle.title("My Turtle Game") turtle.bgcolor("blue") turtle.setup(600,600) screen = turtle.Screen() bob = turtle.Turtle() bob.shape("turtle") bob.color("white") screen.onclick(bob.goto) #bob.ondrag(bob.goto) screen.listen() #The pattern above consists of circles drawn repeatedly at different angles - #Declare a function to draw a circle - Use a while loop to draw a circle and turn repeatedly
true
b9bc55c14baaf0d0f11234c3c8593fe4b5a4ba47
Benzlxs/Algorithms
/sorting/merge_sort.py
1,103
4.125
4
# merge sortting https://en.wikipedia.org/wiki/Merge_sort import os import time def merge(left, right): # merging two parts sorted_list = [] left_idx = right_idx = 0 left_len, right_len = len(left), len(right) while (left_idx < left_len) and (right_idx < right_len): if left[left_idx] <= right[right_idx]: sorted_list.append(left[left_idx]) left_idx += 1 else: sorted_list.append(right[right_idx]) right_idx += 1 # merging together sorted_list = sorted_list + left[left_idx:] + right[right_idx:] return sorted_list def merge_sort(list_nums): if len(list_nums) <= 1: return list_nums mid = len(list_nums) // 2 left = merge_sort(list_nums[:mid]) right = merge_sort(list_nums[mid:]) return merge(left, right) if __name__=='__main__': # Verify it works random_list_of_nums = [120, 45, 68, 250, 176] print('Before sorting\n') print(random_list_of_nums) sorted_list = merge_sort(random_list_of_nums) print('After sorting\n') print(sorted_list)
true
cac68f6a0cb20080f211d0c83f6482a2827f60c7
Benzlxs/Algorithms
/sorting/selection_sort.py
784
4.40625
4
# merge sortting https://en.wikipedia.org/wiki/Selection_sort # time complexity is O(n^2) import os import time def selection_sort(list_nums): for i in range(len(list_nums)): lowest_value_index = i # loop through unsorted times for j in range(i+1, len(list_nums)): if list_nums[j] < list_nums[lowest_value_index]: lowest_value_index = j list_nums[i], list_nums[lowest_value_index] = list_nums[lowest_value_index], list_nums[i] #return list_nums if __name__=='__main__': # Verify it works random_list_of_nums = [120, 45, 68, 250, 176] print('Before sorting\n') print(random_list_of_nums) selection_sort(random_list_of_nums) print('After sorting\n') print(random_list_of_nums)
true
251b46112a4ba9c6983a3baa6545bd2f47a10edb
PersianBuddy/emailsearcher
/main.py
1,039
4.25
4
#! Python 3 # main.py - finds all email addresses import re , pyperclip # user guid print('Copy your text so it saves into clipboard') user_response = input('Are you ready? y=\'yes\' n=\'no\' :') while str(user_response).lower() != 'y': user_response = input("Make sure type 'y' when you copied your desired text :") # take text from clipboard sample_string = str(pyperclip.paste()) phone_reg_ex = re.compile('[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}', re.VERBOSE) emails_list = re.findall(phone_reg_ex, sample_string) # convert list of emails to a string of emails emails_string = '' if len(emails_list) > 0: for email in emails_list: emails_string += email + '\n' pyperclip.copy(emails_string) print('\nThese email addresses copied to your clipboard so you can paste it anywhere') print('All email addresses available in your desired text') print(emails_string) else: print('\nThere is no email address in your desired text') print('Or maybe you just forgot to copy your desired text')
true
7ce7b8965c78c0e772953895bc81b4bd9023f15a
pezLyfe/algorithm_design
/intro_challenges/max_pairwise_product_2.py
615
4.15625
4
# Uses python3 ''' The starter file provided by the course used nested for loops to calculate the solution as a result, the submission failed due to an excessive runtime. The list.sort() method in python works really fast, so use that to order the list and then multiply the largest entry in the list by the second largest entry in the list ''' n = int(input()) a = [int(x) for x in input().split()] assert(len(a) == n) result = 0 a.sort() x = len(a) result = a[x-1] * a[x-2] '''for i in range(0, n): for j in range(i+1, n): if a[i]*a[j] > result: result = a[i]*a[j] ''' print(result)
true
d5af7c56bda22cef4a6855838d23b33ade9ef340
WilliamMcCann/holbertonschool-higher_level_programming
/divide_and_rule/h_fibonacci.py
520
4.21875
4
'''prints out the Fibonacci number for a given input''' import threading class FibonacciThread(threading.Thread): def __init__(self, number): threading.Thread.__init__(self) try: val = int(number) except ValueError: print("number is not an integer") self.number = val def run(self): a = 0 b = 1 for i in range(0, self.number): temp = a a = b b = temp + b print(str(self.number) + "=>" + str(a))
true
5ed3875dee928cc5a1b65ad7d9f1f582e2358660
ShruKin/Pre-Placement-Training-Python
/WEEK-3/1.py
215
4.625
5
# 1. Write a python program to check if a user given string is Palindrome or not. n = input("Enter a string: ") if(n == n[::-1]): print("Its a palindrome string") else: print("Its not a palindrome string")
true
9663393bb56c77a277bc1b62c44a3c6ae3b8b4ee
ShruKin/Pre-Placement-Training-Python
/WEEK-3/2.py
364
4.46875
4
# 2. Write a python program to take Firstname and lastname as input. # Check whether the first letter of both strings are in uppercase or not. # If not change accordingly and print reformatted string. fn = input('Firstname: ') ln = input('Lastname: ') if not fn[0].isupper(): fn = fn.title() if not ln[0].isupper(): ln = ln.title() print(fn + " " + ln)
true
ceaf2f949eb9840fbeed64d74c0cd37b808f5816
kb7664/Fibonacci-Sequence
/fibonacciSequence.py
673
4.3125
4
############################## # Fibinacci Sequence # # Author: Karim Boyd ############################## # This program demonstrates one of the many ways to build the Fibonacci # sequence using recursion and memoization # First import lru_cache to store the results of previous runs to # memory from functools import lru_cache # Set the dictionary to hold upto 1000 items in cache @lru_cache(maxsize = 1000) # Set up Fibinacci function def fibonacci(n): if n == 1: return 1 elif n == 2: return 1 elif n > 2: return fibonacci(n-1) + fibonacci(n-2) # Test the function for n in range (1, 1001): print(n, " : ", fibonacci(n))
true
d48b59a7708afea878e06c1d910ff304e2772316
hintermeier-t/projet_3_liberez_macgyver
/graph/maze.py
1,601
4.125
4
# -*coding: UTF-8-* """Module containing the MazeSpriteClass.""" import pygame as pg from . import gdisplay class MazeSprite (pg.sprite.Sprite): """Class displaying the maze sprite. Gathering all we need to display the walls sprites, and the path sprites. (position, source picture etc...). Inherit the pygame Sprite class. Attributes : sheet (Surface) : SpriteSheet used to design the walls and path. sheet_rect (Rect) : Area of the sprite. """ def __init__(self): """Class constructor. Class constructor whiwh resize the spritesheet to make the 20x20 tiles 2.5 times bigger (50x50). """ self.sheet, self.sheet_rect = gdisplay.load_image( "floor-tiles-20x20.png") self.sheet = pg.transform.scale(self.sheet, (1000, 650)) def print_maze(self, board, screen): """Method to display the entire maze. Args: board (GamingBoard): Core maze to get the walls and path positions. screen (Surface): Surface used to draw the maze. """ x = 0 y = 0 for i in range(226): if x > 1 and x % 15 == 0: x = 0 y += 1 if i in board._walls: # 300px from left, 80px from top, size_x, size_y screen.blit(self.sheet, (x * 50, y * 50), pg.Rect((650, 200, 50, 50))) if i in board._path: screen.blit(self.sheet, (x * 50, y * 50), pg.Rect((500, 0, 50, 50))) x += 1
true
be80b0aea58b2005699f667c15102be2d2398d42
riaz4519/python_practice
/programiz/_6_list.py
922
4.375
4
#list #create list myList = [5,6,7,8] print(myList) #mixed data type list myList = [5,8,'data',3.5] print(myList) #nested list myList = ['hello',[5,6]] print(myList) #accessing the list myList = ['p','r','o','b','e'] #by index print(myList[0]) #nested n_list = ["Happy", [2,0,1,5]] print(n_list[1][1]) print(n_list[1]) #negative print(myList[-1]) #slice list in python listSlice = ['p','r','o','g','r','a','m','i','z'] #index 0 upto index 3 print(listSlice[1:3]) #now begaining to last print(listSlice[:]) #a certain number to last print(listSlice[1:]) #change list or add list odd = [2, 4, 6, 8] #change the 1st item odd[0] =1 print(odd) odd[1:4] = [3,4,5] print(odd) #append list odd.append(7) print(odd) #len print(len(odd)) #extend odd.extend([9,10,11]) print(odd) #using + operator to extend odd = odd + [1,5,6] print(odd) #repeat number print(odd * 3) #insert odd.insert(1,10)
true
7be5d30cda7b2fea9dda47792dd011c530ebe639
riaz4519/python_practice
/problem_solving/_4_swap_case.py
305
4.15625
4
def swap_case(s): new_string = "" for lat in s: if lat.isupper() == True: new_string += (lat.lower()) else: new_string += (lat.upper()) return new_string if __name__ == '__main__': s = input().strip() result = swap_case(s) print(result)
false
51eb5831e885cff30bdefa175b7ba153222156ac
CupidOfDeath/Algorithms
/Bisection Search.py
402
4.15625
4
#Finding the square root of a number using bisection search x = int(input('Enter the number which you want to find the square root of: ')) epsilon = 0.01 n = 0 low = 1 high = x g = (low+high) / 2 while abs(g*g-x) >= epsilon: if (g*g) > x: high = g elif (g*g) < x: low = g g = (low+high) / 2 n += 1 print('The square root of', x, 'is', g) print('The number of computations it took is', n)
true
42a8dcd380e302595f43a72bea8eb5c0c0a1fff3
mightymax/uva-inleiding-programmeren
/module-1-numbers/sequence.alt.py
1,530
4.25
4
highestPrime = 10000 number = 1 #Keep track of current number testing for prime nonPrimes = [] while number < highestPrime: number = number + 1 if (number == 2 or number % 2 != 0): #test only uneven numbers and 2 #loop thru all integers using steps of 2, no need to test even numbers for x in range(3, number, 2): if (number % x) == 0: #Number {number} is not a prime nonPrimes.append(number) break else: nonPrimes.append(number) i = 0 tmpList = [] #temporary list used in for-loop to keep track of current sequence tempSeqCount = 1 longestSeq = [] #placeholder for final result longestSeqCount = 0 for nonPrime in nonPrimes: # compare current non-prime against previous non-prime # if previous == current - 1 then it is part of seq if i > 0 and nonPrime - 1 == nonPrimes[i-1]: tmpList.append(nonPrime) tempSeqCount += 1 #increase seq counter else: # seq has endend, move temp list to placeholder if it's size is bigger than previous placeholder's size if tempSeqCount > longestSeqCount: longestSeq = tmpList longestSeqCount = tempSeqCount #create new tmp-list for next seq test and reset counter tmpList = [nonPrime] tempSeqCount = 1 i += 1 print(f"The longest sequence non-primes under {highestPrime} starts at {longestSeq[0]} and ends at {longestSeq[longestSeqCount-1]}") print(f"The sequence is {longestSeqCount} long.")
true
0bca3a56b899c73b9f63201d6eb1cb0070976972
lasj00/Python_project
/OOP.py
1,965
4.1875
4
import math class Rectangle: # the init method is not mandatory def __init__(self, a, b): self.a = a self.b = b # self.set_parameters(10,20) def calc_surface(self): return self.a * self.b # Encapsulation class Rectangle2(): def __init__(self, a, b): self.__a = a self.__b = b # self.set_parameters(10,20) def calc_surface(self): return self.__a * self.__b r = Rectangle2(4, 6) r.__a = 10 # can't change the parameters - the field (__a) cannot be accessed - creates another filed inside the object r.a = 10 # a is created as a different value print(r.calc_surface()) # Special methods class Rectangle3: def __init__(self, a, b): self.a = a self.b = b def calc_surface(self): return self.a * self.b def __str__(self): return "Rect: {0} by {1}".format(self.a, self.b) def __add__(self, other): a = self.a + other.a b = self.b + other.b return Rectangle(a, b) def __lt__(self, other): self_area = self.calc_surface() other_area = other.calc_surface() return self_area < other_area r1 = Rectangle3(4, 6) r2 = Rectangle3(6, 8) r = r1 + r2 print(r) print(r2 < r1) # inheritance class Shape: def __init__(self, a=0, b=0): self._a = a self._b = b def get_a(self): return self._a def get_b(self): return self._b def __str__(self): return "{0}: [{1},{2}]".format(self.__class__.__name__, self._a, self._b) class RectangleIn(Shape): def calc_surface(self): return self._a * self._b class Circle(Shape): def calc_surface(self): return math.pi * self._a ** 2 # example of polymorphism def __str__(self): return "{0}: [{1}]".format(self.__class__.__name__, self._a) s = Shape(4, 5) r = RectangleIn(4, 5) print(r.calc_surface()) c = Circle(5) print(c.calc_surface())
true
36b585cb0372c121c7307bb04ecc3a1b220ad0a6
lasj00/Python_project
/abstract.py
917
4.59375
5
from abc import ABC import math # by inheriting from ABC, we create an abstract class class Shape(ABC): def __init__(self, a=0, b=0): self._a = a self._b = b def get_a(self): return self._a def get_b(self): return self._b def __str__(self): return "{0}: [{1},{2}]".format(self.__class__.__name__, self._a, self._b) # there is a need of at least one abstract method to make the class abstract @abstractmethod def calc_surface(self): pass class Rectangle(Shape): def calc_surface(self): return self._a * self._b class Circle(Shape): def calc_surface(self): return math.pi * self._a ** 2 # example of polymorphism def __str__(self): return "{0}: [{1}]".format(self.__class__.__name__, self._a) s = Shape(4, 5) r = Rectangle(4, 5) print(r.calc_surface()) c = Circle(5) print(c.calc_surface())
false
b451055efe0de3395b4c49beb4d67ee77694bece
KaylaBaum/astr-119-hw-1
/variables_and_loops.py
706
4.375
4
import numpy as np #we use numpy for many things def main(): i = 0 #integers can be declared with a number n = 10 #here is another integer x = 119.0 #floating point nums are declared with a "." #we can use numpy to declare arrays quickly y = np.zeros(n,dtype=float) #declares 10 zeros as floats using np #we can use for loops to iterate with a variable for i in range(n): #i in range [0,n-1] y[i] = 2.0 * float(i) + 1. #set y = 2i+1 as floats #we can also simply iterate through a variable for y_element in y: print(y_element) #execute the main function if __name__ == "__main__": main()
true
5fd79aec14f570b55d10153e52c7d67e751d5877
ch1huizong/study
/lang/py/cookbook/v2/19/merge_source.py
1,096
4.1875
4
import heapq def merge(*subsequences): # prepare a priority queue whose items are pairs of the form # (current-value, iterator), one each per (non-empty) subsequence heap = [] for subseq in subsequences: iterator = iter(subseq) for current_value in iterator: # subseq is not empty, therefore add this subseq's pair # (current-value, iterator) to the list heap.append((current_value, iterator)) break # make the priority queue into a heap heapq.heapify(heap) while heap: # get and yield lowest current value (and corresponding iterator) current_value, iterator = heap[0] yield current_value for current_value in iterator: # subseq is not finished, therefore add this subseq's pair # (current-value, iterator) back into the priority queue heapq.heapreplace(heap, (current_value, iterator)) break else: # subseq has been exhausted, therefore remove it from the queue heapq.heappop(heap) if __name__ == '__main__': r = merge([102,1,50,3,7],[11,2,5,6],[3,3,-2,-3]) print list(r)
true
c7c2681a6ca8de03dc17e2fc584bc5a85db1de04
Jasbeauty/Learning-with-Python
/assn0/test3.py
2,967
4.1875
4
# -*- coding=utf-8 -*- # 获取对象信息 class MyObject(object): def __init__(self): self.x = 9 def power(self): return self.x * self.x obj = MyObject() print('hasattr(obj, \'x\') =', hasattr(obj, 'x')) # 有属性'x'吗? print('hasattr(obj, \'y\') =', hasattr(obj, 'y')) # 有属性'y'吗? setattr(obj, 'y', 19) # 设置一个属性'y' print('hasattr(obj, \'y\') =', hasattr(obj, 'y')) # 有属性'y'吗? print('getattr(obj, \'y\') =', getattr(obj, 'y')) # 获取属性'y' print('obj.y =', obj.y) # 获取属性'y' print('getattr(obj, \'z\') =',getattr(obj, 'z', 404)) # 获取属性'z',如果不存在,返回默认值404 f = getattr(obj, 'power') # 获取属性'power' print(f) print(f()) # 继承和多态 class Animal(object): def run(self): print('Animal is running...') class Dog(Animal): def run(self): print('Dog is running...') class Cat(Animal): def run(self): print('Cat is running...') def run_twice(animal): animal.run() animal.run() a = Animal() d = Dog() c = Cat() print('a is Animal?', isinstance(a, Animal)) print('a is Dog?', isinstance(a, Dog)) print('a is Cat?', isinstance(a, Cat)) print('d is Animal?', isinstance(d, Animal)) print('d is Dog?', isinstance(d, Dog)) print('d is Cat?', isinstance(d, Cat)) run_twice(c) # 类 class Student(object): # 特殊方法“__init__”前后分别有两个下划线 # 注意到__init__方法的第一个参数永远是self,表示创建的实例本身,因此,在__init__方法内部,就可以把各种属性绑定到self,因为self就指向创建的实例本身 def __init__(self, name, score): self.name = name self.score = score def print_score(self): print('%s: %s' % (self.name, self.score)) def get_grade(self): if self.score >= 90: return 'A' elif self.score >= 60: return 'B' else: return 'C' bart = Student('Bart Simpson', 59) lisa = Student('Lisa Simpson', 87) print('bart.name =', bart.name) print('bart.score =', bart.score) bart.print_score() print('grade of Bart:', bart.get_grade()) print('grade of Lisa:', lisa.get_grade()) # 访问限制 class Student(object): def __init__(self, name, score): self.__name = name self.__score = score def get_name(self): return self.__name def get_score(self): return self.__score def set_score(self, score): if 0 <= score <= 100: self.__score = score else: raise ValueError('bad score') def get_grade(self): if self.__score >= 90: return 'A' elif self.__score >= 60: return 'B' else: return 'C' bart = Student('Bart Simpson', 59) print('bart.get_name() =', bart.get_name()) bart.set_score(60) print('bart.get_score() =', bart.get_score()) print('DO NOT use bart._Student__name:', bart._Student__name)
false
dec5ec698cc7d469dfbb97cebdc485e9603fc16e
luandeomartins/Script-s-Python
/ex028.py
810
4.28125
4
from math import radians,cos,sin,tan angulo = float(input('Digite um ângulo qualquer: ')) seno = sin(radians(angulo)) cosseno = cos(radians(angulo)) tangente = tan(radians(angulo)) print('O ângulo de {} tem o seno de {:.2f}.'.format(angulo, seno)) print('O ângulo de {} tem o cosseno de {:.2f}.'.format(angulo, cosseno)) print('O ângulo de {} tem a tangente de {:.2f}.'.format(angulo, tangente)) # Faça um programa que leia um ângulo qualquer e mostre na tela o valor do seno, cosseno e tangente desse ângulo. # Neste exemplo, eu fiz importando apenas os métodos que foi usar no meu programa. # Sendo assim, não necessita referenciar a biblioteca (cos(variável a ser aplicado o método)) # Como precisei transformar o número para radianos, escrevi cos(radians(variável a ser aplicado o método))
false
5afb03eae042cc84d9c770e3153fa07d12884906
shashikant231/100-Days-of-Code-
/Pascal Traingle.py
938
4.1875
4
'''Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: Example 1: Input: numRows = 5 Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] solution We are first creating an 2D array .our array after creation for rows = 5 will look like follows: [[0], [0, 0], [0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0, 0]] we will iterate through each rows and according to the position of "i" pointer ,we will put values. ''' #non recursive solution def generate(numRows): arr = [] for i in range(numRows): col = [] for j in range(i+1): col.append(0) arr.append(col) for line in range(0,numRows): for i in range(0,line+1): if i == 0 or i == line: arr[line][i] = 1 else: arr[line][i] = arr[line-1][i-1] + arr[line-1][i] return arr
true
6763a48aa0e4c976e75b68ae74f18394512b1e85
DrN3RD/PythonProgramming
/Chapter 3/c03e01.py
378
4.34375
4
#Volume calculator from math import * def main(): r = float(input("Enter the radius of the shpere to be calculated: ")) volume = (4/3)*pi*(r**3) area = 4*pi * r**2 print("The area of the Shpere is {0:0.1f} square meters ".format(area)) print("\n The Volume of the sphere is {0:0.1f} cubic meters".format(volume)) input("Enter to quit") main()
true
1ae36388c286daad1d37d101d9ca05db4bd7384a
mamatha20/ifelse_py
/IF ELSE_PY/if else4.py
276
4.34375
4
#write a program to check whethernit is alphabet digit or special character ch=input("enter any character=") if ch>="a" and ch<="z" or ch>="A" and ch<="Z": print("it is alphabet") elif ch>="0" and ch<="9": print("it is digit") else: print("it is special charcter")
true
75c9868ff8d055492da5bb749b20d5a919a440e8
mamatha20/ifelse_py
/IF ELSE_PY/if else25.py
658
4.125
4
day=input('enter any day') size=input('enter any size') if day=='sunday': if size=='large': print('piza with free brounick') elif size=='medium': print('piza with free garlick stick') else: print('free coca') elif day=='monday' or day=='tuesday': if size=='large': print('pizza with 10%discount') elif size=='medium': print('pizza with 20%discount') else: print('pizza without discount') elif day=='wednseday' or day=='Thursday': if size=='large'or size=='medium' or size =='small': print('pizza with garlic stick and coce free') elif day=='friday' or day=='saturday': if size=='large': print('pizza only') else: print('invalid day')
true
a566f238d1a9cc97699986160a108e3c9e88cbd5
yameenjavaid/bigdata2019
/01. Jump to python/Chap07/3_Python_Exercise/21.py
281
4.21875
4
import re # Write a Python program to find the substrings within a string. while True : original_setence = input("입력하세요 : ") if original_setence == "ㅈㄹ" : exit() m = re.findall("exercises", original_setence) for i in m : print(i)
true
9d6ea6b45c26fccabafd08a13e39d54ce906f918
yameenjavaid/bigdata2019
/01. Jump to python/Chap07/3_Python_Exercise/18.py
342
4.40625
4
import re # Write a Python program to search the numbers (0-9) of length between 1 to 3 in a given string. p = re.compile(r"([0-9]{1,3})") while True : original_setence = input("입력하세요 : ") if original_setence == "ㅈㄹ" : exit() m = p.finditer(original_setence) for i in m : print(i.group(0))
true
29e8979d532b3060ed5a15ab0fd7971108987ce5
SKO7OPENDRA/python_start
/Урок 2. Переменные, ветвления/hw_02_01.py
830
4.15625
4
def lesson2(): print("Great Python Program!") print("Привет, программист!") name = input("Ваше имя: ") print(name, ", добро пожаловать в мир Python!") answer = input("Давайте поработаем? (Y/N)") # PEP-8 рекомендует делать отступ, равный 4 пробелам if answer == 'y' or answer == 'Y': print("Вам премия!") # <- здесь будет код домашнего задания else: # Оператор == (двойное равно) - это логический оператор сравнения print("До встречи!") lesson2() while True: flag = input('Ещё раз? [Y/N]: ') if flag == 'y' or flag == 'Y': lesson2() else: break
false
8822adfd5f0a1d8732e8fa92f0834af2de2764e2
shaheenery/udacity_ds_and_a_project2
/problem_5.py
2,548
4.375
4
# Blockchain # A Blockchain is a sequential chain of records, similar to a linked list. Each # block contains some information and how it is connected related to the other # blocks in the chain. Each block contains a cryptographic hash of the previous # block, a timestamp, and transaction data. For our blockchain we will be using # a SHA-256 hash, the Greenwich Mean Time when the block was created, and text # strings as the data. # Use your knowledge of linked lists and hashing to create a blockchain # implementation. import time import hashlib # We do this for the information we want to store in the block chain such as # transaction time, data, and information like the previous chain. class Block: def __init__(self, timestamp, data, previous): self.timestamp = timestamp self.data = data self.previous_hash = previous.hash self.previous = previous self.hash = self.calc_hash() def calc_hash(self): sha = hashlib.sha256() hash_str = "" hash_str += self.data hash_str += str(self.timestamp) hash_str += self.previous_hash hash_str = hash_str.encode('utf-8') sha.update(hash_str) return sha.hexdigest() def __repr__(self): return f"{str(int(self.timestamp * 100) / 100)}\t{self.hash}\t{self.previous_hash}\t{self.data}" class DummyBlock(Block): def __init__(self): self.timestamp = time.time() self.data = "I am Groot" self.previous_hash = "DummyHashDummyHashDummyHashDummyHashDummyHashDummyHashDummyHashD" self.previous = None self.hash = self.calc_hash() class BlockChain(object): def __init__(self): self.tail = DummyBlock() self.size = 0 def append(self, data): old = self.tail new = Block(time.time(), data, old) self.tail = new self.size += 1 def __repr__(self): if self.size == 0: return "Block Chain Empty" str = "" block = self.tail.previous while block: str += block.__repr__() + "\n" block = block.previous return str # Test 1 - Empty Blockchain chain = BlockChain() print(chain) # Block Chain Empty print (chain.size) # 0 print (chain.tail.data) # I am Groot # Test 2 - 4 Blocks in chain chain.append("Rocket") chain.append("Star Lord") chain.append("Gemorrah") chain.append("Drax") print (chain) # Drax # Test 3 - 10k blocks for _ in range(10_000): chain.append("something else!") print(chain)
true
efce9bd907d2493ea03807cd09ef298ac5facf58
zoecahill1/pands-problem-set
/collatz.py
1,060
4.34375
4
# Zoe Cahill - Question 4 Solution # Imports a function from PCInput which was created to handle user input from PCInput import getPosInt def collatz1(): # Calls the function imported above # This function will check that the number entered is a positive integer only num = getPosInt("Please enter a positive number: ") # Check will run until number gets to 1 while num!=1: # Prints the current value of num. Have to cast int type as anything divided becomes a float type. print(int((num))) # Checking to see if number is even (there will be no remainder if it is) if num%2 == 0: # If this check returns true then program will divide num by 2 num=num/2 # Otherwise then number is not even so it must be odd else: # When number is odd we multiply by 3 and add 1 num = (num*3)+1 # Returns control to beginning of loop to check next number continue # Prints out last number which will be 1 print (int((num))) collatz1()
true
f9dfbf8b29d1a1673076aa512e2d89653af38b6a
codeshef/SummerInternship
/Day5/classesPython.py
483
4.125
4
# <------- Day 8 work -------> # classes in python class User: def __init__(self): print("Hello!! I am constructor of class user") def setUserName(self, fn, ln): print("I am inside setUserNameFunc") self.firstName = fn self.lastName = ln def printData(self): print(self.firstName+" "+self.lastName) ## Creating objects objUser = User() ## Calling class functions objUser.setUserName("abc", "xyz") objUser.printData()
true
bc502be94ca45d1750cce48ca3c39f0eb9dd389c
dergaj79/python-learning-campus
/unit5_function/test.py
959
4.125
4
# animal = "rabbit" # # def water(): # animal = "goldfish" # print(animal) # # water() # print(animal) # a = 0 # # # def my_function() : # a = 3 # print(a) # # # my_function() # print(a) # a=1 # def foo1(): # print(a) # foo1() # print(a) # def amount_of_oranges(small_cups=20, large_cups=10): # oranges_result=small_cups+large_cups*3 # kg_result=oranges_result/5 # print("Today you'll need",oranges_result,"oranges.") # print("Buy",kg_result,"kg of oranges.") # return oranges_result,kg_result # # results=amount_of_oranges(15,5) # print(type(results)) # print(results) def main(): # City forcast generator program city_name = get_city_from_user() valid_city = is_city_valid(city_name) if not valid_city: print("Error! Wrong City!") return None temperature = get_current_weather(city_name) # Show forecast for the user show_weather(temperature, city_name) if __name__ == "__main__": main()
true
9f8220cbed18b0e05822ae99a652b649c682b08f
sandeeppal1991/D08
/mimsmind0.py
2,527
4.5625
5
"""In this version, the program generates a random number with number of digits equal to length. If the command line argument length is not provided, the default value is 1. Then, the program prompts the user to type in a guess, informing the user of the number of digits expected. The program will then read the user input, and provide basic feedback to the user. If the guess is correct, the program will print a congratulatory message with the number of guesses made and terminate the game. Otherwise, the program will print a message asking the user to guess a higher or lower number, and prompt the user to type in the next guess.""" ############################################################################### #import section from random import randint import sys ############################################################################### #Body #function to generate a random n digit number where n is entered by the user or 1 def generate_random_number(no_of_digits): return randint(10**(no_of_digits-1),(10**no_of_digits)-1) def the_game(random_number,no_of_digits): print("Let's play the mimsmind0 game.") #starting of the game user_input = input("Guess a {} digit number : ".format(no_of_digits)) no_of_tries = 0 while True: try: user_input = int(user_input) except: #exception raised if user input is not an integer user_input = input("Invalid Input. Try again : ") continue no_of_tries += 1 #case when the guessed number is the same as the guessed number if(user_input == random_number): print("Congratulations ! You guessed the number in {} tries".format(no_of_tries)) break #case when the number guessed is lower than the random number elif(user_input < random_number): user_input = input("Try Again ! Guess a higher number : ") #case when the number guessex is higher than the random number elif(user_input > random_number): user_input = input("Try Again ! Guess a lower number : ") ############################################################################### #main def main(): no_of_digits = 1 try: if(int(sys.argv[1]) > 0): no_of_digits = int(sys.argv[1]) except: print("The no of digits you entered isnt a valid input. We will proceed with 1 digit for now") the_game(generate_random_number(no_of_digits),no_of_digits) if __name__ == "__main__": main()
true
3adcd38f83d45e722077960cf50aaf3c435572ea
kncalderong/codeBackUp
/python/Rosalind_programming/stronghold/dna_as_rna.py
305
4.3125
4
dna=input('please enter your DNA sequence: ') rna=list() #!string to print a list as a string after.. string="" for nt in dna: if nt == 'T': rna.append('U') else: rna.append(nt) print('dna:',dna) #!with .join() I can print a list as a string: print('rna:', string.join(rna))
false
46888f48af85aa51067e50b537e670510dad01c8
asuddenwhim/DM
/own_text.py
776
4.125
4
from nltk import word_tokenize, sent_tokenize text = "Generally, data mining (sometimes called data or knowledge discovery) is the process of analyzing data from different perspectives and summarizing it into useful information - information that can be used to increase revenue, cuts costs, or both. Data mining software is one of a number of analytical tools for analyzing data. It allows users to analyze data from many different dimensions or angles, categorize it, and summarize the relationships identified. Technically, data mining is the process of finding correlations or patterns among dozens of fields in large relational databases. " sents = sent_tokenize(text) tokens = word_tokenize(text) textObj = Text(tokens) print len(sents) print len(tokens) print textObj
true
1e7db90033a0f66814ddd3eada5fbaf26424755d
rashedrahat/wee-py-proj
/hangman.py
1,407
4.25
4
# a program about guessing the correct word. import random i = random.randint(0, 10) list = [["H*ng*a*", "Hangman"], ["B*n**a", "Banana"], ["*wk*ar*", "Awkward"], ["B*n**", "Banjo"], ["Ba*pi*e*", "Bagpipes"], ["H*p**n", "Hyphen"], ["J*k*b*x", "Jukebox"], ["O*y**n", "Oxygen"], ["Num*sk*l*", "Numbskull"], ["P*j*m*", "Pajama"], ["Rh*t*m*c", "Rhythmic"]] print("Welcome to HANGMAN game :)") print("Guess the below word..") print(list[i][0]) print("You have only one attempt to guess!") while True: left = input("Enter the left hidden letter: ") mid = input("Enter the mid hidden letter: ") right = input("Enter the right hidden letter: ") if len(left) == 0 or len(mid) == 0 or len(right) == 0: print("Empty field(s) not allowed! Please type a letter.") continue elif len(left) > 1 or len(mid) > 1 or len(right) > 1: print("More than one letter(s) not allowed! Please type only a letter.") continue else: letters = [left, mid, right] pos = 0 word = list[i][0] guess_word = "" for l in word: if l == "*": guess_word = guess_word + letters[pos] pos += 1 else: guess_word = guess_word + l guess_word = guess_word.capitalize() if guess_word == list[i][1]: print("Hurrah! You guessed the correct word '", guess_word, "'") break else: print("Sorry! Better luck next time.", "The word is:", list[i][1]) break
true
6a2aad8c018ac579ba11c1ac1d7405e03950bf16
jslee6091/python_basic
/exercise/age_student.py
348
4.21875
4
# age = now year - born year +1 from datetime import datetime as dt current = dt.today().year print(current) my_year = int(input()) print(type(my_year)) age = current - my_year + 1 if 17 <= age < 20: print('you are high school student!') elif 20 <= age <= 27: print('you are university student!') else: print('you are not student!')
false
ae8899b2735de9b712b11e1e20f95afcd5008be2
erikac613/PythonCrashCourse
/11-1.py
483
4.15625
4
from city_functions import city_country print("Enter 'q' at any time to quit.") while True: city = raw_input("\nPlease enter the name of a city: ") if city == 'q': break country = raw_input("Please enter the name of the country where that city is located: ") if country == 'q': break formatted_city_and_country = city_country(city, country, population='') print("\tNeatly formatted location: " + formatted_city_and_country + ".")
true
3e8767209a85af8982664909ec45c948c95eafb3
alridwanluthfi00/Labpy
/Lab 4/Syntax/Latihan 1.py
738
4.125
4
# list bebas a = [2, 4, 6, 8, 10] # akses list print(a[2]) # tampilkan elemen ke - 3 print(a[1:4]) # ambil nilai elemen ke - 2 sampai ke - 4 print(a[4]) # ambil elemen terakhir print('==================================================') # ubah elemen list a[3] = 12 # ubah elemen ke 4 nilai lainnya print(a) a[3:5] = [11, 13] # ubah elemen ke 4 sampai dengan elemen terakhir print(a) print('==================================================') # tambah elemen list b = a [0:2] # ambil 2 bagian dari list pertama (A) dan jadikan list kedua (B) print(b) b.append('hai') # tambah list B dengan nilai string print(b) b.extend([16, 18, 20]) # tambah list B dengan 3 nilai print(b) x = a + b # gabungkan list B dengan list A print(x)
false
6db90e6de92dc5a3ca12f22a6e94577abd42a6c1
gungorefecetin/CS-BRIDGE-2020
/Day3PM - Lecture 3.1/khansole_academy.py
1,021
4.375
4
""" File: khansole_academy.py ------------------- This program generates random addition problems for the user to solve, and gives them feedback on whether their answer is right or wrong. It keeps giving them practice problems until they answer correctly 3 times in a row. """ # This is needed to generate random numbers import random def main(): # Your code here # Delete the `pass` line before starting to write your own code counter = 0 while True: num1, num2 = random.randint(10, 99), random.randint(10, 99) answer = int(input('What is ' + str(num1) + ' + ' + str(num2) + '? ')) if answer == num1 + num2: counter += 1 print("Correct! You've gotten " + str(counter) + " correct in a row.") else: print('Incorrect. The expected answer is ' + str(num1 + num2)) counter = 0 if counter == 3: print('Congratulations! You mastered addition.') break if __name__ == "__main__": main()
true
52963e18085b20a2f20020a0093b01ea26e34e0c
LucianoAlbanes/AyEDI
/TP1/Parte1/1/restrictions.py
250
4.125
4
## The purpose of the following code is to have certain functions ## that python provides, but they are restricted in the course. # Absolute Value (Aka 'abs()') def abs(number): if number < 0: return number*-1 else: return number
true
6735f531a626eb2dd8999e26136e950299a978d4
LucianoAlbanes/AyEDI
/TP6/1/fibonacci.py
1,058
4.25
4
# Calc the n-th number of the Fibonacci sequence def fibonacci(n): ''' Explanation: This function calcs and return the number at a given position of the fibonacci sequence. Params: n: The position of the number on the fibonacci sequence. Return: The number at the given position of the fibonacci sequence. Returns 'None' if the given position is negative or non a integer. ''' # Base cases if (n == 0) or (n == 1): return n # Case if negative or non integer if (n < 0) or (n % 1): return None # General case return fibonacci(n-1) + fibonacci(n-2) # Basic interface from algo1 import input_real result = None while result == None: result = fibonacci(input_real( 'Ingrese la posición del número a obtener en la secuencia de fibonacci: ')) if result == None: print('El número ingresado no es válido. (Debe ser un número entero positivo).') print( f'El número de fibonacci que corresponde a la posición dada es: {int(result)}')
true
c828a8ab988f60b7a7c73a79ca678e5d7264415e
navbharti/java
/python-cookbook/other/ex7.py
2,366
4.1875
4
''' Created on Sep 19, 2014 @author: rajni ''' months = ('January','February','March','April','May','June',\ 'July','August','September','October','November',' December') print months cats = ['Tom', 'Snappy', 'Kitty', 'Jessie', 'Chester'] print cats #fetching items from tupble and list print cats[2] print months[2] #appending items in list cats.append('Catherine') print cats #Remove your 2nd cat, Snappy. Woe is you. del cats[1] print cats #Make the phone book: #this nothing but dictionary phonebook = {'Andrew Parson':8806336, \ 'Emily Everett':6784346, 'Peter Power':7658344, \ 'Lewis Lame':1122345} print phonebook print phonebook['Emily Everett'] #Add the person 'Gingerbread Man' to the phonebook: phonebook['Gingerbread Man'] = 1234567 # Didn't think I would give you # my real number now, would I? print phonebook # deleting item in the dictionary del phonebook['Andrew Parson'] print phonebook #A few examples of a dictionary #First we define the dictionary #it will have nothing in it this time ages = {} #Add a couple of names to the dictionary ages['Sue'] = 23 ages['Peter'] = 19 ages['Andrew'] = 78 ages['Karren'] = 45 #Use the function has_key() - #This function takes this form: #function_name.has_key(key-name) #It returns TRUE #if the dictionary has key-name in it #but returns FALSE if it doesn't. #Remember - this is how 'if' statements work - #they run if something is true #and they don't when something is false. if ages.has_key('Sue'): print "Sue is in the dictionary. She is", \ ages['Sue'], "years old" else: print "Sue is not in the dictionary" #Use the function keys() - #This function returns a list #of all the names of the keys. #E.g. print "The following people are in the dictionary:" print ages.keys() #You could use this function to #put all the key names in a list: keys = ages.keys() #You can also get a list #of all the values in a dictionary. #You use the values() function: print "People are aged the following:", \ ages.values() #Put it in a list: values = ages.values() #You can sort lists, with the sort() function #It will sort all values in a list #alphabetically, numerically, etc... #You can't sort dictionaries - #they are in no particular order print keys keys.sort() print keys print values values.sort() print values #You can find the number of entries #with the len() function: print "The dictionary has", \ len(ages), "entries in it"
true
7357beca1c38efca4e040d1ade5fc2275e658942
nemeth-bence/exam-trial-basics
/pirates/pirates.py
775
4.25
4
pirates = [ {'Name': 'Olaf', 'has_wooden_leg': False, 'gold': 12}, {'Name': 'Uwe', 'has_wooden_leg': True, 'gold': 9}, {'Name': 'Jack', 'has_wooden_leg': True, 'gold': 16}, {'Name': 'Morgan', 'has_wooden_leg': False, 'gold': 17}, {'Name': 'Hook', 'has_wooden_leg': True, 'gold': 20}, ] # Write a function that takes any list that contains pirates as in the example, # And returns a list of names containing the pirates that # - have wooden leg and # - have more than 15 gold def gold_filter(list): for i in range(0, len(list)): if list[i]['gold'] > 15: print(list[i]['Name'] + " have more than 15 gold") if list[i]['has_wooden_leg'] is True: print(list[i]['Name'] + " have wooden leg") gold_filter(pirates)
false
fc7dd582f1d3fcff14bd071ddf53081faa20488a
mrmezan06/Python-Learning
/Real World Project-2.py
364
4.25
4
# Design a program to find avarage of three subject marks x1 = int(input("Enter subject-1 marks:")) x2 = int(input("Enter subject-2 marks:")) x3 = int(input("Enter subject-3 marks:")) sum = x1 + x2 + x3 avg = sum / 3 print("The average marks:", int(avg)) print("The average marks:", avg) # Formatting the float value print("The average marks:", format(avg, '.2f'))
true
c765b56d4d457bd428b05d59a0c882ccf7325910
kkkansal/FSDP_2019
/DAY 02/pangram.py
956
4.21875
4
""" Code Challenge Name: Pangram Filename: pangram.py Problem Statement: Write a Python function to check whether a string is PANGRAM or not Take input from User and give the output as PANGRAM or NOT PANGRAM. Hint: Pangrams are words or sentences containing every letter of the alphabet at least once. For example: "The quick brown fox jumps over the lazy dog" is a PANGRAM. Input: The five boxing wizards jumps. Output: NOT PANGRAM """ # To check if a string is pangram or not input_string = input("Enter the string :") count = 0 _list = [] _lower = input_string.lower() for alpha in _lower: _list.append(alpha) # remove duplicates final_list = [] for num in _list: if num not in final_list: final_list.append(num) for elements in final_list: if elements in 'abcdefghijklmnopqrstuvwxyz': count += 1 if count == 26: print ("Pangram") else: print ("Not Pangram")
true
5528f3822a981c88f14222da69060e68581dd6dd
matheusCalaca/estudos-python-alura
/str_metodos/forca.py
1,494
4.25
4
# para definir uma funcao no python voce usa a palavra "def" segue o examplo encapsulando o jogo em uma função para ser # chamado em outro arquivo def jogar(): print("********************************") print("***Bem vindo ao jogo de Forca***") print("********************************") #variaveis palavra_secreta = "banana" # definindo uma variavel para ver se a forca acabou # essa variavel e booleana pode ser "True" ou "False" enforcou = False acertou = False # para negar se usa a palavra "not" e para a condiciona usa se a palavra "and" while(not enforcou and not acertou): chute = input("Qual letra? ") # remove os espaços da string "strip()" chute = chute.strip() index = 0 # for pela iterando por cada letra da palavra for letra in palavra_secreta: # verifica se a letra digitada tem no chute # usa o metodo upper para colocar tudo maiuscolo para fazer a comparação metodo "str.upper()" if (chute.upper() == letra.upper()): print(f"Encontrei a letra {letra} na posição {index + 1}") index = index + 1 print("fim de jogo") # esse codigop so vai executar quando o este arquivo for executado como arquivo principal # ou seja não sera executado caso ele estaja como um importe , # sendo assim quando cahmarmos somente este arquivo o jogo ira iniciar, agora se ele # tiver sido importado o jogo so inicia se agente chamar explicitamente o metodo jogar if(__name__ == "__main__"): jogar()
false
0e58b02c59fe57bf55e8c1c61a0442f35146876f
dev-di/python
/helloworld.py
323
4.1875
4
#name = input("What is your name my friend? ") name = "Diana" message = "Hello my friend, " + name + "!" print(message) #comment print(message.upper()) print(message.capitalize()) print(message.count("i")) print(f"message = '{message}', name = '{name}'") print("Hello {}!!".format(name)) print("Hello {0}!".format(name))
true
6cf6799c4f652c47a3cb818ab1910b4c8d3d6d1c
JustinTrombley96/Python-Coding-Challenges
/drunk_python.py
730
4.1875
4
''' Drunken Python Python got drunk and the built-in functions str() and int() are acting odd: str(4) ➞ 4 str("4") ➞ 4 int("4") ➞ "4" int(4) ➞ "4" You need to create two functions to substitute str() and int(). A function called int_to_str() that converts integers into strings and a function called str_to_int() that converts strings into integers. Examples: int_to_str(4) ➞ "4" str_to_int("4") ➞ 4 int_to_str(29348) ➞ "29348" Notes This is meant to illustrate the dangers of using already-existing function names. Extra points if you can de-drunk Python. ''' str, int = int, str def int_to_str(n): return str(n) def str_to_int(s): return int(s) print(int_to_str(25)) print(int_to_str('25'))
true
89b69d5b3a2e700b7f49bd7537ed6a56f1eaaef5
anvandev/TMS_HW
/HW/task_1_5/task_5_7.py
948
4.34375
4
""" Закрепить знания по работе с циклами и условиями. Дана целочисленная квадратная матрица. Найти в каждой строке наи- больший элемент и поменять его местами с элементом главной диагонали. """ from random import randint # function to print matrix in a convenient form def print_matrix(matrix): for element in matrix: print(element) # create and print random matrix n = 4 random_matrix = [[randint(1, 9) for j in range(n)] for k in range(n)] print_matrix(random_matrix) # find max element and swap elements for i, line in enumerate(random_matrix): index_max_num = line.index(max(line)) if line[i] != line[index_max_num]: line[i], line[index_max_num] = line[index_max_num], line[i] print('Matrix with diagonal swapped elements:') print_matrix(random_matrix)
false
106c85e88fcc4fbb246c8270d652cedc9de10446
SreeNru/ReDiProject
/main.py
580
4.125
4
from datetime import * import pytz print(">>Welcome to Python program to get Current Time") print(">>Please select your desired country") list=["Europe/Berlin","Asia/Kolkata","America/Los_Angeles", "America/New_York","Europe/London","Hongkong","Europe/Minsk","Australia/Sydney"] serial = 1 for item in list: print(serial , " : " , item) serial = serial + 1 selection = int(input("Please enter country ID : ")) tz_Germany = pytz.timezone(list[selection-1]) datetime_Germany = datetime.now(tz_Germany) print(list[selection-1] , " time:", datetime_Germany.strftime("%H:%M:%S"))
false
94db4a5c592136be5afeccac3323c5c598e41900
STProgrammer/PythonExercises
/Rock Paper Scissor.py
1,571
4.125
4
import random print("Welcome to \"Rock Paper Scissor\" game") print("""Type in "rock", "paper", or "scissor" and see who wins. first one that win 10 times win the game.""") HandsList = ["rock", "paper", "scissor"] while True: x = int() #Your score y = int() #Computer's score while x < 10 and y < 10: hand1 = input("Type in your choice:" ) hand2 = random.choice(HandsList) print(hand1, " - ",hand2) if hand1 == hand2: print("It's a tie!") elif hand1 == "rock": if hand2 == "scissor": print("Rocks beats scissor. You score!") x += 1 else: print("Paper beats rock, computer scores!") y += 1 elif hand1 == "paper": if hand2 == "rock": print("Paper beats rock, you score!") x += 1 else: print("Scissor beats paper, computer scores!") y += 1 elif hand1 == "scissor": if hand2 == "paper": print("Scissor beats paper, you score!") x += 1 else: print("Rock beats scissor, computer scores!") y += 1 else: print("""Invalid input. Plese type in: "rock", "paper" or "scissor".""") continue print("You: ", x, " - ", y, " computer") if x == 10: print("You win the game!") if y == 10: print("you lose the game!") print("Let's play again")
true
8f7e92a384cf95b4b45ee3eb41d0edf8afdb38ff
Esther-Guo/python_crash_course_code
/chapter4-working with lists/4.10-slices.py
265
4.40625
4
odd = list(range(1,21,2)) for number in odd: print(number) print('The first three items in the list are: ') print(odd[:3]) print('Three items from the middle of the list are: ') print(odd[4:7]) print('The last three items in the list are: ') print(odd[-3:])
true
0777824a168e8bc5eabcb35a58e2c6aa62e122d2
Esther-Guo/python_crash_course_code
/chapter8-functions/8.8-user_albums.py
651
4.21875
4
def make_album(name, title, tracks=0): """builds a dictionary describing a music album""" album_dict = { 'artist name': f'{name.title()}', 'album title': f'{title.title()}' } if tracks: album_dict['tracks'] = tracks return album_dict name_prompt = 'Please input the name of the artist:("q" to exit) ' title_prompt = 'Please input the title of the album:("q" to exit) ' while True: name = input(name_prompt) if name == 'q': break title = input(title_prompt) if title == 'q': break album = make_album(name, title) print(album) print('Thanks for your respond.')
true
5e29635e085e9f0199f8e7e6b7e97e47fae30fcd
hefeholuwah/wejapa_internship
/Hefeholuwahwave4 lab/Scripting labs/match_flower_name.py
1,388
4.34375
4
#For the following practice question you will need to write code in Python in the workspace below. This will allow you to practice the concepts discussed in the Scripting lesson, such as reading and writing files. You will see some older concepts too, but again, we have them there to review and reinforce your understanding of those concepts. #Question: Create a function that opens the flowers.txt, reads every line in it, and saves it as a dictionary. The main (separate) function should take user input (user's first name and last name) and parse the user input to identify the first letter of the first name. It should then use it to print the flower name with the same first letter (from dictionary created in the first function). #Sample Output: #>>> Enter your First [space] Last name only: Bill Newman #>>> Unique flower name with the first letter: Bellflower # Write your code here # HINT: create a dictionary from flowers.txt # HINT: create a function def user(): dictionary = {} with open('flowers.txt') as file: for names in file: (key,value) = names.split(": ") dictionary[key.upper()] = value return dictionary def my_main(): dictionary = user() user_input = input("Enter your first [space] last name only:") print("unique flower name with first letter : {}".format(dictionary.get(user_input[0]))) my_main()
true
100d133d879ff910586c3f5c49ec068ee3c01fb8
huioo/byte_of_python
/main/str_format.py
1,189
4.34375
4
# format 方法 # 有时候我们想要从其他信息中构造字符串。这就是 format() 方法可以发挥作用的地方。 age = 20 name = 'Swaroop' # {0}对应name,format方法的第一个参数 # {1}对应age,format方法的第二个参数 # 使用字符串连接实现相同的效果,name + ' is ' + str(age) + ' years old' template = '{0} was {1} years old when he wrote this book.' print(template.format(name, age)) template = 'Why is {0} playing with that python?' print(template.format(name)) # 数字可选,可填可不填,如下: print('{} was {} years old when he wrote this book'.format(name, age)) print('Why is {} playing with that python?'.format(name)) # python在 format() 方法中的作用就是将每一个参数值替换为规范的位置,可以有更详细的规范。 # 取十进制小数点后的精度为3,得到的浮点数为0.333 print('{0:.3f}'.format(1/3)) # 填充下划线(_),文本居中 # 将 '__hello__' 的宽度扩充为 11 print('{0:_^11}'.format('hello')) # 用基于关键字的方法打印显示 ‘Swaroop wrote A Byte of Python’ print('{name} wrote {book}'.format( name='Swaroop', book='A Byte of Python') )
false
73c3bcce9c5509b858bb2d149ded24f592b78207
xuyichen2010/Leetcode_in_Python
/general_templates/tree_bfs.py
1,170
4.1875
4
# https://www.geeksforgeeks.org/level-order-tree-traversal/ # Method 1 (Use function to print a given level) # O(n^2) time the worst case # Because it takes O(n) for printGivenLevel when there's a skewed tree # O(w) space where w is maximum width # Max binary tree width is 2^h. Worst case when perfect binary tree # Worst cas value 2^h is ceil(n/2) # When tree is balanced BFS takes more space from collections import deque class Node : def __init__(self, v): self.val = v self.left = None self.right = None def printLevelOrder(self, root): h = self.height(root) for i in range (1, h+1): self.printGivenLevel(root, i) def height(self, node): if node is None: return 0 else: lheight = self.height(node.left) rheight = self.height(node.right) return max(lheight, rheight) + 1 def printGivenLevel(self, node, level): if node is None: return if level == 1: print(node.val) else: self.printGivenLevel(node.left, level-1) self.printGivenLevel(node.right, level-1)
true
c03486f525084d5fd5f06c48f371db8cbdfa9666
phganh/CSC110---SCC
/Labs/Lab 3/coffeeShop.py
984
4.15625
4
# Project: Lab 03 (TrinhAnhLab03Sec03.py) # Name: Anh Trinh # Date: 01/20/2016 # Description: Calculate the cost of a coffee # shop's products def coffeeShop(): #Greeting print("Welcome to the Konditorei Coffee Shop!\n") #User's Input fltPound = float(input("Enter the amount of coffee (in pounds): ")) print() #Set Variables Value fltPrice = 10.50 * fltPound #$10.50 per pound fltShippingFee = 0.86 * fltPound #$0.86 per pound fltOverhead = 1.50 #fixed cost fltTotal = fltPrice + fltOverhead + fltShippingFee #Display The Result - round up to 2nd decimal place print("Amount : " , fltPound , "lb(s)") print("Price : $" , round(fltPrice,2) ) print("Shipping fee: $" , round(fltShippingFee,2) ) print("Overhead fee: $" , fltOverhead) print("--------------------------") print("Total: $" , round(fltTotal,2) ) coffeeShop()
true
02cf5510fb1edd89a53edb3c85b72f41307934b4
phganh/CSC110---SCC
/Statements for String.py
750
4.21875
4
## ------ STATEMENTS FOR STRING ------ ## def main(): print("Numeric Value of A Character") print("'a':",ord("a"),"\n'b':",ord("b")) print("\nString Value of A Number") print("'97':",chr(97),"\n'98':",chr(98)) print("\nNumeric Length of A String") string = "How are you" print("'",string,"' (w/ space) :",len(string),"letters") print("'",string,"' (w/o space):",len(string.split()),"letters") count = 0 for i in string: count += len(i.split()) print("'",string,"' (w/o space):",count,"words") print("\nSeperate a String (seperating words w/o spaces)") string = "Baba Black Sheep" print("Baba Black Sheep:",string.split()) main()
false
60357647015686ebbb09aee4122feb1fec8a8511
huahuijay/learn-python-with-L
/dict_set.py
1,446
4.15625
4
# -*- coding: utf-8 -*- # dict: 字典 ,使用key——value存储 d = {'Michael': 95, 'Bob': 75, 'Tracy': 85} print d['Michael'] d['Adam'] = 67 print d['Adam'] #一个key只能对应一个value,多次对一个key放入多个value,前面的值会被冲掉 #如果key不存在,dict会报错 #为避免key不存在的错误,两种办法: #1 'Thomas' in d #2 d.get('Thomas') d.get('Thomas', -1) #其中-1为key不存在时自己指定的返回的value,不指定的话为None #删除key d.pop('Bob') d # key 应为不可变对象,list可变,不能作为key #哈希算法: 通过key 计算位置的算法 #set : 也是一组key的集合,但是不储存value,key不能重复, #重复元素在set中会被过滤 s = set([1, 2, 3]) print s s.add(4) print s s.remove(4) print s s1 = set([1, 2, 3]) s2 = set([2, 3, 4]) #交集 s1 & s2 #并集 s1 | s2 s = set([1, [2, 3]]) #set只能放入不可变对象,将list放入set会报错 #TypeError: unhashable type: 'list' #关于不可变对象的探讨 # str 是不变对象, list是可变对象 a = ['c', 'b', 'a'] a.sort() a #['a', 'b', 'c'] a = 'abc' a.replace('a', 'A') #'Abc' a #'abc' #解释!replace是创建了一个新的字符串并返回。 # a是变量, 'abc'才是字符串 dict1 = {(1,2,3): 1, (2,3,4): 2} set1 = set([(1, 2, 3), 2, 3]) # 可以实现 dict2 = {(1,[2,3]), 2, 3} set2 = set([(1, [2, 3]), 2, 3]) #TypeError: unhashable type: 'list'
false
4a0989e726ccdea9ec4b69028dd3f5b1c5e54312
ccchao/2018Spring
/Software Engineering/hw1/good.py
858
4.34375
4
""" 1. pick a list of 100 random integers in the range -500 to 500 2. find the largest and smallest values in the list 3. find the second-largest and second-smallest values in the list 4. calculate the median value of the elements in the list """ import random #Generate a list containing 100 randomly generated integers ranged between -500 and 500 intList = [] for i in range(100): intList.append(random.randint(-500,500)) #Sort the list to find the largest two, the smallest two, and the median values intList.sort() #Show the result print("The largest value in the list:", intList[0]) print("The smallest value in the list:", intList[-1]) print("The second-largest value in the list:", intList[1]) print("The second-smallest value in the list:", intList[-2]) print("the median value of the elements in the list:", (intList[49]+intList[50])/2)
true
1a5decdca960e40d6c0bd1939d4461176a7fee70
parastooveisi/CtCI-6th-Edition-Python
/Linked Lists/palindrome.py
1,202
4.1875
4
# Implement a function to check if a linked list is a palindrome class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def printList(self): curr = self.head while curr: print(curr.data) curr = curr.next def append(self, data): newNode = Node(data) if not self.head: self.head = newNode return lastNode = self.head while lastNode.next: lastNode = lastNode.next lastNode.next = newNode def palindrome(self): hashMap = {} curr = self.head while curr: if curr.data in hashMap: hashMap[curr.data] += 1 else: hashMap[curr.data] = 1 curr = curr.next countOdds = 0 for value in hashMap.values(): if value % 2 != 0: countOdds += 1 return countOdds <= 1 llist = LinkedList() llist.append("R") llist.append("A") llist.append("D") llist.append("A") llist.append("R") llist.append("R") print(llist.palindrome()) # False
true
dcc6441b4f35dbf2962552d305fd7212c561ae3b
Brody-Liston/Pracs-by-Brody-Liston
/Prac 5/Colours.py
783
4.28125
4
hex_colour = {"f0f8ff": "AliceBlue", "f5f5dc": "Beige", "000000": "Black", "ffebcd": "BlanchedAlmond", "8a2be2": "BlueViolet", "5f9ea0": "CadetBlue", "d2691e": "Chocolate", "ff7f50": "Coral", "6495ed": "CornflowerBlue", "b8860b": "DarkGoldenrod"} def main(): hexadecimal = input("Enter hexadecimal: ").lower() while hexadecimal != "": if hexadecimal in hex_colour: print(hexadecimal, "is", hex_colour[hexadecimal]) else: print("Invalid hexadecimal") hexadecimal = input("Enter hexadecimal: ").lower() def all_colour(hexadecimal): # loop prints all colour, im just not sure where to put it into the code. for i in hex_colour: print(i, "is", hex_colour[hexadecimal]) main()
false
04229618cfcd1a1d69e3da28b9ca8f3ea03cc199
ash/python-tut
/41.py
241
4.1875
4
name = "John" print("Hello, " + name + '!') print("Hello, %s!" % name) print("Hello, {0}!".format(name)) print("{0}, {1}!".format('Hi', name)) print("{1}, {0}!".format(name, 'Hi')) print('My name is {0}. {0} {1}.'.format('James', 'Bond'))
false
5819dbb5b6c308ac62f478185a3d52718832a533
jbehrend89/she_codes_python
/functions/functions_exercises.py
429
4.125
4
# Q1)Write a function that takes a temperature in fahrenheitand returns the temperature in celsius. def convert_f_to_c(temp_in_f): temp_in_c = (temp_in_f - 32) * 5 / 9 return round(temp_in_c, 2) print(convert_f_to_c(350)) # Q2)Write a function that accepts one parameter (an integer) and returns True when that parameter is odd and False when that parameter is even. def odd(x): return x % 2 == 1 print(odd(4))
true
8e05d610dc575187daeddc918c9395d9709a43c4
niceman5/pythonProject
/02.교육/Python-응용SW개발/Project/day20190420/whileEx01.py
561
4.125
4
num = 1 # 초기값 while num < 3: #조건식 : #반복할 조건 true일동안만 실 #명령문 print('num = {}'.format(num)) num += 1 # 증감식 print('실행종료') # 무한loop돌면서 조건으로 체크하는 방식이 있음 num = 1 while True: print('num = {}'.format(num)) num += 1 # 증감식 if num == 3: break print('실행종료') num = 1 while num < 11: num += 1 if num % 2 == 0: #짝수일때만 실행됨....skip된다. continue print('num = {}'.format(num))
false
9dcd83d636b054f122adb049fb0ecb97b342d3f4
nishanthegde/bitesofpy
/105/slicing.py
1,848
4.3125
4
from string import ascii_lowercase text = """ One really nice feature of Python is polymorphism: using the same operation on different types of objects. Let's talk about an elegant feature: slicing. You can use this on a string as well as a list for example 'pybites'[0:2] gives 'py'. The first value is inclusive and the last one is exclusive so here we grab indexes 0 and 1, the letter p and y. When you have a 0 index you can leave it out so can write this as 'pybites'[:2] but here is the kicker: you can use this on a list too! ['pybites', 'teaches', 'you', 'Python'][-2:] would gives ['you', 'Python'] and now you know about slicing from the end as well :) keep enjoying our bites! """ another_text = """ Take the block of text provided and strip() off the whitespace at the ends. Split the whole block up by newline (\n). if the first character is lowercase, split it into words and add the last word of that line to the results list. Strip the trailing dot (.) and exclamation mark (!) from the word first. finally return the results list! """ def slice_and_dice(text: str = text) -> list: """Get a list of words from the passed in text. See the Bite description for step by step instructions""" results = [] lines = [l.lstrip() for l in text.split('\n')] for l in lines: # print(l[:1], l[:1].islower()) if l[:1].islower(): words_lower = [word for word in l.split()] results.append(words_lower[-1].replace('.', '').replace('!', '')) # is_first_lower = [c for l in lines for c in l[:1]] return results # def main(): # print('here ..') # actual = slice_and_dice(text) # print(actual) # actual = slice_and_dice(another_text) # print(actual) # if __name__ == '__main__': # main()
true
1ad2e7463aff6086e9506fe45d87a94b0d6b9226
nishanthegde/bitesofpy
/9/palindrome.py
1,805
4.21875
4
"""A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward""" import os import urllib.request as ur import re local = '/tmp' # local = os.getcwd() DICTIONARY = os.path.join(local, 'dictionary_m_words.txt') ur.urlretrieve('http://bit.ly/2Cbj6zn', DICTIONARY) def prep_word(word): """Prep the word for the palindrome test 1. case insensitive 3. strip /n 2. remove non-alpha numeric """ word = word.strip().casefold() word = re.sub(r'[^a-zA-Z0-9]','',word) return word def load_dictionary(): """Load dictionary (sample) and return as generator (done)""" with open(DICTIONARY,'r') as f: return [prep_word(w) for w in f.readlines()] def is_palindrome(word): """Return if word is palindrome, 'madam' would be one. Case insensitive, so Madam is valid too. It should work for phrases too so strip all but alphanumeric chars. So "No 'x' in 'Nixon'" should pass (see tests for more)""" is_palindrome = False if prep_word(word) == prep_word(word[::-1]): is_palindrome = True return is_palindrome def get_longest_palindrome(words=None): """Given a list of words return the longest palindrome If called without argument use the load_dictionary helper to populate the words list""" if words == None: words = load_dictionary() pal = [p for p in words if is_palindrome(p)] m = max([len(p) for p in pal]) max_words = [p for p in pal if len(p) == m] max_words = sorted(max_words) return max_words[0] # def main(): # """ main program entry point""" # p = get_longest_palindrome() # print(p) # if __name__=="__main__": # main()
true
489a9fbaa6d206101364ed5db32b3bf291c3d875
nishanthegde/bitesofpy
/304/max_letter.py
2,435
4.25
4
from typing import Tuple import re from collections import Counter sample_text = '''It is a truth universally acknowledged, that a single man in possession of a good fortune, must be in want of a wife.''' with_numbers_text = '''20,000 Leagues Under the Sea is a 1954 American Technicolor science fiction-adventure film...''' emoji_text = 'emoji like 😃😃😃😃 are not letters' accents_text = 'Société Générale est une des principales banques françaises' mixed_case_text = 'Short Plays By Lady Gregory The Knickerbocker Press 1916' hyphenated_word_text = 'six-feet-two in height' compound_character_text = 'der Schloß is riesig' no_repeat_characters_text = 'the quick brown fox jumped over the lazy dog' non_ascii_symbols_text = '«¿Tiene sentido la TV pública?»' apostrophe_in_word_text = "but we've been there already!!!" underscore_torture_text = '"____".isalpha() is True, thus this test text' digit_text = '99abc99 __abc__ --abc-- digits _ and - are not letters' repeat_words_text = 'test test test test test correct-answer.' no_words_in_text = '1, 2, 3' empty_text = '' def max_letter_word(text: str) -> Tuple[str, str, int]: """ Find the word in text with the most repeated letters. If more than one word has the highest number of repeated letters choose the first one. Return a tuple of the word, the (first) repeated letter and the count of that letter in the word. # >>> max_letter_word('I have just returned from a visit...') ('returned', 'r', 2) # >>> max_letter_word('$5000 !!') ('', '', 0) """ return_value = ('', '', 0) regex = re.compile('[«¿\"#!@$%%&*()0-9._]') regex1 = re.compile(r'[^ \nA-Za-zÀ-ÖØ-öø-ÿ/]+') if not isinstance(text, str): raise ValueError else: words_orig = [regex.sub('', w) for w in text.split()] words = [regex1.sub('', w.casefold()) for w in text.split()] for i, word in enumerate(words): if word: # print(word) cnt = Counter(word).most_common()[0] # print(cnt) if i == 0: # initiate return_value = (words_orig[i], cnt[0], cnt[1]) else: if cnt[1] > return_value[2]: return_value = (words_orig[i], cnt[0], cnt[1]) # else: # break return return_value
true
c2e0d08cf977c216e326da83a6e1580b01c3af7b
nishanthegde/bitesofpy
/66/running_mean.py
666
4.125
4
import itertools def running_mean(sequence: list) -> list: """Calculate the running mean of the sequence passed in, returns a sequence of same length with the averages. You can assume all items in sequence are numeric.""" it = iter(sequence) n = len(sequence) run_mean = [] for i in range(1, n + 1): win = list(itertools.islice(sequence, 0, i, 1)) run_mean.append(round(sum(win) / len(win), 2)) return run_mean # def main(): # print('thank you...') # print(running_mean([1, 2, 3])) # assert [1.0, 1.5, 2.0] == [1, 1.5, 2] # if __name__ == '__main__': # main()
true
f70649cbba312ef901ac9aa035cc529e46127200
Caleb-o/VU405
/sort.py
694
4.1875
4
""" Author: Caleb Otto-Hayes Date: 11/2/2021 """ def swap(x: int, y: int) -> tuple: return (y, x) def bubbleSort(unsorted: list) -> None: length: int = len(unsorted) full_pass: bool = False # Cannot parse if only 1 number exists if length < 2: return while not full_pass: full_pass = True for i in range(length - 1): if (unsorted[i] > unsorted[i + 1]): unsorted[i], unsorted[i + 1] = swap(unsorted[i], unsorted[i + 1]) full_pass = False if __name__ == '__main__': li: list = [2, 1, 9, 3, 7, 5, 6, 8] print(f'Unsorted list: {li}') bubbleSort(li) print(f'Sorted list: {li}')
true
1572a767db054bb13877a5d56f5efb212d0b844d
ahumoe/dragonfly-commands
/_text_utils.py
1,978
4.15625
4
#!/usr/bin/env python # (c) Copyright 2015 by James Stout # (c) Copyright 2016 by Andreas Hagen Ulltveit-Moe # Licensed under the LGPL, see <http://www.gnu.org/licenses/> """Library for extracting words and phrases from text.""" import re def split_dictation(dictation, strip=True): """Preprocess dictation to do a better job of word separation. Returns a list of words.""" clean_dictation = str(dictation) if strip: # Make lowercase. clean_dictation = clean_dictation.lower() # Strip apostrophe and "the ". clean_dictation = re.sub(r"'|^(a |the )", "", clean_dictation) # Convert dashes and " a " into spaces. clean_dictation = re.sub(r"-| a | the ", " ", clean_dictation) # Surround all other punctuation marks with spaces. clean_dictation = re.sub(r"(\W)", r" \1 ", clean_dictation) # Convert the input to a list of words and punctuation marks. raw_words = [word for word in clean_dictation.split(" ") if len(word) > 0] # Merge contiguous letters into a single word, and merge words separated by # punctuation marks into a single word. This way we can dictate something # like "score test case dot start now" and only have the underscores applied # at word boundaries, to produce "test_case.start_now". words = [] previous_letter = False previous_punctuation = False punctuation_pattern = r"\W" for word in raw_words: current_punctuation = re.match(punctuation_pattern, word) current_letter = len(word) == 1 and not re.match(punctuation_pattern, word) if len(words) == 0: words.append(word) else: if current_punctuation or previous_punctuation or (current_letter and previous_letter): words.append(words.pop() + word) else: words.append(word) previous_letter = current_letter previous_punctuation = current_punctuation return words
true
c3062c4b5da4a684bb5ce8a19b074e6585618620
josepicon/practice.code.py
/Exercise Files/Ch2/functions_start.py
747
4.34375
4
# # Example file for working with functions # # define a basic function def func1(): print("i am a function") # function that takes arguments def func2(arg1, arg2): print(arg1, "", arg2) # function that returns a value def cube(x): return x*x*x # function with default value for an argument def power(num, x=1): result=1 for i in range(x): result = result * num return result #function with variable number of arguments def multi_add(*args): result=0 for x in args: result = result + x return result #func1() #print(func1()) #print(func1) #func2(10, 20) #print (func2(10,20)) #print (cube(3)) #print(power(2)) #print (power(2,3)) #print(power(x=3, num=2)) print (multi_add(10,4,10,5,4))
true
080fa1a292fe225984f8889d5e5bd13ed05b0f07
MayThuHtun/python-exercises
/ex3.py
444
4.28125
4
print("I will now count my chickens") print("Hens", 25+30/6) print("Roosters", 100-25*3 % 4) print("Now I will count the egg:") print(3+2+1-5+4 % 2-1/4+6) print("Is it true that 3+2<5-7?") print(3+2 < 5-7) print("What is 3+2?", 3+2) print("What is 5-7?", 5-7) print("Oh, that is why it is false") print("How about some more") print("It is greater?", 5 > -2) print("It is greater or equal?", 5 >= -2) print("It is less than or equal?", 5 <= -2)
true
71191aff305c9dae5028b28c2f43b0d963112b9b
dev-aleks/info_2021
/lab4/house.py
1,380
4.125
4
def main(): x, y = 300, 400 width, height = 200, 300 draw_house(x, y, width, height) def draw_house(x, y, width, height): ''' Функция рисует домик :param x: координата x у низа фундамента :param y: координата y у низа фундамента :param width: полная ширина домика (фундамент или вылеты крыши включены) :param height: полная высота домика :return: None ''' print('drawing house', x, y, width, height) foundation_height = 0.05 * height walls_height = 0.9 * width walls_weight = 0.5 * height roof_height = height - foundation_height - walls_height draw_house_foundation(x, y, width, foundation_height) draw_house_walls(x, y - foundation_height, walls_weight, walls_height) draw_house_roof(x, y - foundation_height - walls_height, width, roof_height) def draw_house_foundation(x, y, width, foundation_height): """ Нарисовать фундамент """ pass def draw_house_walls(x, y - foundation_height, walls_weight, walls_height): """ Нарисовать стены """ pass def draw_house_roof(x, y - foundation_height - walls_height, width, roof_height): """ Нарисовать крышу """ pass main()
false
aeb5e4b72d128ac04131053125ed663ad059d5f5
Patricia888/data-structures-and-algorithms
/sorting_algos/merge_sort/merge_sort.py
927
4.5
4
def merge_sort_the_list(lst): ''' Performs a merge sort on a list. Checks the length and doesn't bother sorting if the length is 0 or 1. If more, it finds the middle, breaks the list in to sublists, sorts, puts in to a single list, and then returns the sorted list ''' # don't bother sorting if list is less than 2 length if len(lst) < 2: return lst # find middle of inputted list middle_of_list = len(lst) // 2 # recursive part new_list1 = merge_sort_the_list(lst[0:middle_of_list]) new_list2 = merge_sort_the_list(lst[middle_of_list:]) list_for_sorting = [] while len(new_list1) and len(new_list2): if new_list1[-1] > new_list2[-1]: list_for_sorting = [new_list1.pop()] + list_for_sorting else: list_for_sorting = [new_list2.pop()] + list_for_sorting sorted_list = new_list1 + new_list2 + list_for_sorting return sorted_list
true
a56350042eb37db6b829f6a1e39aafaf25f8bca8
Roderich25/mac
/python_cookbook/chapter_02/cookbook_11.py
391
4.25
4
# 2.11 Stripping unwanted characters from strings # whitespace stripping import re s = ' hello world \n' print(s) print(s.strip()) print(s.lstrip()) print(s.rstrip()) # character stripping t = '-----hello=====' print(t.lstrip('-')) print(t.strip('-=')) # another example s = ' hello world \n' print(s.strip()) print(s.replace(' ', '')) print(re.sub('\s+', ' ', s).strip())
false
4e2dcb79a87788232e4ea09ff6e3688a6a6f4b8c
Roderich25/mac
/python-scripts/square_root.py
233
4.21875
4
#!/usr/bin/env python3 def square_root(a): x = a//2 while True: print(int(x)*"*", x) y = (x + a/x)/2 print if abs(y-x) < 0.00001: return y x = y print(square_root(125))
false
e10e5f413c7f9e4b84f8fe20a314a4be4d36a9a9
TheWronskians/capture_the_flag
/turtlebot_ws/src/turtle_pkg/scripts/primeCalc.py
912
4.125
4
from math import * import time def checkingPrime(number): #Recieves number, true if prime. Algorithem reference mentioned in readme file. checkValue = int(sqrt(number))+1 printBool = True #print checkValue for i in range(2, checkValue): if (number%i) == 0: printBool = False break return printBool def countPrimes(lLimit, uLimit): #Recieves range limit and returns amount of primes and total search time. start_time = time.time() count = 0 temp=lLimit if lLimit<=1: #Since 1 cannot be considered a prime. lLimit=2 if (uLimit<lLimit) or (uLimit<=1): return 0,0 for number in range(lLimit,uLimit+1): if checkingPrime(number): count = count + 1 elapsed_time = time.time() - start_time lLimit=temp print("There are " + str(count) + " primes between " + str(lLimit) + " and " + str(uLimit)) print("Time elapsed " + str(elapsed_time) + " seconds.") return count, elapsed_time
true
273b92997f588d6aeee2ae42928258d04f0a4187
drliebe/python_crash_course
/ch7/restaurant_seating.py
214
4.28125
4
dinner_party_size = input("How many people are in your dinner group? ") if int(dinner_party_size) > 8: print("I'm sorry, but you will have to wait to be seated.") else: print('Great, we can seat you now.')
true
20b3792997a403dda5086e24d5914c0157d91ea3
drliebe/python_crash_course
/ch9/restaurant.py
628
4.125
4
class Restaurant(): """A class modeling a simple restaurant.""" def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): print('Restaurant name: ' + self.restaurant_name + ' Cuisine type: ' + self.cuisine_type) def open_restaurant(self): print('We are now open!') #my_restaurant = Restaurant("Josh's Curry House", "Thai") #print(my_restaurant.restaurant_name) #print(my_restaurant.cuisine_type) #my_restaurant.describe_restaurant() #my_restaurant.open_restaurant()
false
1a747fc8d6fefd929318c717954420f3e36ce54a
drliebe/python_crash_course
/ch9/ice_cream_stand.py
888
4.28125
4
class Restaurant(): """A class modeling a simple restaurant.""" def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): print('Restaurant name: ' + self.restaurant_name + ' Cuisine type: ' + self.cuisine_type) def open_restaurant(self): print('We are now open!') class IceCreamStand(Restaurant): """A class modeling a simple ice cream stand.""" def __init__(self, restaurant_name, flavors): super().__init__(restaurant_name, 'ice cream') self.flavors = flavors def display_flavors(self): for flavor in self.flavors: print('-' + flavor) bonnie_doon = IceCreamStand('Bonnie Doon', ['chocolate', 'vanilla', 'strawberry']) bonnie_doon.display_flavors()
true
42b2a2848527d4f024d2bdc5ff385b2ce9753dc4
aurafrost/Python
/DivisorCheck.py
518
4.21875
4
""" This program takes an int from the user then returns all divisors of that int from lowest to highest. """ num = int(input("Enter an integer: ")) divisorList = [] for x in range(1,num+1): if num%x==0: divisorList.append(x) #adds x to divisorList if it has no remainder when divided into num print("The divisors of "+str(num)+" are: "+", ".join(str(n) for n in divisorList)) if(len(divisorList)==2): print("The number "+str(num)+" is prime.") #prints this if there're only two elements in divisorList
true
edaaa9d51915039e033c950b030fbc08a9ef4084
fharookshaik/Mobius_GUI
/mobius.py
2,932
4.28125
4
''' Möbius function: For any positive integer n,n, define μ(n)μ(n) as the sum of the primitive n^\text{th}nth roots of unity. It has values in \{-1, 0, 1\}{−1,0,1} depending on the factorization of nn into prime factors: a) \mu(n) = 1μ(n)=1 if nn is a square-free positive integer with an even number of prime factors. b) \mu(n) = -1μ(n)=−1 if nn is a square-free positive integer with an odd number of prime factors. c) \mu(n) = 0μ(n)=0 if nn has a squared prime factor. ''' import math def isSquareRoot(num): ''' Checks whether the input num is a square root or not. Output is a boolean. ''' try: num_sqrt = math.sqrt(num) if int(num_sqrt)**2 == num: return True else: return False except Exception as e: return('Error in finding Square Root:' + str(e)) def get_factors(num): try: ''' outputs the factors between 1 and num excluding both eg: for 8 -> [2,4,8] ''' factors = [] for i in range(2, num // 2 + 1): if num % i == 0: factors.append(i) factors.append(num) return factors except Exception as e: return('Error in getting factors: ' + str(e)) def isPrime(num): ''' Checks whether the input num is a prime or not output is a boolean ''' try: if num < 2: return False else: for i in range(2, num): if (num % i == 0): return False return True except Exception as e: return ('Error in evaluating prime number: ' + str(e)) def Mobius(num): ''' Returns the mobius value of a number. ''' try: exp = '' if num <= 0: exp = f'Number can\'t be zero or negative.' return {'val': None, 'exp' : exp} if num == 1: exp = f'The Möbius Value of number 1 is 1.' return {'val': 1, 'exp' : exp} factors = get_factors(num) prime_count = 0 prime_numbers = [] for i in factors: if isSquareRoot(i): exp ="The number {} can be divided by {} which is a perfect square.".format(num,i) return {'val': 0, 'exp' : exp} elif isPrime(i): prime_numbers.append(i) prime_count += 1 exp = 'The number {} can be get by multiplying {}.'.format(num,prime_numbers) if (prime_count % 2 != 0): return {'val': -1, 'exp' : exp} else: return {'val': 1, 'exp' : exp} except Exception as e: return ('Error Finding Möbius function: ' + str(e)) if __name__ == '__main__': n = int(input("Enter a number to get it's mobius value: ")) op = Mobius(n) print('Mobius Value = {} \nExplaination: {}'.format(op['val'], op['exp']))
true
86ae948be11bd8decc10050c7cea5fb41397e9d6
ms0695861/age
/age.py
657
4.1875
4
#age judement driving = input('Have you ever driven a car? (Y/N): ') if driving != 'Y' and driving != 'N': print('Please enter Y or N! Thanks!') raise SystemExit age = input('How old are you?: ') age = int(age) if driving == 'Y': if age >= 18: print('PASS!!') else: print('It is illegal') elif driving == 'N': if age >= 18: license = input('Did you have driver license? (Y/N): ') if license != 'Y' and license != 'N': print('Please enter Y or N! Thanks!') raise SystemExit elif license == 'Y': print('Why not drive?') elif license == 'N': print('Why not get driver license?') else: print('You can drive few year later.')
false
cb98c118df80bbe3ef89900bc63d6e38d01514c8
jpozin/Math-Projects
/TriangleStuff.py
652
4.375
4
import sys from math import sqrt class TriangleException(Exception): pass def isValidTriangle(a, b, c): return (a + b > c) and (a + c > b) and (b + c > a) def Perimeter(a, b, c): return a + b + c def Area(a, b, c): s = Perimeter(a, b, c) / 2 return sqrt(s*(s-a)*(s-b)*(s-c)) if __name__ == '__main__': a = float(sys.argv[1]) b = float(sys.argv[2]) c = float(sys.argv[3]) if not isValidTriangle(a, b, c): raise TriangleException("Your triangle is invalid; please check your side lengths.") ShowThis = f"""The perimeter off your triangle is {Perimeter(a, b, c)}. The area of your triangle is {Area(a, b, c)}."""
true
907bc6613731a110a451fc19caae9ac35a8b7a86
moontasirabtahee/OOP_Python_BRACU
/CSE111 Lab Assignment 2/Task7.py
413
4.34375
4
def Palindrome(String): word = "" for i in String: if i != " ": word += i oppositeWord = "" for i in range(len(String)-1,-1,-1): if String[i] != " ": oppositeWord += String[i] # # print(word) # print(oppositeWord) # if word == oppositeWord: print("Palindrome") else: print("Not a Palindrome") Palindrome(input())
false
d6218b40c283b8ec5eda0c7f77e63e650a4eac75
FKistic/Python-Personal
/calci project/calci v5.py
2,422
4.21875
4
#simple calcultor using python import time time.sleep(1) print('''|||||||| //\\\ || |||||||| || || || //\\\ |||||||||| |||||||| ||||||\\''') time.sleep(1) print('''|| // \\\ || || || || || // \\\ || || || || ||''') time.sleep(1) print('''|| //====\\\ || || || || || //====\\\ || || || ||||||/''') time.sleep(1) print('''|||||||| // \\\ ||||||| |||||||| ||||||| |||||| // \\\ || |||||||| || \\\\''') time.sleep(2) print("MADE BY FARAAZ!") name = input("Type your name here: ") print("Hello and Welcome "+ name +"!") print() x = int(input("Please Type the 1st number: ")) y = int(input("Please Type the 2nd number: ")) z = int(input('''What operator you want to use? Press 1 for +, 2 for -, 3 for *, 4 for /: ''')) a = x+y b = x-y c = x*y d = x/y if z==3: print("IF MULTIPLIED THEN THE ANSWER WILL BE") print(c) if z==1: print("IF ADDED THEN ANSWER WILL BE") print(a) if z==2: print("IF SUBTRACTED THEN THE ANSWER WILL BE") print(b) if z==4: print("IF DEVIDED THEN THE ANSWER WILL BE") print(d) print() print("Thank you "+ name +" for using this CALCULATOR LITE, LOL!!") if input("Do you want to repeat (y/n): ") =='n': exit() while True: x = int(input("Please Type the 1st number: ")) y = int(input("Please Type the 2nd number: ")) z = int(input('''What operator you want to use? Press 1 for +, 2 for -, 3 for *, 4 for /: ''')) a = x+y b = x-y c = x*y d = x/y if z==3: print("IF MULTIPLIED THEN THE ANSWER WILL BE") print(c) if z==1: print("IF ADDED THEN ANSWER WILL BE") print(a) if z==2: print("IF SUBTRACTED THEN THE ANSWER WILL BE") print(b) if z==4: print("IF DEVIDED THEN THE ANSWER WILL BE") print(d) print() print("Thank you "+ name +" for using this CALCULATOR LITE, LOL!!") if input("Do you want to repeat (y/n): ") =='n': break print('''HOPE TO SEE YOU AGAIN, SEE YA''') input("Press ENTER to exit this program: ")
false
52756187aec18fc94ecc77d26594ab3d50a502a5
kellylougheed/raspberry-pi
/bubble_sort.py
956
4.375
4
#!/usr/bin/env python # This program sorts a list of comma-separated integers using bubble sort # Swaps two numbers in a list given their indices def swap(l, index1, index2): temp = l[index2] l[index2] = l[index1] l[index1] = temp numbers = input("Enter a list of comma-separated integers: ") lst = numbers.split(",") done = False passes = 0 while not done: # Make done variable true so that it can be changed to false if the sorting is not yet done done = True for index, item in enumerate(lst): # If it's not the end of the list and the two adjacent items are out of order if index + 1 != len(lst) and lst[index] > lst[index + 1]: swap(lst, index, index + 1) # Make done variable false because the list was not done being sorted done = False passes += 1 print("Pass %s: %s" %(passes, ",".join(lst))) print("Original List: %s" %(numbers)) print("Sorted List: %s" %(",".join(lst))) print("Passes: %s" %(passes))
true
473d78088b698ab07eca912a5ef5bf23a76d32dc
dibaggioj/bioinformatics-rosalind
/textbook/src/ba1d.py
2,138
4.3125
4
#!/usr/bin/env # encoding: utf-8 """ Created by John DiBaggio on 2018-07-28 Find All Occurrences of a Pattern in a String In this problem, we ask a simple question: how many times can one string occur as a substring of another? Recall from “Find the Most Frequent Words in a String” that different occurrences of a substring can overlap with each other. For example, ATA occurs three times in CGATATATCCATAG. Pattern Matching Problem Find all occurrences of a pattern in a string. Given: Strings Pattern and Genome. Return: All starting positions in Genome where Pattern appears as a substring. Use 0-based indexing. Sample Dataset ATAT GATATATGCATATACTT Sample Output 1 3 9 Execute like: python src/ba1d.py data/ba1d.txt output/ba1d.txt """ __author__ = 'johndibaggio' import sys import fileinput argv = list(sys.argv) input_pattern = "" input_genome = "" for line in fileinput.input(argv[1]): if len(line) > 0: if len(input_pattern) == 0: input_pattern += line.replace('\n', '') else: input_genome += line.replace('\n', '') def find_occurrences(genome, pattern): """ Find the indices of all occurrences of pattern in genome :param genome: DNA string :type genome: str :param pattern: DNA substring :type pattern: str :return: list of indices of occurrences of pattern in genome :rtype: list[int] """ k = len(pattern) buffer = genome[0:k] genome = genome[k:len(genome)] i = 0 indices = [] if buffer == pattern: indices.append(i) for c in genome: i += 1 buffer = buffer[1:k] + c if buffer == pattern: indices.append(i) return indices occurrences = find_occurrences(input_genome, input_pattern) output_string = str.join(" ", [str(i) for i in occurrences]) print("The following are the occurrences of pattern \"{}\" in genome \"{}\":\n{}".format(input_pattern, input_genome, output_string)) output_file = open(argv[2], "w+") output_file.write(output_string) output_file.close()
true
47f6f9ad980659dc5b1408cb50f588adda37c9cf
FierySama/vspython
/Module7ComplexDecisions/m7cont.py
1,121
4.21875
4
team = input('Enter your favorite hockey team: ').upper() sport = input('Enter your favorite sport: ').upper() sportIsHockey = False if sport == 'HOCKEY': sportIsHockey = True teamIsCorrect = False if team == 'SENATORS' or team == 'LEAFS': teamIsCorrect = True if sportIsHockey and teamIsCorrect: print('good luck getting to the cup this year') # if the sport is hockey, and the team is the senators or leafs, display cup message # AND StATEMENt IS oVERRIDING EVERYTHING if sport == 'HOCKEY' and (team == 'SENATORS' or team == 'LEAFS'): print('Good luck getting to the cup this year ') # if sport == 'HOCKEY' and team == 'RANGERS': # print('I miss messier') # elif team == 'LEAFS' or team == 'SENATORS': # print('Good luck getitng the cup this year') # else: # print('I don't know that team ') # if team == 'FLYERS': # print('Best team ever!! ') # elif team == 'SENATORS': # print('Go sens go! ') # elif team == 'RANGERS': # print('Go rangers ') # else: # print('I don\'t have anything clever to say but hell, we're programming in python! ')
false
b2b59660795297211f00f7b98497fb289583e46a
FierySama/vspython
/Module3StringVariables/Module3StringVariables/Module3StringVariables.py
1,330
4.5625
5
#String variables, and asking users to input a value print("What is your name? ") # This allows for the next line to be user input name = input("") country = input("What country do you live in? ") country = country.upper() print(country) # input is command to ask user to enter info!! # name is actually the name of a custom variable that we've created above. #Create a friendly output print("Hello! " + name + ", please create your story! ") print("\n") #Variables allow you to manipulate contents of VARIABLES message1 = "Hello World \n" print(message1.lower()) #hello world print(message1.upper()) #HELLO WORLD print(message1.swapcase()) #hELLO wORLD #Update value of name after user input # name = "banana hammock" #print(name) # Variables are case sensitive!!! Name does NOT EQUAL name # Treat everything like it's case sensitive in python. # Variables cannot start with a number. # name3 name2 name1 are all okay # Newer functions!! print("\n") message2 = "hello World" print(message2.find("world")) print(message2.count("o")) print(message2.capitalize()) print(message2.replace("Hello","Hi")) #Good habit. Initializing values #ex below postalCode = " " #this is declaring that this is a string, with initializing postalCode = input("Please enter your postal code: ") print(postalCode.upper())
true
89786e3d23a48edae281b38edcc1df05db998b13
AtilioA/Python-20191
/lista7jordana/Ex062.py
744
4.15625
4
# 12. Faça uma função que receba uma lista de números armazenados de forma crescente , e # dois valores ( limite inferior e limite superior), e exiba a sublista cujos elementos são maiores # ou iguais ao limite inferior e menores ou iguais ao limite superior def intervalo(listaOrdenada, limInferior, limSuperior): if not listaOrdenada: return [] elif listaOrdenada[0] >= limInferior and listaOrdenada[0] <= limSuperior: return [listaOrdenada[0]] + \ intervalo(listaOrdenada[1:], limInferior, limSuperior) else: return intervalo(listaOrdenada[1:], limInferior, limSuperior) lista = [1, 2, 3, 4, 5, 6, 7] limInferior = 2 limSuperior = 5 print(intervalo(lista, limInferior, limSuperior))
false
75db23491fd660c007860b03e4ed99cca64a9025
zengh100/PythonForKids
/lesson02/07_keyboard_number.py
316
4.15625
4
# keyboard # we can use keyboard as an input to get informations or data (such as number or string) from users x1 = input("please give your first number? ") #print('x1=', x1) x2 = input("please give your second number? ") #print('x2=', x2) sum = x1 + x2 #sum = int(x1) + int(x2) print('the sum is {}'.format(sum))
true
ab38aaac210610d8b6b26ef0cab0d918d58f81b7
muhamadziaurrehman/Python
/Finding and printing odd numbers from list.py
283
4.34375
4
List = (1,2,3,4,5,6,7,8,9) ###This function is printing odd position numbers according to programmers who starts counting from 0 minor changes occur to start it from 1 i-e change x to x+1 only in if statement for x in range(0,9): if (x)%2 == 0: print() else: print(List[x])
true
c75d693b5f9e6fbf51573a8e2ede8070b52ec4cb
kasataku777/PY4E
/chap8-list/ex8-5.py
1,126
4.125
4
# Exercise 5: Write a program to read through the mail box data and # when you find line that starts with “From”, you will split the line into # words using the split function. We are interested in who sent the # message, which is the second word on the From line. # From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 # You will parse the From line and print out the second word for each # From line, then you will also count the number of From (not From:) # lines and print out a count at the end. This is a good sample output # with a few lines removed: # python fromcount.py # Enter a file name: mbox-short.txt # stephen.marquard@uct.ac.za # louis@media.berkeley.edu # zqian@umich.edu # [...some output removed...] # ray@media.berkeley.edu # cwen@iupui.edu # cwen@iupui.edu # cwen@iupui.edu # There were 27 lines in the file with From as the first word fname = input("Enter file: ") try: fileh = open(fname) except: print("No exists") exit() cnt = 0 for line in fileh: splist = line.split() if len(splist) > 1 and splist[0] == 'From': cnt = cnt+1 print(splist[1]) print("There were", cnt, "lines in the file with From as the first word")
true
bc204746027f72a2c68e230e9be6a4a3fc8bce26
sneceesay77/python_projects
/python_basics/classes.py
933
4.125
4
class Tutorial: """Modelling a Tutorial class""" #a docstring, mainly printed in documentation #constructor def __init__(self, module_name, max_students): self.module_name = module_name self.max_students = max_students def display_max_stud(self): print(f"Maximum number of students in this {self.module_name.title()} is {self.max_students}") def display_module_name(self): print(f"The name of this module is {self.module_name}") def get_name(self): return self.module_name my_tutorial = Tutorial("Programming Data", 7) print(f"The name of the module is: {my_tutorial.module_name}") print(f"The max number of students is: {my_tutorial.max_students}") print("==========================================================") my_tutorial.display_max_stud() my_tutorial.display_module_name() print(f"Tutorial name is: {my_tutorial.get_name()}")
true
6194db2615e2819ffb8437cbbc8a2f511a093854
ivaylospasov/programming-101
/week0/prime_number_of_divisors.py
329
4.125
4
#!/usr/bin/env python3 from is_prime import is_prime def prime_number_of_divisors(n): divisors = [x for x in range(1, n+1) if n % x == 0] if is_prime(len(divisors)) is True: return True else: return False def main(): print(prime_number_of_divisors(45)) if __name__ == '__main__': main()
false
a3387722a6d8ac4ecf061ed08de7887fa38c7e59
MayankVerma105/Python_Programs
/max3.py
530
4.125
4
def max3(n1,n2,n3): maxNumber = 0 if n1 > n2: if n2 > n3: maxNumber = n1 else: maxNumber = n3 elif n2 > n3: maxNumber = n2 else: maxNumber = n3 return maxNumber def main(): n1=int(input('Enter first number : ')) n2=int(input('Enter second number : ')) n3=int(input('Enter third number : ')) maximum = max3(n1,n2,n3) print('Maximum Number is : ',maximum) if __name__ == '__main__': main()
false