blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
656e09380a177f4c4343b1a7030684c773640619
hguochen/algorithms
/python/random_questions/speed_of_sound.py
480
4.15625
4
################################## ### Title: Speed of Sound ######## ### Author: GuoChen Hou ######## ################################## # Given temperature T in fahrenheits, calculates the speed of sound in air. import math def speed_of_sound(temp): speed = 1086 * math.sqrt((5*temp + 297)/247) return speed temp = float(raw_input('Temperature in degree Fahrenheit: ')) speed = speed_of_sound(temp) print 'Speed of sound in air of %.2f degree = %.2f ft/sec' % (temp, speed)
true
9919adb1a788ceff87ffcd14d5eededd2b1dca95
hguochen/algorithms
/python/sort/selection_sort/selection_sort_4.py
699
4.1875
4
# selection sort def selection_sort(array): """ Divides the array in 2 sublist, sorted and unsorted. Left sublist contains list of sorted elements, right sublist contains list of unsorted elements. Find the least element and put in sorted sublist. """ # traverse the array for i in xrange(len(array)): # initialize min_index min_index = i # traverse the unsorted sublist, update min index for j in xrange(i+1, len(array)): if array[j] < array[min_index]: min_index = j # swap current with min index value array[i], array[min_index] = array[min_index], array[i] # return array return array
true
c1c5cfbec9dda7b4b8ffdfbd67b2400c5f456c3d
hguochen/algorithms
/python/data_structures/hashes/hash_table.py
1,806
4.15625
4
HASH_TABLE_SIZE = 32 HASH_PRIME = 13 class HashTable(object): """ Implementation of a hash table using a 2d list structure to store english words. """ def __init__(self): self.hash_table = [[] for i in range(HASH_TABLE_SIZE)] @staticmethod def calculate_index(a_string): """ Calculate the index of a_string parameter in the hash table. """ total = 0 for alphabet in a_string: total += ord(alphabet) total *= HASH_PRIME return total % (HASH_TABLE_SIZE-1) def insert(self, a_string): """ Insert a_string into the hash table. """ index = self.calculate_index(a_string) self.hash_table[index].extend([a_string]) return self.hash_table def lookup(self, key): """ Lookup the hash table with key and return all the values associated with the key. """ return self.hash_table[key] def delete(self, a_string): """ Delete a_string parameter at hash table and return the hash table. Return None if a_string is not in hash table. """ index = self.calculate_index(a_string) print index if len(self.hash_table[index]) < 1: return None for i in range(len(self.hash_table[index])): if self.hash_table[index][i] == a_string: self.hash_table[index].pop(i) return self.hash_table return None def print_table(self): print self.hash_table if __name__ == "__main__": test = HashTable() test.print_table() test.insert('apple') test.insert('pear') test.insert('paple') test.print_table() print test.lookup(3) print test.delete('paple')
true
69fff3054e59da7160e4d4bf96d93233ef33142d
hguochen/algorithms
/python/sort/revision/quick_sort.py
1,500
4.21875
4
import unittest def quick_sort(a_list): """ Sort *a_list* using quicksort technique. Time Complexity: Best: O(n log(n)) Average: O(n log(n)) Worst: O(n^2) Space Complexity: O(log(n)) """ # check list has at least 2 elements if len(a_list) < 2: return a_list return quicksort_recur(a_list, 0, len(a_list)-1) def quicksort_recur(a_list, start, end): # pick the last list element as pivot to array # recursively sort the left of pivot # recursively sort the right of pivot if start < end: partition_index = partition(a_list, start, end) quicksort_recur(a_list, start, partition_index) quicksort_recur(a_list, partition_index+1, end) return a_list def partition(a_list, start, end): value = a_list[start] h = start for k in range(start+1, len(a_list)): if a_list[k] < value: h += 1 # swap between value at partition index and value at index k a_list[h], a_list[k] = a_list[k], a_list[h] # swap values between index at partition index and h a_list[start], a_list[h] = a_list[h], a_list[start] return h class QuickSortTestCase(unittest.TestCase): def setUp(self): self.test = [3, 7, 4, 9, 5, 2, 6, 1] def test_quick_sort(self): self.assertEqual(quick_sort(self.test), [1, 2, 3, 4, 5, 6, 7, 9]) if __name__ == "__main__": test = [3, 7, 4, 9, 5, 2, 6, 1] print quick_sort(test) unittest.main()
true
3822101aaac818755b35d2073c13aa06151c47fa
hguochen/algorithms
/python/interviews/asana_interview.py
1,880
4.21875
4
# Write a function that takes a matrix and examines each item in a spiral # order, printing each item as it comes to it. # # For example, given a matrix like this as input: # # [[11, 12, 13, 14, 15], # [21, 22, 23, 24, 25], # [31, 32, 33, 34, 35], # [41, 42, 43, 44, 45]] # Your program must print: # # 11 12 13 14 15 25 35 45 44 43 42 41 31 21 22 23 24 34 33 32 # cases: # 1. input 2d array is empty # 2. must not assume matrix is 'square' shaped import copy mod = __import__(__name__) def spiral_output(matrix): if len(matrix) == 0: return result = [] fns = ['left_right', 'top_bottom', 'right_left', 'bottom_top'] new_matrix = copy.deepcopy(matrix) count = 0 while len(new_matrix) != 0: temp = getattr(mod, fns[count % 4])(new_matrix) result.extend(temp[0]) new_matrix = temp[1] count += 1 return " ".join(str(x) for x in result) def left_right(matrix): """ Takes in a matrix and print top outermost layer from left to right. """ return matrix.pop(0), matrix def top_bottom(matrix): """ Takes in a matrix and print right outermost layer from top to bottom. """ result = [] for array in matrix: result.append(array.pop(-1)) return result, matrix def right_left(matrix): """ Takes in a matrix and print bottom outermost layer from right to left. """ return matrix.pop(-1)[::-1], matrix def bottom_top(matrix): """ Takes in a matrix and print left outermost layer from bottom to top. """ result = [] for array in matrix: result.append(array.pop(0)) return result[::-1], matrix if __name__ == "__main__": test = [[11, 12, 13, 14, 15], [21, 22, 23, 24, 25], [31, 32, 33, 34, 35], [41, 42, 43, 44, 45]] print spiral_output(test) print mod print getattr(mod, 'right_left')
true
8b68c60339737640c9c5024879fdf5795dc9850d
hguochen/algorithms
/python/cci/bits/5_6_swap_bits.py
544
4.21875
4
# Write a program to swap odd and even bits in an integer with as few # instructions as possible (e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 # are swapped, etc). def swap_bits(num): array = list(bin(num)[2:][::-1]) for i in xrange(1, len(array), 2): array[i], array[i-1] = array[i-1], array[i] result = "" for item in array: result += item return result[::-1] def swap_bits_2(num): return (num & 0xaaaaaaaa) >> 1 | (num & 0x55555555) << 1 if __name__ == "__main__": print swap_bits(21)
true
96127af2c4e724e7927184d5fe4fc058a398f085
hguochen/algorithms
/python/random_questions/magic_number.py
684
4.3125
4
################################## ### Title: Magic Number ######## ### Author: GuoChen Hou ######## ################################## # Reads positive integers and for each, adds up the numbers(from right) in positions 1,3, and 5. # The right-most number of the sum is the required answer def compute_magic_number(number): value = 0 for digit in range(len(number)): if digit % 2 == 0: print number[digit] value += int(number[digit]) while value >= 10: value -= 10 return value while True: num = raw_input('Enter a value: ') number = num[::-1] if number == 'quit': break else: magic_number = compute_magic_number(number) print 'Magic number =', magic_number
true
e16e5aa99b21af12dc05ba4cff56f415c141b7bf
EdwinDrn/portfolio_syntax_practice
/for_squared.py
493
4.34375
4
#This program shows different ways of how to take a number, square it for a range given. #Then we are able to print the output in either brackets, or a list. #We also loop through a function as well. #Program Prints Squared numbers begining with the number 1, in brackets. even_squares = [x * x for x in range(1, 11)] for x in range(1, 11): x = x * x print x def even_squares_function(): for x in range(1, 100): print x * x print even_squares even_squares_function()
true
5d02dda3e0af49eaf9c5171c7c46b8031fd3df8e
zemni01/small-banking-system
/savingsAccounts.py
2,149
4.125
4
""" small banking system author : Houssem Zemni year : 2020 """ # import neccessary libraries from abc import ABCMeta, abstractmethod from random import randint # abstraction class base for accounts class account(metaclass = ABCMeta): @abstractmethod def createAccount(): return 0 @abstractmethod def authenticate(): return 0 @abstractmethod def withdraw(): return 0 @abstractmethod def deposit(): return 0 @abstractmethod def displayBalance(): return 0 # savings accounts class that inherite account class class SavingsAccount(account): def __init__(self): # [key][0]=> name ; [key][1] => balance self.savingsAccounts = {} def createAccount(self, name, initialDeposit): self.accountNumber = randint(10000, 99999) self.savingsAccounts[self.accountNumber] = [name, initialDeposit] print("Creation was successful, Your account Number is : ", self.accountNumber) def authenticate(self, name, accountNumber): if (accountNumber in self.savingsAccounts.keys()): if self.savingsAccounts[accountNumber][0] == name : print("Authentification successful") self.accountNumber = accountNumber return True else : print("Authentification failed") return False else : print('authentification failed') return False def withdraw(self, withdrawAmount): if (withdrawAmount > self.savingsAccounts[self.accountNumber][1]): print("Insufficient Balance") else: self.savingsAccounts[self.accountNumber][1] -= withdrawAmount print("Withdraw was successful. ") self.displayBalance() def deposit(self, depositAmount): self.savingsAccounts[self.accountNumber][1] += depositAmount print("Deposit was successful.") self.displayBalance() def displayBalance(self): print("available balance : ", self.savingsAccounts[self.accountNumber][1])
true
08553c8a316f1a28db133c0fed31318dbb7b71fc
Ricardolv/Happynumbers
/happynumbers.py
1,040
4.1875
4
""" Os números felizes são definidos pelo seguinte procedimento. Começando com qualquer número inteiro positivo, o número é substituído pela soma dos quadrados dos seus dígitos, e repetir o processo até que o número seja igual a 1 ou até que ele entre num ciclo infinito que não inclui um ou seja a somo dos quadrados dos algarismos do quadrado de um número positivo inicial. Os números no fim do processo de extremidade com 1, são conhecidos como números feliz, mas aqueles que não terminam com um 1 são números chamados infelizes. Exemplo: 7 é um número feliz:[3] 72 = 49 42 + 92 = 97 92 + 72 = 130 12 + 32 + 02 = 10 12 + 02 = 1. Se n não é feliz, a soma dos quadrados nunca dará 1, serão gerados infinitos termos. 4, 16, 37, 58, 89, 145, 42, 20, 4, ... """ def happy(number): next_ = sum([int(char) ** 2 for char in str(number)]) return number in (1, 7) if number < 10 else happy(next_) assert all(happy(n) for n in (1, 10, 100, 130, 97)) assert not all(happy(n) for n in (2, 3, 4, 5, 6, 8, 9))
false
c60777e60e2e7932f045bd883cf33dc47d4a381c
Aritra-901/java-solution-in-python
/12.py
454
4.1875
4
#Write a program that prompts the user to input a positive integer. It should then output a message indicating whether the number is a prime number def prime(a): s = "not prime" if a > 1: for i in range(2, a): if (a % i) == 0: s = "not prime" break else: s = "prime" else: s = "not prime" return (s) print(prime(3))
true
1288d8c5b31cbb14852ebd8eccddb73e711da9aa
fiso0/my_python
/objvar.py
1,259
4.28125
4
# Filename:objvar.py class Person: '''Represents a person.''' population = 0 __private = 1 def __init__(self,name): '''Initializes the person's date.''' self.name = name print('(Initializing %s)'%self.name) # When this person is created, he/she # adds to the population Person.population += 1 Person.__private += 3 def __del__(self): '''I am dying.''' print('%s says bye.'%self.name) Person.population -= 1 if Person.population == 1: print('I am the last one.') else: print('There are still %d people left.'%Person.population) print(Person.__private) def sayHi(self): '''Greeting by the person. Really, that's all it does.''' print('Hi, my name is %s'%self.name) def howMany(self): '''Prints the current population.''' if Person.population == 1: print('I am the only person here.') else: print('We have %d persons here.'%Person.population) print(Person.__private) jackie = Person('Jackie') jackie.sayHi() jackie.howMany() kalam = Person('Abdul Kalam') kalam.sayHi() kalam.howMany() jackie.sayHi() jackie.howMany()
true
920c2818cd5cef05eb2d6014608cc30a0ce00781
Aasma786/python_drills
/dictionaries.py
880
4.125
4
def word_count(s): a=[] a= s.split() count=len(a) print(count) """ f Find the number of occurrences of each word in a string(Don't consider punctuation characters) """ pass def dict_items(d): print("dictionary items:") for i in d: print(i,":",d[i]) """ Return a list of all the items - (key, value) pair tuples - of the dictionary, `d` """ pass def dict_items_sorted(d): a=sorted(d.items(),key=lambda x: x[1]) print("sorted dictionary items:") for i in a: print(i[0],':',i[1]) """ Return a list of all the items - (key, value) pair tuples - of the dictionary, `d` sorted by `d`'s keys """ pass word_count("Don't consider punctuation characters") dict_items({'1':'one','4':'four','3': 'three','2':'two'}) dict_items_sorted({ 'three':'3','four':'4','two':'2','one':'1'})
false
1b5302e5332b358635fd10cc27bbee7cf056fd55
abnormalmakers/python_high
/decorator.py
628
4.15625
4
""" 装饰器:不改变原有函数的基础上为函数添加新的功能 通过闭包实现,原有函数添加上装饰器以后,实际调用时是调用装饰器函数的内部函数 """ # 闭包实现装饰器 def mydec(fn): def fx(): print('this is mydec add start') fn() print("this is mydec add stop") return fx def fn(): print('this is fn') myfn=mydec(fn) myfn() # pythn装饰器 def mydec(fn): def fx(): print('this is mydec add start') fn() print("this is mydec add stop") return fx @mydec def fn(): print('this is fn') fn()
false
6d3acb417c822a39c61f4707210845b04a5d23b9
joy952/Introduction-to-python
/venv/lesson_2.py
1,083
4.375
4
# Operators :used to perform operations to variables and values # 1.Arithmetic # 2.Assignmen # 3.Comparison # 4.Logical x= 23 y =32 print("Addition of {} and {} is {} ".format(x,y,x+y)) print("Subtraction of {} and {} is {} ".format(x,y,x-y)) print("Division of {} and {} is {} ".format(x,y,x+y)) print("Multiplicarion of {} and {} is {} ".format(x,y,x*y)) print(" of {} and {} is {} ".format(x,y,x+y)) print("Modulus of {} and {} is {} ".format(x,y,x+y)) # 5min ass: write a program that calculates the area of a circle of radius 7 x=22 y=7 print(x/y*y*y) # 2.assignment:used assign a value to a variable # 1, = name = "John" # 2. =+ x = 5 x = x + 6 x+=6 # comparison operators # 1. ==equals # 2. =not equal # 3. >,<,>=,<= # logical operators:used to combine conditonal operations # 1.and # 2.or # 3.not x=3 y=2 # and :returns True if both conditions are true print(x > y and x < 10) # or :returns True if one condition is true print(x > y and x < 10) # not:returns True if one conditionsis false print(not(x > y and x < 10)) # list datatype,dictionary,assest ,tuple
true
fafa313dfa7a4960cf4bf5b315140ffb7e704ef4
ReinhardtGao/Python
/lists.py
1,198
4.3125
4
year_list = [1992, 1993, 1994, 1995, 1996, 1997] print('''I was 3 years old in''',year_list[3]) print(year_list.pop(),'''is the oldest year''') ################################################### things = ['mozzarella','cinderella','salmonella'] print(things) THINGS = list(things) THINGS[0] = THINGS[0].capitalize() THINGS[1] = THINGS[1].capitalize() THINGS[2] = THINGS[2].capitalize() print(THINGS) things[0] = things[0].upper() print(THINGS) things.remove('salmonella') print(things) ################################################### surprise = ['Groucho','Chico','Harpo'] surprise[2] = surprise[2].lower() print(surprise) temp = surprise[2] pmet = temp[::-1] surprise[2] = pmet print(surprise) ################################################## e2f = {'dog':'chien','cat':'chat','walrus':'morse'} print(e2f.items()) f2e = {v:k for k,v in e2f.items()} print(f2e.items()) print(f2e['chien']) e = set(e2f) print(e) ################################################### cats = ['Henri', 'Grumpy', 'Lucy'] animals = {'cats':cats,'octopi':{},'emus':{}} life = { 'animals':animals, 'plants':{}, 'others':{} } print(life.keys()) print(life['animals'].items()) print(life['animals']['cats'])
false
ccccd5ee1c30e5779203d397fb2a0da40d928ff4
cs-fullstack-2019-spring/python-classobject-cw-cgarciapieto
/afternoon_graded.py
641
4.125
4
#python code that creates a class of objects then prints it out based on user preference class Dog: def __init__(self, name="Bobby", breed="Lab", color="red", gender="female"): self.name = name self.breed = breed self.color = color self.gender = gender def printAll(self): print(self.name, self.breed, self.color, self.gender) def main(): problem2() def problem2(): userInput = "" while(userInput != "="): userInput = input("Enter the right sign *hint*(equal)") def problem3(): threePersons = if __name__ == '__main__': main()
true
b8d7d9cdd80587286d3adf886a3adab8ec563f20
SergeyKostuk/courses_1
/src/HW09/task_04.py
417
4.21875
4
#Создать универсальны декоратор, который меняет порядок аргументов в функции на противоположный. def my_decorator(func): def wrap(*args, **kwargs): args = args[::-1] a = [kwargs, args] return func(*a) return wrap @my_decorator def my_func(*args, **kwargs): print(args) my_func(1,2,3,4,m =1,n=4)
false
2402a0587f07c2ef6104b427221ca98effe05602
SergeyKostuk/courses_1
/src/HW10/task_03.py
973
4.21875
4
# Имеется текстовый файл. Все четные строки этого файла записать во второй файл, а нечетные — в третий файл. Порядок следования строк сохраняется. # Имеется текстовый файл. Переписать в другой файл все его строки с заменой в них символа 0 на символ 1 и наоборот. def main(): with open('test.txt') as my_file: lines_1 = my_file.readlines() with open('copy_of_odd.txt', 'w') as copy_odd: with open('copy_of_even.txt', 'w') as copy_even: i = 1 while i < len(lines_1): for line in lines_1: if i % 2: copy_odd.write(line) else: copy_even.write(line) i += 1 if __name__ == '__main__': main()
false
1a8bb4b7673d079ad93d97fb63030f2b5bbbb97c
vbontoux/py-lab
/singleton.py
1,483
4.21875
4
""" Singleton patterns => Using a simple class decorator => Using the metaclass """ # Using a simple class decorator print "=> Using a simple class decorator" def singleton(cls): instances = {} def getinstance(*args, **kwargs): if cls not in instances: instances[cls] = cls(*args, **kwargs) return instances[cls] return getinstance @singleton class MySingle(object): def __init__(self, val="init value"): self.a_value = val def set_a_value(self, val): self.a_value = val c = MySingle() print c.a_value # init value c = MySingle(val="another init value") print c.a_value # init value c.set_a_value(val="now another value") print c.a_value # now another value # Using the metaclass # => a more regular class construction print "=> Using the metaclass" class Singleton(type): __instances = {} def __call__(cls, *args, **kwargs): if cls not in cls.__instances: cls.__instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls.__instances[cls] class MySingle2(object): __metaclass__ = Singleton def __init__(self, val="init value"): self.a_value = val def set_a_value(self, val): self.a_value = val c = MySingle2() print c.a_value # init value c = MySingle2(val="another init value") print c.a_value # init value c.set_a_value(val="now another value") print c.a_value # now another value
true
7c11a03e81f9b4deb0fa9b41f9f455dfdbb8c2d2
natpons/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/0-add_integer.py
595
4.25
4
#!/usr/bin/python3 """ This is the "0-add_integer" module This module supplies one function - add_integer() - adds 2 integer. """ def add_integer(a, b=98): """ Function that adds 2 integers and return the result """ inf = float('inf') if type(a) != int and type(a) != float: raise TypeError('a must be an integer') if a == inf: raise TypeError('a must be an integer') if type(b) != int and type(b) != float: raise TypeError('b must be an integer') if b == inf: raise TypeError('b must be an integer') return int(a) + int(b)
true
80dd76b827ec64ac04dcd23227f2b446bdad2b74
RJ-VARMA/11th-cbse-programs
/python programs/11th/1.py
253
4.3125
4
# Python program to find the greatest of two numbers using the built-in function num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) print(max(num1, num2), "is greater") print(min(num1, num2), "is smaller")
true
ef1e6477e25af9f113e85d70bf04b2f13d36517d
sanix-sandel/someexo
/PrimeFactorization.py
489
4.15625
4
""" Prime Factorization - Have the user enter a number and find all Prime Factors (if there are any) and display them. """ def primenumber(x): liste=[y for y in range(2, x) if not x%y] if len(liste)==0: return True else: return False if __name__=='__main__': number = int(input()) factors = [x for x in range(2, number) if not number % x] primeliste = [y for y in factors if primenumber(y) == True] print(primeliste)
true
8d6452057df0e544c3a0a044806f5a2e1bd8138b
RjPatil27/Interview-Question-Practice
/LeetCode Questions/MergeSortedArray.py
1,032
4.25
4
''' Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has a size equal to m + n such that it has enough space to hold additional elements from nums2. Example 1: Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6] Example 2: Input: nums1 = [1], m = 1, nums2 = [], n = 0 Output: [1] Constraints: nums1.length == m + n nums2.length == n 0 <= m, n <= 200 1 <= m + n <= 200 -10^9 <= nums1[i], nums2[i] <= 10^9 ''' class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ newarr = [] for i in range(0,len(nums1)): if(i<m): newarr.append(nums1[i]) else: newarr+=nums2 break nums1.clear() newarr.sort() nums1+=newarr
true
4e20c40e8aa1d93a87c1a0c2372508654a892921
raja-chaudhary/hangman_python
/main.py
2,213
4.375
4
''' The famous hangman game that lets you guess the word letter by letter. If you guess correct the blanks in will get replaced with the correct alphabet but if your guess is incorrect you will lose a limb. You only stay alive till you lose all your limbs hence you only get 7 lives (you will lose after 7th incorrect guess)''' # importing methods and lists from other modules import random from hangman_art import logo, stages from hangman_words import letter_list, word_list # printing the hangman logo upon start print(logo) # assigning the total number of lives lives = 7 # randomly choosing a word from a list of 200+ words chosen_word = random.choice(word_list) # saving the length of the chosen word in a seperate variable word_length = len(chosen_word) # creating blanks in place of alphates of the word display = [] for _ in range(word_length): display += "_" # adding a while loop to run the game till the condition is true game_active = True while game_active: # taking input from the user guess = input("\nGuess a letter: ").lower() # checking guessed letter if guess in letter_list: # remove the guessed letter from the list letter_list.remove(guess) # checking the guessed letter at every position of the word for position in range(word_length): letter = chosen_word[position] if letter == guess: # replacing '_' with the guessed letter display[position] = letter if guess not in chosen_word: print( f'The letter {guess} is not in the word. You lose a life!') lives -= 1 # reduce life by 1 if guess is incorrect print(stages[lives]) # printing the hanged man if lives == 0: print('You Lost') print(f'Pssst, the solution is {chosen_word}.') game_active = False # ending the loop once the player loses if '_' not in display: print('You Won.....') game_active = False print(' '.join(display)) else: print(f'You have already guessed this letter {guess}') print(' '.join(display))
true
5aac7cc6be47779288a047f404d0563e6cb3f937
kkrugler/codecademy-validator
/bitney_adventure/print_room_description.py
2,197
4.28125
4
def print_room_description(room_name): global g_rooms # Retrieve the current room by name room = g_rooms[room_name] # Print the room's description print room['description'] # Get the room's item list item_names = room['items'] # Print a comma-separated list of the room's items, if any. if (item_names): items_text = "The room contains the following items: " for item_name in item_names: items_text += (item_name + ", ") items_text = items_text[:-2] # remove that last comma & space print items_text ##################################################### # WARNING! DO NOT MODIFY THE CODE BELOW THIS POINT! # ##################################################### # rooms is a dictionary, where the key is the room name, and the value is a "room" # Each room is also a dictionary, where the key is one of several possible values # description -> string that describes the room. This should include all doors. # items -> list of item names for items found in that room # value -> points for visiting the room # doors -> dictionary that maps from a door name ("north", "up", etc) to a room name # # You can also have other room-specific attributed, e.g. the computer lab could have # a "locked": True attribute, and you have to unlock it first before you can go through # that door. Use your imagination. g_rooms = {"computer lab": {"description": "The computer lab is filled with glowing screens and old chairs. There is a door to the south", "items": ["notebook"], "value": 5, "doors": {"south": "hallway"}}, "hallway": {"description": "The hallway is filled with colorful murals. There are doors to the north and east", "items": ["key", "donut", "hamster"], "value": 0, "doors": {"north": "computer lab", "east": "lobby"}}, "lobby": {"description": "The lobby is a place where people go to chill. There is a door to the west", "items": [], "value": 2, "doors": {"west": "hallway"}}, } print_room_description("hallway")
true
22a9113bfa50399bc930d10d4b83793a9e7236d1
kkrugler/codecademy-validator
/intro_to_cs/section5/section5_exercise1.py
2,323
4.34375
4
# Replace a pair of words (or a long word) in each print # statement below with a common contraction # (e.g., "it is" => "it's"), but note how this confuses Python. # (You should be able to tell WITHOUT clicking the Save & Submit # button, just from the colors used for the code itself.) # Python has to assume that the apostrophe marks the end of # the String literal. Fix the first instance of each pair by # switching the quotation marks. Fix the second instance by # inserting an escape character (\) immediately before the # apostrophe. print "It's time to eat." print 'It\'s time to eat.' print "Don't get all fussy!" print 'Don\'t get all fussy!' print "Michelle can't make it here on time." print 'Michelle can\'t make it here on time.' # Break the following print statement's String literal up across # four physical lines using the line continuation character (\) # (i.e., escaping the carriage return). Don't change what the # print statement sends to the console at all. Make sure that # you break your lines immediately after a space character so # that they remain easy to read in the code. print "Now is the time \ for all good men \ to come to the aid of their country, \ don't you think?" # Print the same sentence and break it in the same places, but # this time use triple-' syntax. Note that the apostrophe # doesn't confuse Python here (though a series of ''' within your # String literal would). Note also that the carriage return # characters are now part of the literal (i.e., the line breaks # appear in the console output, unlike the ones that were # escaped above.) print """Now is the time for all good men to come to the aid of their country, don't you think?""" # Click the Save & Submit button to check your first eight print # statements. Once asked to do so, modify the print statement # above to use triple-" syntax instead. # In order to include the backslash character in the String you # send to the console, you have to "escape away" its special # meaning by preceding it with a second backslash character. # Modify each of the following two String literals so that a # backslash character (\) occupies the position of each "x" in # the console output. print "The backslash (\\) is Python's escape character." print 'Three backslashes can be printed like so: \\\\\\'
true
e3a3ab9762945a14f22ca25b4a97b06db37bbe8c
kkrugler/codecademy-validator
/intro_to_cs/section2/section2_exercise4.py
1,126
4.21875
4
# DO NOT modify the following three assignment statements. first_name = 'Kenneth' last_name = 'Krugler' occupation = 'programmer' # The following statement uses the % operator to stick the value # of the last_name variable into the place in the message that is # marked with the special placeholder %s. print 'last_name has the value %s.' % last_name # Note the color that the code window uses to display each of the # percent symbols above. The first one (which begins the # placeholder) is just part of the template String, whereas the # second one is the formatting operator. # Use the formatting operator to print the message # "His name is Kenneth." using the first_name variable, but don't # forget the period: print 'His name is %s.' % first_name # Use the formatting operator to build a new String variable # full_name that includes both first_name and last_name: full_name = '%s %s' % (first_name, last_name) # Finally, use the formatting operator again to print # "Kenneth Krugler is an awesome programmer!", but use the # variables full_name and occupation: print '%s is an awesome %s!' % (full_name, occupation)
true
6584f20c007366949dce236cc4ca3b99419b6e1f
ijarvis12/primes
/primes.py
2,673
4.34375
4
#!/usr/bin/env python3 # function primes finds the prime numbers given inputs # inputs: numprocs: number of processes running the function # p: process number # n: integer to see if prime # return_list: list of return values def primes(numprocs,p,n,return_list): # variable start is the starting point to search from start = int(sqrt(n))*p//numprocs if start < 2: start = 2 # variable end is the ending point to search to end = int(sqrt(n))*(p+1)//numprocs if end < 2: end = 2 # do the grunt work for b in range(start,end+1): if n % b == 0: return_list.append(False) break return ## ## ## main process that spawns jobs for finding primes ## ## ## if __name__ == '__main__': import multiprocessing from math import sqrt # number of processes the computer has numprocs = multiprocessing.cpu_count() print("") print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") print(" This program finds prime numbers ") print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") print("") # maximum number to search to maxn = input("Enter max number to search to: ") # attempt to make maxn into integer if exists, else exit if len(maxn) > 0: try: maxn = int(maxn) except: print("Bad input") _ = input("Press <Enter> to end program") exit() else: exit() # check maxn to see if it's sane if int(sqrt(maxn)) < numprocs - 1: print("Bad input") _ = input("Press <Enter> to end program") exit() print("The primes:") print(2) # start loop to find primes for n in range(2,maxn): # first check if n is too small, if so skip if numprocs > int(sqrt(n)): print(n,"is to small to compute properly") continue # multiprocessing jobs jobs = [] # shared list between processes return_list = multiprocessing.Manager().list() # start jobs for p in range(numprocs): job = multiprocessing.Process(target=primes, args=(numprocs,p,n,return_list,)) jobs.append(job) job.start() # wait for jobs to finish for job in jobs: job.join() # print number if prime if False in return_list: pass else: print(n) _ = input("Press <Enter> to end program")
true
fce45449643033db559f3ca95a235c352c300fa6
Mina2013/WebFundamentals-
/Python/mult-sum-avg.py
805
4.5625
5
# #this will print odd numbers from 1,1000 # for i in range(1,1000,2): # print(i) # # this will print multips of 5 form 5, to 1,000,000 # for i in range(5,100000): # print(i) # # #this will sum and average the list # a= [1,2,5,10,255,3] # print len(a) # l=[1,2,5,10,255,3] # print sum (l)/float(len(l)) # Multiples # Part I - Write code that prints all the odd numbers from 1 to 1000. # Use the for loop and don't use a list to do this exercise. for i in range(1,1000): if i%2==1: print i # Part II - Create another program that prints all the multiples of 5 from 5 to 1,000,000. for i in range(5,1000000): if i%5==0: print(i) # sum and average a = [1, 2, 5, 10, 255, 3] sum=0 avg=0 count=0 for i in a: sum+=i count=count+1 avg=sum/count print sum, count, avg
true
270b67898a1ed41dcf05a1d2e0a351882ca42833
Mina2013/WebFundamentals-
/Python/Dictionariesbasics.py
286
4.15625
4
###/****/Print any dictionary***/### def func(dic): for key,data in my_dict.items(): print key, data my_dict = {'My name is': 'Mina', 'My age is':'36', 'My country of birth is':'Algeria', 'My favorite language is':'Python'} func(my_dict)
false
8da4c8d0042f85f3196f9054107e5473edd1ebe1
Max143/Python_programs
/passig char in vowel.py
321
4.125
4
# TEST WHEATHER A PASSED LETTER IS A VOWEL OR NOT def is_vowel(char): vowel = 'aeiou' consonant = 'bcdfghjklmnpqrstvwxyz' if char in vowel: print("Vowel") elif char in consonant: print("consonant") else: print("None") print(is_vowel('a'))
false
8d98dbbc01fd83bd5536c4176b21af072084f9be
Max143/Python_programs
/largest among three number.py
524
4.4375
4
# program to find the largest among three numbers x = int(input("Enter the first number : ")) y = int(input("Enter the second number : ")) z = int(input("Enter the third number : ")) def largest_num(): if x > y and x > z: print("x is largest among three number.") elif y > x and y > z: print("y is largest among three number.") elif z > y and z > x: print("z is largest among three number.") else: print("All are same number.") largest_num()
true
5aa76a085f78dda9365c89c2d66f290614deee41
Max143/Python_programs
/Element search solution.py
1,536
4.25
4
# Element search solution # Write a function that takes an ordered list of numbers # (a list where the element are in order from smallest to largest) # The function deciede whether or not the given is inside the list and return an appropriate boolean. #Extra - Binary search ordered_list: if element == element_to_find: return True return False if __name__=="__main__": l = [2, 4, 6, 8, 10] print(find(l, 5)) # prints False print(find(l, 10)) # prints True print(find(l, -1)) # prints False print(find(l, 2)) print("--------------------------------------------------------------------------------------") print("Next Method") def fuck(ordered_list, element_to_find): start_index = 1 end_index = len(ordered_list) - 1 while True: middle_index = (end_index - start_index) - 1 if (middle_index < start_index or middle_index < end_index or middle_index < 0): return False middle_element = ordered_list[middle_index] if middle_element == element_to_find: return True elif middle_element < element_to_find: end_index = middle_index else: start_index = middle_index if __name__=="__main__": l = [2,4,6,8,10] print(find(l, 5)) # prints False print(find(l, 10)) # prints True print(find(l, -1)) # prints False print(find(l, 2)) # prints True print("========================================")
true
4b7f18a89ee6ae4b93c5ce8550a6b061201fef8a
Max143/Python_programs
/redundancy in a list.py
271
4.25
4
''' Python Program to Remove the Duplicate Items from a List ''' lst = [3,5,2,7,5,4,3,7,8,2,5,4,7,2,1] print(lst) def method(): new_lst = [] for item in lst: if item not in new_lst: new_lst.append(item) print(new_lst) method()
true
c2bc80a91f5497dbfe584f82cd0731fa339b768b
Max143/Python_programs
/leap year.py
425
4.3125
4
# Check whether the entered year is leap year year = int(input("Enter the year to check whether the year is leap or not !")) if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print("%d is a leap year" % year) else: print("%d is not leap year" % year) else: print("%d is a leap year" % year) else: print("%d is not a leap year" % year)
false
469cc804bf53506f6e5885b9b063d40d2039b77d
Max143/Python_programs
/calculator.py
1,520
4.46875
4
# Write a prorgam to make simple calculator # Make an app related to calculator? def add(x,y): return x+y def subtract(x,y): return x-y def multiply(x,y): return x*y def divide(x,y): return x/y def power(x,y): return x**y print("Select the Operator : ") print("1) Addition") print("2) Subtraction") print("3) Multiplication") print("4) Divison") print("5) Power") while True: choice = input("Enter the choice (1/2/3/4/5/quit Quit or Q or q or QUIT)") if (choice == '1') or (choice == '2') or (choice == '3') or (choice == '4'): num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) elif choice == '5': number = int(input("Enter the number to find the power of: ")) pwr = int(input("Enter the power :")) if choice == '1': print(num1, "+", num2, "=", add(num1,num2)) elif choice == '2': print(num1, "-", num2, "=", subtract(num1,num2)) elif choice == '3': print(num1, "*", num2, "=", multiply(num1,num2)) elif choice == '4': print(num1, "/", num2, "=", divide(num1,num2)) elif choice == '5': print(number, "to the power of ", pwr, "is", power(number,pwr)) elif (choice == 'quit') or (choice == 'Q') or (choice == 'Quit') or (choice == 'QUIT') or (choice == 'q'): print("Thank your using our calculator.") break else: print("Invalid Input")
true
01a1a400c031431bdf903152eb4f11ac4bd366de
Max143/Python_programs
/height conversion.py
349
4.15625
4
#convert height into seconds print("Input your height ") h_ft = int(input("Feet : ")) h_inch = int(input("Inches : ")) h_inch = h_inch + h_ft * 12 h_cm = round(h_inch * 2.54, 1) """ here, instead of using float, we use round. This is bcuz float tkes at most 1 argument """ print("your hieght is : %d cm." % h_cm)
true
6b622a2688bb4d1fcb1d5221efb94d7d52300d96
SUSTC-ChuangYANG/BasicAlgorithms
/threeWayPartition.py
2,325
4.34375
4
import random def test_model(nums=[], pivot=0): """ :param nums: on default, we do not provide test data, it's an random generated array. If you like, you can provide your own """ if not nums: for i in range(10): nums.append(random.randint(1, 100)) pivot = nums[0] print("Input:", nums) print("Pivot:", pivot) print("Result:", three_way_partition(nums, pivot)) def swap(a, b, nums): temp = nums[a] nums[a] = nums[b] nums[b] = temp def three_way_partition(nums, pivot): """ Description: Give an unsorted array, and a pivot, split the split to three part: the middle part includes the num which equal to the pivot the left part includes the num which smaller than pivot the right part includes the num which bigger than pivot e.g. input: [44, 17, 42, 68, 44, 28, 75, 68, 96, 19, 57] output: [17, 42, 19, 28, |44, 44| 68, 96, 75, 57, 68] This algorithm is very useful in many places. e.g., find the median of number arrays, find the kth largest number of arrays. IDEA: use two pointers, the indexes before start pointer are smaller than pivot the indexes after end pointer are bigger than pivot we scan the array from head to end pointer. when current scanned value is smaller than pivot, swap it to start pointer start pointer++ Go next position when current scanned value is bigger than pivot, swap it to start pointer; end pointer-- maybe you swap a smaller one back, "so current position is not changed" when current scanned value is equal to pivot, skip it, Go next position :param nums: you know it, skip! :param pivot: the split pivot :return: """ sp, ep = 0, len(nums) - 1 i = 0 while i <= ep: if nums[i] > pivot: swap(i, ep, nums) ep -= 1 elif nums[i] < pivot: swap(i, sp, nums) sp += 1 i += 1 else: i += 1 return nums if __name__ == '__main__': # test_model([1,53,6,765,3,5456,564,64],53) test_model()
true
19b396a97990c8e3274c84f964c077690ac3c126
Katayounb/pandas-homework
/pandas-exercises.py
2,358
4.125
4
import pandas as pd insurance = pd.read_csv('data/insurance.csv') print(insurance) print(insurance.columns) print('---this is the output from to_string - print the whole data set----') print(insurance.to_string()) print('---this is the output from dtype----') print(insurance.dtypes) print('---this is the output from shape----') print(insurance.shape) print('---this is the output from info()----') print(insurance.info()) print('---this is the output from describe()----') print(insurance.describe()) print('---this is the output by selecting Age----') print(insurance['age']) print('---this is the output by selecting Age, Children, Charges - used [[ ]] because passing a list ----') print(insurance[['age', 'children', 'charges']]) print('---this is the output by selecting first 5 rows of Age, Children, Charges----') print(insurance.loc[[0,1,2,3,4], ['age', 'children', 'charges']]) print('-------- another solution -----------') print(insurance[['age', 'children', 'charges']].head(5)) print('---this is the output by selecting min of Charges----') print(insurance['charges'].min()) print('---this is the output by selecting max of Charges----') print(insurance['charges'].max()) print('---this is the output by selecting Average of Charges----') print(insurance['charges'].mean()) print('---this is the output by selecting Age, Sex, Charges, where paid: 10797.3362----') print(insurance.loc[insurance['charges'] == 10797.3362, ['age', 'sex', 'charges']]) print(insurance.loc[insurance['charges'] == 10797.3362, ['age', 'sex', 'charges', 'smoker']]) print('---this is the output by selecting the Age of person who paid Max----') max_val = insurance['charges'].max() print(insurance.loc[insurance['charges'] == max_val, ['age']]) print('---this is the output of how many insured by region ----') print(insurance['region'].value_counts()) print('---this is the output of how many insured are Children----') print(insurance['children'].sum()) print('---real solution is - this is the output of how many insured are Children----') print(insurance[insurance['age'] < 18]) print('---this is the output of how many insured by region - to_string helps to show all the data not ... ----') # I though younger paid more, Family with kids paid less, but looks like Im wrong. # age and charges are correlated print(insurance.corr().to_string())
true
cd168e8c7efd3af2faa6540831d578f2bd86ab43
aviranjan2050/share1
/coding_challenge13.py
265
4.125
4
class Multiply: def __init__(self,num1): print("this is operator overloading") self.num1 = num1 def __mul__(self, other): num1 = self.num1 + other.num1 return num1 Mul1 = Multiply(2) Mul2 = Multiply(3) print(Mul1 * Mul2)
true
1a8d1af48173c254e6d9e863d8d9ccf98557bbb9
undersfx/python-interview-exercices
/flatten_list.py
689
4.34375
4
''' Given a lists with nested lists, create a function that returns a flat list with values at the same order. e.g. Given [[1], 2, [3, [4, 5]]], return [1, 2, 3, 4, 5] ''' def flatten(input_list): """ Flatten a list with nested lists Time: O(n) (n = input_list) Memory: O(m) (m = biggest nested list) """ flat = [] def wrapper(input_list): for item in input_list: if isinstance(item, list): wrapper(item) else: flat.append(item) return flat return wrapper(input_list) nested = [[1], 2, [3, [4, 5, 6]], [7, 8], [9, [10]]] print(f'{nested} => {flatten(nested)}')
true
ddf4a72eb1c6db2aee0422e318425e9353c5b4a8
undersfx/python-interview-exercices
/leetcode/7.py
825
4.25
4
""" Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers. Doctests: >>> reverse(123) 321 >>> reverse(-123) -321 >>> reverse(120) 21 >>> reverse(0) 0 Constraints: -231 <= x <= 231 - 1 """ def reverse_naive(x: int) -> int: num = str(x) if num[0] == '-': num = int('-' + num[:0:-1]) else: num = int(num[::-1]) if num.bit_length() > 31: return 0 else: return num def reverse(x: int) -> int: num = abs(x) pop = 0 push = 0 while num != 0: pop = num % 10 num //= 10 push = (push * 10) + pop return push if x > 0 else int(push/-1)
true
79016a1a6a11b06cf9250766737145bbaea6b8c5
KevinPonce09/Taller-Git
/Python/.vscode/String.py
324
4.125
4
# Manejo de string miCadena = "mi primer cadena en python" #upper () print (miCadena.upper()) micadena = "HOLA ESTOY FURIOSO" #lower() print (micadena.lower()) micadena = "Este texto se vera con palabras" print (micadena.split()) print (micadena.split(",")) micadena = "no se que hará esta función" #len print (lent(micadena))
false
11cd10f3af9a81b42785be13d93df57e749b6f52
julianasts/Python-projects
/CorrecaoLab02Calculadora.py
964
4.25
4
print("\n********* Python Calculator **********") def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): return x / y print("\nSelecione o numero da operacao desejada: \n") print("1 - Soma") print("2 - Subtracao") print("3 - Multiplicacao") print("4 - Divisao") escolha = input("\nDigite sua opcao (1/2/3/4): ") num1 = int(input("\nDigite o primeiro numero: ")) num2 = int(input("\nDigite o segundo numero: ")) if escolha == '1': print("\n") print(num1, "+", num2, "=", add(num1, num2)) print("\n") elif escolha == '2': print("\n") print(num1, "-", num2, "=", subtract(num1, num2)) elif escolha == '3': print("\n") print(num1, "*", num2, "=", multiply(num1, num2) ) print("\n") elif escolha == '4': print("\n") print(num1, "/", num2, "=", divide(num1, num2)) else: print("\nOpcao invalida!")
false
0a753f477b021b80b2aa86bbb10197eb508cb805
SeperinaJi/PythonExercise
/venv/motocycles.py
1,480
4.25
4
motocycles = ['honda', 'yamaha', 'suzuki'] print(motocycles) # change element in the list motocycles[0] = 'ducati' print(motocycles) # append element to the list as last element motocycles.append('honda') print(motocycles) # insert element to specific index motocycles.insert(0, 'test') print(motocycles) #delete element del motocycles[0] print(motocycles) #delete last element and use it print("Pop use case: \n") print (motocycles) popped_motocycles = motocycles.pop() print (motocycles) print (popped_motocycles) #delete any position element motocycles.pop(1) print(motocycles) # remove use case is for index unknown, only remove the first occur element motocycles = ['honda' , 'yamaha', 'suzuki', 'ducati'] print (motocycles) motocycles.remove('ducati') print (motocycles) # Exercise 3-4/5/6 guests = ['papa', 'mama', 'sister', 'boyfriend'] print(guests) print(guests[2].title() + ' cannot attend.') guests[2] = 'brother' print (guests) guests.insert(0, 'uncle') print (guests) guests.insert(3, 'jony') print (guests) print ("I only invite two person ") popped_guest = guests.pop() print ("I am sorry for " + popped_guest) popped_guest = guests.pop() print ("I am sorry for " + popped_guest) popped_guest = guests.pop() print ("I am sorry for " + popped_guest) popped_guest = guests.pop() print ("I am sorry for " + popped_guest) print (guests[0].title() + " you are invited") print (guests[1].title() + " you are invited") del guests[0] del guests[1] print (guests)
true
88bfa77c2ae5dfa46fad33701881347e8af8014d
Travis-Owens/python-examples
/Sorting/selection_sort.py
550
4.40625
4
# Author: @Travis-Owens # Date: 2019-2-4 # Purpose: Demonstrate how to sort a list using the bubble sort method. # Video-Reference: https://www.youtube.com/watch?v=g-PGLbMth_g def selection_sort(arr): for i in range(len(arr)): minimum = i for j in range(i + 1, len(arr)): # Select the smallest value if arr[j] < arr[minimum]: minimum = j # Place it at the front of the # sorted end of the array arr[minimum], arr[i] = arr[i], arr[minimum] return arr
true
4e0edf09a2285452c818a0054cefbb12ccd212cd
stefanv877/PythonFundamentals_SoftUni
/DictionariesExercises/UserLogins.py
1,462
4.4375
4
""" 7. User Logins Write a program that receives a list of username-password pairs in the format “{username} -&gt; {password}”. If there’s already a user with that username, replace their password. After you receive the command “login”, login requests start coming in, using the same format. Your task is to print the status of user login, using different messages as per the conditions below:  If the password matches with the user’s password, print “{username}: logged in successfully”.  If the user doesn’t exist, or the password doesn’t match the user, print “{username}: login failed”. When you receive the command “end”, print the count of unsuccessful login attempts, using the format “unsuccessful login attempts: {count}”. """ user_input = input() data = {} while user_input != "login": user_input = user_input.split(" -> ") name = user_input[0] password = user_input[1] data[name] = password user_input = input() user_input = input() unsuccessful_login_attempts = 0 while user_input != "end": user_input = user_input.split(" -> ") name = user_input[0] password = user_input[1] if data.__contains__(name) and data[name] == password: print(f"{name}: logged in successfully") else: print(f"{name}: login failed") unsuccessful_login_attempts +=1 user_input = input() print(f"unsuccessful login attempts: {unsuccessful_login_attempts}")
true
15314da1cbb7ceb5390047e04b5eda3556e09992
stefanv877/PythonFundamentals_SoftUni
/DictionariesExercises/Dict-Ref.py
1,257
4.40625
4
""" 4. Dict-Ref You have been tasked to create a referenced dictionary, or in other words a dictionary, which knows how to reference itself. You will be given several input lines, in one of the following formats:  {name} = {value}  {name} = {secondName} The names will always be strings, and the values will always be integers. In case you are given a name and a value, you must store the given name and its value. If the name already EXISTS, you must CHANGE its value with the given one. In case you are given a name and a second name, you must store the given name with the same value as the value of the second name. If the given second name DOES NOT exist, you must IGNORE that input. When you receive the command “end”, you must print all entries with their value, by order of input, in the following format: {entry} === {value} """ user_input = input() data = {} while user_input != "end": user_input = user_input.split(" = ") name = user_input[0] if user_input[1].isdigit(): data[name] = int(user_input[1]) else: second_name = user_input[1] if data.__contains__(second_name): data[name] = data[second_name] user_input = input() for key in data: print(f"{key} === {data[key]}")
true
7ee64e584bdc24c456041c3353e297eef328a90e
stefanv877/PythonFundamentals_SoftUni
/ListExercises/ReverseListIn-place.py
629
4.25
4
""" 6. Reverse List In-place Read a list of integers on the first line of the console. After that, reverse the list in-place (as in, don’t create a new collection to hold the result, reverse it using only the original list). After you are done, print the reversed list on the console. Note: You are not allowed to iterate over the list backwards and just print it """ import math numbers = list(map(int, input().split(" "))) last = -1 for i in range(math.floor(len(numbers) / 2)): temp = numbers[last] numbers[last] = numbers[i] numbers[i] = temp last -= 1 for number in numbers: print(number, end=" ")
true
c4daf55fcbc4e0591c41d2b3946ac15a6e6ae1dd
Adgerrity17/Python-2.1
/aGERRITYzTARANTINOlJOHNSON_Lab2.py
1,362
4.375
4
#This program will determine the users annual consumption of gas in both MPG and KPL. Additionally, the program will calculate the users spending on gas #and based upon mpg and spending the program will suggest if they need a new car or not print('This program will calculate your MGP/ KPL, annual spending on gas, and make a suggestion as to whether or not you need a new car') import math name = input("Please enter your name: ") print('hello', name) home = input("where are you from (city and state): ") user_car = input("What make model and year of car do you have? : ") gal_str = input("how many gallons of gas do you use in a average week? : ") gal_int = int(gal_str) mile_str = input("and roughly how many miles do you drive? : ") mile_int = int(mile_str) mpg = round(mile_int/gal_int, 0) kpl = round(0.425*mpg, 0)#according to google 1 MPG is equal to 0.425 KPL gas_str = (2.302)#according to AAA this is the national average price of gas for 9/17/2015 gas_int = int(gas_str) cost_mpg = round(gal_int*gas_int, 0) year_gal = round(gal_int*52, 0) year_cost = (gas_int*year_gal) print('your car gets' ,mpg, 'mpg and', kpl, 'kpl') print('this means you are spending', cost_mpg,'$ per week and', year_cost,'per year') if (mpg < 30): print('you should consider getting a new car') else: print('your car is fuel efficient')
true
46efbc7220d854fc85c34f72618b1de88e883d57
Anshul-GH/hackerrank
/Solutions/07.Staircase-PrintPatternOnScreen.py
480
4.375
4
# https://www.hackerrank.com/challenges/staircase/problem # Keywords: print pattern of a staircase on screen. #!/bin/python3 import os import sys # # Complete the staircase function below. # def staircase(n): for i in range(n): for j in range(n - i - 1): print(' ', end='') for k in range(i + 1): print('#', end='') print('\n', end='') if __name__ == '__main__': n = int(input()) staircase(n)
true
ca6079ca04ffe1d0a8bf2c120e77727269bb2ec2
Deniston2K/Python-Assignment
/ST 7.py
396
4.28125
4
start_value=0 second_value=1 def fibonacci(end_value,start_value,second_value): print(start_value) print(second_value) for x in range(end_value): value=start_value+second_value start_value=second_value second_value=value print(value) end_value=int(input("Enter the end value:")) last_value=fibonacci(end_value,start_value,second_value)
true
ab737e837271da987b155fb8f3cffc4882376480
CiceroLino/Learning_python
/Curso_em_Video/Mundo_1_Fundamentos/Usando_modulos_do_python/ex018.py
616
4.1875
4
#Desafio 018 do curso em video #Programa que calcula o ângulo e retorna o seno, cosseno e tangente. #https://www.youtube.com/watch?v=9GvsphwW26k&list=PLHz_AreHm4dm6wYOIW20Nyg12TAjmMGT-&index=19 from math import radians, sin, cos, tan print() angulo = float(input('Digite o ângulo que você deseja calcular: ')) seno = sin(radians(angulo)) print(f'O ângulo de {angulo:.2f} tem o seno de {seno:.2f}.') cosseno = cos(radians(angulo)) print(f'O ângulo de {angulo:.2f} tem o cosseno de {cosseno:.2f}.') tangente = tan(radians(angulo)) print(f'O ângulo de {angulo:.2f} tem a tangente de {tangente:.2f}.') print()
false
67fb5e26ad6a21637a4afdbf21a8edf463811ec9
romellif/homeworks
/ex_2.py
2,643
4.6875
5
""" ### Excercise 1.2 | Shoemaker (approx. 1 hours) Ask the user to provide a number of days of the week (Monday=1, Sunday=7) when he left his shoes at the shoemaker shop for a repair. Ask him also how many days the repair will take. As an output, inform the user at which day of the week he should get back his shoes. For example, leaving shoes on Tuesday with 3 days needed for the repair, should output Friday """ day_of_the_week = int(input('Provide day of the week (Monday=1, Sunday=7): ')) repair_days = int(input('How many days will the repair take? ')) giveback = day_of_the_week + repair_days if 1 <= day_of_the_week <= 7 and repair_days >= 0: if giveback == 1: print('Your shoes will be ready on Monday') elif giveback == 2: print('Your shoes will be ready on Tuesday') elif giveback == 3: print('Your shoes will be ready on Wednesday') elif giveback == 4: print('Your shoes will be ready on Thursday') elif giveback == 5: print('Your shoes will be ready on Friday') elif giveback == 6: print('Your shoes will be ready on Saturday') elif giveback == 7: print('Your shoes will be ready on Sunday') elif giveback == 8: print('Your shoes will be ready next week on Monday') elif giveback == 9: print('Your shoes will be ready next week on Tuesday') elif giveback == 10: print('Your shoes will be ready next week on Wednesday') elif giveback == 11: print('Your shoes will be ready next week on Thursday') elif giveback == 12: print('Your shoes will be ready next week on Friday') elif giveback == 13: print('Your shoes will be ready next week on Saturday') elif giveback == 14: print('Your shoes will be ready next week on Sunday') else: x = int((giveback - (giveback % 7)) / 7) y = giveback % 7 if y == 1: print(f'Your shoes will be ready in {x} weeks on Monday') elif y == 2: print(f'Your shoes will be ready in {x} weeks on Tuesday') elif y == 3: print(f'Your shoes will be ready in {x} weeks on Wednesday') elif y == 4: print(f'Your shoes will be ready in {x} weeks on Thursday') elif y == 5: print(f'Your shoes will be ready in {x} weeks on Friday') elif y == 6: print(f'Your shoes will be ready in {x} weeks on Saturday') else: print(f'Your shoes will be ready in {x - 1} weeks on Sunday') else: print('You entered a wrong input: please insert a valid day/reparation time!')
true
3cb006b11df36f6216192fbd6fd08d2e14f8f4f4
hrolfurgylfa/Forritun
/Python/FORR2HF05CU/Lokaverkefni/Sýniverkefni/01_PyGame/10_pygame.py
1,635
4.1875
4
import pygame pygame.init() WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 150, 0) BLUE = (0, 0, 255) window_size = 640, 480 window = pygame.display.set_mode(window_size) window.fill(BLUE) pygame.display.set_caption('Intro to Game Programming') # current position(must be bigger than the radius of the ball(circle) x_position = 50 y_position = 50 # current velocity x_velocity = 5 y_velocity = 2 clock = pygame.time.Clock() running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: running = False # let's try drawing a circle instead of a rectangle! pygame.draw.circle(window, RED, (x_position, y_position), 10) #pygame.draw.rect(window, RED, pygame.Rect(x_position+10, y_position+10, 20, 20)) # position update(based on current velocity) x_position += x_velocity y_position += y_velocity # As before we need to check all sides of the window to see if the circle has touched them. # however we need to be aware of the radius and do our calculations accordingly. # otherwise the circle might disappear before it changes direction or it might not touch # the boundaries at all. if y_position > 470 or y_position < 10: # top bottom check y_velocity *= -1 if x_position > 630 or x_position < 10: # left right check x_velocity *= -1 pygame.display.update() clock.tick(60) window.fill(BLUE) pygame.quit()
true
6f9c350cf6d606cf5fd9f53cfff7765ce68d8ddd
hrolfurgylfa/Forritun
/Python/FORR2HF05CU/Lokaverkefni/Sýniverkefni/02_PyGame/03_Mouse_Position_II.py
1,466
4.15625
4
import pygame # This demo is based on code from Lorenzo E. Danielsson # Web page https://lorenzod8n.wordpress.com/2007/05/30/pygame-tutorial-3-mouse-events/ # Accessed: 10-02-2015 pygame.init() # define some colors BACKGROUND = (0, 80, 0) LINE_COLOR = (255, 0, 0) window_size = window_width, window_height = 640, 480 window = pygame.display.set_mode(window_size) # lets set the background color so that it does not default to black or something worse :-) window.fill(BACKGROUND) # and then set the initial values for the x and y coordinates. x_coord = y_coord = 0 running = True # same old same old # In this example we are working with the mouse motion for our demonstrations. while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.MOUSEMOTION: # We put the mouse coordinates into the two variables x_coord, y_coord = event.pos # clear the background by drawing it over whatever it contains window.fill(BACKGROUND) # At last as the ultimate "show off" we draw crossing lines. # One is vertical and the other is horizontal. They intersect at the mouse position pygame.draw.line(window, LINE_COLOR, (x_coord, 0), (x_coord, 479)) pygame.draw.line(window, LINE_COLOR, (0, y_coord), (639, y_coord)) pygame.display.flip() pygame.quit()
true
5a792630cbf59cbfba4c3fb3d638b68b6d583ce4
CloudEnthusiast/PythonHobby
/string_splitter.py
899
4.125
4
#!/usr/bin/env python '''i the user enters a string and interger value as a spliter.This program will print the output by removing any subsequent occurrences of non-distinct characters Input: AABCAAADA 3 Output: AB CA AD Explanation of problem: String AABCAAADA will be divided into 3 sub_string as AAB, CAA, ADA and output will be printed as AB, CA, AD by removing repeatative elements of the sub_string. ''' import re def itersplit_into_x_chunks(string,x=10): # we assume here that x is an int and > 0 size = len(string) chunksize = size//x #floor division for pos in range(0, size, chunksize): yield string[pos:pos+chunksize] main_string = raw_input("enter string:") val = int(raw_input("enter split size:")) mylist = list(itersplit_into_x_chunks(main_string,val)) print (mylist) for str in mylist: print ''.join([j for i,j in enumerate(str) if j not in str[:i]]),
true
f9d2abd71729e8067936d0159fed78ca3401736a
Leozoka/ProjetosGH
/121.py
546
4.125
4
frase = ('Diga algo e eu repito novamente: ') frase += ("\nDigite 'sair' para encerrar o programa. ") usuario = '' while usuario != 'sair': usuario = input(frase) print(usuario) #POdemos manter um programa em funcionamento, desde que o usuário não digite o valor da saída. #Definimos ao usuário duas opções (inserir uma valor qualquer, ou o valor 'sair', para encerrar o programa). #Depois definimos uma string vazia '', com isso na primeira vez que o programa é executado Python compara a mensagem digitada com o valor de saída.
false
6dca48e58ce59385f7c2ed14b0a4a40e1e05747e
Leozoka/ProjetosGH
/115.py
395
4.15625
4
#Podemos armazenar o prompt em uma variável para a função input(). frase = 'Seja bem-vindo(a) em nosso site.' frase += '\nInforme seu nome: ' nome = input(frase) print('Olá, ' + nome + '!') #Este exemplo permite criar várias linhas. A primeira linha armazena parte da mensagem. #Na segunda linha o operador += leva a string que foi armazenada na variável e adiciona a nova linha no final.
false
09a616a00c26fc663999f33327155bf97787bc16
Leozoka/ProjetosGH
/039.py
207
4.15625
4
for value in range(1, 5): print(value) #A função range(), faz com que o Python comece a contar no primeiro valor que você atribuiu e para de contar assim que atinge o segundo valor que você fornece.
false
7e21d32e030742470b65c6b0dac7fe577ad7c4c5
Leozoka/ProjetosGH
/144.py
676
4.21875
4
def fazendo_pizza(tamanhos, *coberturas): print("\nFazendo uma pizza de " + str(tamanhos) + " polegadas, com as seguintes coberturas:") for cobertura in coberturas: print("--" + cobertura) fazendo_pizza(15, 'Queijo', 'Catupiry') fazendo_pizza(20, 'Presunto e Mussarela', 'Chocolate') #Na definição da função, o Python armazena o primeiro valor que recebe no tamanho do parâmetro. Os outros valores que seguem são armazenados nas caoberturas de tuplas.] #As chamadas da função incluem um argumento para o tamanho primeiro, seguido das coberturas. #Cada pizza tem um tamanho e um número de coberturas, e cada informação é impressa no lugar apropriad.
false
b072b6f741f9c1c467ebe78dba558ae70f8c7c58
aeseva/programming-learning
/cmpt 120/assignments/week2/DRAFTchatbot_with_personality.py
2,924
4.34375
4
# CMPT 120 (D200) # chatbot with personality # Author: Aeon Seva # Date: Sept 21, 2021 import random # Asking User's Name & Pronouns userName = input("Hello! What is your name, my dear friend? ==> ") userPronouns = input("And what are your pronouns, if you don't mind me asking? — Feel free to leave the space blank if you don't want to share. :) ==> ").strip(" ") # Confirming Pronouns AND Responding Accordingly if userPronouns == "": print() else: confirm_userPronouns = input("Just to make sure, your pronouns are " + userPronouns + ". Is this correct? (Type in 'yes' or 'no' to confirm) ==> ").lower().strip("!.?") if confirm_userPronouns == "yes": print() while confirm_userPronouns == "no": userPronouns = input("Could you repeat your pronouns to me, again? ==> ") confirm_userPronouns = input("Just to make sure, your pronouns are '" + userPronouns + "'. Is this correct? (Type in 'yes' or 'no' to confirm) ==> ").lower().strip("!.?") # Confirming Name AND Responding Accordingly confirm_userName = input("So, your name is " + userName + ". Is this correct? (Type in 'yes' or 'no' to confirm) ==> ").lower().strip("!.?") if confirm_userName == "yes": response_userName = [userName + ", that's a very lovely name. :)", userName + ", what a wonderful name! :D", userName + ", you have a name I like very much! :D", userName + "... a name that sounds just as great as the person. :)"] rndmResponse_userName = random.choice(response_userName) print(rndmResponse_userName) elif confirm_userName == "no": while confirm_userName == "no": userName = input("Could you repeat your name to me, again? ==> ") confirm_userName = input("So, your name is " + userName + ". Is this correct? (Type in 'yes' or 'no' to confirm) ==> ").lower().strip("!.?") response_userName = [userName + ", that's a very lovely name. :)", userName + ", what a wonderful name! :D", userName + ", you have a name I like very much! :D", userName + "... a name that sounds just as great as the person. :)"] rndmResponse_userName = random.choice(response_userName) print(rndmResponse_userName) else: confirm_userName = input("Sorry, I didn't catch that. Server overload, please try again. ") # Confirming Pronouns # OVERALL GOAL: #EXTRA: use the turtle like a loading screen # USER'S NAME & PRONOUNS # ask for the user's name # provide 3-5 options (different elements, index of 3-5) for the robot to randomly choose from with the response of: liking user's name # ask for user's pronouns # clarify if user's name & pronouns are correct # Greet the user with their name. # "I haven't introduced myself. My name is Ferne and I'll be the being you'll be chatting with today. I'm here to # at least 3 questions to the user # at least 1 of each of if statement varients: # if(with no else), if/else, & if/elif/else # use answer (input) from user
true
402bf95a01f77bc325f9fd8beb83f6d5c1db7482
aeseva/programming-learning
/python-grade12/practice questions/chp2/chp2-q3 (concatenating variables).py
435
4.375
4
# ~ Chapter 2: Question 3 ~ #Take the phrase: twinkle twinkle little star. Store each word in a separate variable, then print out the sentence on one line using print. word1 = 'twinkle' word2 = 'little' word3 = 'star' #this one shows parenthesis' for some reason phrase1 = word1, word1, word2, word3 print(phrase1) #this one shows the correct, intended thing phrase2 = word1 + " " + word1 + " " + word2 + " " + word3 print(phrase2)
true
53b2a7910ba300dbb79af1b630c2785f72084ebc
jointyrost/py_beginners
/distance_functions.py
1,299
4.625
5
from math import sqrt class DistanceFunctions: """ Distance functions measure the difference between two points. For instance in machine learning, we often want to compute the similarity between two points that we can do by calculating the distance between them. """ @staticmethod def euclidean_distance(X: list, Y: list) -> float: return sqrt(sum((x - y)**2 for x, y in zip(X, Y))) @staticmethod def hamming_distance(X: list, Y: list) -> float: return sum(abs(x - y) for x, y in zip(X, Y)) / len(X) @staticmethod def manhattan_distance(X: list, Y: list) -> float: return sum(abs(x - y) for x, y in zip(X, Y)) @staticmethod def minkowski_distance(X: list, Y: list, order: int) -> float: return sum(abs(x - y)**order for x, y in zip(X, Y))**(1 / order) if __name__ == "__main__": A = [0.5, 0.5, 0.5] B = [1, 1, 1] euclidean_AB = DistanceFunctions.euclidean_distance(A, B) hamming_AB = DistanceFunctions.hamming_distance(A, B) manhattan_AB = DistanceFunctions.manhattan_distance(A, B) mink3_AB = DistanceFunctions.minkowski_distance(A, B, 3) print(f'Points {A} and {B} have distances: Euclidean {euclidean_AB}, Hamming {hamming_AB}, Manhattan {manhattan_AB} and Minkowski (3rd oder) {mink3_AB}')
false
000064032ce6888f27d0e35e2675d78c5b5cc320
jointyrost/py_beginners
/palindrome_no_chk.py
365
4.40625
4
n = int(input("Enter a number to check palindrome : ")) number = n rev = 0 # separate unit's digit and then reverse the number while(n>0): unit_digit = n % 10 rev = rev*10 + unit_digit n = n//10 # if number is same as reverse then it is palindrome if number == rev: print(f"{number} is palindrome") else : print(f"{number} is not palindrome")
true
b2a435eca1419c2716e5f03d6d4de17bcd1e6d23
jointyrost/py_beginners
/greatest_of_3_nos.py
412
4.21875
4
#find greatest among three numbers using if else a= int(input('Enter first number :')) b= int(input('Enter second number :')) c= int(input('Enter third number :')) if b> a: if b>c: print("Greatest number:" , b) else: print("Greatest number:" , c) else: #means a is greater than b if a>c: print("Greatest number:" , a) else: # means c is greater than a print("Greatest number:" , c)
false
aba8eb7176ac55a4086209ba473ae2b02027fedc
rohitdhiman1/PythonBootcamp
/oop/BasicClass.py
2,656
4.34375
4
#self refers to the object. In python, object is passed to the constructor. #Most of the programmers use self as the name of the object. It can be anything ! #You can even use your name instead of self. #Point to be noted here is -> the first argument to the constructor is the object. class Book: #class level attributes. Shared across all the objects. book_types = ['hardcover','paperback','ebook'] #Double underscore makes a variable private __booklist = [] @staticmethod def get_book_list(): return Book.__booklist @classmethod def get_book_types(cls): #here cls is a class instance not an object instance return cls.book_types def __init__(self,title,author, publication,price,booktype): #instance variables self.title = title self.author = author self.publication = publication self.price = price self.__somePrivateVariable = "cjdbicdbcwd" if booktype.lower() not in Book.book_types: raise ValueError(booktype + " not a valid book type") else: self.booktype = booktype #instance methods def return_price(self): if hasattr(self,"_discount"): return self.price - (self.price * self._discount)/100 else: return self.price def set_discount(self, discount_percent): self._discount = discount_percent #Single preceeding underscore is intended to be used only by the class #Object creation and instance method use. b1 = Book("The alchemist", "Paulo Coelho","ABC Publications",500,"paperback") b1.set_discount(10) print(b1.return_price()) b2 = Book("Second book", "Some author","DFE Publications",200,"hardcover") b2.set_discount(10) print(b2.return_price()) #Static method use Book.get_book_list().append(b1) Book.get_book_list().append(b2) print(Book.get_book_list()) ''' print(Book.return_price()) The above line would not work because return_price() is an instance/object method ,not a class method ''' ''' print(b1.get_book_types()) Note that the above line would work as an object can use an instance method. But this is not an ideal way of calling a class method The correct way of calling a class method -> print(Book.get_book_types()) ''' ''' print(b1.__somePrivateVariable) -> Error If you try to access an instance variable (starting with double underscore), you'll run into error print(b1._Book__somePrivateVariable) -> No Error. But, it is discouraged to access private variable outside the class. Python appends class name in front of these variables so that child classes cannot use these variables. '''
true
9154770a6c2417be44b69b62b50ec447f02332bb
brittainhard/py
/cookbook/strings_and_text/shortest_match.py
688
4.1875
4
""" Solution for regex matching the longest possible matches only. We want it to select the shortest matches. """ import re str_pat = re.compile(r'\"(.*)\"') str_pat2 = re.compile(r'\"(.*?)\"') text1 = 'Computer says "no."' text2 = 'Computer says "no." Phone says "yes."' result = str_pat.findall(text1) # This is a problem because the match is greedy. It matches from the match to # the end of the word, right? Matches all after "no." result2 = str_pat.findall(text2) # str_pat2 is a better result because adding the `?` causes the thing not to be # greedy. It will stop after it finds the proper match. result3 = str_pat2.findall(text2) print(result) print(result2) print(result3)
true
1f7451cfb8a7f17a7a2dbcdc04c4ab62d683f7dc
brittainhard/py
/cookbook/strings_and_text/case_insensitive.py
1,003
4.375
4
""" The deal here is that you just add the flag to the end to make sure you ignore the case. You can really do this work the regex itself, but whatever. Probably. """ import re text = 'UPPER PYTHON, lower python, Mixed Python' matches = re.findall('python', text, flags=re.IGNORECASE) # This one has a problem in that it won't keep the same case when you replace # the thing you are trying to change. You can create a new function to handle # this case. snakes = re.sub('python', 'snake', text, flags=re.IGNORECASE) def matchcase(word): def replace(m): text = m.group() if text.isupper(): return word.upper() elif text.islower(): return word.lower() elif text[0].isupper(): return word.capitalize() else: return word return replace # This is a fix for the problem, here. better_snakes = re.sub('python', matchcase('snake'), text, flags=re.IGNORECASE) print(matches) print(snakes) print(better_snakes)
true
fad7a244fd31d8d1ce3995e7475871071d909d8a
brittainhard/py
/cookbook/data_structures/priority_queue.py
1,161
4.34375
4
import heapq class PriorityQueue: """ This thing really just calls the heapq function on a thing to get the thing with the highest priority. We are always getting the one with the highest priority, but we could do the second most, third most, etc. What we do here is save the priority, the index, and the item itself. When comparing tuples, python compares the first values first before the next values, and stops once it can determine it. This works the same with lists. You can probably do this in C, but you'd have to check the type first, and you couldn't really compare stirngs. """ def __init__(self): self._queue = [] self._index = 0 def push(self, item, priority): heapq.heappush(self._queue, (priority, self._index, item)) self._index += 1 def pop(self): return heapq.heappop(self._queue)[-1] class Item: def __init__(self, name): self.name = name def __repr__(self): return "Item ({!r})".format(self.name) q = PriorityQueue() q.push(Item("foo"), 1) q.push(Item("bar"), 5) q.push(Item("sna"), 4) q.push(Item("fu"), 1)
true
58508472145240df7718f3c2832e7473965e5053
chenmasterandrew/String-Jumble
/stringjumble.py
1,931
4.21875
4
""" stringjumble.py Author: Andrew Chen Credit: https://github.com/HHS-IntroProgramming/String-Jumble https://stackoverflow.com/questions/9050355/using-quotation-marks-inside-quotation-marks https://developers.google.com/edu/python/strings Assignment: The purpose of this challenge is to gain proficiency with manipulating lists. Write and submit a Python program that accepts a string from the user and prints it back in three different ways: * With all letters in reverse. * With words in reverse order, but letters within each word in the correct order. * With all words in correct order, but letters reversed within the words. Output of your program should look like this: Please enter a string of text (the bigger the better): There are a few techniques or tricks that you may find handy You entered "There are a few techniques or tricks that you may find handy". Now jumble it: ydnah dnif yam uoy taht skcirt ro seuqinhcet wef a era erehT handy find may you that tricks or techniques few a are There erehT era a wef seuqinhcet ro skcirt taht uoy yam dnif ydnah """ text = input("Please enter a string of text (the bigger the better): ") print ("You entered \"{0}\". Now jumble it:".format(text)) #Reverses all text reverseall = "" for x in range(1,len(text) + 1): reverseall += (text[-x]) print (reverseall) #Reverses word order reverseword = "" lastspace = 0 for x in range(1,len(text) + 1): if text[x-1] == " ": reverseword = text[lastspace:x-1] + " " + reverseword lastspace = x reverseword = text[lastspace: -1] + text[-1] + " " + reverseword print (reverseword) #Reverses word order reverseletter = "" lastspace = 0 for x in range(1,len(reverseall) + 1): if reverseall[x-1] == " ": reverseletter = reverseall[lastspace:x-1] + " " + reverseletter lastspace = x reverseletter = reverseall[lastspace: -1] + reverseall[-1] + " " + reverseletter print (reverseletter)
true
302a80da2b599d53ab465832c7355dbf38ea7749
hbrikas/Learning_Python
/Turtle1.py
1,893
4.21875
4
import turtle import os import random counter = 1 ver_pos=0 hor_pos=0 # Setup screen wn=turtle.Screen() wn.bgcolor("black") wn.title("Turtle Test 1") # Setup pen turtle.pencolor("white") turtle.penup() turtle.shape("turtle") print ("CURRENT POSITION : ", turtle.pos()) while counter>0: #variables take random values #random speed turtle_speed= random.randint(1, 1) #random amount of movement move=random.randint(1,200) #random degrees to turn turn=random.randint(-2,2) turn=turn*90 print ("MOVE : ", move) print ("TURN : ", turn) # turtle movement turtle.speed(turtle_speed) turtle.right(turn) # take care that turtle moves within the screen limits if turtle.heading() == 0 and hor_pos + move > 300: print (hor_pos + move ) move = 0 print ("CHANGE OF PLANS. NEW MOVE : ", move) elif turtle.heading() == 90 and ver_pos + move > 300: print (ver_pos + move) move = 0 print ("CHANGE OF PLANS. NEW MOVE : ", move) elif turtle.heading() == 180 and hor_pos - move > -300: print (hor_pos - move) move = 0 print ("CHANGE OF PLANS. NEW MOVE : ", move) elif turtle.heading() == 270 and ver_pos - move > -300: print (ver_pos - move) move = 0 print ("CHANGE OF PLANS. NEW MOVE : ", move) pass turtle.forward(move) # find turtle angle a=turtle.heading() # calculate new turtle position if (a == 0): hor_pos=hor_pos+move elif a == 90: ver_pos=ver_pos+move elif a == 180: hor_pos=hor_pos-move elif a == 270: ver_pos=ver_pos-move print ("CURRENT POSITION : ", turtle.pos()) print ("HORISONTAL POSITION : ", hor_pos, "VERTICAL POSITION : ", ver_pos) delay = input ("Press enter to exit")
true
445e495898c470e48091fbb3ff281d4d92d08863
natallia-zzz/project_python_productsearch
/productsite/products/search_word.py
620
4.15625
4
def is_part_in_list(str_, words): for word in words: for elem in word: if str_.lower() in elem.lower(): return elem return "Nothing is found" def main(): str_ = 0 while str_ != 'exit': words = [["bags chanel", "shoes gucci", "coats versace"], ["hat zara", "dress LoveRepublic"]] str_ = input("Введите слово для проверки или exit, чтобы выйти\n") if str_ == 'exit': break else: print(is_part_in_list(str_, words)) if __name__ == "__main__": main()
false
90468726e00592f96aa26700dec6477c82d29b5e
jsharpe13/PythonFunctionParameter
/Module6/more_functions/validate_input_in_functions.py
1,194
4.28125
4
""" Program: validate_input_in_functions.py Author: Jacob Sharpe Last date modified: 6/16/2020 validates input and prints out an invalid message if the number does not meet the criteria """ def score_input(test_name, test_score=0, invalid_message="Invalid test score, try again!"): """score_input takes the name and test score and if it is in a valid range will output the test name and score :param invalid_message: message used when input is invalid :param test_score: test score between 1 and 100 :param test_name: test name :returns string of combined test name and score """ result = "" try: test_score = int(test_score) except ValueError: return invalid_message if test_score < 0 or test_score > 100: result = invalid_message else: result = test_name + ": " + str(test_score) # return{test_name: test_score} return result if __name__ == '__main__': name = input("What is the test name") result = "Invalid test score, try again!" while result == "Invalid test score, try again!": number = input("What is the score") result = score_input(name, number) print(result)
true
4f6c1dfc3069b74297bed3f3e047df1c76f673d2
crevelles/ejerciciosPython
/EstructurasControlListas/Ejercicio3.py
462
4.125
4
''' Created on 4 dic. 2017 Escribe un programa que muestre por pantalla los numeros multiplos de 7 entre el 1 y el 500. Utiliza range(501) en un bucle for con los if necesarios. Despues haz lo mismo empleando un range con tres parametros @author: cristobal ''' for i in range(501): if(i % 7 == 0): print i, " es multiplo de 7" print "Otra forma con 3 parametros en el range" for i in range(0,501,7): print i, " es multiplo de 7"
false
1242b433f9137d21443f86f605ca59fdf7bb6620
andrewjknapp/CS138_Python
/hw7KnappAndrew/hw7project1.py
1,615
4.5
4
#! /usr/bin/python # File Name: hw7project1.py # Programmer: Andrew Knapp # Date: Jun 22, 2021 # # Problem Statement: Estimate a child's adult height given the height of # the father and mother as well as the child's gender # # # FORMULAS # 1. Height (male) = ((Hmother * 13/12) + Hfather ) / 2 # 2. Height (female) = ((Hfather * 12/13) + Hmother ) / 2 # # Overall Plan: # 1. Prompt user for height of mother and father as well as gender of child # 2. If child is male use FORMULA 1 # 3. else use FORMULA 2 # 4. display the child's height # # # import the necessary python libraries # Converts a number representing inches into # a string formatted as feet and inches def inchesToFeetAndInches(height): feet = height // 12 inches = height % 12 return f"{feet:.0f}'{inches:.0f}\"" def main(): print("Predict your child's height!") # Prompt for user input heightMother = eval(input("What is the height of the child's mother in inches (Ex. 62): ")) heightFather = eval(input("What is the height of the child's father in inches (Ex. 62): ")) gender = input("Enter the child's biological gender (male/female): ").lower() # Calculate height based on correct formula for specified gender if (gender == "male"): height = ((heightMother * 13/12) + heightFather ) / 2 elif (gender == "female"): height = ((heightFather * 12/13) + heightMother ) / 2 else: print("Please choose one of the gender options") return # Display result print(f"This child's estimated adult height is {inchesToFeetAndInches(height)}") main()
true
4fb4ba2570b4217e81351402091ec9e2f6dd3dd2
andrewjknapp/CS138_Python
/hw2KnappAndrew/hw2project1.py
901
4.375
4
#! /usr/bin/python # Exercise No. 1 # File Name: hw2project1.py # Programmer: Andrew Knapp # Date: June 15, 2021 # # Problem Statement: Ask user to enter a temperature in Fahrenheit and convert # it to celsius # # # Overall Plan: # 1. Print an initial welcoming message to the screen # 2. Prompt the to enter temp in Fahrenheit # 3. Convert temp into Celsius # 4. Print temp in Celsius # # # import the necessary python libraries # for this example none are needed def main(): # Print welcome message to screen print("Welcome to the Fahrenheit to Celsius temperature converter") # Prompt for temperature userTempF = eval(input("Enter a temperature in Fahrenheit: ")) # Convert temperature from Fahrenheit to Celsius tempInCelsius = 5 * (userTempF - 32) / 9 # Display temp in Celsius print(f'{userTempF:.1f}\u00B0F is {tempInCelsius:.1f}\u00B0C') main()
true
49be39843d607557e331516c32bbe180023bc6aa
kavyasreesg/Datastructures_Algorithms
/Binary_Trees/tree_balanced_or_not.py
1,055
4.25
4
""" 1) Left subtree of T is balanced 2) Right subtree of T is balanced 3) The difference between heights of left subtree and right subtree is not more than 1. """ class BinaryTreeNode: def __init__(self, data): self.data = data self.left = None self.right = None def height(root): if root is None: return 0 return max(height(root.left), height(root.right)) + 1 def isBalanced(root): if root is None: return True lh = height(root.left) rh = height(root.right) l = isBalanced(root.left) r = isBalanced(root.right) if abs(lh - rh) <= 1: return l and r return False if __name__ == '__main__': root = BinaryTreeNode(1) root.left = BinaryTreeNode(2) root.right = BinaryTreeNode(3) root.left.left = BinaryTreeNode(4) root.left.right = BinaryTreeNode(5) root.right.left = BinaryTreeNode(6) root.left.left.left = BinaryTreeNode(7) if isBalanced(root): print("Tree is balanced") else: print("Tree is not balanced")
true
ab0d6580f85d72f5bc5e1649630834b4cd996422
kavyasreesg/Datastructures_Algorithms
/Arrays/arrays.py
698
4.1875
4
import array # creating array using array module arr = array.array('i', [1, 1, 3, 1, 2, 3]) # Performing append() operation arr.append(4) # [1, 1, 3, 1, 2, 3, 4] # performing insert() operation arr.insert(2, 7) # [1, 1, 3, 7, 1, 2, 3, 4] # Performing pop() operation arr.pop(1) # [1, 3, 7, 1, 2, 3, 4] # Performing remove() operation arr.remove(1) # [3, 7, 1, 2, 3, 4] # Performing index() operation print("The index of first occurrence of element 3 is {}".format(arr.index(3))) # Performing reverse() operation arr.reverse() # [4, 3, 2, 1, 3, 7] # Printing the transformed array print("The final array after performing above operations is {} " + format(arr))
true
4b5dabafa6a10a0340c294e9c9a612aba6916cbc
AnthonyLuZhu/CorePythonProgramming
/Chapter2/2-13.py
659
4.15625
4
print 'I like to use the internet for: ' for item in ['e-mail','net-surfing', 'homework','char']: print item print 'I like to use the internet for: ' for item in ['e-mail','net-surfing', 'homework','char']: print item, print who = 'knights' what= 'Ni' print 'We are the ', who , 'who say' , what , what , what, what print 'We are the %s who say %s' % (who, ((what + ' ') * 4)) for eachNum in [1,2,3]: print eachNum for eachNum in range(3): print eachNum foo = 'abc' for o in foo: print o foo = 'abc' for i in range(len(foo)): print foo[i], '(%d)' % i print for i, ch in enumerate(foo): print ch, '(%d)' % i
false
9e6cc871728ee27cf36f30c43e8828fda1c6537a
I-will-miss-you/CodePython
/Curso em Video/Aula 10 - Condições (Parte 1)/Desafio01.py
562
4.21875
4
# Escreva um programa que faça o computador "pensar" em um número inteiro entre 0 e 5 e # peça para o usuário tentar descobrir quel foi o número escolhido pelo computador. # O programa deverá escrever na tela se o usuário venceu ou perdeu import random secret_number = random.randint(0, 5) user_number = int(input('Escolha um número entre 0 e 5: ')) mensagem = 'Parabéns, você acertou!' \ if secret_number == user_number \ else 'Oooh :(, você perdeu. O número secreto era {}'.format(secret_number) print(mensagem)
false
a09ac3066517fac2567c8157302b5f5f903b256a
I-will-miss-you/CodePython
/Curso em Video/Exercicios/ex018.py
533
4.125
4
# Faça um programa que leia um ângulo qualquer e mostre na tela o valor do seno, cosseno, e tagente desse ângulo from math import radians, sin, cos, tan ângulo = float(input('Digite o ângulo que você deseja: ')) seno = sin(radians(ângulo)) print('O ângulo de {} tem o SENO de {:.2} '.format(ângulo, seno)) cosseno = cos(radians(ângulo)) print('O ângulo de {} tem o COSENO de {:.2} '.format(ângulo, cosseno)) tangente = tan(radians(ângulo)) print('O ângulo de {} tem o TANGENTE de {:.2} '.format(ângulo, tangente))
false
3f5962820469d3070436891a9b14c3f9a8b6a8de
adsigua/ProjectEulerCodes
/Python/Problem 001-050/problem_001.py
309
4.125
4
""" Problem 1 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ #233168 ans = 0 for x in range(3,1000): if(x%3==0 or x%5==0): ans+=x print(ans)
true
558b63263fdefe012ce4aeea9e993cc588fd3b5c
iamsuv/Marvel
/Ironman/isPrime.py
221
4.1875
4
num=(int(input("Enter a number :"))) def isPrime(num): for i in range(2,num): mod= num % i if mod==0: return print(num,' is not Prime') return print(num,' is prime') isPrime(num)
false
7a2369d306cb086f2d3a01ecad51f25054090a28
adamstanton96/Python_Math_Quiz
/PythonApplication/Question.py
1,618
4.3125
4
import random class Question(object): """Definition of a simple mathematical formula""" value_1 = 0 #First value of formula value_2 = 0 #Second value of formula solution = 0 #Solution to formula operator = "" #Symbol of active operator #//Constructor//# def __init__(self): RefreshQuestion() #//Generates a new question//# def RefreshQuestion(): Question.value_1 = random.randint(0,101) #Randomly generates first value Question.value_2 = random.randint(0,101) #Randomly generates second value value_operator = random.randint(0,2) #Defines operator used randomly if value_operator == 0: Question.operator = "+" Question.solution = Question.value_1 + Question.value_2 elif value_operator == 1: Question.operator = "-" Question.solution = Question.value_1 - Question.value_2 elif value_operator == 2: Question.operator = "*" Question.solution = Question.value_1 * Question.value_2 #//Returns a valid integer input by the user using recursive exception handling//# def TryInput(): try: userInput = int(input(Question.ToString())) except ValueError: print('You did not enter a valid integer as your answer. Please try again') userInput = Question.TryInput() return userInput #//Returns The Question In Readable Format//# def ToString(): return str(Question.value_1) + " " + Question.operator + " " + str(Question.value_2) + " = "
true
516fc44876de59c237679b040c25dd2eda7c6b67
jarkynashyrova/pythoProject
/lists_slicing.py
1,930
4.5
4
#03/13/2021 chapter 4 # working with part of the list cars = ['bugatti','ferrai', 'tesla', 'lexus'] # slice of the list list_name[start:stop] #start is inclusive, stop is exclusive value # value: list_name[start, list list_name [start +1], ......[stop-1] for car in cars[1:3]: # using range of index 1-3 print(f"the car is : {car}") print("----------second---------------") for car in cars[:3]: # same thing as cars as cars [0-3} print(f"the car is : {car}") print("----------thirtd--------------") for car in cars[2:]: # the same thing as cars [2:end of thelist] print(f"the car is : {car}") print("----------fourth--------------") for car in cars[2:10]: # no index out of range error print(f"the car is : {car}") print("----------copying and linking--------------") print("----------linking the 2 variable to the same value--------------") cars2 = cars print(f"the car is : {car}") print(f"the car2 is : {cars2}") cars.append('bmw') print(f"the car is : {car}") print(f"the car2 is : {cars2}") print("----------copying--------------") cars3 = cars [:] #del cars[2] print(f"cars") print(f"cars") print(f"the car is : {car}") print(f"the car2 is : {cars2}") print(" --------4-10----------") print(f"The fisrt three items in the list are:{cars[:3]}") print(f"The three items from the middle of the list are:{cars[2:5]}") print(f"The last three items in the list are:{cars[3:]}") print("-------Tuples----------") # lists can be modified (mutable) #Tuples - (immutable) data structure similar to the list but can not be- # -modified ( you cant change or update) cars_t = ('bugatti','ferrai', 'tesla', 'lexus') print(f"fisrt value is : {cars_t[0]}") cars [0] = 'honda' # this is possible since cars is the list data structure #cars_t[0] = 'honda' # this is not possible since the cars _t is tuple d/s print(f"cars _t :{cars_t}") cars_t = ('honda','ferrari','tesla') # override print(f"cars_t tuple:{cars_t}")
true
89c834f2ed5e19a102f011f8708f176d8ffec988
irimina/pythonDictionaries
/translateFunction#1.py
1,490
4.15625
4
''' Create the translation function Alright, our translator wouldn't be a translator without a translation function, so let's build that now. We will need to pass in a word as a parameter, then use that word as the key to find the translation, and print out the translation. Create a function called translate that takes one parameter word. Write an if statement that will check if word is in WORD_LIST. If it is (in the if branch), set a new variable translation equal to the value in WORD_LIST using the key. Still inside the if branch, print out word and its translation in the format Apple in Maori is aporo. Create an else branch and print Sorry that word is not in the dictionary as the error message. Test the function by calling it at the end of the program and passing in apple as a string. ''' # English to Maori dictionary WORD_LIST = {'apple':'aporo','chair':'turu','pen':'pene','hello':'kia ora','goodbye':'ka kite'} # Menu function def menu(): print("Type: \n", "'1' to view menu\n", "'2' to see word list\n", "'3' to translate a word\n", "'4' to end program") # Show word list function def show_list(): for word, translation in WORD_LIST.items(): print(word,"in Maoro is", translation) # Translation function def translate(word): if word in WORD_LIST: translation=WORD_LIST[word] print(word,"in Maori is.", translation) else: print("Sorry that word is not in the dictionary") translate("chair")
true
732fd7fc04dad2f5fa5e8948caafa4989da9375c
akash-mitra/pykarma
/pelindrome.py
368
4.1875
4
def isPel(string): l = len(string) i = 0 while(i<l): start = string[i] end = string[l-1-i] if (start != end): return False else: i += 1 return True if (__name__ == "__main__"): if(isPel(input("Enter your string: "))): print("Pelindrome") else: print("Not Pelindrome")
false
b6d4c01c6b52b4752c31fe9410fc4ee859ed898e
dEiC/SNWebdevNaloge
/Naloga8/naloga8_1.py
446
4.125
4
mood = input("How are you feeling today? ( write one of: happy, nervous, sad, excited, relaxed )") if mood == "happy": print("It is great to see you happy!") elif mood == "nervous": print("Take a deep brath 3 times.") elif mood == "sad": print("Oh what is wrong?") elif mood == "excited": print("Yaaay! I am happy for you ! :)") elif mood == "relaxed": print("This is the best mood!") else: print("I dont know this mood")
true
48ab768babadfa4e79793ebb855097eb9eaaf741
jnau/Jnau-Sample-Scripts
/Python/Other/M2K.py
254
4.375
4
#Converts miles to kilometers Miles = float(input("Enter a distance in miles: ")) #enter a float of miles Kilometers = 1.60934 * Miles #the equation for the coversion print ("Distance:", Miles, "Miles = ", Kilometers, " KM") #prints conversion
true
9a74fd65584ef1dcf4e66c77ef72c90ff05f1365
ArunShishodia/Most-repeated-quesns-of-Python
/items-display.py
428
4.15625
4
# Question 9 - WAP that will check all items in the list. # If the items are number display their sum, if items are string, # display after concatenating them list1 = [1, 2, "three", 4, "five", "six", 7] string = "" sum = 0 for x in list1: if type(x) == int or type(x) == float: sum += x elif type(x) == str: string += x print("String concatenation: ", string) print("Sum of numbers : ", sum)
true
f36af77be65370bda4687c55c868e3b8f219ad86
ArunShishodia/Most-repeated-quesns-of-Python
/create-a-dict.py
368
4.28125
4
# Create a dictionary and retrieve its value and keys dict = {} size = int(input("Enter dictionary size: ")) for x in range(size): key = input("Enter key: ") value = input("Enter value: ") dict[key] = value print("Original dictionary: ", dict) print("Dictionary keys: ", list(dict.keys())) print("Dictionary values: ", list(dict.values()))
true
16ac18a659e9054da4549c2ad142927e5d62aa8f
ArunShishodia/Most-repeated-quesns-of-Python
/reverse.py
324
4.46875
4
# Question 3 # WAP to reverse a string. It must use function rev() to reverse the string, # taking string as an argument and must return the reversed string def rev(string): return string[::-1] string = input("Enter the string: ") print("Original string: ", string) print("Reversed string: ", rev(string))
true
7afa7c0ee233597f703250fef7be90456434d6f1
ArunShishodia/Most-repeated-quesns-of-Python
/number-in-range.py
442
4.1875
4
# Write a function test to check if a number lies within a range. # Enter staring and ending range values from the user def test(start, end, number): if number >= start and number <= end: print(number, "is in range.") else: print(number, "is out of range.") start = int(input("Enter starting range: ")) end = int(input("Enter ending range: ")) number = int(input("Enter the number: ")) test(start, end, number)
true
c1ebca41f8047d606f0aa9264256ccd1512f5e86
ArunShishodia/Most-repeated-quesns-of-Python
/Reactangle.operation.py
1,475
4.59375
5
# Question 14 - Define a class Rectangle. The class should contain sides: length and breadth of the rectangle as data members. It should report the following methods # (a) - __init__ for initializing data members length and breadth # (b) - setLength() for updating the length of the rectangle # (c) - setBreadth() for updating the breadth of the rectangle # (d) - getLength() for retrieving the length of the rectangle # (e) - getBreadth() for retrieving the breadth of the rectangle # (f) - area() to find the area of the rectangle # (g) - perimeter() to find the perimeter of the rectangle class Rectangle: length = 0 breadth = 0 def __init__(self, len, bre): self.length = len self.breadth = bre def setLength(self, newLength): self.length = newLength def setBreadth(self, newBreadth): self.breadth = newBreadth def getLength(self): return self.length def getBreadth(self): return self.breadth def area(self): return self.length * self.breadth def perimeter(self): return 2 * (self.length + self.breadth) rect = Rectangle(10, 20) print("Rectangle dimensions: ") print(rect.length, rect.breadth) print("Updating rectangle dimensions: ") rect.setLength(20) rect.setBreadth(40) print("New dimensions: ") print(rect.getLength(), rect.getBreadth()) print("Area of rectangle: ") print(rect.area()) print("Perimeter of rectangle: ") print(rect.perimeter())
true
7dd45dc22f05d25dd7328afdb35781653be47886
MustafaHamedHussien/Data-Science
/Numpy Exercise .py
2,608
4.21875
4
#!/usr/bin/env python # coding: utf-8 # # NumPy Exercises # # # #### Import NumPy as np # In[1]: import numpy as np # #### Create an array of 10 zeros # In[2]: zero_array = np.zeros(10) zero_array # #### Create an array of 10 ones # In[4]: ones_array = np.ones(10) ones_array # #### Create an array of 10 fives # In[6]: fives_array = ones_array * 5 fives_array # #### Create an array of the integers from 10 to 50 # In[8]: np.arange(10,51) # #### Create an array of all the even integers from 10 to 50 # In[9]: np.arange(10,51,2) # #### Create a 3x3 matrix with values ranging from 0 to 8 # In[10]: np.arange(0,9,1).reshape(3,3) # #### Create a 3x3 identity matrix # In[14]: np.eye(3) # #### Use NumPy to generate a random number between 0 and 1 # In[19]: np.random.rand(2) # #### Use NumPy to generate an array of 25 random numbers sampled from a standard normal distribution # In[20]: np.random.randn(25) # #### Create the following matrix: # In[25]: np.linspace(.01,1,100).reshape(10,10) # #### Create an array of 20 linearly spaced points between 0 and 1: # In[26]: np.linspace(0,1,20) # ## Numpy Indexing and Selection # # Now you will be given a few matrices, and be asked to replicate the resulting matrix outputs: # In[28]: arr = np.arange(1,26,1).reshape(5,5) arr # In[39]: # WRITE CODE HERE THAT REPRODUCES THE OUTPUT OF THE CELL BELOW # BE CAREFUL NOT TO RUN THE CELL BELOW, OTHERWISE YOU WON'T # BE ABLE TO SEE THE OUTPUT ANY MORE # In[29]: arr[2:,1:] # In[29]: # WRITE CODE HERE THAT REPRODUCES THE OUTPUT OF THE CELL BELOW # BE CAREFUL NOT TO RUN THE CELL BELOW, OTHERWISE YOU WON'T # BE ABLE TO SEE THE OUTPUT ANY MORE # In[31]: arr[3:4,4] # In[30]: # WRITE CODE HERE THAT REPRODUCES THE OUTPUT OF THE CELL BELOW # BE CAREFUL NOT TO RUN THE CELL BELOW, OTHERWISE YOU WON'T # BE ABLE TO SEE THE OUTPUT ANY MORE # In[32]: arr[0:3,1:2] # In[31]: # WRITE CODE HERE THAT REPRODUCES THE OUTPUT OF THE CELL BELOW # BE CAREFUL NOT TO RUN THE CELL BELOW, OTHERWISE YOU WON'T # BE ABLE TO SEE THE OUTPUT ANY MORE # In[34]: arr[4:5,:] # In[32]: # WRITE CODE HERE THAT REPRODUCES THE OUTPUT OF THE CELL BELOW # BE CAREFUL NOT TO RUN THE CELL BELOW, OTHERWISE YOU WON'T # BE ABLE TO SEE THE OUTPUT ANY MORE # In[35]: arr[3:5,:] # ### Now do the following # #### Get the sum of all the values in mat # In[36]: arr.sum() # #### Get the standard deviation of the values in mat # In[38]: arr.std() # #### Get the sum of all the columns in mat # In[39]: arr.sum(axis=0) # In[ ]:
true
6e2b0bce4d99740e9a02479f06953be478d81918
gerostenko/MIT_Intro_in_CS_and_programming_Python
/book_tasks/chapter-2/while-loop-2.py
484
4.25
4
# Write a program that asks the user to input 10integers, and then prints the largest # odd number that was entered. If no odd number was entered, it should print a message to that effect. NUM_OF_INPUTS = 10; iterator = 0; result = "No odd number given" while (iterator < NUM_OF_INPUTS): num = int(input("Input a number: ")) iterator = iterator + 1 if num%2 != 0: if type(result) == str or num > result: result = num print(result)
true
b428d7282283653e5582b5a6f9b465808e3f2a64
KrisLange/CodeSavvy_Python_20150805
/Number_Guessing/NumberGame_2.py
1,965
4.21875
4
################################################################################ ## ## ## Title: NumberGame_2.py ## ## Author: Kris Lange ## ## ## ## Description: A simple, text-based number guessing game ## ## Asks player to guess a number (5 guesses) ## ## ## ################################################################################ # Tells python that we would like to use the random library code import random # Sets random_number to a random integer between 0 and 10 random_number = random.randint(0, 10) # Prompts user for input, stores input in response # then converts response to an integer response = input("Guess a number between 0 and 10:\t") guess = int(response) # Checks if guess equals random_number if guess == random_number: print("Correct!") exit(0) #if correct, exit the program else: print("Wrong!") #else, print wrong and continue # Ask the user for another guess response = input("Guess a number between 0 and 10:\t") guess = int(response) if guess == random_number: print("Correct!") exit(0) else: print("Wrong!") response = input("Guess a number between 0 and 10:\t") guess = int(response) if guess == random_number: print("Correct!") exit(0) else: print("Wrong!") response = input("Guess a number between 0 and 10:\t") guess = int(response) if guess == random_number: print("Correct!") exit(0) else: print("Wrong!") response = input("Guess a number between 0 and 10:\t") guess = int(response) if guess == random_number: print("Correct!") exit(0) else: print("Wrong!")
true
8de995495643bb2e4813d642931d8df258b6fd95
nesteves/introcs
/scripts/introcs/merge_sort.py
1,453
4.5
4
__author__ = 'nunoe' import operator def merge_sort(l, compare = operator.lt): """ Recursive function that implements the merge sort algorithm to an unsorted list :param l: list, unsorted lists :param compare: function, the function used to compare two objects, should take 2 arguments :return: list, sorted result """ if len(l) < 2: return l[:] else: middle = len(l) / 2 left = merge_sort(l[:middle], compare) right = merge_sort(l[middle:], compare) return merge(left, right, compare) def merge(left, right, compare): """ Function used to merge 2 lists into a single sorted list :param left: list, left list :param right: list, right list :param compare: function, used to compare elements from the left list with elements from the right list :return: a single list where all elements are sorted """ result = [] i, j = 0, 0 while i < len(left) and j < len(right): if compare(left[i], right[j]): result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 while i < len(left): result.append(left[i]) i += 1 while j < len(right): result.append(right[j]) j += 1 return result if __name__ == '__main__': l = [2, 5, 7, 4, 10, 99, 9, 3, 6, 10] print 'Unsorted list: ' + str(l) print 'Sorted list: ' + str(merge_sort(l))
true