blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
8b599baaa69f6af2e424dba6424c37c38670ba25
Martondegz/python-snippets
/caps.py
699
4.21875
4
"""Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized. Suppose the following input is supplied to the program: Hello world Practice makes perfect Then, the output should be: HELLO WORLD PRACTICE MAKES PERFECT""" # create a list variable # create a while loop to loop over my list # create a raw input variable for my input # set an if condition for my statement # append my statements to the list when they are in uppercase # for any sentence in my list print out the sentence lines = [] while True: s = raw_input() if s: lines.append(s.upper()) else: break; for sentence in lines: print sentence
true
2424df63a9e39b2bc3c9a884963e9b849eed6686
Martondegz/python-snippets
/larger.py
490
4.125
4
# Given a number whose digits are unique, find the next larger number that can be formed with those digits. # For example: 241 will output 421, 27 will output 72 and 68734 will output 87643 def larger_num(num): # convert to string num_str = str(num) # create a empty list # add each the char to list lst = [x for x in num_str] # sort list in ascending order n_list = sorted(lst, reverse=True) # join list and convert to int return int("".join(n_list)) print larger_num(2365)
true
4726176ffbd1b58eb92f860fa4bd3a32e7ca8849
htjhia/superfluous
/master_101/create_perm.py
743
4.15625
4
def create_perm(actual_list, add_list): """ https://stackoverflow.com/questions/64614220/python-permutation-using-recursion Recursive function for the creation of the permutation """ if len(add_list)==1: # If you reach the last item, print the found permutation # (add the 0 at the beginning) print([0] + actual_list + add_list) else: for i in add_list: # Go one step deeper by removing one item and add it to the found permutation new_add_list = add_list.copy() new_add_list.remove(i) # Make the recursion create_perm(actual_list + [i], new_add_list) li = [i for i in range(1, 10)] for i in create_perm([], li): print(i)
true
f4fec23292dcc55a195d57b98798f71abcebd306
CatPhillips103/Python-Crash-Course
/functions/passing_arguments.py
1,660
4.375
4
# T-shirt: Write a function called make_shirt() that accepts a size and the text of a message that should be printed on the shirt. # The function should print a sentence summarising the size of the shirt and the message printed on it. # Call the function once using positional arguments to make a shirt. Call the function a second time using keyword arguments. def make_shirt(size, message): print(f'Shirt Size: {size.upper()}') print(f'Message: {message}') make_shirt('xs', 'It\'s my birthday and all I got was this T-shirt') make_shirt(message='Don\'t be vague. Ask for a T-shirt', size='m') # Large Shirts: Modify the make_shirt() function so that shirts are large by default with a message that reads 'I love Python'. # Make a large shirt and medium shiirt with the default message, and a shirt size of any size with a different message. def make_shirt(size= 'l', message= 'I love Python'): print(f'Shirt Size: {size.upper()}') print(f'Message: {message}') make_shirt() make_shirt('m') make_shirt(message= 'Python-Lickin Good!', size='s') # Cities: Write a functiion called describe_city() that accepts the name of a city and its country. The functions should print # a simple sentence such as 'Rekjavik is in Iceland'. Give the parameter for the country a default value. Call your function # for three different cities, at least one of which is not in the default country. def describe_city(city, country= 'United Kingdom'): print(f'{city.title()} is in {country.title()}') describe_city(city= 'asuncion', country= 'paraguay') describe_city('castries', 'st lucia') describe_city(country= 'south africa', city= 'johannesburg')
true
9e77ebf344d2ec17a639ed1e0355e0c991712e55
rahulcs754/100daysofcode-Python
/code/files/47.py
1,013
4.59375
5
# This function uses global variable s def f(): print s # Global scope s = "I love Geeksforgeeks" f() # This function has a variable with # name same as s. def f(): s = "Me too." print s # Global scope s = "I love Geeksforgeeks" f() print s def f(): print s # This program will NOT show error # if we comment below line. s = "Me too." print s # Global scope s = "I love Geeksforgeeks" f() print s # This function modifies global variable 's' def f(): global s print s s = "Look for Geeksforgeeks Python Section" print s # Global Scope s = "Python is great!" f() print s a = 1 # Uses global because there is no local 'a' def f(): print 'Inside f() : ', a # Variable 'a' is redefined as a local def g(): a = 2 print 'Inside g() : ',a # Uses global keyword to modify global 'a' def h(): global a a = 3 print 'Inside h() : ',a # Global scope print 'global : ',a f() print 'global : ',a g() print 'global : ',a h() print 'global : ',a
false
0f978cb8a0a7c4cc90d8fd827f71249fcb3aa448
rahulcs754/100daysofcode-Python
/code/files/50.py
1,992
4.125
4
# Python code to demonstrate the working of # typecode, itemsize, buffer_info() # importing "array" for array operations import array # initializing array with array values # initializes array with signed integers arr= array.array('i',[1, 2, 3, 1, 2, 5]) # using typecode to print datatype of array print ("The datatype of array is : ",end="") print (arr.typecode) # using itemsize to print itemsize of array print ("The itemsize of array is : ",end="") print (arr.itemsize) # using buffer_info() to print buffer info. of array print ("The buffer info. of array is : ",end="") print (arr.buffer_info()) # Python code to demonstrate the working of # count() and extend() # importing "array" for array operations import array # initializing array 1 with array values # initializes array with signed integers arr1 = array.array('i',[1, 2, 3, 1, 2, 5]) # initializing array 2 with array values # initializes array with signed integers arr2 = array.array('i',[1, 2, 3]) # using count() to count occurrences of 1 in array print ("The occurrences of 1 in array is : ",end="") print (arr1.count(1)) # using extend() to add array 2 elements to array 1 arr1.extend(arr2) print ("The modified array is : ",end="") for i in range (0,9): print (arr1[i],end=" ") # Python code to demonstrate the working of # fromlist() and tolist() # importing "array" for array operations import array # initializing array with array values # initializes array with signed integers arr = array.array('i',[1, 2, 3, 1, 2, 5]) # initializing list li = [1, 2, 3] # using fromlist() to append list at end of array arr.fromlist(li) # printing the modified array print ("The modified array is : ",end="") for i in range (0,9): print (arr[i],end=" ") # using tolist() to convert array into list li2 = arr.tolist() print ("\r") # printing the new list print ("The new list created is : ",end="") for i in range (0,len(li2)): print (li2[i],end=" ")
true
59a84b56875201034c45a92d95c1483eb124a3de
aojie654/codes_store
/python/python/eric/part1_basic/ch06_dictionary/ex06_survey.py
670
4.1875
4
# Survey """init favorite_languages_dictionary""" favorite_language0_dict = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python' } """print dictionary""" for name, language in favorite_language0_dict.items(): print(name.title() + "'s favorite language is", language.title() + '.') print() """init people list""" people0_list = ['jen', 'sarah', 'edward', 'zt', 'jym'] """print information""" for people in people0_list: if people.lower() in favorite_language0_dict.keys(): print('Thanks for the survey,', people.title() + '.') else: print('Hi', people.title() + ', would you like to have a survey?') print()
false
28e092fb4808c373068861f1ac6ef869885943b2
Eduardo-LP/Python
/grafico_basico.py
636
4.1875
4
# visualização de dados em python #o atributo "as" faz com q a palavra seguinte seja usada #como um apelido para aquela biblioteca sempre que quisermos usala import matplotlib.pyplot as plt #função usada para fazer um grafico de linhas x = [1,2]#numero minimo ate o maximo y = [2,3]#numero minimo ate o maximo #-------------add uma legenda-------- plt.title("meu primeiro grafico")#add um titulo ao grafico plt.xlabel("eixo x")#cria uma legenda para o eixo x plt.ylabel("eixo y")#cria uma legenda para o eixo y plt.plot(x,y)#lista de valores que indicaram as posições no "x" e no "y" plt.show()#exibe o grafico
false
7aa725d79bb803f1e1d7f94ce3d26d4cd334fee9
behrokhGitHub/Ex_Files_Python_EssT
/Exercise Files/Chap15/db-api.py
1,710
4.84375
5
#!/usr/bin/env python3 # Copyright 2009-2017 BHG http://bw.org/ import sqlite3 as sq def main(): print('connect') ''' To create a databases using the connect() function of the sqlite3 module. db is the connection object. ''' db = sq.connect('db-api.db') ''' Create a Cursor object to call its execute() method to perform SQL commands: ''' cur = db.cursor() print('create') ''' Executes an SQL statement using execute() DROP TABLE IF EXISTS SQL statement checks if the table exists prior to drop/delete it ''' cur.execute("DROP TABLE IF EXISTS test") ''' CREATE TABLE() to create a table ''' cur.execute(""" CREATE TABLE test ( id INTEGER PRIMARY KEY, string TEXT, number INTEGER ) """) print('insert row') cur.execute(""" INSERT INTO test (string, number) VALUES ('one', 1) """) print('insert row') cur.execute(""" INSERT INTO test (string, number) VALUES ('two', 2) """) print('insert row') cur.execute(""" INSERT INTO test (string, number) VALUES ('three', 3) """) print('commit') ''' to save the table use commit() ''' db.commit() print('count') ''' SELECT COUNT find the number of products ''' cur.execute("SELECT COUNT(*) FROM test") count = cur.fetchone()[0] print(f'there are {count} rows in the table.') print('read') for row in cur.execute("SELECT * FROM test"): print(row) print('drop') cur.execute("DROP TABLE test") print('close') db.close() if __name__ == '__main__': main()
true
c36f8e781595c203ef9503cda1e9819e668abe22
shumeiberk/Election-Analysis
/python_practice.py
2,953
4.1875
4
# print("Hello World") # print(type(3)) # print(type(True)) # voting_data = [] # voting_data.append({"county":"Arapahoe", "registered_voters": 422829}) # voting_data.append({"county":"Denver", "registered_voters": 463353}) # voting_data.append({"county":"Jefferson", "registered_voters": 432438}) # print(voting_data) # # How many votes did you get? # my_votes = int(input("How many votes did you get in the election? ")) # # Total votes in the election # total_votes = int(input("What is the total votes in the election? ")) # # Calculate the percentage of votes you received. # percentage_votes = (my_votes / total_votes) * 100 # print("I received " + str(percentage_votes)+"% of the total votes.") # counties = ["Arapahoe","Denver","Jefferson"] # if counties[1] == 'Denver': # print(counties[1]) # temperature = int(input("What is the temperature outside? ")) # if temperature > 80: # print("Turn on the AC.") # else: # print("Open the windows.") # #What is the score? # score = int(input("What is your test score? ")) # # Determine the grade. # if score >= 90: # print('Your grade is an A.') # else: # if score >= 80: # print('Your grade is a B.') # else: # if score >= 70: # print('Your grade is a C.') # else: # if score >= 60: # print('Your grade is a D.') # else: # print('Your grade is an F.') # # What is the score? # score = int(input("What is your test score? ")) # # Determine the grade. # if score >= 90: # print('Your grade is an A.') # elif score >= 80: # print('Your grade is a B.') # elif score >= 70: # print('Your grade is a C.') # elif score >= 60: # print('Your grade is a D.') # else: # print('Your grade is an F.') # counties = ["Arapahoe","Denver","Jefferson"] # if "El Paso" in counties: # print("El Paso is in the list of counties.") # else: # print("El Paso is not the list of counties.") # if "Arapahoe" in counties and "El Paso" in counties: # print("Arapahoe and El Paso are in the list of counties.") # else: # print("Arapahoe or El Paso is not in the list of counties.") # if "Arapahoe" in counties or "El Paso" in counties: # print("Arapahoe or El Paso is in the list of counties.") # else: # print("Arapahoe and El Paso are not in the list of counties.") x = 0 while x <= 5: print(x) x = x + 1 counties = ["Arapahoe","Denver","Jefferson"] for county in counties: print(county) numbers = [0, 1, 2, 3, 4] for num in numbers: print(num) for num in range(5): print(num) for i in range(len(counties)): print(counties[i]) counties_dict = {"Arapahoe": 422829, "Denver": 463353, "Jefferson": 432438} for county in counties_dict: print(county) for county in counties_dict.keys(): print(county) for voters in counties_dict.values(): print(voters) for county in counties_dict: print(counties_dict[county])
true
89278ae5660b4c63bfef73dc9f0eaab4b9bbff62
haynes1/python-datastructures
/product.py
304
4.21875
4
def multiply(a,b): product = 0 if b < 0: a = multiply(a,-1) b = abs(b) for i in range(0,b): product = product + a return product print "multiply 2 * 3 ", multiply(2,3) print "multiply -2 * 3", multiply(-2,3) print "multiply 2 * -3", multiply(2,-3) print "multiply -2 * -3", multiply(-2,-3)
true
54bd12e727969f2e4ee9754c9a0a7d27f9feac91
necrospiritus/Python-Working-Examples
/P11-Factorial Function/Factorial Function.py
286
4.40625
4
#Factorial Function - Burak Karabey def factorial_function(): number = int(input("Enter the number: ")) i = 1 factorial = 1 while i <= number: factorial = factorial * i i += 1 return print("{}! = {}".format(number, factorial)) #USAGE factorial_function()
true
51286499c8aa00670d9c6e4b1e012dce2a9ee171
necrospiritus/Python-Working-Examples
/P20-Stack Abstract Data Type/Stack - Reverse Stack.py
825
4.28125
4
"""Reverse stack is using a list where the top is at the beginning instead of at the end.""" class Reverse_Stack: def __init__(self): self.items = [] def is_empty(self): # test to see whether the stack is empty. return self.items == [] def push(self, item): # adds a new item to the base of the stack. self.items.insert(0, item) def pop(self): # removes the base item from the stack. return self.items.pop(0) def peek(self): # return the base item from the stack. return self.items[0] def size(self): # returns the number of items on the stack. return len(self.items) s = Reverse_Stack() print(s.is_empty()) s.push(4) s.push("Dog") print(s.peek()) s.push("Cat") print(s.size()) print(s.is_empty()) s.pop() print(s.peek()) print(s.size())
true
ca7b889cc7e389dd81f88edd4823717a3721cfed
seddap/LPTHW
/ex11.py
532
4.28125
4
#Exercise 11: Asking Questions print ("How old are you?", end =' '), age = input() print ("How tall are you?", end =' '), height = input() print ("How much do you weigh?", end = ' '), weight = input() print ("Give me number:", end = ' ') number = int(input()) #gets number as string and converts it to int print ("So you're {} old, {} tall and {} heavy.".format(age, height, weight)) print ("Your number was {}.".format(number)) #for python2: raw_input for accepting strings as an input. #input takes expression and does an eval
true
1a9a23fc5d161152b3dc8a99d124d77cc5b672c4
git123hub121/Python-basickonwledge
/函数和控制流/for循环.py
219
4.15625
4
#for i in range(1,5) <==> 遍历1,2,3,4 <==> for(i=1;i<5;i++) for i in range(1,5) print(i) else: print('我是可选的') #list(range(5)) => [0,1,2,3,4] #python中的for相当于其他语言中的foreach
false
1fb48b20102a716f2731866000ebfb1efe9b462b
lightningholt/CodeSignalPortfolio
/Arcade/Intro/IslandOfKnowledge/areEquallyStrong.py
594
4.15625
4
def areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight): ''' Two arms are equally strong if they can lift the same weight. Evaluate if you and your friends arms are equally strong given the max weight they can all lift. ''' yourArms = [yourLeft, yourRight] if yourLeft == friendsLeft: if yourRight == friendsRight: return True else: return False elif yourLeft == friendsRight: if yourRight == friendsLeft: return True else: return False else: return False
false
6a795e0e3e4eaff44d3b5dc88e7f4046436a58e1
roderickyao/Projects
/Python/Numbers/fibonacci.py
376
4.21875
4
number = 8 def fibonacci(number): if number < 2: raise ValueError("Number has to larger than 2.") n1, n2 = 1, 1 sum = 0 print(n1, n2, end=' ') while sum < number: sum = n1 + n2 if sum > number: raise ValueError("Does not have Fibonacci sequence match exactly to that number.") print(sum, end=' ') n1 = n2 n2 = sum fibonacci(number)
true
6358f5c54d79d21147559e2bff038b85adfb27fc
NCBS-students/Workshop2017
/material/Python/day1_find_prime_numbers.py
1,643
4.25
4
# Following code finds prime number in first 100 positive integer. Whatever # is written after "#" is called comment and will NOT be executed by # compiler. We will use these comments to explain our logic behind every step # Let us understand logic first. # Prime number is any number who is not divisible by 1 and itself. # So if we want to find prime number, we need to check if any number lower than # current number giving reminder as 0 # Mathematically we only need to check till square root of any number. However # for the simplicity, we will check till n-1 element. # We will use range to create list of numbers starting from 1 to 100 As # range will give number excluding last number, we will use 101 as last number for number in range(1, 101): # We will iterate through numbers till we find reminder zero. # We will also create one variable to check if we have found prime number temp_variable = True # Temporary variable, which we will change to false if we find any # number with reminder 0 for i in range(1, number): # Every element will be divisible by 1, hence we have to exclude 1 if number % i == 0 and i != 1: # Change value of tem variable temp_variable = False # Given number is not prime. Break the second for loop break # Now value of tem_variable will be false if we find any reminder as 0 # Hence if temp_variable is still True, then we have found prime number # Also we need to exclude 1 because 1 is not a prime number if temp_variable and number != 1: print(str(number) + " is a prime number")
true
98e11c0d0772f0a1f08b939cef63e9f98c6b6f98
AnabelCarmen/Python
/Comparacionnumeros.py
491
4.15625
4
#!/usr/bin/env pyhton # __*__ coding:utf-8 __*__ def main(): print("COMPARADOR DE NÚMEROS") numero_1 = float(input("Escriba un número: ")) numero_2 = float(input("Escriba otro número: ")) if numero_1 > numero_2: print("Menor: {1} Mayor: {0}".format(numero_1,numero_2)) elif numero_1 < numero_2: print("Menor: {0} Mayor: {1}".format(numero_1,numero_2)) else: print("Los dos números son iguales.") if __name__ == "__main__": main()
false
ffcc1df0e245da05b3cf4f9b09dbf1ba67ce1b9c
AnkitaDeshmukh/Importing-data-in-python-part2
/diving deep into the twitter API/Plotting your Twitter data.py
1,014
4.1875
4
#Now you have the number of tweets that each candidate was mentioned in, #you can plot a bar chart of this data. use the statistical data visualization library seaborn # You'll first import seaborn as sns. You'll then construct a barplot of the data using sns.barplot, #passing it two arguments: #a list of labels and #a list containing the variables you wish to plot (clinton, trump and so on.). #Import both matplotlib.pyplot and seaborn using the aliases plt and sns, respectively. #Complete the arguments of sns.barplot: the first argument should be the labels to appear on the x-axis; #the second argument should be the list of the variables you wish to plot, as produced in the previous exercise. # Import packages import matplotlib.pyplot as plt import seaborn as sns # Set seaborn style sns.set(color_codes=True) # Create a list of labels:cd cd = ['clinton', 'trump', 'sanders', 'cruz'] # Plot histogram ax = sns.barplot(cd, [clinton, trump, sanders, cruz]) ax.set(ylabel="count") plt.show()
true
b6a2a488c6b408b1e12b7a15e6bc79eeadb622bf
daemonyj/cic
/exercises/CI/linting/resources/src/operations.py
1,398
4.1875
4
""" Calculator operations - module containing classes to perform the mathematical operations provided through a calculator. """ from abc import ABC, abstractmethod class Operation(ABC): """ Abstract class defining required interface for calculator operations """ def __init__(self, value): self.value = value def __string__(self): """ :return: A description of the instance :rtype string: """ return f"{self.operation()} {self.value}" @abstractmethod def apply(self, running_total): """ Interface method for applying an operation to a given valuee """ @abstractmethod def operation(self): """ Interface method to declare the operation """ class AddOperation(Operation): """ Class used to apply addition operations """ def apply(self, running_total): """ Apply this add operation to the given value :param running_total: The value to which the operation should be applied :type running_total: int :return: the result having applied the operation :rtype :int """ return running_total + self.value def operation(self): """ Operation applied by this class of operation :return: the operation :rtype: string """ return "+"
true
cc55d0d14b1e5f9b302ad48fec07c807316a2e0c
zeeshan-akram/Python-Code
/exercise 6.py
363
4.28125
4
weight = float(input("Enter weight: ")) unit = input("Kg or Lbs? ").lower() kilogram = 'kg' pounds = 'lbs' if unit == kilogram: result = weight / 0.45 result = round(result, 2) unit = 'Lbs' elif unit == pounds: result = weight * 0.45 unit = 'Kg' else: print("You entered wrong unit!") print(f'Your weight is: {result} {unit}')
true
5e3ac49a65d7e562ab4ec1479ca66455775d9c5d
zeeshan-akram/Python-Code
/program 6 formatted strings.py
423
4.28125
4
first_name = input("Enter your first name: ") last_name = input("Enter your second name: ") print(f"Your full name is: {first_name} {last_name}") conformation = input('do you have middle name? ').lower() if conformation == 'yes': middle_name = input("Enter middle name as well: ") print(f'''ok! Your full name is : {first_name} {middle_name} {last_name} Registered.''') else: print("ok! thank you.")
true
f81f735b36a8bde8a9686ccb76440bd072882a00
obabawale/pytricks
/isogram.py
440
4.21875
4
# Check if the word is an isogram import collections def main(word): """Check if Word is an isoggram or not""" word_count = collections.Counter(word) for item in word_count.items(): if item[1] > 1: print(f"{word} is not an isogram!") break else: print(f"Yippee... {word} is an isogram") if __name__ == "__main__": word = input("pls supply a word: \n") main(word=word)
true
5938ccad9fef649a6daa799870c1587443e7e5c9
AmaniEzz/SOLID-principles-Python
/Dependency Inversion/DIP_after.py
828
4.25
4
from abc import ABC, abstractmethod # define a common interface any food should have and implement class Food(ABC): @abstractmethod def bake(self): pass @abstractmethod def eat(self): pass class Bread(Food): def bake(self): print("Bread was baked") def eat(self): print("Bread was eaten") class Pastry(Food): def bake(self): print("Pastry was baked") def eat(self): print("Pastry was eaten") class Production: def __init__(self, food: Food): # food now is any concrete implementation of abstract class Food self.food = food # this is also dependnecy injection, as it is a parameter not hardcoded def produce(self): self.food.bake() def consume(self): self.food.eat()
true
5928e226eaf690d6b0dd1794069944e4d9d27e61
shakibul07/com411
/basics/output/if_elif_else.py
697
4.46875
4
print(" Which direction should I paint (up, down, left or right )") #asking user for input directions = input() #starting if statement #this is for upward direction if directions == "up" : print(" I am printing in the upward direction! ") #this is for downward direction elif directions == "down": print(" I am printing in the downward direction! ") #this is for left side direction elif directions == "left": print(" I am painting leftside direction! ") #this is for right direction elif directions == " right": print(" I am painting rightside directions!" ) #if user give invaild directions else: print(" Invalid direction. Give direction ( up , down , right , left ")
true
4f109e093c783a514ec4fffc7c6a886f88415396
shakibul07/com411
/basics/practice/c4.py
211
4.125
4
insum = int(input("How many numbers should i sum up")) num = 0 sum = 0 while num < insum : num += 1 print(f"please enter number {num} of {insum} ..") numb = int(input()) sum += numb print(sum)
true
c903c1570a68b8e0a363f777ed71aaa32af854ba
shakibul07/com411
/basics/output/nesting.py
540
4.125
4
#Ask user for sequence and marker print("Please enter a sequence: ") sequence = input() print("Please enter the charecter for the marker: ") marker = input() #find markers marker1_position = -1 marker2_position = -1 for position in range (0, len(sequence), 1): letter = sequence[position] if letter == marker: if (marker1_position == -1): marker1_position = position else: marker2_position = position print(f"The distance between the marker is {marker2_position - marker1_position - 1}.")
true
4da72088262688bd52292bb28a6bc2465cd0b918
taras193/pythonhomework
/Classwork 07.05.py
1,972
4.15625
4
# #1 # def avr(*args): # average=sum(args)/len(args) # return average # print(avr (4, 8, 8, 3)) #2. Написати функцію, яка повертає абсолютне значення числа # def abs(num): # if num >=0: # return num # else: # return -num # print(abs(-7)) #3 # def maximum_number (x, y): # """This function shows which argument is bigger""" # if x>y: # return x # else: # return y # print (maximum_number(3, 7)) # print (maximum_number.__doc__) #4 # PI=3.14 # t=input(int("""Enter please a number of figure you want to calcute: # 1:triangle # 2:square # 3:circle""")) # def triangle_area(a, h): # a=float(input('input base')) # h=float(input('input high')) # a=0.5*a*h # print ("Triangle are is ={}" .format (0.5*a*h)) # def square_area(x,y): # a=a*b # return a # def circle_area(r) # a=PI * r**2 # return a # def area(t) # if t=1: # triangle_area() # elif: t=2 # square_area() # elif: t=3 # circle_area() # 5. Написати функцію, яка обчислює суму цифр введеного числа. # numbers = input("Please enter your number:\n") # def sumval (a): # x = 0 # for num in a: # x += int(num) # return x # print("Sum of numbers: "+str(sumval(numbers))) # 6. Написати програму калькулятор, яка складається з наступних функцій: # головної, яка пропонує вибрати дію та додаткових, які реалізовують вибрані дії, калькулятор працює доти, поки ми не виберемо дію вийти з калькулятора, після виходу, користувач отримує повідомлення з подякою за вибір нашого програмного продукту!!! TO DO
false
4cd1af78903cac839291ca5865ff94b126fb2922
CodeSlayer10/school
/school1.py
455
4.21875
4
Ticket_Price = 42 Glasses3D_Price = 5 def Total_Price_Calculator(Ticket_Amount, Glasses3D_Amount): return Ticket_Price*Ticket_Amount+Glasses3D_Price*Glasses3D_Amount ticket_requested_amount = int(input("Enter Number of tickets: ")) glasses3d_requested_amount = int(input("Enter Number of 3D glasses: ")) total_cost = Total_Price_Calculator(ticket_requested_amount, glasses3d_requested_amount) print("your total cost will be {}".format(total_cost))
true
aa53cc27d87b21d9c7f5db722992a03f2f2d5a8d
heyitshelina/HELINA-GWC-2018
/survey.py
2,121
4.1875
4
import json #friends = { # "Tasfia": 16, #"Mo": 16, #} #friendAge = friends["Mo"] #print (friendAge) #user = {} #user['Diana'] = 30 #print (user) #user['Amy'] = 27 #print (user) # TODO Part I: Add your survey questions to this empty list. survey = [ "What is your favorite color?", "How old are you?", "Who is your favorite artist/band?", "What is your favorite food?", "What is your favorite sport?" ] # TODO Part I: store the related keys corresponding to the survey answers here. keys = [ "color", "age", "music", "food", "sport" ] # Create a list that will store each person's individual survey responses. # Use for Part II. list_of_answers = [] # Creates the dictionary to store responses. while True: answers = {} for i in range(len(survey)): response = input(survey[i] + " ") answers[keys[i]] = response list_of_answers.append(answers) print ("Are there more users?") user_input = input() if user_input == "no": print("Okay thanks!") break # TODO Part I: write code that asks each survey question and prompts the user for a response. # Hint: how can you go through each element of a list? # Print the context of the dictionary. print(list_of_answers) """ This code should be pasted after the code you have previously written! Do NOT delete your older code!!!! Before running this code, be sure to open a new Atom file. Make the file contain only [] and save it as allanswers.json. """ # Open the file containing all past results and append them to our current list. f = open("allanswers.json", "r") olddata = json.load(f) list_of_answers.extend(olddata) f.close() # Reopen the file in write mode and write each entry in json format. f = open("allanswers.json", "w") f.write('[\n') index = 0 for t in list_of_answers: if (index < len(list_of_answers)-1): json.dump(t, f) f.write(',\n') else: json.dump(t, f) f.write('\n') index += 1 f.write(']') f.close()
true
d4d71f74caf95bc7f5956453a5180b3863951f50
bforman/Generating-map-using-BaseMap-and-querying-the-MSD-via-hdf5_getters
/buildWorldMap.py
1,019
4.1875
4
""" Program: buildWorldMap.py Author: Benjamin Forman Description: this script utilizes matplotlib and the basemap package it provides to users. The script produces a map of the world and displays different ways of customizing the map and adding value and detail where desired. pyplot, another package of matplotlib, is used to display the map. """ import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.basemap import Basemap #create the map object #'robin' setting displays map laid out, 'ortho' displays world as a globe map = Basemap(projection='robin', lat_0=0, lon_0=-100, resolution='l', area_thresh=1000.0) #drawcoastlines() and drawcountries() produce sharper lines on the image map.drawcoastlines() map.drawcountries() #map.fillcontinents(color='coral') map.bluemarble() map.drawmapboundary() #drawmeridians and drawparallels places lat and long lines on the map map.drawmeridians(np.arange(0,360,30)) map.drawparallels(np.arange(-90,90,30)) plt.show() ~
true
e400321d0dadaf48afe994f2e18bcb8db65f2642
Aluriak/24hducode2016
/src/visualisation/distance.py
862
4.125
4
""" Computes distances between two points from their Gmap coordinates """ from math import radians, cos, sin, asin, sqrt def distance_gps(coordinates_A, coordinates_B): """ Input: two tuples of coordinates (longitude, latitude) Output: distance between the two points """ lon1 = coordinates_A[0] lat1 = coordinates_A[1] lon2 = coordinates_B[0] lat2 = coordinates_B[1] # convert decimal degrees to radians lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) # haversine formula dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2 c = 2 * asin(sqrt(a)) r = 6371 # Radius of earth in kilometers. Use 3956 for miles return c * r # Usage example # test = distance_gps((-0.0693341, 47.6971825), (0.24142796, 47.9908779)) # print(test)
true
b0541487fcfa71828e341258046b1062e858f92e
Angkirat/MachineLearningTutorial
/PythonCode/TensorflowCode/TFKeras_Mnist.py
2,222
4.4375
4
#!/Library/anaconda3/envs/MachineLearning/bin/python """ Copyright 2019 The TensorFlow Authors. This is a modified piece of code copied from the Tensorflow learning link: https://www.tensorflow.org/overview/ This is a documented Hello world program for Tensorflow beginners. It uses the MNIST data to show how to build a sequential categorical model using Tensorflow Keras. v0.1 - Sequential Model with acc ~98% """ __author__ = "TensorFlow Authors, Angkirat Sandhu" __source__ = \ "https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/quickstart/beginner.ipynb" __version__ = 0.1 __license__ = "Apache License, Version 2.0" __email__ = "angkirat@gmail.com" __status__ = "Prototype" __maintainer__ = "Angkirat Sandhu" # Importing the required packages import tensorflow as tf # Loading MNIST dataset from the Keras package. The data(both x and y) is split into train and test sets. `x` # variables are normalized by dividing the whole set with 255(maximum integer value that can be held in grayscale # images) to bring the data in the range of 0-1. mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 print("Training Set count {}".format(x_train.shape[0])) print("Testing Set Count {}".format(x_test.shape[0])) # Creating a Keras sequential model with a single hidden layer of 128 neurons and one dropout layer. # The input layer takes in a np array of size (28,28). # The output layer predicts probability of 10 classes. model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10, activation='softmax') ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # Finally the model is trained using the training set with 5 epoch(periods). # The evaluate function directly shares the accuracy and loss of model over the test set # without sharing the prediction result model.fit(x_train, y_train, epochs=5) loss, Acc = model.evaluate(x_test, y_test) print("Loss value is {} Accuracy is {}".format(loss, Acc))
true
9994631e1c07cc596e28778317931b2e2c7d7a27
sydul-fahim-pantha/python-practice
/tutorials-point/while_loop.py
804
4.15625
4
#!/usr/bin/python3 count = 0 print(">>>>>>>>>>>>>>>> simple count loop started >>>>>>>>>>>>") while count < 9: print('The count is:', count) count+=1 print("Good bye!") print(">>>>>>>>>>>>>>>> simple count loop ended >>>>>>>>>>>>") print("\n\n>>>>>>>>>>>>>>>> break loop started >>>>>>>>>>>>") while True : print("\nWrite \"exit\" to exit") a = str(input("Enter anything:")) print("You entered: ", a) if a == "exit": print("Exiting using if") break print(">>>>>>>>>>>>>>>> break loop ended >>>>>>>>>>>>") print("\n\n>>>>>>>>>>>>>>>> infinite loop started >>>>>>>>>>>>") a = 10 while a != "exit": print("\nWrite \"exit\" to exit") a = str(input("Enter anything:")) print("You entered: ", a) print(">>>>>>>>>>>>>>>> infinite loop ended >>>>>>>>>>>>")
false
a99ed52d627dde9157cf08ec2bac2090343ab10e
sydul-fahim-pantha/python-practice
/tutorials-point/function_advance.py
1,219
4.34375
4
#!/usr/bin/python3 print() print("Function can have four types of argument") print() print("Required argument: def func1(arg1)") print("Invocation: func1(\'value\')") def func1(arg1): print("arg1: ", arg1) return func1("arg") print() print("Keyword argument: def func(id, age, name)") print("Invocation: func(name ='Bla', id = 10, age = 24)") print("NOTE: One can change the order of the argument") def func2(id, age, name): print("id: ", id, " age: ", age, " name: ", name) return func2(name = "Bla", id = 10, age = 24) print() print("Default argument: def func(id = 100)") print("Invocation: func(10) or func()") print("NOTE: If no argument specified the default value == 10 is used") def func3(id = 100): if id == 10: print("using default value id: ", id) else : print("value passed by argument id: ", id) return func3(555) func3() print() print("Variable length argument: def func(*vararg)") print("Invocation: func() or func(10, 20) or func(10,...n)") print("NOTE: the variable is a tuple ") def func4(*items): print("inside var-arg func with argument: ", items) for item in items: print(item) return func4() func4(10) func4(10, 20, 30)
true
f9455199dffae5eb9b11b39cfdbb7611e919c49e
all3n/buildfly
/buildfly/utils/string_utils.py
1,929
4.84375
5
import re def underscore(word): """ Make an underscored, lowercase form from the expression in the string. Example:: >>> underscore("DeviceType") "device_type" As a rule of thumb you can think of :func:`underscore` as the inverse of :func:`camelize`, though there are cases where that does not hold:: >>> camelize(underscore("IOError")) "IoError" """ word = re.sub(r"([A-Z]+)([A-Z][a-z])", r'\1_\2', word) word = re.sub(r"([a-z\d])([A-Z])", r'\1_\2', word) word = word.replace("-", "_") return word.lower() def camelize(string, uppercase_first_letter=True): """ Convert strings to CamelCase. Examples:: >>> camelize("device_type") "DeviceType" >>> camelize("device_type", False) "deviceType" :func:`camelize` can be thought of as a inverse of :func:`underscore`, although there are some cases where that does not hold:: >>> camelize(underscore("IOError")) "IoError" :param uppercase_first_letter: if set to `True` :func:`camelize` converts strings to UpperCamelCase. If set to `False` :func:`camelize` produces lowerCamelCase. Defaults to `True`. """ if uppercase_first_letter: return re.sub(r"(?:^|_)(.)", lambda m: m.group(1).upper(), string) else: return string[0].lower() + camelize(string)[1:] def replace_with_vars_map(string, var_map): for key, value in var_map.items(): string = string.replace("{" + key + "}", str(value)) return string def is_int(sval: str): try: int(sval) except: return False else: return True def is_num(sval: str): """ because str.isnumeric can't detact negative number use exception to detact :param sval:str :return: """ try: float(sval) except: return False else: return True
true
9612e4537295e29f4aa8d0a747b5c21621372d0b
DuaaS-Codes/Arithmetic.py-
/Arithmetic.py
716
4.28125
4
#Author: Duaa #Date: November 19, 2019 #Arithmetic int_numberOne = (int)(input("Enter a number: ")) str_operator = (input("Enter an operator: ")) int_numberTwo = (int)(input("Enter a second number: ")) if str_operator == "/" and int_numberOne == 0 or int_numberTwo == 0: print("The answer is undefined.") elif str_operator == "+": print("The answer is", int_numberOne + int_numberTwo) elif str_operator == "-": print("The answer is", int_numberOne - int_numberTwo) elif str_operator == "*": print("The answer is", int_numberOne * int_numberTwo) elif str_operator == "/": print("The answer is", int_numberOne // int_numberTwo) else: print("Error: That is not a valid operator. Please try again.")
false
df51e06526f6f724eee94c3a5d2b9ff78af25777
ValerieMauduit/46-simple-python-exercises
/srcs/ex07.py
330
4.25
4
'''Define a function reverse() that computes the reversal of a string. For example, reverse("I am testing") should return the string "gnitset ma I".''' def reverse(txt): ''' This function computes the reversal of a string Parameters ---------- txt (string) Returns ---------- The reversed string ''' return txt[::-1]
true
a16177ca7016c260f6b0c2d70a3d8a886a042d5b
ValerieMauduit/46-simple-python-exercises
/srcs/ex10.py
652
4.21875
4
'''Define a function overlapping() that takes two lists and returns True if they have at least one member in common, False otherwise. You may use your is_member() function, or the in operator, but for the sake of the exercise, you should (also) write it using two nested for-loops.''' def overlapping(lst1, lst2): ''' This function returns true if two lists passed as parameters have a least one member in common Parameters ---------- lst1 (list) lst2 (list) Returns ---------- True the two lists shares at least one member in common False otherwise ''' if [i == j for j in lst2 for i in lst1 if i == j]: return True return False
true
62397ed2e4784fd4a6d0b78c6eb4aa3cac6c58bb
Vantime03/Grading-App
/grading_app.py
1,958
4.5
4
''' Lab 3: Grading Let's convert a number grade to a letter grade, using if and elif statements and comparisons. Concepts Covered input, print type conversion (str to int) comparisons (< <= > >=) if, elif, else Instructions Have the user enter a number representing the grade (0-100) Convert the number grade to a letter grade Numeric Ranges 90-100: A 80-89: B 70-79: C 60-69: D 0-59: F Version 2 Find the specific letter grade (A+, B-, etc). You can check for more specific ranges using if statements, or use modulus % to get the ones-digit to set another string to '+', '-', or ' '. Then you can concatenate that string with your grade string. Version 3 Extract the logic used to determine the grade and its qualifier ('+', '-', or ' ') into functions. Additionally, use a while loop to repeatedly ask the user if they'd like to compute another grade after each computation. ''' #functions def sign_func(grade): if grade < 60: return "" remainder = grade % 10 if 0 <= remainder < 5 and grade != 100: sign = "-" elif 5 < remainder or grade == 100 : sign = "+" else: sign = "" return sign #variables letter = "" sign = "" compute_again = True print("Welcome to Grading app!\n") while compute_again is True: grade = int(input("Enter a grade from 1 to 100: ")) if 90 <= grade <= 100: letter = "A" elif 80 <= grade < 90: letter = "B" elif 70 <= grade < 80: letter = "C" elif 60 <= grade < 70: letter = "D" elif 0 <= grade <60: letter = "F" else: print("That number is out of range. Try again!") sign = sign_func(grade) print(f"Your grade is {letter+sign}.") response_play_again = input("\nDo you like to calculate another grade (yes/no)? ").lower() if response_play_again in ["yes", "y"]: compute_again = True else: compute_again = False print("\n***Thank you for using this app!***")
true
be1a74e365c5106c244bbeb226dbc44f32d3f9bd
akmaniatis/Number_Guessing
/main.py
1,383
4.28125
4
# Importing Python libraries import random # End Imports # Global Variables # Computer generating a random number between 0 and 10 ComputerNumber = random.randint(0,10) # Defining the largest number of allowable guesses GuessMax = 3 Win = False Play = True print("Welcome to the Number Guessing Game!\n\n") print("You have " + str(GuessMax) + " guesses for each round") # Looping on game play while Play == True: while GuessMax > 0: PlayerGuess = input("Enter a number between 0 and 10: ") PlayerGuess = float(PlayerGuess) if (PlayerGuess < 0 or PlayerGuess >10): print("Bad input! Only number between 0 and 10 inclusively") break else: if (PlayerGuess > ComputerNumber): print("Your guess was too big!") elif (PlayerGuess < ComputerNumber): print("Your guess was too small!") else: print("You guessed correctly!!!") Win = True break GuessMax = GuessMax-1 print("You have " + str(GuessMax) + " guess left") if Win == True: print("Congratulations! You won at " + str(GuessMax) + " tries") else: print("No more guesses left!") print("The number was: " + str(ComputerNumber)) answer = input("Would you like to play again? Y/N ") if answer == "N" or answer == "n": print("OK. Goodbye!") Play = False else: Win = False GuessMax = 3
true
c3f0ec0d2ff98427838cec8afb1b07346cddd50f
DivijeshVarma/PythonBasics
/variables&datatypes.py
909
4.34375
4
# variable message = "hello divi!" print(message) # seperator print("-------------------") # strings name = 'divijesh varma' print(name.title()) print(name.upper()) print(name.lower()) # seperator print("-------------------") # variables in strings, f-strings, f is format # To insert a variable’s value into a string, place the letter f first_name = "divijesh" last_name = "alluri" full_name = f"{first_name} {last_name}" print(full_name) print(f"hi {full_name.title()}!") message = f"hi {full_name.title()}!" print(message) # seperator print("-------------------") # Adding Whitespace to Strings with Tabs or Newlines print("Languages: \n\tc \n\tpython \n\tjava") # Stripping Whitespace, to eliminate extraneous whitespace from data language = 'python ' print(language.rstrip()) # constants MAX_CONNECTIONS = 5000 print(MAX_CONNECTIONS) # multiple assignment x, y, z = 0, 1, 2 print(x, y, z)
true
5f81e1259ed095fc3fd2e939395ccaa0026ad52f
mryingster/ProjectEuler
/problem_001.py
318
4.15625
4
#!/usr/bin/env python print("Project Euler - Problem 1") print("Find the sum of all the multiples of 3 or 5 below 1000.\n") number = 1 sum = 0 while number < 1000: if number % 3 == 0: sum += number else: if number % 5 == 0: sum += number number += 1 print("Sum: "+str(sum))
true
40259eb130200eddedcfc6aeef5176379062928d
orlandodiaz/CS303E-Python-Problem-Solving-Problems
/A3_Day.py
1,716
4.1875
4
# File: Day.py # Description: Print out the day of the week for that date # Student Name: Orlando Reategui # Student UT EID: or3562 # Course Name: CS 303E # Unique Number: 51635 # Date Created: 2/14/2015 # Date Last Modified: 2/14/2015 def main(): # Check whether the year is between 1900 and 2011 c = 0 #year while (c < 1900) or (c > 2100): c = eval(input("Enter year: ")) # Check whether month is in the range of 1 to 12 a = 0 #month while (a < 1) or (a > 12): a = eval(input("Enter month: ")) # Assign a true/false variable to leap year leap_year = (c % 400 == 0) or ((c % 100 != 0) and (c % 4 == 0)) #Determine the day range that is appropiate for the month b = 0 #day if (a == 2): if (leap_year): while (b < 1) or (b > 29): b = eval(input("Enter day: ")) else: while (b < 1) or (b > 28): b = eval(input("Enter day: ")) else: while (b < 1) or (b > 31): b = eval(input("Enter day: ")) #The century d = c // 100 #The year of the century c = c % 100 #Make adjustments to calendar so that the year begins in Jan and ends in Dec if (a < 3): a = a + 10 c = c - 1 else: a = a - 2 #Algorithm to compute the day of the week. "r" gives the day of the week w = (13 * a - 1) // 5 x = c // 4 y = d // 4 z = w + x + y + b + c - 2 * d r = z % 7 r = (r + 7) % 7 #Assign string names to the actual day of the week values if r == 0: r = "Sunday" if r == 1: r = "Monday" if r == 2: r = "Tuesday" if r == 3: r = "Wednesday" if r == 4: r = "Thursday" if r == 5: r = "Friday" if r == 6: r = "Saturday" #Print the day of the week print("The day is", r) main()
false
322a637f22f36c79da148cf8920045868c79a896
vpagano10/Intro-Python-I
/src/13_file_io.py
1,332
4.46875
4
""" Python makes performing file I/O simple. Take a look at how to read and write to files here: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files """ # Open up the "foo.txt" file (which already exists) for reading # Print all the contents of the file, then close the file # Note: pay close attention to your current directory when trying to open "foo.txt" # open() returns a file object, and is most commonly used with two arguments: # open(filename, mode) # ======== modes can be: ======== # "r" when the file will be only read # "w" for only writing - an existing file with the same name will be erased # "a" opens the file for appending and any data written to the file is automatically added to the end # "r+" opens the file for both reading and writing # adding with -> with open("filename", "mode") so that the file is properly closed when done. # YOUR CODE HERE f = open("foo.txt", "r") for line in f: print(line, end="") # Open up a file called "bar.txt" (which doesn't exist yet) for # writing. Write three lines of arbitrary content to that file, # then close the file. Open up "bar.txt" and inspect it to make # sure that it contains what you expect it to contain # YOUR CODE HERE b = open("bar.txt", "w") b.write("First line \n") b.write("Second line \n") b.write("Third line \n")
true
ebc19b89794caea4a6de92d71096596e43c4e003
Git-Good-Milo/Slither_in_to_python_chapter_3
/exercises.py
1,879
4.375
4
# Question 1 # Assume a population of rabbits doubles every 3 months. How many rabbits after 2 years? Initial population is 11 # First, set up all the required variables initial_number_of_rabbits = 11 pop_growth_rate_months = 3 time_frame_years = 2 # change time frame from years to months time_frame_months = time_frame_years * 12 # create script to calculate the final rabbit population final_population = initial_number_of_rabbits * (time_frame_months // pop_growth_rate_months) # Print answer print(F"The final population is: {final_population}") # Question 2 # Same as question one, except include a user input for the initial number of rabbits and time frame initial_number_of_rabbits = int(input("How many rabbits are there to start? ")) time_frame_years = int(input("How long will you have them? ")) time_frame_months = time_frame_years * 12 # This script should be saved as a function instead so that it can be reusable final_population = initial_number_of_rabbits * (time_frame_months // pop_growth_rate_months) print(F"The final population is: {final_population}") # Question 3 # Assume the user is going to input 2 numbers, x and y for example. Write a Python program that will swap the numbers stored in these variables x = 3 y = 11 u = x v = y y = u x = v print(f"{x} and {y}") # Question 4 # The goal of this task is to derive a single assignment statement for the following sequences such that, if the variable x has the first value in a sequence, then x will have the next value in the sequence after the assignment statement is executed. And if the assignment statement were executed repeatedly, then x would cycle through all of the values in the sequence. # first series: 0 2 4 6 8 x = 0 x = x + 2 # second series: 0 -1 -2 -3 -4 y = 0 y = y -1 # Third series: 6 -6 6 -6 6 -6 z = 6 z = z/-1 # Forth series: 0 3 6 0 3 6 0 3 6 a = 0 a = (a+3) % 9
true
c936f52a26dd93fa4bc091bc3a6d59c4dd2b8e29
lufanx/python_usage_summary
/module/usage_random.py
1,412
4.15625
4
#!/usr/bin/env python import random class Random: """these methods include random, randint, sample, shuffle, choice""" member = 0; def random(self): Random.member += 1 ret = random.random() return ret def randint(self, a, b): #self.a = a #self.b = b Random.member += 1 #ret = random.randint(self.a, self.b) ret = random.randint(a, b) return ret def choice(self, dts): Random.member += 1 ret = random.choice(dts) return ret def sample(self, dts, val): Random.member += 1 ret = random.sample(dts, val) return ret def shuffle(self, dts): Random.member += 1 random.shuffle(dts) return dts def main(): test_random1 = Random() ret = test_random1.random() print (ret) print (test_random1.member) test_random2 = Random() ret = test_random2.randint(4, 10) print (ret) print (test_random2.member) test_random3 = Random() ret = test_random3.choice("hello world") print (ret) print (test_random3.member) test_random4 = Random() ret = test_random4.sample("hello world", 3) print (ret) print (test_random4.member) test_random5 = Random() ret = test_random5.shuffle([3, 5, 7, 9]) print (ret) print (test_random5.member) if __name__ == '__main__': main()
false
66bf61a9c743fb89c506050802c064478ab8e8e1
SchrodengerY/Python-Programming
/Chapter5/C5.py
2,371
4.53125
5
# 文件和异常 # Read It # 读取文件 print("Open and close the file.") text_file = open("read_it.txt","r") text_file.close() print("\nReading characters from the file.") text_file = open("read_it.txt","r") print(text_file.read(1)) print(text_file.read(5)) text_file.close() print("\nReading the entire file at once.") text_file = open("read_it.txt","r") whole_thing = text_file.read() print(whole_thing) text_file.close() print("\nReading characters from a line.") text_file = open("read_it.txt","r") print(text_file.readline(1)) print(text_file.readline(5)) text_file.close() print("\nReading one line at a time.") text_file = open("read_it.txt","r") print(text_file.readline()) print(text_file.readline()) print(text_file.readline()) text_file.close() print("\nReading the entire file into a list.") text_file = open("read_it.txt","r") lines = text_file.readlines() print(lines) print(len(lines)) for line in lines: print(line) text_file.close() print("\nLooping through the file, line by line.") text_file = open("read_it.txt","r") for line in text_file: print(line) text_file.close() # 写入文本 print("Creating a text file with the write() method.") text_file = open("write_it.txt","w") text_file.write("Line 3\n") text_file.write("This is Line 2\n") text_file.write("That makes this Line 1\n") text_file.close() text_file = open("write_it.txt","r") print("\nReading the newly created file.") print(text_file.read()) text_file.close() # pickle it # 演示数据的序列化处理(pickle和shelve) import pickle, shelve print("Pickling lists.") variety = ["sweet", "hot", "dill"] shape = ["whole", "spear", "chip"] brand = ["Claussen", "Heinz", "Vlassic"] print(variety) print(shape) print(brand) f = open("pickles1.dat", "wb") pickle.dump(variety,f) pickle.dump(shape,f) pickle.dump(brand,f) f.close() print("\nUnpickling lists.") f = open("pickles1.dat","rb") variety = pickle.load(f) shape = pickle.load(f) brand = pickle.load(f) print(variety) print(shape) print(brand) f.close() # 使用shelf print("\nShelving lists.") s = shelve.open("pickle2.dat") s["variety"] = ["sweet","hot","dill"] s["shape"] = ["whole","spear","chip"] s["brand"] = ["Claussen","Heinz","Vlassic"] s.sync() print("\nRetrieving lists from a shelved file:") print("brand -",s["brand"]) print("shape -",s["shape"]) print("variety -",s["variety"]) s.close()
true
4ffc62c5492842ff6ddbebc1cf58d3718c913a78
pboonupala/day-3-roller-coaster
/main.py
292
4.1875
4
#Write your code below this line 👇 print("Welcome to the rollercoaster program") height = int(input("Please input your height")) age = int(input("Please input your age")) bill = 0 if height >= 120: if age < 12: bill += 5 else: print("Sorry, you have to grow taller to ride this.")
true
d546fe562e62d92bd2cde6b14d2926de629cdbae
sdixit03/calc
/calc.py
1,026
4.125
4
print("1. Addition"); print("2. Subtraction"); print("3. Multiplication"); print("4. Division"); try: print("Enter first value:") num1 = float(input()) val = float(num1) except ValueError: print("No.. input string is not an Integer. It's a string") exit(); try: print("Enter second value:") num2= float(input()) val = float(num2) print("Processing..!!") except ValueError: print("No.. input string is not an Integer. It's a string") exit(); choice = float(input("Enter your choice: ")); if(choice==1 or choice==2 or choice==3 or choice==4): if choice == 1: res = num1 + num2; print("Result = ", res); elif choice == 2: res = num1 - num2; print("Result = ", res); elif choice == 3: res = num1 * num2; print("Result = ", res); elif choice == 4: if(num2==0): print("Error: Division by zero!!!!!!"); else: res = num1 / num2; print("Result = ", res); else: print("Wrong input..!!");
true
87516085c69415f5489425684d35a91daf862a7e
Viren-Patil/PPL_Assignments_2020
/Python/Program8.py
1,137
4.125
4
'''Computers usually solve square systems of linear equations using the LU decomposition. Write a program to compute LU decomposition.''' import sys def lu(a, n) : l = [[0 for x in range(n)] for y in range(n)] u = [[0 for x in range(n)] for y in range(n)] for i in range(n): for k in range(i, n): sum_l = 0 for j in range(i): sum_l += (l[i][j] * u[j][k]) u[i][k] = a[i][k] - sum_l for k in range(i, n): if k == i: l[k][k] = 1 else: sum_u = 0 for j in range(i): sum_u += (l[k][j] * u[j][i]) l[k][i] = (a[k][i] - sum_u) // u[i][i] print_mat(l, u, n) def print_mat(l, u, n) : print('Lower triangular matrix :') for i in range(n) : for j in range(n) : print(str(l[i][j]), end = '\t') print('\n') print('Upper triangular matrix :') for i in range(n) : for j in range(n) : print(str(u[i][j]), end = '\t') print('\n') if __name__ == '__main__' : n = int(input('Enter the order of the matrix : ')) print('Enter the matrix A :') a = [[0 for x in range(n)] for y in range(n)] for i in range(n) : for j in range(n) : a[i][j] = (int(input())) lu(a, len(a))
false
1a81ee7f39faa01e1ebd045190ca06ad49ab75c6
jon-jacky/Piety
/samples/writer.py
2,798
4.40625
4
""" writer.py - write to files to demonstrate interleaving concurrency. Defines class Writer, with a method that writes a single line to the end of a file. By default, this line contains the file name and a timestamp. A different function to generate the line in some other form can be passed as an optional argument to the constructor. Multiple Writer instances can run concurrently, with the output of each displayed in its own window. """ import datetime class Writer(object): """ Write to files to demonstrate interleaving concurrency. The method write() writes a single line to the end of a file. Schedule calls to write() on a recurring event, such as a periodic timeout. View the growing file in a terminal window with tail -f. Multiple Writer instances can run concurrently, with the output of each displayed in its own window. Each Writer instance includes a sequence number attribute, seqno, that counts the calls to its write(). """ fileno = 0 # used to generate default filenames def __init__(self, fname=None, makeline=None): """ Creates a Writer instance and opens its file for writing. fname - optional argument, the name of the file to write. Otherwise Writer generates a unique name of the form file_N.txt, where N is a small decimal integer. The file is opened in 'a' append mode (so opening the same name multiple times can make that file bigger, it doesn't start over). makeline - optional argument, the function to generate the line of text to write. Otherwise Writer uses self.default_makeline defined here. """ self.seqno = 0 self.fname = fname if fname else 'file_%d.txt' % Writer.fileno self.makeline = makeline if makeline else self.default_makeline self.f = open(self.fname, 'a') Writer.fileno += 1 def default_makeline(self, seqno, fname): """ generates a line from the sequence number seqno, the filename fname, and also a new timestamp, for example: 5 file_2.txt 2013-07-13 11:32:42.231009 """ return '%6d %s %s\n' % (seqno, fname, datetime.datetime.now()) def write(self): """ writes a single line to the end of a file, flushes the file so the line appears immediately, increments the sequence number. """ s = self.makeline(self.seqno, self.fname) self.f.write(s) self.f.flush() self.seqno += 1 def close(self): """ closes the file """ return self.f.close() # Test def main(): w = Writer(fname='w.txt') for i in range(10): w.write() print('See output in w.txt') if __name__ == '__main__': main()
true
32f3825aaa61b554709071ff172ece044a1e408d
ParshutinRoman/Class
/Class.py
2,958
4.1875
4
meat = 0 class Animals(): """Class to create an animal""" def __init__(self, name, weight, ration, voice): """initiate new animal""" self.name = name self.weight = weight self.ration = ration self.voice = voice def show_animal(self): """Prints all info about this animal""" info = ("Name is: " + self.name + " weight is: " + str(self.weight) + " ration is " + str(self.ration) + " of forage") print(info) def says (self): print(self.name + "says" + self.voice + "twice") class Birds(Animals): """Class to create a bird""" def __init__(self, name, weight, ration, voice, egg): """initiate new bird""" super().__init__(name, weight, ration, voice) self.egg = egg class HornedCattle(Animals): """Class to create a bird""" def __init__(self, name, weight, ration, voice, milk): """initiate new bird""" super().__init__(name, weight, ration, voice) self.milk = milk class Cattle(Animals): """Class to create a bird""" def __init__(self, name, weight, ration, voice, wool): """initiate new bird""" super().__init__(name, weight, ration, voice) self.wool = wool sheep1 = Cattle("Барашек", 87, 8, "бееее", 2.5) sheep2 = Cattle("Кудрявый", 95, 11, "бееее", 3) goose1 = Birds("Серый", 4.5, 1, "Гага", 1) goose2 = Birds("Белый", 3, 0.7, "Гага", 1) cow = HornedCattle("Манька", 170, 15, "Муууу", 5) goat1 = HornedCattle("Рога", 60, 11, "Мееее", 3) goat2 = HornedCattle("Копыта", 65, 9, "Меее", 3.5) chicken1 = Birds("Ко-Ко", 3, 0.5, "КоКО", 5) chicken2 = Birds("Кукареку", 2.5, 0.5, "КоКО", 4) duck = Birds("Кряква", 3.4, 0.5, "КряКря", 1) animals = (sheep1, sheep2, goat2, goat1, goose1, goose2, cow, chicken1, chicken2, duck) forage = 1000 meat = 0 milk = 0 eggs = 0 wool = 0 def heaviest_animal(): max_weight = 0 champion_name = "..." for animal in animals: if animal.weight > max_weight: max_weight = animal.weight champion_name = animal.name print("Самое тяжелое животное - " + champion_name + ", который весит " + str(max_weight)) def total_weight(): total_weight = 0 for animal in animals: total_weight += animal.weight print("Общий вес обитателей фермы - " + str(total_weight)) def feed_animal(): """Spend some forage""" forage = 1000 for animal in animals: forage -= animal.ration animal.weight += animal.ration / 20 print(forage) goat2.show_animal() goat2.show_animal() print(sheep1.weight) print(animals) heaviest_animal() total_weight() feed_animal() total_weight()
false
529b44a9066658309065e59bdb29a40722286007
deep-adeshraa/array-kit
/move_nagatives_2.py
608
4.21875
4
# ? https://www.geeksforgeeks.org/rearrange-positive-and-negative-numbers/ # Rearrange positive and negative numbers with constant extra space # Given an array of positive and negative numbers, arrange them such that all negative integers appear before all the positive integers in the array without using any additional data structure like hash table, arrays, etc. The order of appearance should be maintained. # Examples: # Input: [12 11 -13 -5 6 -7 5 -3 -6] # Output: [-13 -5 -7 -3 -6 12 11 6 5] def move_nagatives(arr): pass arr = [12, 11, -13, -5, 6, -7, 5, -3, -6] print(move_nagatives(arr))
true
06a7f11a5cec991f34e88710ea4de3fc172e93dd
volodymyr-1/ARZP
/birsdays.py
471
4.25
4
birthdays = {'Bob': '18 nov', 'Sveta': '8 oct', 'Kristina': '13 june'} while True: print('Enter a name: (blanc to quit)') name = input() if name == '': break if name in birthdays: print(birthdays[name], ' is the birthday of ', name) else: print('I don\'t have information of ' + name) print('What is their birthday?') bday = input() birthdays[name] = bday print('Birthdays database updated!')
true
96df71545f7733d80686dc898626f805faa81235
miichy/python_repo
/base_one/str_op.py
731
4.28125
4
#!/usr/bin/python #string operate ### wrong #v = '2' - '1' #print v #a = 'eggs'/'easy' #print a #b = 'third' * 'a charm' #print b ### f = 'hello' b = 'world' print f + b var1 = 'hello world' var2 = 'python programming' print "var1[0]: ",var1[0] print "var2[1:5]: ",var2[1:5] print "updated string :- ",var1[:6] + "python" print "My name is %s and weight is %d kg!" % ('Zara', 21) para_str = """this is a long string that is made up of several lines and non-printable characters such as TAB ( \t ) and they will show up that way when displayed. NEWLINEs within the string, whether explicitly given like this within the brackets [ \n ], or just a NEWLINE within the variable assignment will also show up. """ print para_str;
true
ddc4e50c2091f45e61e437de0b43c7c5b757b38d
rakeshchauhan0007/lab2
/condition.py/q_5.py
212
4.125
4
""" game finding a secret number within 3 attempts using while loop for i in range(5): if i==3: break print(i) """ guess = int(input('guess number:')) i = 3 while i==3: break print(i)
false
3de7c4d3339e9e090a8286288918aadb3be893a6
rakeshchauhan0007/lab2
/condition.py/q_2.py
369
4.28125
4
""" if the temperature is greater then 30, its a hot day otherwise if its less then 10: its a cold day; otherwise its neither hot not cold """ temperature = int(input('temperature:')) cold_day = 10 > temperature hot_day = 30< temperature if cold_day: print(f' its a old day') elif hot_day: print(f'its a hot day') else: print(f'its neither hot nor cold')
true
e414e5c826b30860960ddd9deeed033db24b971e
Gulks/Simple-Games
/check_phrases.py
623
4.375
4
import re from time import sleep def reverse(a): """Reverses the phrase. Excludes all the symbols except for the letters and makes them in lower case.""" a = re.sub("[^A-Za-z]", "", a) a = a.lower() return a[::-1] def is_palindrome(a): return a == reverse(a) phrase = input("Enter a phrase and I'll check if it is a palindrome: ") phrase = re.sub("[^A-Za-z]", "", phrase) phrase = phrase.lower() if (is_palindrome(phrase)): sleep(1) print("Yes, your phrase is a palindrome.") else: sleep(1) print("No, your phrase isn't a palindrome.")
true
827097e041057a830241b5bc8f6526f640930d35
IngridFanfan/python_course
/function/recursive.py
458
4.28125
4
#Recursive function #factorial #fact(n) = n x fact(n-1) def fact(n): if n==1: return 1 return n * fact(n - 1) #Take care to prevent stack overflow: Tail recursion #Tail recursion is when a function calls itself when it returns, and the return statement cannot contain an expression. def fact(n): return fact_iter(n, 1) def fact_iter(num, product): if num == 1: return product return fact_iter(num - 1, num * product)
true
c1199fbc50a4ffb1a9d31faa36347af554072927
Mpanshuman/Oretes_test-19-02-21-
/Q6.py
811
4.125
4
import re sentence = input('Enter The Sentence:') output = '' # condition to check any special character special_character_check = re.compile('[@_!#$%^&*()<>?/\|}{~:.]') # condition to check any small character small_character_check = re.compile('[a-z]') # condition to check any capital character capital_character_check = re.compile('[A-Z]') # condition to check any digits digit_check = re.compile('[0-9]') list_compile = [special_character_check,small_character_check,capital_character_check,digit_check] # find all the matching conditions and appending the results to a list matches = [] for r in list_compile: matches += re.findall( r, sentence) if __name__ == "__main__": for characters in matches: output+=characters print(output+str(len(re.findall("[ \s]+", sentence))))
true
ae9c551f98c10c057b788259916c9cfb361fe4e4
alikomurcu/ali-burkan-projects
/search method.py
951
4.25
4
# Here is the find the biggest value. def Search_method (values, l, r): # check whether len of array is bigger than 1. if r >= l: mid = l + r // 2 # Right values if (values[mid] > values[mid+1]) and (values[mid] < values[mid-1]): return binarySearch(values, l, mid) # left values elif (values[mid] < values[mid+1]) and (values[mid] > values[mid-1]): return binarySearch(values, mid, r) else: return mid else: # For this case there won't be since it's a pseudocode for just this array. return False # Our values values = [12,17,38,54,55,69,68,44,39,19,14,7] result = Search_method(values, 0, len(values)-1) if True: print ("Element you picked is in the {} place, and it's value is {}. ".format(result+1, values[result])) else: print ("No element in the system. ")
true
545694602e2aa66f044443e3755f98ddce0fed72
Orchidocx/nato-alphabet
/main.py
341
4.1875
4
import pandas data = pandas.read_csv("nato_phonetic_alphabet.csv") nato_alphabet = {row.letter: row.code for (index, row) in data.iterrows()} word = input("Enter a word: ").upper() while word != "0": result = [nato_alphabet[letter] for letter in word] print(result) word = input("Enter a new word (enter 0 to exit): ").upper()
true
4ca0463a00a03a4a0aab20e3b38ec0104c6f45e7
molssi-seamm/seamm_util
/seamm_util/variable_names.py
795
4.3125
4
# -*- coding: utf-8 -*- """Utility routines to help with variable names for scripts""" from keyword import iskeyword import re def is_valid(name): """Check if a variable name is valid and is not a keyword""" return name.isidentifier() and not iskeyword(name) def clean(raw_name): """Fix up an input string so that it is a valid variable name""" # Remove invalid characters name = re.sub("[^0-9a-zA-Z_]", "_", raw_name) # Check that it is a valid variable name. If not # put an underscore on the front if not is_valid(name): name = "_" + name # should be valid, but check once more if not is_valid(name): raise RuntimeError( "Variable name {} (from {}) is not valid!".format(name, raw_name) ) return name
true
cb668bb28e77b20e4dde6a7bd3389d32e9d31b82
cholleran/python_exercises
/collatzloop.py
579
4.4375
4
# https://en.wikipedia.org/wiki/Collatz_conjecture # Code based on lecture by Dr Ian McLoughlin # Week 3 exercise - program which applies Collatz to an integer chosen by the user. # Student: Cormac Holleran, GMIT - Module: 52167 #input is taken from the user and stored as n. n = int(input('Please enter and integer:')) # Uses Boolean statements to apply the rules of Collatz conjecture. # The 'while' keyword ensures the program runs until the number reaches 1. while n != 1: if n % 2 == 0: n = n / 2 print (n) elif n % 2 > 0: n = (n * 3) + 1 print (n)
true
8ffbc30af161801cd218444aae13f77fecb4b4d6
guiscaranse/logica
/Segundo Ano/lista 1/3.py
236
4.15625
4
# -*- coding: UTF-8 -*- numero1 = int(input("Insira o primeiro número: ")) numero2 = int(input("Insira o segundo número: ")) numero3 = int(input("Insira o terceiro número: ")) print ("Maior número é", max(numero1,numero2,numero3))
false
e66275f1f3bb1b6ad3c6f7a1fa2c6fe95b6b2f9d
ranjennaidu21/python_basic_project
/control_structures/list_functions.py
426
4.25
4
fruits = ["Mango", "Banana", "Orange"] print(fruits) #insert element into list (at the end of list automatically) fruits.append("Apple") print(fruits) #insert element into list in a particular position fruits.insert(2,"PineApple") print(fruits) #find the length of the list print(len(fruits)) #find index/position of particular element in the list #if not found will give error not in list print(fruits.index("PineApple"))
true
4428af84147aa3ebc43d27c72861e9d2b8aac020
PallabDotCom/Python-Basics
/TextReadWrite.py
1,072
4.25
4
#file= open('test.txt', 'r') # Optimized way to open file is below line. You don't have to close the file at the end. # with open('test.txt') as file: #read all lines of file ''' print(file.read()) ''' #read n number of characters from file ''' print(file.read(7)) ''' #read one single line at a time ''' print(file.readline()) ''' #Print line by line using readline ''' line = file.readline() while line !="": print(line) line = file.readline() ''' #list will be returned in readlines ''' print(file.readlines()) ''' #Iterate for loop to get all the lines from list ''' line = file.readlines() for i in line: print(i) ''' #read the file , reverse list and write it back ''' line = file.readlines() file= open('test.txt', 'w') for i in reversed(line): file.write(i) print("Done") ''' #another way to do it - with open('test.txt', 'r') as reader: line = reader.readlines() with open('test.txt', 'w') as writer: for i in reversed(line): writer.write(i) #file.close()
true
526d4bcf20f5022240990c881429df70adc10d75
manjulamishra/DS-Unit-3-Sprint-2-SQL-and-Databases
/demo_data.py
954
4.59375
5
# import sqlite3 and create a file 'demo_data.sqlite3' # open a connection import sqlite3 conn = sqlite3.connect('demo_data.sqlite3') # create a cursor curs = conn.cursor() # create a table curs.execute('''CREATE TABLE demo (s text, x INT, y INT)''') # insert the data into the table curs.execute("INSERT INTO demo VALUES ('g', 3, 9),('v', 5, 7), ('f', 8, 7)") conn.commit() conn.close() # Question1: Count how many rows you have - it should be 3! total_rows_query = """SELECT COUNT(*) FROM demo;""" curs.execute(total_rows_query) print(curs.fetchall()) # How many rows are there where both x and y are at least 5? total_xy_query = """SELECT COUNT(*) FROM demo WHERE x >= 5 AND y >= 5;""" curs.execute(total_xy_query) print(curs.fetchall()) # How many unique values of y are there (hint - COUNT() can accept a keyword DISTINCT)? distinct_y_query = """SELECT COUNT(DISTINCT y) FROM demo;""" curs.execute(distinct_y_query) print(curs.fetchall())
true
ffae658138f117034f082aca4b4b5e7643b21553
segerphilip/SoftwareDesign
/inclass/day11/Point1.py
1,943
4.375
4
""" Code example from Think Python, by Allen B. Downey. Available from http://thinkpython.com Copyright 2012 Allen B. Downey. Distributed under the GNU General Public License at gnu.org/licenses/gpl.html. """ import math class Point(object): """Represents a point in 2-D space.""" def print_point(p): """Print a Point object in human-readable format.""" print '(%g, %g)' % (p.x, p.y) def distance_between_points(p1,p2): distance = math.sqrt((p1.x + p2.x)**2 + (p1.y + p2.y)**2) print distance class Rectangle(object): """Represents a rectangle. attributes: width, height, corner. """ def find_center(rect): """Returns a Point at the center of a Rectangle.""" p = Point() p.x = rect.corner.x + rect.width/2.0 p.y = rect.corner.y + rect.height/2.0 return p def grow_rectangle(rect, dwidth, dheight): """Modify the Rectangle by adding to its width and height. rect: Rectangle object. dwidth: change in width (can be negative). dheight: change in height (can be negative). """ rect.width += dwidth rect.height += dheight def move_rectangle(rect, dx, dy): rect.corner.x += dx rect.corner.y += dy def main(): blank = Point() blank.x = 3 blank.y = 4 blank1 = Point() blank1.x = 5 blank1.y = 2 distance_between_points(blank,blank1) print 'blank', print_point(blank) box = Rectangle() box.width = 100.0 box.height = 200.0 box.corner = Point() box.corner.x = 0.0 box.corner.y = 0.0 center = find_center(box) print 'center', print_point(center) print box.width print box.height print 'grow' grow_rectangle(box, 50, 100) print box.width print box.height box1 = Rectangle() box.width = 50.0 box.height = 20.0 box.corner = Point() box.corner.x = 2.0 box.corner.y = 3.0 move_rectangle(box1, 6, 4) if __name__ == '__main__': main()
true
0c0970e05f15cc2eb667389d82206736a5e490c4
rayruicai/coding-interview
/hash-tables/find-the-length-of-a-longest-contained-interval.py
1,305
4.3125
4
# 12.9 in Elements of Programming Interviews in Python (Sep 15, 2016) # Write a program which takes as input a set of integers represented by an # array, and returns the size of a largest subset of integers in the array # having the property that if two integers are in the subset, then so are all # integers between them. import unittest # time complexity O(len(arr)) # space complexity O(len(arr)) def longest_interval(arr): # for each element in the list, check whether the adjacent numbers are also # in the list, if yes, remove them, and then calculate the max length, # iterate the checking until the list is empty. max_interval = 0 while len(arr) > 0: current_value = arr.pop() value_before = current_value - 1 value_after = current_value + 1 while value_before in arr: arr.remove(value_before) value_before -= 1 while value_after in arr: arr.remove(value_after) value_after += 1 max_interval = max(max_interval, value_after - value_before - 1) return max_interval class Test(unittest.TestCase): def test_longest_interval(self): arr = [3,-2,7,9,8,1,2,0,-1,5,8] self.assertEqual(longest_interval(arr), 6); if __name__ == "__main__": unittest.main()
true
b4c58230c0d1a19b7533812fdd30576f7f6823a6
rayruicai/coding-interview
/stacks-and-queues/normalize-pathnames.py
1,899
4.15625
4
# 8.4 in Elements of Programming Interviews in Python (Sep 15, 2016) # write a program which takes a pathname, and returns the shortest # equivalent pathname. import unittest # time complexity O(len(string)) # space complexity O(len(string)) class Stack(): def __init__(self): self.items = [] def isEmpty(self): return len(self.items) == 0 def push(self, item): self.items.append(item) def pop(self): if len(self.items) == 0: return None return self.items.pop() def peek(self): return self.items[-1] def normalize_pathnames(string): # split string with / path_lst = string.split('/') # push each element in the list to stack path_lst_short = [] P = Stack() for i in path_lst: if i != '' and i != '.': if i == '..': if P.isEmpty() or P.peek() == '..': P.push(i) else: P.pop() else: P.push(i) # pop short pathname while not P.isEmpty(): path_lst_short.insert(0, P.pop()) # distinguish between absolute and relative pathname if path_lst[0] == '': if path_lst_short[0] == '..': raise ValueError('Path error') else: return '/' + '/'.join(path_lst_short) else: return '/'.join(path_lst_short) class Test(unittest.TestCase): def test_normalize_pathnames(self): pathname1 = 'scripts//./../scripts/awkscripts/././' self.assertEqual(normalize_pathnames(pathname1), 'scripts/awkscripts'); pathname2 = '/usr/lib/../bin/gcc' self.assertEqual(normalize_pathnames(pathname2), '/usr/bin/gcc'); pathname3 = '/../scripts/awkscripts/././' self.assertRaises(ValueError, normalize_pathnames, pathname3) if __name__ == "__main__": unittest.main()
true
f06ca77a5ee8e2adedbfa2037211938840891526
7azabet/studentsGradesAndDegrees
/grades.py
1,028
4.3125
4
# Students List students = [ ['Amal', 95], ['Danah', 60], ['Eman', 90], ['Haneen', 97], ['Kholud', 64] ] # Start Of Code. print('\t Students Grades') print('*' * 40) print("Name\t\tGrade\t\tDegree") for name, grade in students: if grade >= 95: degree = "A+" elif grade >= 90 or grade == 94: degree = "A" elif grade >= 85 or grade == 89: degree = "B+" elif grade >= 80 or grade == 84: degree = "B" elif grade >= 75 or grade == 79: degree = "C+" elif grade >= 70 or grade == 74: degree = "C" elif grade >= 65 or grade == 69: degree = "D+" elif grade >= 60 or grade == 64: degree = "D" else: degree = "F" # Printing Result print(f"{name} \t|\t {grade} \t|\t {degree}") """# The Highest && Lowest Grade At Grades. grades = [column[1] for column in students] highestGrade = max(grades) lowestGrade = min(grades) print(f'\nHighest Grade: {highestGrade}\nLowest Grade: {lowestGrade}\n') """
false
3e7808d1433978ffd11a865569f430d1f51324e9
OzgurORUC/GlobalAIHubPythonCourse
/Homeworks/HW1.py
783
4.125
4
# HW1 DAY.2 # Question 1 # Create a list and swap the second half of the list with the first half of the list # and print this list on the screen mylist=[0,1,2,3,4,5,6,7] mylist=mylist[int(len(mylist)/2):len(mylist)]+mylist[0:int(len(mylist)/2)] print(mylist) input("Herhangi bir tuşa basarak devam edebilirsiniz!") # Question 2 # Ask the user to input a single digit integer to a variable 'n'. # Then, print out all of even numbers from 0 to n (including n) n=10 while n>9 or n<0: n=int(input('tek basamaklı pozitif bir sayı giriniz:')) if n>9: print("Hatalı giriş: " + str(len(str(n))) + " basamaklı sayı girdiniz") elif n<0: print("Hatalı giriş: negatif sayı girdiniz") print(list(range(0,n+1,2))) input("Herhangi bir tuşa basarak çıkabilirsiniz!")
false
f74387e88f69f7ddfbe0af237b1f3c3957d241e3
SchaefferDuncan/CodeDuplicateTest1
/main.py
2,508
4.25
4
def bubble_sort(arr): n = len(arr) # Traverse through all array elements for i in range(n): # Last i elements are already in place for j in range(0, n - i - 1): # traverse the array from 0 to n-i-1 # Swap if the element found is greater # than the next element if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] def merge_sort(arr): if len(arr) > 1: mid = len(arr) // 2 # Finding the mid of the array L = arr[:mid] # Dividing the array elements R = arr[mid:] # into 2 halves merge_sort(L) # Sorting the first half merge_sort(R) # Sorting the second half i = j = k = 0 # Copy data to temp arrays L[] and R[] while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 # Checking if any element was left while i < len(L): arr[k] = L[i] i += 1 k += 1 while j < len(R): arr[k] = R[j] j += 1 k += 1 def insertion_sort(arr): # Traverse through 1 to len(arr) for i in range(1, len(arr)): key = arr[i] # Move elements of arr[0..i-1], that are # greater than key, to one position ahead # of their current position j = i - 1 while j >= 0 and key < arr[j]: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key def partition(arr, low, high): i = (low - 1) # index of smaller element pivot = arr[high] # pivot for j in range(low, high): # If current element is smaller than or # equal to pivot if arr[j] <= pivot: # increment index of smaller element i = i + 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[high] = arr[high], arr[i + 1] return i + 1 # The main function that implements QuickSort # arr[] --> Array to be sorted, # low --> Starting index, # high --> Ending index # Function to do Quick sort def quick_sort(arr, low, high): if low < high: # pi is partitioning index, arr[p] is now # at right place pi = partition(arr, low, high) # Separately sort elements before # partition and after partition quick_sort(arr, low, pi - 1) quick_sort(arr, pi + 1, high)
false
dddf31b5e24c4c3d8db6850a8436cac4e539d769
SandraEtoile/test-python
/tasks/fundamentals/triangle_are.py
1,100
4.3125
4
import math def basement_height_area(height, base): return (height * base) / 2 def two_sides_angle(a, b, angleC): return (a * b * math.sin(math.radians(angleC))) / 2 print("Welcome to the triangle area calculation tool") area_calc_user_choice = 0 while area_calc_user_choice < 3: print("Menu") print("1. Calculate triangle area by base and height") print("2. Calculate triangle area by 2 sidea and angle between them") print("3. Exit") area_calc_user_choice = int(input("Enter menu item number: ")) if area_calc_user_choice == 1: input_array = input("Enter base and height: ").split(" ") height = int(input_array[0]) base = int(input_array[1]) area = basement_height_area(height, base) print("Area is: " + str(area)) elif area_calc_user_choice == 2: input_array = input("Enter two sides and angle between them: ").split(" ") a = int(input_array[0]) b = int(input_array[1]) angle = int(input_array[2]) area = two_sides_angle(a, b, angle) print("Area is: " + str(area))
true
e090b2b6218e561366fcea6a4afa0a2dd1532a20
error404compiled/py-mastr
/Basics/dict_tuple.py
1,298
4.1875
4
def add_and_multiple(n1,n2): ''' Exercise 2 :param n1: Number 1 :param n2: Number 2 :return: a tuple containing sum and multiplication of two input numbers ''' sum = n1 + n2 mult = n1 * n2 return sum, mult def age_dictionary(): ''' Exercise 1 This program asks for person name and age and builds a dictionary using that Later on you can input person name and it will tell you the age of that person :return: ''' d = {} while True: person = input("Enter name of the person(To stop don't enter anything and hi Enter key):") if person == '': break age = input("Enter age:") d[person] = age print("Building dictionary is complete.Now enter name of the person and I'll tell you his/her age") while True: name = input("Enter name of the person(To stop don't enter anything and hi Enter key):") if name == '': break if name in d: print ("Age of", name, "is:", d[name]) else: print ("I don't know the age of",name) print ("Age dictionary program is finished now") # Exercise 1 age_dictionary() # Exercise 2 n1=4 n2=6 s,m=add_and_multiple(n1,n2) print("sum:",s,"multipication:",m," Input numbers:",n1,"and",n2)
true
8c1be4db8c58b0868595128508dd42899a9db84f
error404compiled/py-mastr
/Basics/Hindi/6_if/Exercise/6_exercise1_1.py
800
4.6875
5
## Exercise: Python If Condition # 1. Using following list of cities per country, # ``` # india = ["mumbai", "banglore", "chennai", "delhi"] # pakistan = ["lahore","karachi","islamabad"] # bangladesh = ["dhaka", "khulna", "rangpur"] # ``` # Write a program that asks user to enter a city name and it should tell which country the city belongs to india = ["mumbai", "banglore", "chennai", "delhi"] pakistan = ["lahore", "karachi", "islamabad"] bangladesh = ["dhaka", "khulna", "rangpur"] city = input("Enter city name: ") if city in india: print(f"{city} is in india") elif city in pakistan: print(f"{city} is in pakistan") elif city in bangladesh: print(f"{city} is in bangladesh") else: print(f"I won't be able to tell you which country {city} is in! Sorry!")
false
b3891ce670d357b7797a9caf3dd9f905fcc95eb3
error404compiled/py-mastr
/Basics/Hindi/6_if/6_if.py
1,067
4.34375
4
# while mentioning topics say that timeline is in video description # so you don't need to watch entire video n=input("Enter a number") n=int(n) if n%2==0: print("Number is even") else: print("Number is odd") # Show the execution by debugging # If is called control statement as it controls the flow of code execution # go to idle and explain different operators # == # != # > # < # >= # <= # # 3>2 and 4>1 # 3>1 or 4>8 # not 4==4 # Cousine checker. Explains if..elif..else indian=["samosa","kachori","dal","naan"] pakistani=["nihari","paya","karahi"] bangladesi=["panta bhat","chorchori","fuchka"] dish=input("Enter a dish name:") if dish in indian: print(f"{dish} is Indian") elif dish in pakistani: print(f"{dish} is pakistani") elif dish in bangladesi: print(f"{dish} is bangladesi") else: print(f"Based on my limited knowledge, I don't know which cuisine is {dish}") # Ternary operator print("Ternary operator demo") n=input("Enter a number:") n=int(n) message="Number is even" if n%2==0 else "Number is odd" print(message)
true
f80608adf67013f2a58cc9472bcd7f97fcef888b
MrChoclate/projecteuler
/python/4.py
885
4.1875
4
""" Largest palindrome product Problem 4 A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. """ import itertools def is_palindrome(number): return str(number) == ''.join(reversed(str(number))) def get_all_number(nb_digits): for digits_list in itertools.product(range(10), repeat=nb_digits): number = 0 for i, digit in enumerate(digits_list): number += digit * 10 ** i yield number def get_palidromes(nb_digits): for x, y in itertools.product(get_all_number(nb_digits), repeat=2): if is_palindrome(x * y): yield x * y if __name__ == '__main__': assert(is_palindrome(9009)) assert(max(get_palidromes(2)) == 9009) print(max(get_palidromes(3)))
true
3c0f5770aec366758c4099f292080f86073c3ef9
cnicacio/atividades_python
/functions/06_24_exercicio_01_function.py
416
4.1875
4
''' Faça um programa, com uma função que necessite de três argumentos, e que forneça a soma desses três argumentos. ''' def function(a, b, c): sum = a + b + c return sum n1 = int(input('Type the first number (N1): ')) n2 = int(input('Type the second number (N2): ')) n3 = int(input('Type the third number (N3): ')) result = function(n1, n2, n3) print(f'The sum of {n1}, {n2} and {n3} is {result}')
false
103e25edc51c7525e9dc79d8f5102493846a7df3
cnicacio/atividades_python
/for_loop/06_15_exercicio_02_for.py
219
4.21875
4
''' 02 - Crie um programa que pergunte ao usuário um número inteiro e faça a tabuada desse número. ''' numero = int(input('Digite um número: ')) for c in range(1,11): print(f'{numero} x {c} = {numero * c}')
false
cc180d3c75a1957d96c179ef3d45ef29a2ce7018
runxunteh/coding-challenges
/CodeChef/Beginner/ICPC16B.py
1,514
4.21875
4
""" Author: Teh Run Xun Date: 22 February 2019 Problem from: https://www.codechef.com/problems/ICPC16B ....................... An array a is called beautiful if for every pair of numbers ai, aj, (i ≠ j), there exists an ak such that ak = ai * aj. k can be equal to i or j too. This program is to find out whether the given array a is beautiful or not Example: 2 0 1 Case #1: yes. 0 * 1 = 0 and a0=0 2 1 2 Case #2: yes. 1 * 2 = 2 and a1=2 2 5 6 Case #3: no. 5 * 6 = 30. We need to accept negative values too. From this, we can observe that we need to keep track the number of negative ones(-1's), number of ones(1's) and zeros(0's) There are three conditions when the array will not be beautiful: 1. when the number of other values(values other than -1,0,1) is more than 1 e.g. 4 1 1 0 is fine but 4 1 2 0 is not 2. when the number of other values is 1 and number of negative ones is more than 0 e.g. 4 -1 1 0. we will get 4*-1=-4 but we want positive 4 to be beautiful 3. when the number of negative ones are more than 1 and number of positive ones and zeros is 0 e.g. -1 -1. -1*-1=1. """ no_of_test=int(input()) for i in range(no_of_test): x=int(input()) y=list(map(int,input().split())) n=0 one_zero=0 others=0 for i in range(x): if y[i]==0 or y[i]==1: one_zero+=1 elif y[i]==-1: n+=1 else: others+=1 if others>1 or (others==1 and n>0) or (n>1 and one_zero==0): print("no") else: print("yes")
true
35de3bfc25350f4b604ee67b8e4c9b9de71a0c9b
aonomike/data-structures
/daily_interview_pro/sort_num.py
453
4.1875
4
# Given a list of numbers with only 3 unique numbers (1, 2, 3), sort the list in O(n) time. #Input: [3, 3, 2, 1, 3, 2, 1] #Output: [1, 1, 2, 2, 3, 3, 3] def sort_nums(nums): lookup = {} for n in nums: if n in lookup: print(n) lookup[n] = lookup[n].append(n) else: lookup[n] = [n] sorted(lookup) look = [ [].append(l) for l in lookup] return look sort_nums([3, 3, 2, 1, 3, 2, 1])
true
c0fbb241822303cbfa13bfbbeaa0b2cc6d6631ea
brisvv/New-project-
/Martin/BookORelly/built_in_functions.py
1,802
4.28125
4
#https://medium.com/@happymishra66/lambda-map-and-filter-in-python-4935f248593 #Filter (used with lists) #unction_object is called for each element of the iterable and filter returns only those element #for which the function_object returns true. #Like map function, filter function also returns a list of element. #Unlike map function filter function can only have one iterable as input. A=list(filter((lambda x: x > 0), range(-5, 5))) print(A) dict_a = [{'name': 'python', 'points': 10}, {'name': 'java', 'points': 8}] #map #map functions expects a function object and any number of iterables like list, #dictionary, etc. It executes the function_object for each element in the sequence #and returns a list of the elements modified by the function object. M = map(abs, (-1, 0, 1)) print("With tuple:",next(M),next(M)) B=list(map(abs, [-1, -2, 0, 1, 2])) print("With list:",B) M1= map(lambda x: 1 * x, range(4)) print("2 range mult:",list(M1)) def multiply2(x): return x * 2 print("Multiply a list with def:",list(map(multiply2, [1, 2, 3, 4]))) print("Multiply a lambda:",list(map(lambda x : x*2, [1, 2, 3, 4]))) dict_a = {'name': 'python', 'points': 10}, {'name': 'java', 'points': 8} print("Output: ['python', 'java']:",list(map(lambda x: x['name'], dict_a))) print("Output: [100, 80]:",list(map(lambda x: x['points'] * 10, dict_a))) list_a = [1, 2, 3] list_b = [10, 20, 30] print(list(map(lambda x, y: x + y, list_a, list_b)))# Output: [11, 22, 33] #difference print("Dictionary to show diff:", dict_a) B=list(filter(lambda x : x['name'] == 'python', dict_a)) # Output: [{'name': 'python', 'points': 10}] print("Filter elements with the function is true:",B) C=list(map(lambda x: x['name'] == "python", dict_a)) print("With Map returns a list of the elements modified by the function:",C)
true
02f09f22ad38f70fe6233f623ab44877a720b9ea
mattycoles/learning_python
/cup_and_ball.py
1,770
4.15625
4
## Cup and Ball Game from random import randint gameon = True display = ["[x]","[x]","[x]"] guess = 0 cupandball = 0 score = 0 print("Welcome to the cup guessing game.") print("Simply guess which cup the ball is in! [x],[x],[x]") def reset_cups(): display = ["[x]","[x]","[x]"] return display def ball_location(display, cupandball): cupandball = randint(0,2) display[cupandball] = '[O]' return display def player_guess(guess): guessing = True while guessing: guess = input("\nWhich cup do you think the ball is in? (0,1 or 2): ") if guess.isdigit() == True and guess in ['0','1','2']: print(f"\nYou have guessed {guess}!") guessing = False break else: print(f"{guess} is not a valid guess!") guess = int(guess) return guess def check_guess(display, guess, cupandball, score): guess = guess score = int(score) cup = cupandball if display[guess] == '[O]': score +=1 print("That was correct!") print(display) else: print("That was the wrong cup!\n") print(display) return score def play_again(gameon, score): again = True print(f"\nYour current score is {score}.") while again: restart = input("\nWould you like to play again? (Y/N): ") if restart == 'Y': gameon = True print("Good Luck!") again = False break elif restart == 'N': gameon = False print("Thanks for playing.") again = False break else: print("Please choose Y or N") again = True return gameon while gameon: display = reset_cups() display = ball_location(display, cupandball) guess = player_guess(guess) score = check_guess(display,guess,cupandball,score) gameon = play_again(gameon,score)
true
07fb716d2df31ac5ba9fd1a319cd11533c78ce88
sourabh-karmarkar/Practicals
/SourabhPractice/Python Training/Day-10/Exercise-3/question1.py
390
4.5625
5
""" 1) Write a program which uses a nested for loop to populate a three-dimensional list representing a calendar: the top-level list should contain a sub-list for each month, and each month should contain four weeks. Each week should be an empty list. """ calendar=[] for x in range(12): month=[] for y in range(4): month.append([]) calendar.append(month) print(calendar)
true
0ade62a85e2dc8f90e174797e58e616e11c38b21
sourabh-karmarkar/Practicals
/SourabhPractice/Python Training/Day-5/Exercise-3/question2.py
1,656
4.34375
4
""" Write a python program to assign grade to students at the end of the year. The program must do the following: a. Ask for a student number. b. Ask for the student's tutorial mark. c. Ask for the student'a test mark d. Calculate whether the student's average is high enough for the student to be permitted to write the examination. If the average (mean) of the tutorial and test marks is lower than 40%, the student should automatically get an F grade, and the program should print the grade and exit without performing the following steps. e. Ask for the student's examination mark. f. Calculate the student's final mark. The tutorial and test marks should count for 25% of the final mark each, and the final examination should count for the remaning 50%. g. Calculate and print the student's grade according to the following table: Weighted final score Final grade 80 <= mark <= 100 A 70 <= mark < 80 B 60 <= mark < 70 C 50 <= mark < 60 D mark < 50 E """ student_number=input("Enter Student Number : ") student_tutorial=float((input("Enter Student Tutorial Marks : "))) student_test=float((input("Enter Student Test Marks : "))) if ((student_tutorial+student_test)/2 < 40): grade = "F" else: student_exam=float(input("Please enter the student's final examination mark: ")) final_mark=(student_tutorial/4)+(student_test/4)+(student_exam/2) if 80 <= final_mark <= 100: grade = "A" elif 70 <= final_mark < 80: grade = "B" elif 60 <= final_mark < 70: grade = "C" elif 50 <= final_mark < 60: grade = "D" else: grade = "E" print ("%s's grade is %s."%(student_number, grade))
true
e1a935993ed9bbd8153bda16832f558a0eb8360e
sourabh-karmarkar/Practicals
/SourabhPractice/Python Training/Day-10/Exercise-1/question2.py
827
4.15625
4
""" Write a program which keeps prompting the user to guess a word. The user is allowed upto 10 guesses - write your code in such a way that the secret word and the number of allowed guesses are easy to change. Print messages to give the user feedback. """ guess_count = 0 secret_word = "ABC" allowed_guesses = 20 while True: # Take word from the user guess_word=input("Guess a word : ") # Check if user-entered word is matching to secret word and print the message then break the loop if( guess_word == secret_word): print("Great, your guess is right!!") break print("Oops, wrong guess!!") # increment guess count guess_count += 1 # if guess count matches the number of allowed guesses then print the message then break the loop if(guess_count == allowed_guesses): print("Sorry, limit reached!!") break
true
1707b6ac212ca2ef7a013b9ce6be1f6cada95fef
sourabh-karmarkar/Practicals
/SourabhPractice/Python Training/Day-11/Exercise-3/question2.py
544
4.375
4
""" Some programs ask to input a variable number of data entries, and finally to enter a specific character or string (called a sentinel) which signifies that there are no more entries. For example, you could be asked to enter your PIN followed by a hash (#). The hash is the sentinel which indicates that you have finished entering your PIN. """ print("Enter Strings and type a single hash(#) to terminate the program") while True: string_1 = input("--> ") if(string_1 == "#"): break print("Program exited successfully")
true
77a0c8f6718c627e1928da56cc5f31e4e2b8af74
sourabh-karmarkar/Practicals
/SourabhPractice/Python Training/Day-12/Exercise-1/question1.py
491
4.1875
4
""" 1) Find all the syntax errors in the code snippet, and explain why they are errors. A) - Missing def keyword before myfunction. - else block without if. - if statement missing the ' : ' symbol. - spelling of else is typed wrongly. - last statement of the program not indented properly. """ myfunction(x, y): return x + y else: print("Hello!") if mark >= 50 print("You passed!") if arriving: print("Hi!") esle: print("Bye!") if flag: print("Flag is set!")
true
14027e0215180fdc5d82e8813dafb5f7f10e636f
alina12358/Projects
/Miscellanea/BST_vs_list/HW3_p1.py
944
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 4 16:06:31 2020 @author: alina """ class Stack: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items)-1] def size(self): return len(self.items) def postoinfix(expression): number_stack = Stack() ops = {"+": (lambda x,y: x+y), "-": (lambda x,y: x-y),"*": (lambda x,y: x*y),"/": (lambda x,y: x/y)} for x in expression: if x == "+" or x == "-" or x == "*" or x == "/": number_stack.push(ops[x](int(number_stack.pop()),int(number_stack.pop()))) elif x == ' ': continue else: number_stack.push(x) return number_stack.pop()
false
a3945b8cb380295d27e3e709ea465638945f7163
keerthanasiva9/INFO6205_PSA_Spring_2021
/rotate_image_assign_7.py
1,273
4.25
4
#Rotate Image #You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). #You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. #DO NOT allocate another 2D matrix and do the rotation. #Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] #Output: [[7,4,1],[8,5,2],[9,6,3]] #Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] #Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] def rotate_image(matrix): if matrix is None: return None n = len(matrix) if n == 1: return matrix for i in range(n): if len(matrix[i]) != n: raise Exception("Matrix must be square") # Transpose the matrix for i in range(n): for j in range(i): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] # Swap columns for i in range(n): for j in range(n // 2): matrix[i][j], matrix[i][n - j - 1] = matrix[i][n - j - 1], matrix[i][j] return matrix if __name__ == '__main__': matrix = [[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16]] print("The input matrix is",matrix) print("Output string is:",rotate_image(matrix))
true
4f2e22a9b56bb114f151843b32b21f1e30df9a57
robertdelaney/CTI110
/CTI 110 Web/M7T1KilometerConverter.py
739
4.21875
4
# CTI-110 # M7T1_Delaney.py Kilometer Converter # Robert DeLaney # 12-4-17 # Write a program that ask the user to enter a distance # in Kilometers, and then converts that distance to miles # Formula Miles = Kilometers * 0.6214 def askUserForKilometer(): userKilometers = float(input('Enter distance in kilometers. ')) return userKilometers def convertKilometersToMiles (userKilometers ): miles = userKilometers * 0.6214 return miles def main(): userTypedKilometers = askUserForKilometer() convertedMiles = convertKilometersToMiles (userTypedKilometers ) print(userTypedKilometers,'Kilometers converted to miles is',\ format (convertedMiles, '.2f') + 'miles. ') main()
false
781ed683c7e964836b3df890bf4a62db03713856
Kaue-Romero/Python_Repository
/Exercícios/exerc_60.py
457
4.21875
4
from math import factorial n = float(input('Digite um número qualquer para ver seu fatorial: ')) print(factorial(n)) continua = str(input('Quer continuar? [S/N] ')).upper() while continua == 'S': n = float(input('Digite outro número: ')) print(factorial(n)) continua = str(input('Quer continuar? [S/N] ')).upper() if continua == 'N': exit('Obrigado') elif continua != 'N' or 'S': print('Opção inválida') else: print('Obrigado')
false
6bdcd2ff8fa1931f67f6435fe2d45907ad13dc3d
Pramod-Mathai/Puzzles
/SumOfPrimes.py
1,839
4.15625
4
# -*- coding: utf-8 -*- """ Objective: Test distribution of primes Created on Tue Nov 17 09:30:49 2015 @author: Pramod Mathai """ from IPython import get_ipython get_ipython().magic('reset -sf') # clear workspace import math, numpy as np def sum_of_primes_Sieve(Number): # Sieve for computing list of primes in_sieve = np.arange(2,(1+Number)) # sieve the composites out of this list factor = 2 factor_idx = 0 while factor <= math.ceil(np.sqrt(Number)) : # All composites less than 'Number' must have a 'factor' in this range remove_this = np.arange(2*factor, (factor*math.floor(Number/factor) + factor), factor) # 'factor' is a prime; we remove its multiples from in_sieve in the next line in_sieve = sorted(list(set(in_sieve) - set(remove_this))) # More efficient sieving? factor_idx = factor_idx + 1 factor = in_sieve[factor_idx] sum_exact = np.dot(in_sieve,np.ones(len(in_sieve))) print("Based on sieving:") print("1. Number of primes <=%d is %d"%(Number, len(in_sieve))) print("2. Largest prime <=%d is %d"%(Number, in_sieve[len(in_sieve) - 1])) return{'exact_sum_primes':sum_exact} def main(): print ('') print ('This script will use a sieve to find all the primes <= N, a natural number. Sieve takes a few seconds to compute for N = 10^6.') print ('It will display the exact sum of those primes as well as an estimate of that sum that relies on a prime-number-theorem (PNT) based heuristic.') N = int(input("Input N (>2) :")) Sum_Sieve = sum_of_primes_Sieve(N) print("3. Exact sum of primes <=%d is %e."%(N, Sum_Sieve['exact_sum_primes'])) print("Estimated sum of primes <=%d is %e, using a PNT based heuristic."%(N, pow(N, 2)/(2*np.log(N)))) # Based on PNT based heuristic main()
true
1758409ac95768d9edc653e03a1041e1fa0359bb
wy193777/Data-Structure-and-Algorithm-with-Python-and-C--
/Markov.py
1,415
4.125
4
import random class Markov(object): """A simple trigram Markov model. The current state is a sequence of the two words seen most recently. Initially, the state is (None, None), since no words have been seen. Scanning the sentence "The man ate the pasta" would casue the model to go through the sequence of states: [(None, None), (None, 'the'), ('The','man'), ('man', 'ate'), ('ate', 'the').""" def __init__(self): self.model = {} self.state = (None, None) def add(self, word): if self.state in self.model: #We have an existing list of words for this state #just add this new one (word). self.model[self.state].append(word) else: #first occurrence of this state, create a new list self.model[self.state] = [word] # transition to the next state given next word self._transition(word) def reset(self): self.state = (None, None) def randomNext(self): #get list of next words for this state lst = self.model[self.state] #choose one at random choice = random.choice(lst) #transition to next state, given the word choice self._transition(choice) return choice def _transition(self, next): # help function to construct next state self.state = (self.state[1], next)
true
49240aaf371201a638acf980636c9a610b6d7e14
rkoehler/Class-Material
/Basic Code (Unorganized)/beginning.py
234
4.15625
4
# Robert Koehler # Basic program showing input and output #robkoehler10@gmail.com print("What's your name") name = input() print("Hello " + name) print("What is the color of your shirt?") x = input() print("Hello " +name +", nice "+x+" colored shirt")
true
b89789b77bd9272327847e16e7ca92bed7765c52
rkoehler/Class-Material
/Basic Code (Unorganized)/RemoveChar.py
335
4.28125
4
#overall program takes a charater from one string and places it into a new one. #assign values to inital string #take specified value and place into new string #keep prompting user until first list is depleted def removeChar(s): removeList = list(s) l = len(s) for t in range(l): print(removeChar("Test"))
true