blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
02c31cd5ea0008ef8b9ad81479fcaf899e8de489 | swaldtmann/python-basic | /Kontrollstrukturen/Loesungen/temperatur_umwandler.py | 731 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf8 -*-
""" author: """
print("(1) Umrechnung von Celsius nach Kelvin")
print("(2) Umrechnung von Celsius nach Fahrenheit")
wahl = input("Bitte wählen: ")
if wahl == "1":
celsius = float(input("Temperatur in Celsius: "))
if celsius >= -273.15:
kelvin = celsius + 273.15
print(celsius, "° = ", kelvin, "K", sep="")
else:
print("Fehler: unmögliche Temperatur!")
elif wahl == "2":
celsius = float(input("Temperatur in Celsius: "))
if celsius >= -273.15:
fahrenheit = 32.0 + 1.8*celsius
print(celsius, "° = ", fahrenheit, "F", sep="")
else:
print("Fehler: unmögliche Temperatur!")
else:
print("Falsche Eingabe!")
| false |
4e7ba243fcdbaa3a8160da84fff10b8df6efc94d | Sam-Power/samples | /LC_1470. Shuffle the Array.py | 1,203 | 4.125 | 4 | # 1470.
# Shuffle
# the
# Array
# Easy
#
# 1064
#
# 120
#
# Add
# to
# List
#
# Share
# Given
# the
# array
# nums
# consisting
# of
# 2
# n
# elements in the
# form[x1, x2, ..., xn, y1, y2, ..., yn].
#
# Return
# the
# array in the
# form[x1, y1, x2, y2, ..., xn, yn].
#
# Example
# 1:
#
# Input: nums = [2, 5, 1, 3, 4, 7], n = 3
# Output: [2, 3, 5, 4, 1, 7]
# Explanation: Since
# x1 = 2, x2 = 5, x3 = 1, y1 = 3, y2 = 4, y3 = 7
# then
# the
# answer is [2, 3, 5, 4, 1, 7].
# Example
# 2:
#
# Input: nums = [1, 2, 3, 4, 4, 3, 2, 1], n = 4
# Output: [1, 4, 2, 3, 3, 2, 4, 1]
# Example
# 3:
#
# Input: nums = [1, 1, 2, 2], n = 2
# Output: [1, 2, 1, 2]
#
# Constraints:
#
# 1 <= n <= 500
# nums.length == 2
# n
# 1 <= nums[i] <= 10 ^ 3
nums = [2,5,1,3,4,7]
n = 3
# Output: [2,3,5,4,1,7]
class Solution:
def shuffle(self, nums, n):
lst = []
for i in range(n):
lst.append(nums[i])
lst.append(nums[n])
n+=1
return lst
print(Solution().shuffle(nums,3))
"""
Runtime: 56 ms, faster than 86.18% of Python3 online submissions for Shuffle the Array.
Memory Usage: 14.3 MB, less than 78.00% of Python3 online submissions for Shuffle the Array.
""" | false |
9167320a70295970059c9001e352d41c596812a3 | leksiam/PythonCourse | /Practice/S.Mikheev/return_maximum.py | 472 | 4.15625 | 4 | def maximum(a, b):
return a if a > b else b
# если a == b, то в любом случае будет выведено максимальное число
a = int(input('enter the first integer: '))
b = int(input('enter the second integer: '))
print('The maximum number is {}'.format(maximum(a, b)))
# можно использовать float вместо int для того,
# чтобы сравнивать числа с плавающей точкой | false |
65a396b28dd09da1ad26dc0a1fad0464e41beb73 | sirdesmond09/univel | /assignment_bank.py | 2,102 | 4.1875 | 4 | class Bank():
def __init__(self, name, bal = 0):
self.name = name
self.balance = bal
def cash_deposit(self):
money = float(input("Enter amount to deposit\n> $"))
self.balance = money + self.balance
print(f"Your account has been credited with ${money}\nCurrent balance is ${self.balance}")
def cash_withdraw(self):
money = float(input("Enter amount to withdraw\n$" ))
if money > self.balance:
print("Insufficient Funds")
print(f"Your current account balance is ${self.balance}")
choose = float(input("Enter amount to withdraw or '1' to cancel transaction"))
if choose == 1:
exit()
else:
self.balance = self.balance - money
print(f"Your account has been debited with ${money}\nCurrent balance is ${self.balance}")
else:
self.balance = self.balance - money
print(f"Your account has been debited with ${money}\nCurrent balance is ${self.balance}")
def check_balance(self):
print(f'Your current balance is ${self.balance}')
def transfer(self, ):
money = float(input("Enter amount to transfer\n$" ))
if money > self.balance:
print("Insufficient Funds")
print(f"Your current account balance is ${self.balance}")
choose = float(input("Enter amount to transfer or '1' to cancel transaction"))
if choose == 1:
exit()
else:
self.balance = self.balance - money
print(f"Your account has been debited with ${money}\nCurrent balance is ${self.balance}")
else:
self.balance = self.balance - money
print(f"Your account has been debited with ${money}\nCurrent balance is ${self.balance}")
print("Welcome to Our BANK")
print("Create an account below")
name = input("Enter your account name\n> ")
newaccount = Bank(name= name)
newaccount.cash_deposit()
newaccount.cash_withdraw()
newaccount.transfer()
newaccount.check_balance() | true |
d90e15aed6356f01189da8b4e916adcf04ef4e84 | SajinKowserSK/algorithms-practice | /mocks/skowser_session2_question2.py | 2,451 | 4.21875 | 4 | # PSEUDOCODE
'''get letters in string
form pairs
for pair in pairs
see the string with just the pairs
check if valid string
get length of string
return highest length'''
# ANSWER
def alternate(n, string):
string = string.lower()
pairs = helper_get_pairs(string)
max = 0
for pair in pairs:
alt_str = ""
for char in string:
if char == pair[0] or char == pair[1]:
alt_str += char
if helper_check_valid(alt_str) and len(alt_str) > max:
max = len(alt_str)
return max
def helper_check_valid(string):
if len(string) == 0 or len(string) == 1 or len(string) == 2 and string[0] == string[1]:
return False
for x in range(0, len(string)-2):
if string[x] != string[x+2] or string[x] == string[x+1]:
return False
return True
def helper_get_pairs(string):
unique_chars = list(set(string))
pairs = []
for x in range(0, len(unique_chars) - 1):
for y in range(x + 1, len(unique_chars)):
pairs.append([unique_chars[x], unique_chars[y]])
return pairs
# TEST CASES
given_test_case = "beabeefeab" # -> 5
custom_test_case = "abbcdabbc" # -> 4
custom_test_case2 = "aaaaa" # -> 0
print(alternate(10, given_test_case))
print(alternate(len(custom_test_case), custom_test_case))
print(alternate(len(custom_test_case2), custom_test_case2))
# ALGORITHM ANALYSIS
## TIME COMPLEXITY
''' The time complexity is O(n) and the space complexity is O(n).
PAIR FUNCTION - O(1)
The string can have 26 unique letters and we look for every unique pair. Using "choose-notation" or binomial
coefficient, we know in the worst case this will yield 25+24+23...+1 (325) operations which is a constant.
The iterations cannot go past this constant number, and does not grow with time hence it is not O(n^2).
CREATING ALTERNATE STRING WITH EACH PAIR OF LETTERS - O(n)
Since we don't know the max length of string (unlike pairs where we did know the max number),
this will iterate through n items in the string so O(n) time
CHECK VALID STRING - O(n)
We iterate through each item in the string up until n-2 so O(n-2) or O(n) time.
Since this happens in the iteration of pair loops
we get a total time complexity of O(n) as O(n * O(325)) -> O(n * O(1)) -> O(n)
'''
## SPACE COMPLEXITY
''' At worst, we create an alt_stirng of all characters, so O(n) space''' | true |
e967bebd2f37df605f28464b65f9cac1e82f5677 | SajinKowserSK/algorithms-practice | /Grokking Coding Interview/P12 - Top 'K' Elements /Frequent Sort.py | 713 | 4.125 | 4 | from heapq import *
def sort_character_by_frequency(str):
maxHeap = []
hmap = {}
for char in str:
if char in hmap:
hmap[char] += 1
else:
hmap[char] = 1
for char, freq in hmap.items():
heappush(maxHeap, (-freq, char))
res = []
while maxHeap:
popped_tuple = heappop(maxHeap)
for x in range(-popped_tuple[0]):
res.append(popped_tuple[1])
return "".join(res)
def main():
print("String after sorting characters by frequency: " +
sort_character_by_frequency("Programming"))
print("String after sorting characters by frequency: " +
sort_character_by_frequency("abcbab"))
main()
| false |
c7739593536ff819851c58af470968eb4bec5ad5 | mcsquared2/peopleSorting | /quickSort.py | 2,154 | 4.15625 | 4 | import random
from debug import *
def quickSort(lst):
# call the recursive quicksort function passing in the the first and last indecies in the list
quickSortR(lst,0,len(lst))
def quickSortR(lst, startIndex, stopIndex):
# if you are only looking at one item in the list, return
if stopIndex-startIndex <= 0:
return
# swap first and middle items in range to keep time to 0(n*Ln(n))
midpoint = (startIndex + stopIndex) // 2
# print("start:, ", startIndex, " end: ", stopIndex)
# print ("midpoint: ", midpoint)
lst[startIndex], lst[midpoint] = lst[midpoint], lst[startIndex]
# start the swap point as the index after the start index
swappoint = startIndex + 1
for i in range(swappoint, stopIndex):
# if current item is less than item at startIndex,
# then swap it with the item at swappoint's location
# and increment swappoint
# else, continue
if lst[i] < lst[startIndex]:
lst[swappoint], lst[i] = lst[i], lst[swappoint]
swappoint += 1
# since swappoint is now the first location where the item
# is greater than or equal to the item at the startIndex, swap
# the item at startIndex and the one at swappoint -1
sortedPoint = swappoint - 1
lst[startIndex], lst[sortedPoint] = lst[sortedPoint], lst[startIndex]
# call quicksort on the indecies left of sortedPoint and the indecies to the right of sortedPoint
quickSortR(lst, startIndex, sortedPoint)
quickSortR(lst, sortedPoint + 1, stopIndex)
if __name__ == "__main__":
j = 8
while j < 20:
lst =[]
length = j
for k in range(length):
lst.append(random.randint(0,length-1))
cpy = lst[:]
Debug("unshuffled lst: " + str(lst))
# for i in range(len(lst)):
# r = random.randint(0,len(lst)-1)
# lst[i], lst[r] = lst[r], lst[i]
Debug("unshuffled lst: " + str(lst))
quickSort(lst)
print ("my sort: ", lst)
print ("pythons sort: ", sorted(lst))
if (lst != sorted(lst)):
print("Quicksort didn't work!!")
print ("my sort: ", lst)
print ("pythons sort: ", sorted(lst))
print()
print()
else:
pass
# print (j, ": success!\n\n")
j*=2
| true |
d9e594b5f898515634c5e0bdcd6815d24e7e1484 | taylynne/Python-Exercises | /guessinggame.py | 870 | 4.125 | 4 | # Practise Python
# Project Guessing Game One, exercise 9
# 8 June 2018
# I think I've done this before with the lrn 2 automate w/ python stuff,
# so it'll be good review... If I can recall exactly what I've done.
import random
def guessingGame(x):
num = random.randint(1,10)
while True:
if x == num:
print("Awesome! That's the number I was thinking of.")
break
elif x > num:
print("Unfortunately, the number I'm thinking of is smaller...")
x = int(input("Try again. "))
elif x < num:
print("It seems the number I am thinking of is larger!")
x = int(input("Try again. "))
print("Let's play a small game! Try to guess the number I'm thinking of, between 1 and 10.")
guess = int(input("What number am I thinking of? \n"))
guessingGame(guess)
# come back to this to update how to keep track of the number of guesses, and do other "extras"
| true |
c1c0a41a8bfa94b7d6c17dc46fcd2738d2fe1167 | bestbestb/csca08_exercises | /untitled-4.py | 1,553 | 4.21875 | 4 | def transpose(strlist):
''' (list of str) -> list of str
Return a list of m strings, where m is the length of a longest string
in strlist, if strlist is not empty, and the i-th string returned
consists of the i-th symbol from each string in strlist, but only from
strings that have an i-th symbol, in the order corresponding to the
order of the strings in strlist.
Return [] if strlist contains no nonempty strings.
>>> transpose([])
>>> []
>>> transpose([''])
>>> []
>>> transpose(['transpose', '', 'list', 'of', 'strings'])
>>> ['tlos', 'rift', 'asr', 'nti', 'sn', 'pg', 'os', 's', 'e']
'''
# create an empty list to use as a result
result = []
useless = []
# loop through every element in the input list
for element in strlist:
ch_result = ' '
# loop through each character in the string
for character in element:
# 2 cases to deal with here:
# case 1: the result list has a string at the correct index,
if character != " ":
ch_result = character + ch_result
# just add this character to the end of that string
# case 2: the result list doesn't have enough elements,
if character == " ":
useless.append(character)
result.append(character)
# need to create a new element to store this character
return result | true |
afda1d805e9585341f83960345682dae2fed70d8 | JacobGT/SQLite3PythonTutorial | /whereClause.py | 799 | 4.5 | 4 | import sqlite3
# Connect to database
conn = sqlite3.connect("customers.db")
# Create a cursor
c = conn.cursor()
# Query the database (db)
# We want to fetch only certain things from the db, so we use the where function
c.execute("SELECT * FROM customers WHERE first_name LIKE 'customer%' ")
# A comparison operator used a lot is: LIKE / which compares to similar results and have to end with % or start with %
# Example: WHERE email LIKE '%customer'
# We can also use all of the other comparison operators like: >, <, ==, >=, etc.
items = c.fetchall()
# Formatting the results
for item in items:
print("Name: " + item[0] + "\tLast Name: " + item[1] + "\tEmail: " + item[2])
# We also can just do: print(item)
# Commit changes to db
conn.commit()
# Close connection to db
conn.close()
| true |
2ef909da6d645996e79bccb50c8d3246fb52f662 | one356/spyder2020 | /base/20201126-demo.py | 1,474 | 4.34375 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:Administrator
@file:20201126-demo.py
@time:2020/11/26
"""
# 列表 list
if __name__ == '__main__':
# 第一种
lst = ['hello','world',98]
# 第二种
lst2 = list(['hello',88,'world'])
print(lst,lst2)
#列表方法
# 定位列表元素位置
print(lst.index('hello',0,1))
# 获取列表中的元素
print(lst[2])
print(lst[-3])
print(lst[1:])
print(lst[:1])
print(lst[-1:])
print(lst[:-2])
print(lst[0:2:2])
# 判断列表元素 in,not in
print('hello' in lst)
print('hello' not in lst)
# 列表遍历 for 迭代变量 in 列表名 :
for item in lst:
print(item)
# 列表元素操作
lst.append('addword')
print(lst)
lst.extend('abcdef') #iterable可迭代对象
print(lst)
lst.insert(1,22)
print(lst)
lst[1:] = lst2 #切片是产生新对象
print(lst)
lst.remove('hello') #删除
print(lst)
lst.pop(1) #根据索引index删除
print(lst)
lst2[1:2] = [] #不产生新对象列表
print(lst2)
# lst2.clear() #清空列表
# del lst2 #删除列表
lst[1] = 20 #单独元素修改
print(lst)
lst2[0:1] = [200,2] #利用切片批量修改
print(lst2)
#lst2.sort(reverse=True) #reverse降序排序
print(lst2)
lst4 = [i for i in range(1, 10)] #生成列表
print(lst4)
| false |
1cef3a92005e6f28ebb6e86ce851b2830861d91f | fadyboy/playground | /compress_string.py | 1,037 | 4.40625 | 4 | #!/usr/bin/env python3
"""
Given an input string 'aaabbdddda', write a function such that the output becomes 'a3bbd4a'
Looking at the output, if the count of the character sequence is >= 3, the character is compressed and displayed in the
format "{character}{count}, otherwise it is displayed the number of times it appears - {character * count}
Author: Anthony Fadero
"""
def compress_string(string):
output = ''
count = 1
string_size = len(string)
for i, j in enumerate(string):
if i + 1 < string_size:
if j == string[i + 1]:
count += 1
else:
output += format_char(j, count)
count = 1
else:
output += format_char(j, count)
return output
def format_char(xter, count):
output = ''
if count <= 2:
a = xter * count
output += a
else:
a = f"{xter}{count}"
output += a
return output
if __name__ == "__main__":
i = "aabbbddddaooowuuurrrzbbf"
print(compress_string(i))
| true |
2f03f7a5b3d9e474b9bab430cad6cea910cbd384 | ieferreira/algorithms | /PyBetter/2021-III/01-membership_test.py | 525 | 4.3125 | 4 | # %%
# Check if a variable is contained in some multiple values
# %%
c = 2
x, y, z = 12, 2, 3
if any(i == c for i in (x, y, z)):
print("exists")
else:
print("does not exist")
# %%
# Membership test with list
if c in [x, y, z]:
print("It exists!")
else:
print("It does not exist!")
# Membership test with tuple
if c in (x, y, z):
print("It exists!")
else:
print("It does not exist!")
# Membership test with set
if c in {x, y, z}:
print("It exists!")
else:
print("It does not exist!")
# %%
| true |
f3474d35fee19a6e4a94cc0a4da661e221013ff5 | wmartin007/ATBS | /passingReference.py | 310 | 4.21875 | 4 | # To display how arguments get passed to functions as references
def eggs(someParameter):
someParameter.append('Hello')
spam = [1, 2, 3]
eggs(spam)
print(spam)
"""Notice that when eggs is called, we don't have to assign it to a new
variable and print that variable. It modifies the list in place. """ | true |
77db19955ac0c1f8461b5a38f8d71f7b8b324311 | Jovan253/Year-12-Computer-Science | /programming techniques/Basics/rock-paper-scissors (2).py | 2,015 | 4.59375 | 5 | from random import randint
print("Lets play rock paper scissors, First to Three!!!")
print("Enter 1 for rock")
print("Enter 2 for paper")
print("Enter 3 for scissors")
player_score = 0
comp_score = 0
### SRC - You typically put import statements at the top of the file
while player_score != 3 or comp_score != 3: ### SRC - I like this, best of 3, but can you let the player choose to play again?
choice = 0
while choice < 1 or choice > 3:
try:
choice = int(input()) ### SRC - it would be good to validate the input
except ValueError:
print("please input a number")
print(choice, " is an invalid input")
print("Enter 1 for rock")
print("Enter 2 for paper")
print("Enter 3 for scissors")
computer_choice = randint(1,3)
if choice == 1 and computer_choice == 2:
comp_score += 1
print("You Lost, Computer Chose Paper, You Chose Rock")
elif choice == 1 and computer_choice == 3:
player_score += 1
print("you Win, Computer Chose Scissors, You Chose Rock")
elif choice == 2 and computer_choice == 1:
player_score += 1
print("You Win, Computer Chose Rock, You Chose Paper")
elif choice == 2 and computer_choice == 3:
comp_score += 1
print("You Lost, Computer Chose Scissors, You Chose Paper")
elif choice == 3 and computer_choice == 1:
comp_score += 1
print("You Lost, Computer Chose Rock, You Chose Scissors")
elif choice == 3 and computer_choice == 2:
player_score += 1
print("You Win, Computer Chose Paper, You Chose Scissors")
else:
print("You chose the same thing")
player_score = player_score
comp_score = comp_score
if comp_score == 3:
print("The Computer Won, Better Luck Next Time")
break ### SRC - I don't like break, do you need it here?
elif player_score == 3:
print("Congrats, You Beat The Computer")
break
| true |
5f440aa34297949a67e99a472fad682b1ae4fe46 | NJC-Spicy-Chef/Slide-2-Conditions-and-Loops | /Guessing number Exercise 4.py | 896 | 4.125 | 4 | # Exercise - 4 Guessing numbers. Write a program that chooses an integer between 0 and 100, inclusive.
# The program prompts the user to enter a number continuously until the number matches the chosen number.
# For each user input, the program tells the user whether the input is too low or too high, so the user can choose
# the next input intelligently. After the user guess correctly, the program will print: “Bravo you guess correctly after ... times”.
import random
chosen_number = random.randint(0, 100)
i = 0
while True:
pick_number = int(input("Please pick a number: "))
i = i + 1
if pick_number == chosen_number:
print("Bravo! You guessed correctly after", i, "times. ")
quit()
elif pick_number < chosen_number:
print("Too low! ")
continue
elif pick_number > chosen_number:
print("Too high! ")
continue | true |
875f98bf03f353130270cec93b79f455f66b97e3 | sotomaque/Python-Coding-Interview-Questions | /firstRecurring.py | 896 | 4.125 | 4 | '''
problem:
given a string of N characters, return the first recurring character in a string
input: string
output: character
solution 1:
first look at character @ index 0
see if you can find it in subsequent string
i.e. Given "DBCABA" look for 'D' in "BCABA"
run complexity: N choose(2) -> (n)(n-1)/2 -> O(n^2)
better solution:
use a data structure such as a dictionary or a hash map to store characters and their counts
return first non single count
'''
def firstRecurring(givenString):
counts = {}
for char in givenString:
if char in counts:
print('Recurrance Found! First Recurring Character: ')
return char
else:
counts[char] = 1
print('No Recurrance in given string!')
return None
# run complexity O(n)
def main():
print('First Recurring Character in a String\n')
x = raw_input("enter a string: ")
print(x)
print(firstRecurring(x))
main() | true |
759ad5b9fb882ed28c10a2ae2abf0bd789e152dd | sotomaque/Python-Coding-Interview-Questions | /secondLargest.py | 662 | 4.25 | 4 | '''
problem: given an array, find and return the second largest number in the array
'''
def secondLargest(givenArray):
'''ideas:
1) sort array, delete largest element, return new max
'''
if len(givenArray) == 0 or len(givenArray) == 1: return
n = [None] * (len(givenArray) - 1)
for i in range(len(givenArray)):
temp = givenArray[i]
if (max(givenArray) == temp):
i+=1
else:
n[i] = temp
return max(n)
def main():
print("This program takes in an array and returns the second largest number in that array")
x = raw_input("enter a string of numbers: ")
y = []
for i in x:
y.append(int(i))
print(secondLargest(y))
main()
| true |
b7a89ecee230f8b2f0859ecc07e6238a1911a8a3 | kyu21/Hunter-CS-Assignments | /127/05/cipher.py | 1,037 | 4.40625 | 4 | def encode_letter(c,r):
newVal = ord(c) + r # stores shifted value of letter
if c.islower(): # determines if letter is uppercase or lowercase
if newVal > ord('z'): # if shifted value is greater than z, loop it back to a
newVal -= 26
elif newVal < ord('a'): # if shifted value is less than a, loop back to z (supports negative r values)
newVal += 26
elif c.isupper():
if newVal > ord('Z'):
newVal -= 26
elif newVal < ord('A'):
newVal += 26
return chr(newVal)
def encode_string(s,r):
newStr = ''
for char in s:
if char.isalpha(): # checks if the character is a letter
char = encode_letter(char,r) # calls previous function to encode each letter
newStr += char
return newStr
def full_encode(s):
newStr = ''
for x in range(26): # encodes string 26 times since there are 26 letters, hence all valid rotations
newStr += (encode_string(s,x) + "\n")
return newStr
print(encode_letter('a',3))
print("")
print(encode_string('abcd',-3))
print("")
print(full_encode('abcd')) | true |
0568592d619ce93f94507b01c61fa69ef315a1dd | sonukrishna/Anandh_python | /chapter_6/q1_product.py | 377 | 4.25 | 4 | """ multiply 2 numbers recursively using + and - operators only. """
def product(x,y):
if y==0 or x==0:
return 0
# if abs(y)==1:
# return 1
if x<0 and y<0:
return abs(x)+product(abs(x),abs(y)-1)
elif x<0 and y>0:
return x+product(x,abs(y)-1)
elif x>0 and y<0:
return -x+product((-x),abs(y)-1)
else:
return x+product(x,y-1)
print product(-11,-5)
| true |
8a5abbd68bad7dfe6fb09d9bad7031a22a05d797 | sonukrishna/Anandh_python | /chapter_6/flatten_list.py | 254 | 4.15625 | 4 | """flatten a nested list """
def flatten(a,result=None):
if result is None:
result=[]
for x in a:
if isinstance(x,list):
print x
flatten(x,result)
else:
result.append(x)
return result
print flatten([1,[2,3,4],[5,6],7])
| true |
8802412197dee90a1ae9577d557950133d11a6cf | malav-parikh/python-for-data-science | /sequence data types.py | 2,494 | 4.34375 | 4 | # python for data science
# sequence data types
# sequence object initialization
# STRING
strSample = 'Malav'
print(strSample)
# strings are immutable i.e. they cannot be changed or altered
# LISTS
lstNumbers = [1,2,3,3,3,4,5,6]
print(lstNumbers)
# this is a list containing only numbers basically a single data type
# another property of list is that it can contain duplicates
lstSample = [1,'Malav',3.0,True,'Hi']
print(lstSample)
# this is a list containing mixed data type
# lists can contain elements of different data types
# lists are mutable i.e they can be changed or altered even after their creation
# ARRAYS
# to use array in python we need to import from array module
# then to define an array we need to pass data type and values in array function
# like array('data-type',[value1, value2,...])
from array import *
arraySample = array('i',[1,2,3,4])
# printing an array
for i in arraySample:
print(i)
# TUPLES
tupeSample = (1,2,3,3,5,'a',3.0,'b')
print(tupeSample)
# tuples are like list, they can have elements of different data types
# they are stored in paranthesis ()
# they are immutable
tupleSample = 1, 2, 'packing'
print(tupleSample)
# tuples can be written without paranthesis as well
# this is called tuple packing
# DICTIONARY
dictSample = {'1':'one',2:'two', 3.0:'three','four':True}
print(dictSample)
# dictionary holds key value pairs in between {}
# the keys and values can be of any data type but
# the keys should be unique i.e, they cannot be repeated
# creating dictionary using dict function
# the only difference is that the key value pairs are passed as tuples in a list
dictSample2 = dict([('1','one'),(2,'two'),(3.0,'three'),('four',True)])
print(dictSample2)
# SET
setSample = {'sample',1,2,3,4.0,True,3,4.0,True}
print(setSample)
# a set is also like list where it can hold elements of different data types
# the difference is that it cannot hold another list or set inside it
# the elements are passed between {}
# sets cannot contain duplicates
# printing the above example will not print the repeated values only once
setSample2 = set([1,2,3,4,5])
print(setSample2)
# creating set using set function
# another way for creating set
setExample = set('example')
print(setExample)
# RANGE
# for creating a sequence of integers
# useful in for loop
# takes in 3arguments (start, end, skip or step)
# if end is 51 considers only upto 50 i.e n-1
rangeSample = range(0,51,10)
print(rangeSample)
for x in rangeSample:
print(x)
| true |
875117d24de1cf904a89b84e28de2beb20e514f0 | SergioBonatto/Meus | /FizzBuzz.py | 651 | 4.1875 | 4 | # Refazendo exercícios do curso de programação em Python da USP
# Projeto FizzBuzz.py
# Todo número divisivel por 3 será substituído por "Fizz"
# e todo divisível por 5 será por "Buzz"
# os que são simultaneamente divisivel por 3 e 5 serão substituídos por "FizzBuzz"
print("FizzBuzz")
numero = int(input("Digite o número máximo de iterações")) # até que número o usuário deseja que seja contado
contador = 0
while contador <= numero:
if contador % 3 == 0 and contador % 5 == 0:
print("FizzBuzz")
elif contador % 3 == 0:
print("Fizz")
elif contador % 5 == 0:
print("Buzz")
else:
print(contador)
contador += 1
| false |
b88dbcbb26dca5161cc5a302d4d9ff3a6589b540 | ElijahBahm/CSE | /Elijah Bahm - Guessgame.py | 840 | 4.1875 | 4 | import random
# Elijah Bahm
# Initializing Variables
number = (random.randint(1, 50))
print("Guess a number 1-50.")
guess = "0"
guesses = 0
# Describes one turn. The while loop is the Game Controller.
while int(guess) != number and guesses < 5:
guess = input("What is your guess?")
if guess == str(number):
print("Correct.")
elif (int(guess) >= number):
print("Lower.")
guesses += 1
elif (int(guess) <= number):
print("Higher.")
guesses += 1
if guesses >= 5:
print("Get le f@#$ed.")
# print(int(c) == 1)
# response = ""
# while response != "Hello":
# response = input("Say \"Hello\"") # \ escape character
# print("Hello \nWorld") # \n = newline
# Generate #
# Get a #(input) from user
# Compare # to input
# Add higher or lower
# Add guesses
# Make variable for guesses
| true |
22fac5fbea4918dcebbfee98f0d3cea8e13e2d5b | lvah/201903python | /day04/code/20_默认参数易错点.py | 415 | 4.1875 | 4 |
# 一定要注意: 默认参数的默认值一定是不可变参数;
def listOperator(li=None):
"""
对于原有的列表后面追加元素‘End’
:return:
"""
if li is None: # is, ==
li = []
li.append('End')
return li
# print(listOperator([1, 2, 3]))
# print(listOperator([]))
# print(listOperator([]))
print(listOperator())
print(listOperator())
print(listOperator()) | false |
a54ce191689d1e79c80e1ed9ea6b3eb22d118864 | lvah/201903python | /day06/code/05_高级特性_列表生成式.py | 1,075 | 4.1875 | 4 | """
# 1). 老办法
# 定义一个空列表,用来存储生成的数据;
import random
nums = []
# 生成100个, 循环100次
for i in range(100):
num = random.randint(1, 100)
nums.append(num)
# 2). 列表生成式快速生成的办法
nums_quick = [random.randint(1, 100) for i in range(100)]
# i=0, 3
# i=1, 39
print(nums)
print(nums_quick)
"""
# 1). 求1-50所有数的平方
square = [(i + 1) ** 2 for i in range(50)]
print(square)
# 2). 生成一个2n+1的数字列表,n为从3到11的数字。
nums_list = [2 * n + 1 for n in range(3, 12)]
print(nums_list)
# 3). 求以r为半径的圆的面积和周长(r的范围从1到10)。
import math
circle = [(math.pi * (r ** 2), 2 * math.pi * r) for r in range(1, 11)]
print(circle)
# 4). 将100以内的所有偶数拿出来;
odd_nums = range(0, 101, 2)
# odd_nums_list = []
# for i in range(0, 101):
# if i%2==0:
# odd_nums_list.append(i)
# odd_nums_1 = [i for i in range(0,101) if i%2==0]
def is_odd(num):
return num % 2 == 0
odd_nums_1 = [i for i in range(0,101) if is_odd(i)]
| false |
819267d4c8a4d5c3e30c038695f60e6c5091a59d | lvah/201903python | /day05/code/04_计算阶乘 factorial.py | 775 | 4.1875 | 4 | def factorial(num):
"""
0! = 1
1! = 1
2! = 2 * 1 = 2 * 1!
3! = 3*2*1 = 3*2!
4! = 4*3*2*1 = 4*3!
....
n! = n * n-1 *n-2 .....1 = n * (n-1)!
求num的阶乘
"""
result = 1
for item in range(1, num + 1):
result = result * item
return result
def recursive_factorial(num):
"""
使用递归求num的阶乘
"""
# 如果num等于0或者1, 返回1;
if num in (0, 1):
return 1
# num的阶乘为num*(num-1)!
else:
return num * recursive_factorial(num - 1)
print("3的阶乘: ", factorial(3))
print("6的阶乘: ", factorial(6))
print("3的阶乘: ", recursive_factorial(3))
print("6的阶乘: ", recursive_factorial(6))
print("998的阶乘: ", recursive_factorial(998)) | false |
79af56545d63c63c203281a44517bb249c87e8bd | joshlaplante/TTA-Course-Work | /Python Drills/Python Drills/drill18.py | 342 | 4.125 | 4 | def weirdSum():
numstring1 = input("Enter 1st number: ")
numstring2 = input("Enter 2nd number: ")
numstring3 = input("Enter 3rd number: ")
num1 = int(numstring1)
num2 = int(numstring2)
num3 = int(numstring3)
if num1 == num2 and num2 == num3:
print(num1*9)
else:
print(num1+num2+num3)
weirdSum() | false |
ad1f5916c1aaa15b30eaf9903aea9a0e37912745 | isaac-friedman/codecademy | /python/exercise-3_area_calculator.py | 1,085 | 4.28125 | 4 | """
This program calculates the area of a various shapes.
Author: Isaac Friedman
"""
print "We're running. I'd rather not be running."
option = raw_input("What shape are we calculating for today? Enter R for rhomboid (including squares, rectangles and parrallelograms), C for Circle and T for Triangle.")
if option == 'C':
radius = float(raw_input("Enter the radius of your cirlce: "))
area = 3.14159 * radius**2
print "The area of your circle is %.2f of whatever unit you were using." % (area)
elif option == 'R':
print "We currently only support rectangles."
ss = float(raw_input("Short side."))
ls = float(raw_input("Long side."))
area = ls*ss
print "The area of your rectangle is %.2f of whatever unit you were using." % (area)
elif option == 'T':
base = float(raw_input("Enter the base of your triangle: "))
height = float(raw_input("Enter the height of your triangle: "))
area = (base*height)/2
print "The area of your triangle is %.2f of whatever unit you were using." % (area)
else:
print "Unrecognized input"
print "Goodbye."
| true |
db18f8dd4a4f492f85c6cd618659e77d6794dfe7 | Jaideep24/Projects | /Test Generator/TestTaker (4).py | 1,232 | 4.34375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
name=input("Enter name")
osnv=input(f"Hello {name}, this test has been made to see how much you have understood your chapter, it contains objective type questions from the notes you have and have to be answered in few words, your final marks will be displayed after your last answer. Best of luck. Press enter to begin the test")
import pandas as pd
pd.set_option('max_colwidth', 0)
test=pd.read_csv("https://raw.githubusercontent.com/Jaideep24/Timepass/master/Testfile.csv",index_col=[0])#enter name of file in which questions are saved
# print((test))
# test.to_csv("advadav.csv")
marks=0
question_num=0
for i in range(len(test.index)):
a=(test.iloc[i])
print(a)
if str(a[0])=="Nothing":
a[0]=""
else:
question_num=i
a[0]=a[0].replace("Main Question","")
a[1]=a[1].replace("Question","")
a[2]=a[2].replace("Answer","")
print(a[0])
print("Q",(i+1-question_num),".",end="")
b=input(a[1])
if b==str(a[2]):
print("Correct Answer")
marks+=1
else:
print("Incorrect answer, the correct answer is ",a[2])
print("Your final score is ",marks)
# In[2]:
vn=input("Press enter to exit")
| true |
cc549dd9d3f1d9fb8f761054cbc81f3cacd4701c | rc4gh2021/capstone_evaluation | /capstone_evaluation.py | 2,778 | 4.15625 | 4 | #capstone evaluation point calculator
#small light weight python to help you avoid headache calculate your points
#All you need is python3 on you machine
#Author: Rithea
#Date: 7/27/2021
P1 = input("enter your name: ")
P2 = input("enter your first teammate name: ")
P3 = input("enter your second teammate name: ")
################################################
def data_calculation(TM1,TM2,TM3):
print()
print(TM1.upper(),"data")
print("Please enter between 1 and 10")
T2 = input(TM2+"(15%): ")
while((T2.isnumeric() == False) or float(T2)<1 or float(T2)>10):
print("Enter between 1-10.")
T2 = input(TM2+"(15%): ")
T3 = input(TM3+"(15%): ")
while((T3.isnumeric() == False) or float(T3)<1 or float(T3)>10):
print("Enter between 1-10.")
T3 = input(TM3+"(15%): ")
SP = input("sponsor(15%): ")
while((SP.isnumeric() == False) or float(SP)<1 or float(SP)>10):
print("Enter between 1-10.")
SP = input("sponsor(15%): ")
CO = input("coordinator(15%): ")
while((CO.isnumeric() == False) or float(CO)<1 or float(CO)>10):
print("Enter between 1-10.")
CO = input("coordinator(15%): ")
SU = input("supervisor(40%): ")
while((SU.isnumeric() == False) or float(SU)<1 or float(SU)>10):
print("Enter between 1-10.")
SU = input("supervisor(40%): ")
myT2 = float(T2)/10*15
myT3 = float(T3)/10*15
mySP = float(SP)/10*15
myCO = float(CO)/10*15
mySU = float(SU)/10*40
myresult = (myT2+myT3+mySP+myCO+mySU)/10
return myresult
##############################################
P1_average = data_calculation(P1,P2,P3)
P2_average = data_calculation(P2,P1,P3)
P3_average = data_calculation(P3,P1,P2)
##############################################
totalWork = P1_average+P2_average+P3_average
P1_con = P1_average/totalWork*100
P2_con = P2_average/totalWork*100
P3_con = P3_average/totalWork*100
##############################################
P1_grade = P1_con*240/100
P2_grade = P2_con*240/100
P3_grade = P3_con*240/100
##############################################
print("\nReport:")
print("######################################")
print("Average Points:")
print(P1.upper(),": ",P1_average)
print(P2.upper(),": ",P2_average)
print(P3.upper(),": ",P3_average)
print("######################################")
print("Contribution in percentage: ")
print(P1.upper(),": ",P1_con)
print(P2.upper(),": ",P2_con)
print(P3.upper(),": ",P3_con)
print("######################################")
print("Final Grade: ")
print(P1.upper(),": ",P1_grade,"%")
print(P2.upper(),": ",P2_grade,"%")
print(P3.upper(),": ",P3_grade,"%")
print("######################################")
| true |
3fbb4531198059f81e3481cc838be41889c95fc6 | thiernodiallo222/Intro-Python-I | /src/13_file_io.py | 942 | 4.25 | 4 | """
Python makes performing file I/O simple. Take a look
at how to read and write to files here:
https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files
"""
# Open up the "foo.txt" file (which already exists) for reading
# Print all the contents of the file, then close the file
# Note: pay close attention to your current directory when trying to open "foo.txt"
# YOUR CODE HERE
# ~/documents/code/CS/part1/Intro-Python/src/foo.txt
read_file = open(r"src/foo.txt", "r")
# read_file.read()
print(read_file.read())
read_file.close()
# Open up a file called "bar.txt" (which doesn't exist yet) for
# writing. Write three lines of arbitrary content to that file,
# then close the file. Open up "bar.txt" and inspect it to make
# sure that it contains what you expect it to contain
# YOUR CODE HERE
write_file = open("src/bar.txt", "w")
text = input('Enter you text below:')
write_file.write(text)
write_file.close()
| true |
619b2500643a3219307b4436266e80684609698b | abhishekkr/tutorials_as_code | /talks-articles/machine-learning/toolbox/numpy/simple-neural-net.py | 2,559 | 4.25 | 4 | #!/usr/bin/env python3
"""
Perceptron: with no inner layers
synapse(with weight)
(Input) -----------> (Neuron) ---> (output)
x {x1w1 + ... + xNwN}
### Training Process
* take inputs from training example and put through formula to get neuron's output
* calculate error which is difference between output we got and actual output
* depending on severeness of error, adjust weights accordingly
* repeat process N00000 times
### Error Weighted Derivative
* adjust weights by = error.input.0'(output)
`Error = output - actual_output`
* Input either 1 or 0
Backpropagation
numpy uses here
exp—for generating the natural exponential
array—for generating a matrix
dot—for multiplying matrices
random—for generating random numbers
"""
import numpy as np
training_inputs = np.array([
[1, 0, 0],
[1, 1, 0],
[1, 0, 1],
[0, 0, 0],
[1, 0, 0],
[1, 1, 0],
[1, 0, 1],
[0, 1, 0],
[0, 1, 1],
[0, 0, 1],
[1, 0, 0],
[1, 1, 0],
[1, 0, 1],
[0, 0, 0],
[1, 0, 0],
[1, 1, 0],
[1, 0, 1],
[0, 1, 0],
[0, 1, 1],
[0, 0, 1]
])
training_outputs = np.array([ [1,1,1,0,1,1,1,0,0,0,1,1,1,0,1,1,1,0,0,0] ]).T
np.random.seed(10)
synaptic_weights = 2 * np.random.random((3, 1)) - 1
print("Random starting synaptic weight", synaptic_weights)
def sigmoid(x):
return 1 / ( 1 + np.exp(-x) )
def sigmoid_derivative(x):
return x * ( 1 - x)
"""
For sigmoid:
https://stackoverflow.com/questions/10626134/derivative-of-sigmoid
https://gist.github.com/jovianlin/805189d4b19332f8b8a79bbd07e3f598
"""
def think(iteration_input):
required_input = iteration_input.astype(float)
return sigmoid(
np.dot(required_input, synaptic_weights)
)
def train():
global training_inputs
global training_outputs
global synaptic_weights
iterations = 500 # 100000
for iteration in range(iterations):
input_layer = training_inputs
outputs = think(input_layer)
error = training_outputs - outputs
adjustments = error * sigmoid_derivative(outputs)
synaptic_weights += np.dot(input_layer.T, adjustments)
print('Synaptic weights after training: ',synaptic_weights)
print('Outputs after training: ',outputs)
def ask_now():
item1 = str(input('enter 0 or 1: '))
item2 = str(input('enter 0 or 1: '))
item3 = str(input('enter 0 or 1: '))
neural_input = np.array([item1, item2, item3])
print("Your result is: ", think(neural_input))
if __name__ == "__main__":
train()
ask_now()
| true |
7dce1847df3c226b66b05086e5ebe489f76db05f | BodaleDenis/Codewars-challenges | /find_the_divisors.py | 1,262 | 4.34375 | 4 | """
Create a function named divisors/Divisors that takes an integer n > 1 and returns an array with all of the integer's divisors
(except for 1 and the number itself), from smallest to largest. If the number is prime return the string '(integer) is prime'
(null in C#) (use Either String a in Haskell and Result<Vec<u32>, String> in Rust).
Example:
divisors(12); #should return [2,3,4,6]
divisors(25); #should return [5]
divisors(13); #should return "13 is prime"
"""
def divisors(integer):
"""
Difficulty: Easy
Show all the divisors of a given number, if the number is prime print {number} is prime
Args:
integer (int): Input number
Status : Completed
Returns:
string : If number is prime
list : containing all the divisors of number
"""
divisors_result = []
for i in range(2, integer//2 + 1):
if integer % i == 0:
divisors_result.append(i)
if divisors_result:
return divisors_result
else:
return str(integer) + " is prime"
# Driver program
primality_check_result = "13 is prime"
divisors_12 = [2, 3, 4, 6]
divisors_15 = [3, 5]
assert divisors(13) == primality_check_result
assert divisors(15) == divisors_15
assert divisors(12) == divisors_12 | true |
e01a3efafba42cb555852b0e795f673958dc7d58 | Aussiroth/cpy5python | /Practical 01/q3_miles_to_kilometre.py | 257 | 4.5 | 4 | #File Name: q3_miles_to_kilometre
#Author: Alvin Yan
#Date Created: 21/3/2013
#Date Modified: 21/1/2013
#Description: Converts miles to kilometers
miles = float(input("Input the number of miles\n"))
area2=float(miles*1.60934)
print ("{0:<.3f}".format(area2))
| true |
79b47fdd7f8c7c3e15320491e21815bd2dd2f83a | Chris-M-Wagner/Hangman | /Hangman.py | 2,475 | 4.28125 | 4 | """
Creator: Chris Wagner
Created Date: 12/03/2015
Last Updated: 12/07/2015
Summary:
Hangman is a game that prompts the user to guess a word, letter by letter.
Word entries are contained in the Hangman.txt file.
"""
import random
def Party_Time():
guessUL = 3 #The amount of guesses the user has.
tries = 0 #The starting number of incorrect guesses the user has made.
inc_guess = [] #The incorrect guesses the user has made.
winflag = False #Flag is True when user wins
text_file = open("Hangman.txt", 'r')
word_bank = []
for line in text_file:
if line.strip() != "" and not line.startswith("#"): #Ignoring blank lines or commented lines
word_bank.append(line.strip())
word = random.choice(word_bank)
ret_word = ["_" for item in range(len(word))] #Return word
print "\n\n\nWe're having a party and you're invited! What can you bring?\n" + ("_ "*len(word))
while tries < guessUL:
guess = raw_input("\nGuess a letter or the full word: ").lower().strip()
guessflag = False #Flag is True if guess letter is found in word
if len(guess)==1: #Check to see if a letter is in the word
for item in range(0, len(word)):
if guess == word[item]: #The letter is in the word
ret_word[item] = guess
guessflag = True
if item==(len(word)-1) and guessflag==False:
print "\nSorry, there is no '%s' in the word.\n" %guess
inc_guess.append(guess)
tries+=1
if "".join(ret_word) == word:
winflag = True
print "\nYou win! The word is '%s'!" %word
break
elif len(guess)>1:
if guess == word:
winflag = True
print "\nYou win! The word is '%s'!" %word
break
else:
print "\nSorry, that's not the word we were looking for."
tries+=1
print '\n' + ' '.join(ret_word) + '\n\n-----Incorrect Guesses-----\n' + ' '.join(inc_guess)
if tries==guessUL and winflag==False: #User has exhausted the tries and has lost game
print "\nSorry, the word we were looking for is '%s'.\n" %word
replay = raw_input("\n\nGame Over. Play again? (Y/N)\n")
if replay.lower() == "y":
Party_Time()
Party_Time()
'''
Testing:
1. Make sure that the answer can work with spaces included
2. Win letter by letter, win with entire word entry
3. Multiples of the same letter register in one turn
4. If incorrect letter guess, will return a error and add to list of letters that are not included
5. Number of tries works, both for individual letter and full word guesses
6. Replay loop works correctly
''' | true |
4b368aa8d05310815cf6caba91d16d0d261a62bb | MarianoMartinez25/Python | /1 - primeros pasos/ejercicio1.py | 1,300 | 4.4375 | 4 | # 1) Identifica el tipo de dato (int, float, string o list) de los siguientes
# valores literales.
"Hola Mundo" #String
[10, 1, 200] #Lista de int
-30 #int
1.0 #float
["Pedro", "Jorge"] #Lista de String
# 2) Determina sin programar el resultado que aparecera en la pantalla
# a partir de las siguientes variables:
a = 20
b = 10
c = "Pepe"
d = [1,2,3]
print(a*4) #a*4=80
print(a-b) #a-b=10
print(c+ "Garcia") #PepeGarcia
print(c*2) #c*2 = PepePepe
print(c[-1]) #c[-1]=e
print(c[1:]) #c[1:]=epe
print(d+d) #d+d=[1,2,3,1,2,3]
# 3) El siguiente codigo pretende realizar una media entre 3 numeros
# pero algo anda mal, ¿Podes identificar el problema y solucionarlo?
num_1 = 9
num_2 = 3
num_3 = 6 #el problema era que decia num-3 y no num_3
media = (num_1 + num_2 + num_3) / 3 #agregar parentesis a la suma
print("La nota media es", media)
# 4) Aqui hay otro problema, ¿Eres capaz de resolverlo? Al querer sumar entrada mas 10
# nos sale un error.¿Que es lo que esta faltando?
# entrada = int(input("Introduzca un numero: ")) #Convertir en entero
# Introduzca un numero: 20
# entrada + 10
# 5)Aqui hay un texto que esta alreves, es un alumno, que tiene una nota
# del examen.¿Como podemos darlo vuelta y verlo normalmente?
texto = "zaid luar, 01"
| false |
85922ca99399f57013fa5dc24d97d0832f5a70d1 | rajcaptainindia/Assignments | /Assignment27.py | 782 | 4.34375 | 4 | import turtle # allows us to use the turtles library
wn = turtle.Screen() # creates a graphics window
wn.setup(500,500) # set window dimension
alex = turtle.Turtle() # create a turtle named alex
alex.shape("turtle") # alex looks like a turtle
alex.color("black") # alex has a color
alex.right(60) # alex turns 60 degrees right
alex.left(60) # alex turns 60 degrees left
alex.circle(50) # draws a circle of radius 50
#draws circles
angle=120
for i in range(3):
for counter in range(1,4):
alex.circle(20*counter)
alex.right(angle)
if(i==0):
alex.color("blue")
elif(i==1):
alex.color("red")
#Write the logic to create the given pattern
#Refer the statements given above to draw the pattern
| true |
be02033434d7c261c244b24e3f4c815a28b19448 | quirogas/MTH | /homework5.py | 1,030 | 4.15625 | 4 | # Homework 5
__author__ = "Santiago Quiroga"
__version__ = "6/Oct/2017"
# This function will return a list with the number of trees per backyard.
def binarytoanalogy(list):
# local variables for value tracking.
answer_list = []
counter = 0
# Iterates though the list.
for i in list:
# Check for trees or fences.
if i == 1:
# Adds the number of threes in the current backyard and resets the counter.
answer_list.append(counter)
counter = 0
else:
# counts the number of tress in a backyard.
counter += 1
# Add the values of the last backyard.
answer_list.append(counter)
# Returns a list with all the number of trees in each backyard.
return answer_list
# Tests for quality assurance ;)
print binarytoanalogy([0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1])
print binarytoanalogy([0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0])
print binarytoanalogy([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])
print binarytoanalogy([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) | true |
7db286b323af4ebf1fd1a1a9cec125d93efd72b9 | JamesonSantos/Curso-Python-Exercicios-Praticados | /ExerciciosPythonMundo2/Aula13/Ex053.py | 558 | 4.25 | 4 | '''Crie um programa que leia uma frase qualquer e diga se ela é um palindromo,
desconsiderando os espaços. Ex:
- APOS A SOPA
- A SACADA DA CASA
- A TORRE DA DERROTA
- O LOBO AMA O BOLO
- ANOTARAM A DATA DA MARATONA'''
nome = str(input('Digite uma frase: ')).strip().upper().replace(' ', '')
inverso = nome[::-1]
if nome == inverso:
print('O inverso de {} é {}'.format(nome, inverso))
print('A frase digitada é um palíndromo!')
else:
print('O inverso de {} é {}'.format(nome, inverso))
print('A frase digitada não é um palíndromo!')
| false |
ab348584cd635736299af77f484e9e9e73afe6c4 | JamesonSantos/Curso-Python-Exercicios-Praticados | /ExerciciosPythonMundo2/Aula12/Ex036.py | 834 | 4.25 | 4 | '''Escreva um programa para aprovar o emprestimo bancario para a compra de uma casa.
O programa vai perguntar o valor da casa, o salario do comprador e em quantos anos ele vai pagar.
Calcule o valor da prestacao mensal, sabendo que ela nao pode exceder 30% do salario ou entao o
emprestimo sera negado.'''
valor = float(input('Valor da casa: R$ '))
salario = float(input('Valor do salário: R$ '))
anos = int(input('Quantidade de anos: '))
prestacao = valor / (anos * 12) #Divide o valor da casa pela quantidade de meses em forma de ano
'''parcela = salario - (salario * 30) / 100 #Subtrai 30% do salário
porcentagem = salario % parcela #Equivale a 30% do salário
#print(p)'''
porcentagem = salario * 30 / 100
if prestacao <= porcentagem:
print('Seu empréstimo será APROVADO!')
else:
print('Seu emprèstimo foi NEGADO! ')
| false |
0421a6b111788a98458752bf87f552195c7c752f | JamesonSantos/Curso-Python-Exercicios-Praticados | /ExerciciosPythonMundo2/Aula14/Ex058.py | 877 | 4.1875 | 4 | ''' Melhore o jogo do DESAFIO 028 onde o computador vai "pensar" em uma numero entre 0 e 10.
Só que agora o jogadoir vai tentar adivinhar até acertar, mostrando no final quantos
palpites foram necessários para vencer.'''
from random import randint
from time import sleep
computador = randint(0, 10) # Faz o computador "SORTEAR"
print('Sou seu computador...\nAcabei de pensar em um número entre 0 e 10.')
print('Será que você consegue adivinhar qual foi? ')
acertou = False
palpites = 0
while not acertou:
jogador = int(input('Qual é o seu palpite? '))
palpites += 1
if jogador == computador:
acertou = True
else:
if jogador > computador:
print('Menos... Tente mais uma vez.')
elif jogador < computador:
print('Mais... Tente mais uma vez.')
print('Acertou com {} tentativas. Parabéns!'.format(palpites))
| false |
a0577cdbd35449837a62040915886fc72529aadf | JamesonSantos/Curso-Python-Exercicios-Praticados | /ExerciciosPythonMundo2/Aula12/Ex039.py | 1,291 | 4.15625 | 4 | '''Faça um programa que leia o ano de nascimento de um jovem e informe, de acordo com sua
idade:
-Se ele ainda vai se alistar ao serviço militar.
-Se é a hora de se alistar.
-Se já passou do tempo do alistamento.
Seu programa também deverá mostrar o tempo que falta ou que passou do prazo.'''
from datetime import date
ano = int(input('Digite o ano de nascimento: '))
anoatual = date.today().year #Ano atual do sistema operacional
idade = anoatual - ano #Subtrai o ano de nascimento do ano atual do sistema
sexo = int(input('[1]Masculino \n[2]Feminino \nOpção:'))
if sexo == 1:
if idade == 18:
print('Você tem {} anos. É hora de se alistar ao serviço militar.'.format(idade))
elif idade <= 16:
print('Você tem {} anos. Você ainda irá se alistar'.format(idade))
print('Faltam {} ano(os) para o seu alistamento.'.format(18 - idade))
saldo = 18 - idade
tempo = anoatual + saldo
print('Seu alistamento será em {}'.format(tempo))
elif idade > 18:
print('Você tem {} anos. Já passou da hora de se alistar.'.format(idade))
print('Passou {} ano(os) do seu alistamento.'.format(idade - 18))
saldo = idade - 18
tempo = anoatual - saldo
print('Seu alistamento foi em {}'.format(tempo))
else:
print('Você não precisa se alistar.') | false |
4ec500ea5dadf0a43370063d0df3e1e46d94c112 | JamesonSantos/Curso-Python-Exercicios-Praticados | /ExerciciosPythonMundo2/Aula12/Ex044.py | 1,479 | 4.125 | 4 | '''Elabore um programa que calcule o valor a ser pago por um produto, considerando o seu:
preço normal e condições de pagamento.
-À vista dinheiro/cheque: 10% de desconto.
-À vista no cartão: 5% de desconto.
-Em até 2x no cartão: Preço normal.
-3x ou mais no cartão: 20% de juros'''
print('{:=^40}'.format(' LOJAS CHINESAS '))#{:=^40} Centraliza o nome em 40 caracteres
preco = float(input('Preço do produto R$: '))
print('-' * 40, '\nFORMA DE PAGAMENTO',)
print('-' * 40)
print('[1] À vista em dinheiro \n[2] Cheque \n[3] Cartão de crédito')
escolha1 = int(input('Escolha a forma de pagamento: '))
if escolha1 == 1 or escolha1 == 2:
print('Você pagará R${:.2f} pelo produto.'.format(preco - (preco * 10) / 100))
elif escolha1 == 3:
print('-' * 30, '\n[1] À vista \n[2] Parcelado')
print('-' * 30)
escolha2 = int(input('Escolha a opção: '))
if escolha2 == 1:
print('Você pagará R${:.2f} pelo produto no crédito á vista.'.format(preco - (preco * 5) / 100))
elif escolha2 == 2:
escolha3 = int(input('Quantidade de parcelas: '))
if escolha3 <= 2:
print('Você pagará R${:.2f} pelo produto em {}x de R${:.2f} SEM JUROS'.format(preco, escolha3, preco / escolha3))
elif escolha3 >= 3:
print('Você pagará R${:.2f} pelo produto em {}x de R${:.2f} COM JUROS'.format(preco + (preco * 20) / 100, escolha3, (preco + (preco * 20) / 100) / escolha3))
else:
print('Opção Inválida') | false |
afd7884ce39fa87c6ec614af7e050eb270ffa403 | geekslayer/python-udemy-blackjack | /game/deck.py | 1,611 | 4.125 | 4 | """
This deck object is at the middle of all
this and is a crucial part of the game.
"""
from random import shuffle
from game.card import Card, Suit
class Deck():
"""
This will hold 52 cards like a regular deck of cards.
One by one we will remove the cards from the deck until no more.
"""
__amount_of_cards_of_one_suit = 13
def __init__(self):
self.full_deck = []
for card_suit in Suit:
for i in range(1, Deck.__amount_of_cards_of_one_suit+1):
self.full_deck.append(Card(card_suit, i, i >= 10, self.__get_card_value(i)))
def shuffle_deck(self):
"""
This will shuffle the deck and all the cards in it.
Of course this should be done only when there's a new deck if not,
this will still work but on a shorter deck
"""
shuffle(self.full_deck)
@classmethod
def __get_card_value(cls, card_number: int):
"""
This is to give the face value of a card.
Numbers are easy, then the face card either J, Q, K or A.
"""
if card_number in (2, 3, 4, 5, 6, 7, 8, 9, 10):
return str(card_number)
if card_number == 1:
return "A"
if card_number == 11:
return "J"
if card_number == 12:
return "Q"
if card_number == 13:
return "K"
return None
def __str__(self):
return f"This deck has {len(self.full_deck)} cards which here they are: \n" + \
f"{[x.visible_value for x in self.full_deck]}"
| true |
b23dc837b4a45412474a9eaa5a8c1793a8a06237 | VGallardo93/lerning_github | /Test.py | 854 | 4.4375 | 4 | # This is a test file in Python 3
print('Welcome to the new file... By vg.\n')
name_ = input('Hi. Insert your name: ')
while True:
if name_.isdigit():
print('\nInvalid name. Please try again.')
name_ = input('Insert your name: ')
continue
else:
print(f'\nHi {name_}! Nice to meet you.\n')
break
# Passing an integer after the ':' will cause that field to be a minimum number of characters wide. This is useful for making columns line up.
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
for name, phone in table.items():
print(f'{name:10} ==> {phone:10d}')
# As an example, the following lines produce a tidily-aligned set of columns giving integers and their squares and cubes:
for x in range(1, 11):
print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
print('\n>>> That\'s all folk!, bye!\n')
#Thank you to see!
| true |
c51d113ee49a6c1218de39f3a9affa41761f502f | liang1024/CrawlerDemo | /Python面试题/1.Python语言的特性——30例/3.@staticmethod和@classmethod.py | 1,431 | 4.21875 | 4 | # coding=utf-8
'''
3 @staticmethod和@classmethod
参考:
http://stackoverflow.com/questions/136097/what-is-the-difference-between-staticmethod-and-classmethod-in-python
Python其实有3个方法,即静态方法(staticmethod),类方法(classmethod)和实例方法,如下:
'''
def foo(x):
print "executing foo(%s)"%(x)
class A(object):
def foo(self,x):
print "executing foo(%s,%s)"%(self,x)
@classmethod
def class_foo(cls,x):
print "executing class_foo(%s,%s)"%(cls,x)
@staticmethod
def static_foo(x):
print "executing static_foo(%s)"%x
a=A()
a.foo("1")
a.class_foo("1")
a.static_foo("1")
A.static_foo("1") #静态方法可以通过类名直接调用,不需要实例对象
'''
这里先理解下函数参数里面的self和cls.这个self和cls是对类或者实例的绑定,
对于一般的函数来说我们可以这么调用foo(x),这个函数就是最常用的,
它的工作跟任何东西(类,实例)无关.对于实例方法,我们知道在类里每次定义方法的时候都需要绑定这个实例,
就是foo(self, x),为什么要这么做呢?因为实例方法的调用离不开实例,我们需要把实例自己传给函数,
调用的时候是这样的a.foo(x)(其实是foo(a, x)).类方法一样,只不过它传递的是类而不是实例,A.class_foo(x).
注意这里的self和cls可以替换别的参数,但是python的约定是这俩,还是不要改的好.
''' | false |
754b12d78bfb0cf9a8774f06c78bdad65b0f7e49 | mohithasan/mathematician | /mathematician.py | 1,755 | 4.25 | 4 |
#Welcome to mathematician.py
#Developers are Working on the file to improve the file more.
#View the terms of uses befor you start using this Module on your work.
#-----------------------------------------------------------------------
#The code starts here-
#To add nmbers, make list of the numbers and call the function add({list name}).
def add(nums):
add = sum(nums)
print(add)
#To minus two nmbers, make list of the numbers and call the function mns({list name})
def mns(nums):
all = (nums.index(nums[-1]))+1
left = all-2
while (left>0):
nums.pop()
left = left-1
a = nums[0]
b = nums[1]
sub = a-b
print(sub)
#To multiply nmbers, make list of the numbers and call the function into({list name})
def into(nums):
into = 1
for j in nums:
into = into * j
print(into)
#To devide two nmbers, make list of the numbers and call the function mns({list name})
def dev(nums):
all = (nums.index(nums[-1]))+1
left = all-2
while (left>0):
nums.pop()
left = left-1
a = nums[0]
b = nums[1]
dev = a/b
print(dev)
#To get a squre root of a number, call the function sqrt({number or number variable})
def sqrt(num):
sqrt = num**0.5
print(sqrt)
#To get the squre value of a number, call the function sqr({number or number variable})
def sqr(num):
sqr = num*num
print(sqr)
#To get the power value of a number, make a list including the number and the power and then call the function sqr({list})
def pow(nums):
all = (nums.index(nums[-1]))+1
left = all-2
while (left>0):
nums.pop()
left = left-1
a = nums[0]
b = nums[1]
pow = a/b
print(pow)
#Work in progress.
| true |
de931e528976d638c99dcad2f91babbc77518fda | jurrehageman/Informatica-1 | /Website/informatics1/seminars/solutions02/seminar2_solution/05_solution.py | 1,117 | 4.625 | 5 | # solution for excersize 05 from lecture1
# define a sequence and assign it to a variable
#seq = "ATGAGTAGGATAGGCTAGATGGCGATGAATT"
seq = "UCAUUAUCAGACGGCAGUUUAUUAUAUAUAU"
# convert to upper case:
seq_up = seq.upper()
# Always check variables by printing them to screen!
print("original sequence:", seq_up)
# check if we have a DNA sequence and not DNA
# DNA does not have the U in the sequence, so lets check this
# we use the string method find() to look for the U character
# find() returns a -1 if nothing was found, so we should set our condition equal to this value
if seq_up.find("U") == -1:
# Using indentation we can define here our block that should be executed if the previous line evaluated to true
# print that the sequence is DNA and print the sequence to the screen
print("Sequence is DNA: ", seq_up)
else:
# Change the U from RNA to the T in DNA and save it in a new variable
DNA = seq_up.replace("U", "T")
# Lastly, print that the sequence is RNA and print the sequence
print("Sequence is RNA")
print("Original sequence:", seq_up)
print("DNA sequence:", DNA)
| true |
a7ac8fc5a9f9225339b04e2806d5d4d4484f8582 | phqlong/Internship-Odoo | /Python-Exercise/iterator.py | 1,488 | 4.625 | 5 | # Iterable is an object, which one can iterate over. It generates an Iterator when passed to iter() method.
# Iterator is an object, which is used to iterate over an iterable object using __next__() method.
# Iterators have __next__() method, which returns the next item of the object.
# Note that every iterator is also an iterable, but not every iterable is an iterator.
# For example, a list is iterable but a list is not an iterator.
# An iterator can be created from an iterable by using the function iter().
# To make this possible, the class of an object needs either a method __iter__,
# which returns an iterator, or a __getitem__ method with sequential indexes starting with 0.
class MyIterator ():
def __init__(self, iterable):
self.iterable = iterable
self.len = len(iterable)
def __iter__(self):
self.idx = 0
return self
def __next__(self):
if self.idx < self.len:
value = self.iterable[self.idx]
self.idx += 1
return value
else:
raise StopIteration
# Create my object
iterable_obj = [1, 'a', True]
my_obj = MyIterator(iterable_obj)
# Create an iterable from my object
my_iterator = iter(my_obj)
# Using next to get to the next iterator element
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
# Using for loop to get iterator item
for i in my_obj:
print(i)
# Iterator is exhausted -> raise error
print(next(my_iterator)) | true |
b60d519421c8f9d6bba79eee1a30385f5a41fa82 | ksr19/python_basics | /L3/4.py | 1,019 | 4.1875 | 4 | def my_func(x, y):
"""Возведение числа x в отрицательную степень y.
:param x: действительное положительное число
:param y: целое отрицательное число
:return:
"""
if x <= 0:
print("Основание степени должно быть положительным!")
else:
if y >= 0:
print("Степень должна быть отрицательной!")
else:
power_result = 1
for i in range(y, 0):
power_result = power_result / x
print(f"Число {x} в степени {y}: {round(power_result, 4)}.")
try:
x = float(input("Введите действительное положительное число: "))
y = int(input("Введите целое отрицательное число: "))
my_func(x, y)
except ValueError:
print("Необходимо вводить числа!")
| false |
8d5fa9ede1449711ea7213452274abe6b73a5af2 | slerpy/ilikepy | /part2/2.02-99problems.py | 2,266 | 4.375 | 4 | ###
# a procedure to add one day to a calendar, assuming all months are 30 days.
# a test run into building a full calendar.
###
###
# commenting out since we have a better method below.
###
# def nextDayMeh(year, month, day):
# if day == 30:
# day = 1
# if month == 12:
# month = 1
# year = year + 1
# else:
# month = month + 1
# else:
# day = day + 1
#
# return(year, month, day)
#
# print nextDayMeh(2011, 12, 1)
###
# a more elegant way to do above, not sure which is going to prove more useful.
###
def nextDay(year, month, day):
if day < 30:
return year, month, day + 1
else:
if month < 12:
return year, month + 1, 1
else:
return year +1, 1, 1
print nextDay(2098, 11, 13)
print nextDay(2011, 12, 1)
###
# a daysBetweenDates procedure that would produce the
# correct output if there was a correct nextDay procedure.
#
# Test procedure, will NOT produce correct ouptuts yet, since
# our nextDay procedure assumes all months have 30 days
# (hence a year is 360 days, instead of 365).
#
# this will surely not work with months that lead to negs when subtracted.
###
def daysBetweenDates(year1, month1, day1, year2, month2, day2):
"""Returns the number of days between year1/month1/day1
and year2/month2/day2. Assumes inputs are valid dates
in Gregorian calendar, and the first date is not after
the second."""
# years = year2 - year1
# months = month2 - month1
# days = day2 - day1
# result = years * 360 + months * 30 + days
# print result
# return result
###
# this is a little sexier than the above. works with negs.
###
daysN = 0
while year1 != year2 or month1 != month2 or day1 != day2:
year1, month1, day1 = nextDay(year1, month1, day1)
daysN = daysN + 1
return daysN
def test():
test_cases = [((2012,9,30,2012,10,20),20),
((2012,1,1,2013,1,1),360),
((2012,9,1,2012,9,4),3)]
for (args, answer) in test_cases:
result = daysBetweenDates(*args)
if result != answer:
print "Test with data:", args, "failed"
else:
print "Test case passed!"
test() | true |
393461a838e4e9e65c597e4e6df2d3845b5f1eff | CallumBrown/Assignment | /development exercise 3.py | 399 | 4.15625 | 4 | #Callum Brown
#16-09-14
#Exercise - Development 3
height_inches = float(input("Please enter your height in inches: "))
weight_stones = float(input("Please enter your weight in stones: "))
height_cm = (height_inches)*2.54
weight_kg = (weight_stones)*6.364
print("Your height in centremetres is: {0}".format(height_cm))
print("Your weight in kilograms is: {0}".format(weight_kg))
| true |
da215def7f73a10a97be2578231883a4c1292997 | Denimbeard/PycharmProjects | /Programs/Finite State Acceptors/ExampleSolution | 2,638 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# This programs implements an FSA. It keeps track of the current FSA's state
# in a variable called "STATE". The algorithm traverses the given string and,
# depending on the current character, decides what the next state will be.
# The INITIAL state is S1, and the ONLY recognising state is S7.
# (c) Max Garagnani 2020
STATE, result = 1, False # Initial state is 1; default 'result' is "False"
s = input("Please enter the string to be checked:")
for c in s: # For each character of the string (starting from left):
# Check if the character considered is 'A' or 'B' or 'C':
if not (c == 'A' or c == 'B' or c == 'C'):
STATE = 8 # If not --> the next state will be S8 (Error)
# If we are in state S1, and...
elif STATE == 1 and c == 'A': # .. the character is 'A',
STATE = 2 # --> next state is S2
elif STATE == 1: # Otherwise (i.e, not 'A'),
STATE = 8 # --> we go to S8 (error)
# If we are in state S2, and..
elif STATE == 2 and c == 'A': # .. the character is 'A',
STATE = 1 # --> we go "back" to S1
elif STATE == 2 and c == 'B': # .. the character is 'B',
STATE = 3 # --> next state is S3
# If we are in state S3, and..
elif STATE == 3 and c == 'A': # .. the character is 'A',
STATE = 4 # --> next state is S4
elif STATE == 3 and c == 'C': # .. the character is 'C',
STATE = 1 # --> we go back to S1
elif STATE == 3: # Otherwise (neither 'A' nor 'C'),
STATE = 8 # --> we go to S8 (error)
# If we are in state S4, and..
elif STATE == 4 and c == 'B': # .. the character is 'B',
STATE = 5 # --> next state is S5
elif STATE == 4 and c == 'C': # .. the character is 'C',
STATE = 3 # --> we go back to S3
# If we are in state S5, and..
elif STATE == 5 and c == 'C': # .. the character is 'C',
STATE = 6 # --> next state is S6
elif STATE == 5: # Otherwise (it's not 'C'),
STATE = 8 # --> we go to S8 (error)
# If we are in state S6, and..
elif STATE == 6 and c == 'A': # .. the character is 'A',
STATE = 5 # --> we go back to S5
elif STATE == 6 and c == 'B': # .. the character is 'B',
STATE = 7 # --> next state is S7
# If we are in S7, and we get ANY character,
elif STATE == 7:
STATE = 8 # --> we must go to S8 (error)
# ELSE (in all other cases): THE STATE we are CURRENTLY IN remains UNCHANGED.
if STATE == 7: # At the END of the string, are we in S7..?
result = True # If so, result = True; otherwise, it remains False
print(result)
| true |
9358e9544ef6fbf7bf12fbd828620b6a1481e79e | anishdhandore/Basic-operational-calculator | /Calculator.py | 1,162 | 4.15625 | 4 |
def calculate():
n1 = float(input("First number : "))
n2 = str(input("Operation : "))
n3 = float(input("Second number : "))
signs = ["+", "-", "*", "/"]
if signs[0] in n2:
print("\n")
print(n1)
print(n2+str(n3))
print("----------")
print(n1+n3)
elif signs[1] in n2:
print("\n")
print(n1)
print(n2+str(n3))
print("----------")
print(n1-n3)
elif signs[2] in n2:
print("\n")
print(n1)
print(n2+str(n3))
print("----------")
print(n1*n3)
elif signs[3] in n2:
print("\n")
print(n1)
print(n2+str(n3))
print("----------")
print(n1/n3)
run = True
while run:
calculate()
inp = input("Do you want to use me again, yes/no? : ")
if inp == "no":
break
elif inp == "yes":
continue
else:
print("enter only yes/no")
re = str(input())
if re == "no":
break
elif inp == "yes":
continue
else:
break
| false |
08d0f5f3424b83750b1b35187df6ba8e653d0757 | jatinsinghnp/python-3-0-to-master-course | /2_stringformatting/code.py | 427 | 4.21875 | 4 | #f' string string formatting in python
#
name ="Bob"
greeting =f"hellow ,{name}"
print(greeting)
print(greeting)
# creating template
name="bob"
greeting="hloow,{}"
with_name=greeting.format()
with_name=greeting.format("nikhil")
with_name=greeting.format("jatin")
print(with_name)
# also kin a make long phraser
long_phraser="helow,{}.Today is {}."
formatted=long_phraser.format("tt",'tte')
print(formatted) | true |
a1e8aefa37ec4814d1e95cd1d77d0a67f2614039 | nisabzahid/Analytics | /Programming/Python/Exercises-Basic/Basics/DateDiff.py | 583 | 4.21875 | 4 | '''Write a Python program to calculate number of days between two dates.
Sample dates : (2014, 7, 2), (2014, 7, 11)
Expected output : 9 days '''
import datetime
d1=int(input("Please enter the day of first date : "))
m1=int(input("Please enter the month of first date : "))
y1=int(input("Please enter the year of first date : "))
date1=datetime.date(y1,m1,d1)
d2=int(input("Please enter the day of second date : "))
m2=int(input("Please enter the month of second date : "))
y2=int(input("Please enter the year of second date : "))
date2=datetime.date(y2,m2,d2)
print(date2-date1)
| true |
e445a2d8823f76b4f6ea02661d7fa1b8a56e86eb | pogromcykodu/PogromcyPythona | /struktury_danych/listy/Zadanie2_Stacja_metorologiczna 💡/rozwiazanie.py | 1,516 | 4.40625 | 4 | """
Pracujesz w stacji meteorologicznej i dostałeś właśnie nowe zadanie.
Przed Tobą lista wahań temperatury z ostatniego tygodnia:
1.5, 3, 2, 0, -1 , 1.9, 0.1
Twoim zadaniem jest podanie następujących informacji:
a) najwyższa zanotowana temperatua
b) najniższa zanotowana temperatura
c) średnia temperatura
d) posortowana lista temperatur, od najmniejszej do największej
e) posortowana lista temperatur, od największej do najmniejszej
Napisz program, który zwróci odpowiednie dane.
"""
# Przygotowanie struktury danych - listy, listy temperatur
temperatures = [1.5, 3, 2, 0, -1, 1.9, 0.1]
# a) Najwyższa temeperatura
max_temperature = max(temperatures)
print(f"Najwyższa temperatura: {max_temperature}")
# b) Najniższa temeperatura
min_temperature = min(temperatures)
print(f"Najniższa temperatura: {min_temperature}")
# c) Średnia temperatura
avg_temperature = sum(temperatures) / len(temperatures)
print(f"Średnia temperatura: {avg_temperature}")
# Wynik warto zaokrąglić do 2 miejsc po przecinku
avg_temperature = round(avg_temperature, 2)
print(f"Średnia temperatura: {avg_temperature}")
# d) posortowana lista temperatur, od najmniejszej do największej
temperatures.sort()
print(f"Temperatura od najmniejszej do największej: {temperatures}")
# e) posortowana lista temperatur, od największej do najmniejszej
temperatures.sort(reverse=True)
print(f"Temperatura od największej do najmniejszej: {temperatures}")
# Spróbuj też wykonać to zadanie bez wbudowanych funkcji :)
| false |
a752ed3288e1fadce812db8c219a4052ff0f0f3d | mchao409/python-algorithms | /algorithms/search/fibonacci_modulo.py | 1,329 | 4.46875 | 4 | """
Calculating (n-th Fibonacci number) mod m
"""
def _fib(number):
"""
Fibonacci number
Args:
number: number of sequence
Returns:
array of numbers
"""
init_array = [0, 1]
for idx in range(2, number + 1):
init_array.append(init_array[idx - 1] + init_array[idx - 2])
return init_array[number]
def _pisano_period_len(modulo):
"""
In number theory, the nth Pisano period, written π(n),
is the period with which the sequence of Fibonacci numbers taken modulo n repeats.
Args:
modulo: modulo
Returns:
length of Pisano period
"""
init_array = [0, 1]
idx = 1
while 1:
idx += 1
init_array.append(init_array[idx - 1] % modulo + init_array[idx - 2] % modulo)
if init_array[idx] % modulo == 1 and init_array[idx - 1] % modulo == 0:
return len(init_array) - 2
def fibonacci_modulo(number, modulo):
"""
Calculating (n-th Fibonacci number) mod m
Args:
number: fibonacci number
modulo: modulo
Returns:
(n-th Fibonacci number) mod m
Examples:
>>> fibonacci_modulo(11527523930876953, 26673)
10552
"""
period = _pisano_period_len(modulo)
answer = _fib(number - number // period * period) % modulo
return answer
| true |
d3c97bbecbae737716e1b0a84d38968f2db76c69 | aniaHrrera4/Python-Projects | /Python_Projects/ScavHunt1.py | 2,651 | 4.15625 | 4 | """
Pygame base template for opening a window
Sample Python/Pygame Programs
Simpson College Computer Science
http://programarcadegames.com/
http://simpson.edu/computer-science/
Explanation video: http://youtu.be/vRB_983kUMc
"""
import pygame
import random
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GREY = (127, 127, 127)
lightSeaGreen=(32,178,170)
rosyBrown=(188,143,143)
mediumPurple=(147,112,219)
skyBlue=(135,206,235)
teal=(0,128,128)
mediumSeaGreen=(60,179,113)
mediumAquaMarine=(102,205,170)
salmon=(250,128,114)
golden=(218,165,32)
maroon=(128,0,0)
darkTurquoise=(0,206,209)
cornFlowerBlue=(100,149,237)
darkOrchid=(153,50,204)
pygame.init()
# Set the width and height of the screen [width, height]
SCREEN_WIDTH = 700
SCREEN_HEIGHT = 500
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Ball Game")
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
possible_ball_colors = [BLACK, WHITE, GREEN, RED, BLUE, GREY,lightSeaGreen,rosyBrown,mediumPurple,skyBlue,teal,mediumAquaMarine,mediumSeaGreen,salmon,golden,maroon,darkOrchid,darkTurquoise,cornFlowerBlue]
x_speed = random.randint(-10, 10)
y_speed = random.randint(-10, 10)
x_loc= int(SCREEN_WIDTH/2)
y_loc= int(SCREEN_HEIGHT/2)
ball_size =random.randint(20,80)
# -------- Main Program Loop -----------
while not done:
# --- Main event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# --- Game logic should go here
# --- Screen-clearing code goes here
# Here, we clear the screen to white. Don't put other drawing commands
# above this, or they will be erased with this command.
# If you want a background image, replace this clear with blit'ing the
# background image.
screen.fill(teal)
# --- Drawing code should go here
ball_color = random.choice(possible_ball_colors) # This is outside because of variable scoping.
pygame.draw.circle(screen, ball_color, [x_loc, y_loc], ball_size)
if x_loc>= SCREEN_WIDTH - ball_size or x_loc< ball_size:
x_speed = x_speed * -1
if y_loc>= SCREEN_HEIGHT - ball_size or y_loc< ball_size:
y_speed = y_speed * -1
x_loc += x_speed
y_loc+= y_speed
# --- Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# --- Limit to 60 frames per second
clock.tick(60)
# Close the window and quit.
pygame.quit()
exit() # Needed when using IDLE
| true |
f14ca98b0da2469335781ab0179e854ae0789565 | BenGilbert98/Python_Week_1 | /data_types_&_operators.py | 558 | 4.15625 | 4 | # What are data types and Operators
# Boolean gives us the outcome in True or False
# a = True
# b = False
#
# print(a == b) #False
# print(a != b) #True
# print(a >= b) #False
greetings = "Hello World!"
print(greetings.isalpha())
# Checks if letters in the string are letters
# How can we check if the string is lower case?
print(greetings.islower()) # Checks if greetings is lower case
print(greetings.startswith("H")) # Checks if greetings starts with "H"
print(greetings.endswith("!")) # Checks if greetings ends with "!"
# None
print(bool(None))
| true |
329dcb06d8525d79fa27b0252b49d9395e98c4ff | tdnam/learncode | /Practice/CrackingAlgo/ArraysAndStrings/StringCompression.py | 1,053 | 4.75 | 5 | #!/usr/bin/env python3
# String Compression: Implement a method to perform basic string compression using the
# counts of repeated characters.
# For example, the string aabcccccaaa would become a2b1c5a3.
# If the "compressed" string would not become smaller than the original string,
# your method should return the original string.
# You can assume the string has only uppercase and lowercase letters (a - z).
# Hints: #92, # 110
def stringCompression(string):
counter = 0
newList = list()
tempChar = string[0]
i = 0
while i < len(string):
if tempChar == string[i]:
counter += 1
tempChar == string[i]
elif tempChar != string[i]:
newList.append(tempChar)
newList.append(str(counter))
counter = 1
tempChar = string[i]
i += 1
# append last character
newList.append(tempChar)
newList.append(str(counter))
return ''.join(newList)
if __name__ == '__main__':
string = input()
print(stringCompression(string))
| true |
9956cb6b7d201af6f796c95f2832a568115ba51e | ashcoder2020/Python-Practice-Code | /simple find factorial.py | 229 | 4.34375 | 4 | num=int(input("Enter a number which you want to find factorial : "))
fact=1
if num==0 or num==1:
print("Factorial is 1")
else:
for i in range(1,num+1):
fact=fact*i
print(f"factorial of {num} is {fact}") | true |
0d33a1a9223b7cdba089a38e43bf4a5c8df23c82 | HanYinnn/cp2019 | /p01/q1_fahreheit_to_celsius.py | 566 | 4.53125 | 5 | #Write a program q1_fahrenheit_to_celsius.py that reads a Fahrenheit degree in double (floating point / decimal) from standard input,
#then converts it to Celsius and displays the result in standard output.
#The formula for the conversion is as follows: celsius = (5/9) * (fahrenheit - 32)
#get input
Fahrenheit = int(input ("Enter temperature in Fahrenheit:")) # use integer function to convert it into numbers
#compute celsius temperature
celsius = (5/9) * (Fahrenheit - 32)
#output result
print("{0:.1f}".format(celsius)) # 0 means the first thing to print
| true |
35b70bf6ea050eae00e5784037e0d948d4ea29c4 | sadjunky/brainstorm | /queue/linkedlist.py | 885 | 4.15625 | 4 | # Queue using Linked List with front and rear pointers
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Queue:
def __init__(self):
self.front = self.rear = None
def isEmpty(self):
return self.front == None
def enqueue(self, data):
if not self.front:
self.front = self.rear = Node(data)
return
self.rear.next = Node(data)
self.rear = self.rear.next
def dequeue(self):
if self.isEmpty():
return "Queue underflow!"
temp = self.front
self.front = self.front.next
if(self.front == None):
self.rear = None
return temp.data
q = Queue()
q.enqueue(10)
q.enqueue(20)
q.enqueue(30)
q.dequeue()
print("Queue front " + str(q.front.data))
print("Queue rear " + str(q.rear.data))
| false |
793d4b2846da7fa419afc67de85881accc271533 | aekempster/Pyber | /03-Python/3/Activities/Solved/05-Ins_List_comprehensions/comprehensions.py | 1,458 | 4.53125 | 5 | # -*- coding: UTF-8 -*-
"""Comprehensions"""
price_strings = ["24", "13", "16000", "1400"]
price_nums = [int(price) for price in price_strings]
fish = "halibut"
# Comprehensions give handles on each element of a collection
letters = [letter for letter in fish]
print(f"We iterate over a string, containing the world: '{fish}'")
print(f"This turns our string into a list: {letters}.")
# We can manipulate each element as we go
capital_letters = [letter.upper() for letter in letters]
print(f"This capitalizes the letters in our list: {capital_letters}.")
# We can remove elements with a boolean test
no_h = [letter for letter in letters if letter != "h"]
dysfunctional_fish = "".join(no_h)
no_h_or_b = [letter for letter in letters if letter != "h" and letter != "b"]
dysfunctional_fish = "".join(no_h_or_b)
print(f"And our filtered string is: {dysfunctional_fish}.")
print("=" * 72)
june_temperatures = [72, 65, 59, 87]
july_temperatures = [87, 85, 92, 79]
august_temperatures = [87, 77, 68, 72]
summer_temperatures = [june_temperatures, july_temperatures, august_temperatures]
# We can use functions inside of list comprehensions
lowest_summer_temperatures = [min(temps) for temps in summer_temperatures]
print(f"The lowest temperature in June was: {lowest_summer_temperatures[0]}.")
print(f"The lowest temperature in July was: {lowest_summer_temperatures[1]}.")
print(f"The lowest temperature in August was: {lowest_summer_temperatures[-1]}.")
| true |
387a706a602f18376859886ddd974451360b1ef7 | izham-sugita/python3-tutorial | /python-container.py | 1,340 | 4.5625 | 5 | #List
xs = [3, 1, 2] # Create a list
print(xs, xs[2]) # Prints "[3, 1, 2] 2"
print(xs[-1]) # Negative indices count from the end of the list; prints "2"
xs[2] = 'foo' # Lists can contain elements of different types
print(xs) # Prints "[3, 1, 'foo']"
xs.append('bar') # Add a new element to the end of the list
print(xs) # Prints "[3, 1, 'foo', 'bar']"
x = xs.pop() # Remove and return the last element of the list
print(x, xs) # Prints "bar [3, 1, 'foo']"
#List-slicing
nums = list(range(5)) # range is a built-in function that creates a list of integers
print(nums) # Prints "[0, 1, 2, 3, 4]"
print(nums[2:4]) # Get a slice from index 2 to 4 (exclusive); prints "[2, 3]"
print(nums[2:]) # Get a slice from index 2 to the end; prints "[2, 3, 4]"
print(nums[:2]) # Get a slice from the start to index 2 (exclusive); prints "[0, 1]"
print(nums[:]) # Get a slice of the whole list; prints "[0, 1, 2, 3, 4]"
print(nums[:-1]) # Slice indices can be negative; prints "[0, 1, 2, 3]"
nums[2:4] = [8, 9] # Assign a new sublist to a slice
print(nums) # Prints "[0, 1, 8, 9, 4]"
#List-loop
animals = ['cat', 'dog', 'monkey']
for animal in animals:
print(animal)
# Prints "cat", "dog", "monkey", each on its own line.
| true |
738b0632eb0b8c29304b49fa612e38e5592bc3e8 | anishcr/iNeuron-Assignments | /MLD6thJune/Assignments/Python-Assignment-3/reduce_filter.py | 1,102 | 4.1875 | 4 | # 1.1 Write a Python Program to implement your own myreduce() function which works exactly
# like Python's built-in function reduce()
#
# 1.2 Write a Python program to implement your own myfilter() function which works exactly
# like Python's built-in function filter()
def myreduce(function, iterable, initializer=None) :
it = iter(iterable)
if initializer is None :
try:
initializer = next(it)
except StopIteration:
raise TypeError('myreduced called with empty sequence')
accu = initializer
for x in it:
accu = function(accu, x)
return accu
def myfilter(function, iterable) :
return myreduce(lambda accu, x : accu + [x] if function(x) else accu, iterable, initializer=[])
if __name__ == "__main__":
my_list = [1, 2, 3, 4, 5]
result = myreduce(lambda x, accu : x + accu, my_list)
print("Sum of list using myreduce is : {}\n".format(result))
my_list = [12, 65, 54, 39, 102, 339, 221, 50, 70, ]
result = list(myfilter(lambda x: (x % 13 == 0), my_list))
print("Filtered list of multiples of 13 using myfilter is : {}\n".format(result))
| true |
a7381d3830c02a342cb3588b14fa54b5e26d0b11 | insigh/Leetcode | /August_18/71. Simplify Path.py | 951 | 4.21875 | 4 | """
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
Corner Cases:
Did you consider the case where path = "/../"?
In this case, you should return "/".
Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
In this case, you should ignore redundant slashes and return "/home/foo".
"""
class Solution:
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
path = path.split('/')
print(path)
res ='/'
stack = []
for item in path:
if item == '' or item == '.' or (item=='..' and not stack):
continue
elif item == '..':
stack.pop(-1)
else:
stack.append(item)
print(stack)
return res+'/'.join(stack)
| true |
ee955e71739318be9a4504d560b5ff9bf57dcd4b | UnKn0wn27/PyhonLearning-3.6.1 | /study14.py | 529 | 4.125 | 4 | def while_function():
i = 0
n = 9
numbers = []
while i < n:
print(f"At the top i is {i}")
numbers.append(i)
m = int(input("Nr > "))
i += m
print("Numbers now: ", numbers)
print("At the bottom i is {i}")
while_function()
def for_function():
numbers = []
for i in range(1,6):
print(f"At the top i is {i}")
numbers.append(i)
i += 1
print("Numbers now: ", numbers)
print(f"At the buttom i is {i}")
for_function()
| false |
58db5a0d25109bd5b5466b9cc5bb63bf8193ceb6 | Fbabsail/Learning-Python | /17.py | 533 | 4.125 | 4 |
#total faliure
command=input()
while command.upper() != 'QUIT':
if command.upper() == 'START':
print('Car started...')
elif command.upper() == 'STOP':
print('Car stopped.')
elif command.upper() == 'EXIT':
break
elif command.upper() == 'HELP':
print('Start - to start the car')
print('Stop - to stop the car')
print('Exit - to quit program')
elif command.upper() != 'HELP'and 'EXIT' and 'STOP'and 'START':
print("I don't understand that")
| true |
288f144096eb930c31c998beecc3fbb256ca68ae | Fbabsail/Learning-Python | /13.py | 245 | 4.40625 | 4 | Name=input("What's your name")
name_length=(len(Name))
if name_length<3:
print("Name must be at least 3 characters")
elif name_length>50:
print('Name can be a maximum of 25 characters')
else:
print('Name looks good')
| true |
c1219edb00ff71005e07698261215ca4b7dfba8f | hahahayden/CPE202 | /LAB1/Lab1.py | 793 | 4.25 | 4 | # Name:
# Section:
# must use iteration not recursion
def max_list_iter(tlist):
""" finds the max of a list of numbers and returns it, not the index"""
if (len(tlist) == 0):
raise ValueError('empty list')
""" finds the max of a list of numbers and returns it, not the index"""
elif (len(tlist) == 1):
return tlist[0]
else:
templist = tlist[1:len(tlist)]
temp= max_list_iter(templist)
return (max(tlist[0],temp))
#must use recursion
def reverse_rec(tempstr):
""" recursively reverses a list and returns it """
# Binary Search
#write your recursive binary search code here
def bin_search(target, low, high, list_val):
""" searches for target in list_val[low..high] and returns index if found"""
| true |
7aa9ed2f2be8cbf8d57491a366959ff5a08dd2ff | Meitsuki/testing | /python/miniProjects/diceRoll/diceRollSimulation.py | 1,415 | 4.375 | 4 | import dice
print("Welcome to the dice roll simulator program!")
validPrompt = False
while not validPrompt:
numDice = input("To get started, how many dice would you like to roll? ")
validInt = False
try:
numDice = int(numDice) + 0
validInt = True
except TypeError:
validInt = False
if validInt:
if numDice >= 1:
validPrompt = True
else:
print("Please provide a positive integer.")
else:
print("You have provided an invalid input, please enter a positive integer.")
print("Excellent, you wish to roll " + str(numDice) + " dice.")
validPrompt = False
sameNumSides = False
while not validPrompt:
sameNumSides = input("Would you like these dice to all have the same number of sides? ")
if sameNumSides.lower() == "yes" or sameNumSides.lower() == "no":
validPrompt = True
else:
print("You have provided an invalid answer. Please enter Yes or No.")
if sameNumSides.lower() == "yes":
sameNumSides = True
else:
sameNumSides = False
validIntPrompt = False
if sameNumSides:
numSides = input("How many sides do you wish the dice to have? )
else:
for x in range(numDice):
numSides = input("How many sides do you wish dice " + str(x) + " to have? ")
sidesForDice.append(numSides)
dices = diceContainer(numDice, sameNumSides, sidesForDice)
print("Have a nice day.")
| true |
a8f5012bd3ed767a604d39d99d90201f275bf7c1 | 666syh/python_cookbook | /python_cookbook/1_data_structure_and_algorithm/1.11_命名切片.py | 612 | 4.125 | 4 | """
问题
你的程序已经出现一大堆已无法直视的硬编码切片下标,然后你想清理下代码。
"""
record = '....................100 .......513.25 ..........'
cost = int(record[20:23]) * float(record[31:37])
print(cost)
# 51325.0
# modify
SHARE = slice(20, 23)
PRICE = slice(31, 37)
cost = int(record[SHARE]) * float(record[PRICE])
print(cost)
# 51325.0
items = [0,1,2,3,4,5,6]
a = slice(2, 4)
print(items[a])
# [2, 3]
items[a] = [10, 11]
print(items)
# [0, 1, 10, 11, 4, 5, 6]
del items[a]
print(items)
# [0, 1, 4, 5, 6]
s = slice(5, 50, 2)
print(s.start, s.stop, s.step)
# 5 50 2
| false |
1b914b3aec24619f31d76e53b6c211fb810ec187 | patricelliG/hacker_rank | /python/classes/complex_numbers.py | 2,586 | 4.3125 | 4 | #!/bin/python
import math
# this script defines a class for imaginary numbers
# it can operate on two numbers with +,-,*,/
# it can also mod a single imaginary number
# INPUT: Two lines with two integers each
# 2 1
# 5 6
# so the first number is 2+1i and the second is 5+6i
# The program then outputs the numbers after each operation +,-,*,/ mod(a) and mod(b)
class ImNum:
''' class that implements imaginary numbers of the form 'a+bi'
+, -, *, /, have been overloaded and mod() returns the modulus'''
real = 0.0
imag = 0.0
def __init__(self, real, imag):
self.real = real
self.imag = imag
def __str__(self):
if self.imag >= 0:
return "{0:.2f}+{1:.2f}i".format(self.real, self.imag)
else:
return "{0:.2f}{1:.2f}i".format(self.real, self.imag)
def __add__(self, other):
if self.imag + other.imag == 0: # no longer imaginary
return ImNum(self.real + other.real, 0.0)
else:
return ImNum(self.real + other.real, self.imag + other.imag)
def __sub__(self, other):
if self.imag - other.imag == 0: # no longer imaginary
return ImNum(self.real - other.real, 0.0)
else:
return ImNum(self.real - other.real, self.imag - other.imag)
def __mul__(self, other):
# FOIL a and b, trick, create 2 partial product numbers, then add them together
pp1 = ImNum(self.real * other.real, self.real * other.imag) # First, Outer
pp2 = ImNum(self.imag * other.imag * -1, self.imag * other.real) # Last * -1 to handle i^2, Inner
return pp1 + pp2
def __truediv__(self, other):
# multiply top and bottom by conjugate of denominator
conjugate = ImNum(other.real, other.imag * -1)
numerator = self * conjugate
denominator = other * conjugate
# reduce, i in denominator is now 0 and can be ignored
quotient = ImNum(numerator.real / denominator.real, numerator.imag / denominator.real)
return quotient
def mod(self):
# mod of a complex number is defined as the square route of a^2 + b^2 where a+bi
# this is not the best way represent it, but the problem requires this format
return ImNum(math.sqrt(self.real ** 2 + self.imag ** 2), 0.0)
# test the functions
line1 = list(map(float, input().split()))
ia = ImNum(line1[0], line1[1])
line2 = list(map(float, input().split()))
ib = ImNum(line2[0], line2[1])
print(ia + ib)
print(ia - ib)
print(ia * ib)
print(ia / ib)
print(ia.mod())
print(ib.mod())
| true |
00c1d5a513bf66ae0701f7b26dd57aa0cc7bc117 | CarltonK/PythonScripts | /Fizz Buzz/fizz_buzz.py | 302 | 4.28125 | 4 | def fizz_buzz(number):
number = int(number)
if number%3 == 0 and number%5 == 0:
print('FizzBuzz')
elif number%3 == 0:
print('Fizz')
elif number%5 == 0:
print('Buzz')
else:
print('This number is not divisible by either 3 or 5')
user_value = input('Enter a number: ')
fizz_buzz(user_value) | true |
4108a8843bc66211c7bd44bb701a16d8fe102a65 | CarltonK/PythonScripts | /Fibonacci Sequence/fibonacci_sequence.py | 547 | 4.53125 | 5 | def fibonacci_generator(number):
number = int(number)
num1 = 0
num2 = 1
num_count = 1
fib_list = [num2]
while num_count < number:
num_total = num1 + num2
#Switch second value to first value
num1 = num2
#Switch total value to second value
num2 = num_total
num_count += 1
fib_list.append(num_total)
print(fib_list)
user_entry = input('Enter a number to compute the fibonacci sequence upto and including the number: ')
fibonacci_generator(user_entry) | true |
5bb0105cb178fa40a33feab048492a8599797b8f | yalothman97/Python | /functions_task.py | 703 | 4.1875 | 4 | def check_birthdate(year, month, day):
from datetime import date
if year > date.today().year and month > date.today().month and day > date.today().day:
return False
else:
return True
def calculate_age(year, month, day):
from datetime import date
calc_year = date.today().year - year
calc_month = date.today().month - month
calc_day = date.today().day - day
print("You are {} year(s), {} month(s), and {} day(s) old".format(calc_year, calc_month, calc_day))
year = int(input("Enter birth year: "))
month = int(input("Enter birth month: "))
day = int(input("Enter birth day: "))
if check_birthdate(year, month, day) == True:
calculate_age(year, month, day)
else:
print("Invalid birthday") | true |
20d3080e9ede4e7070fc02d26049e795fc9a03fe | pulkitpahwa/Python-practice | /count_vowels.py | 1,181 | 4.21875 | 4 | # !usr/bin/python
import fileinput
def main():
print "This program will count the number of vowels in a string or in a file."
print "Press 1 if you want to enter a string. "
print "Press 2 if you want to open a file. "
a=raw_input("Enter your choice > ")
# 2 cases are possible according to the choice of user. he may want to open a file or he may want to enter a string
if a=="1":
content=raw_input("Enter string: ")
elif a=="2":
b=raw_input("Enter File name: ")
content=open(b).readlines()
content=''.join(content)
l=len(content) #to find the length of the string or file
#making all characters uppercase to make search easier and better
content=content.upper()
#variable to count the no=umber of vowels
count=0
for i in range(0,l):
if content[i]=="A" :
count=count+1
if content[i]=="E" :
count=count+1
if content[i]=="I" :
count=count+1
if content[i]=="O" :
count=count+1
if content[i]=="U" :
count=count+1
print "Number of vowels in ="+str(count)
if __name__=="__main__":
main()
| true |
a5a5b74a995c3f7393f8077b55a248693e9cefb5 | Ryanwolff14/validemail | /email.py | 281 | 4.28125 | 4 | import re
def validemail():
email= userInput = input("please enter an email: ");
match= re.search(r'[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+.[a-zA-Z]',email)
if match:
print("Valid Email")
else:
print("Invalid Email")
validemail() | false |
91942c8e37b9b847ecd5dffe41be3c53ee1e944c | nhouston/Ice-Core-Analysis | /ImageAnalysis.nosync/sliceImage.py | 1,231 | 4.125 | 4 | from PIL import Image
import os
import math
"""
image_slice is a function that is used to take the input image that the user defines
and split the image. The function takes the image and splits the image vertically
by 1500 pixels.
"""
def image_slice(image_path, outdir):
Image.MAX_IMAGE_PIXELS = None # Set the maximum number of pixels to None - allows image to read
img = Image.open(image_path) # Open the image defined by the user
w,h = img.size # Find the width and the height of the image
upperLimit = 0
leftLimit = 0
sliceHeight = int(math.ceil(h/1500)) #find the height of the image and divide by 1500
count = 1
# For each image slice in the sliced image height then if the count is equal to the slice height
# then make h equal to the lower height
for imageSlice in range(sliceHeight):
if count == sliceHeight:
lower = h
else:
lower = int(count * 1500)
boundingBox = (leftLimit,upperLimit,w,lower) # Create a 'box' that slides over the image
currentImageSlice = img.crop(boundingBox) # Crop the current slice based on the bounding box
upperLimit += 1500
currentImageSlice.save(os.path.join(outdir, str(count)+ ".bmp")) # Save the image
count += 1 | true |
a8606407b754328ea7574e919ed6547853838709 | nwthomas/code-challenges | /src/codewars/7-kyu/least-larger/least_larger.py | 874 | 4.28125 | 4 | """
Task
Given an array of numbers and an index, return the index of the least number larger than the element at the given index, or -1 if there is no such index ( or, where applicable, Nothing or a similarly empty value ).
Notes
Multiple correct answers may be possible. In this case, return any one of them.
The given index will be inside the given array.
The given array will, therefore, never be empty.
Example
least_larger( [4, 1, 3, 5, 6], 0 ) -> 3
least_larger( [4, 1, 3, 5, 6], 4 ) -> -1
"""
def least_larger(num_list, index):
element = num_list[index]
least_larger = None
for i, num in enumerate(num_list):
if num > element:
if not least_larger:
least_larger = (num, i)
elif num < least_larger[0]:
least_larger = (num, i)
return least_larger[1] if least_larger else -1 | true |
17531a8d026adbf09e0c5262bfa6d097e21ad68e | nwthomas/code-challenges | /src/interview-cake/cake-thief/cake_thief.py | 1,914 | 4.25 | 4 | """
You are a renowned thief who has recently switched from stealing precious metals to stealing cakes because of the insane profit margins. You end up hitting the jackpot, breaking into the world's largest privately owned stock of cakes—the vault of the Queen of England.
While Queen Elizabeth has a limited number of types of cake, she has an unlimited supply of each type.
Each type of cake has a weight and a value, stored in an object with two properties:
weight: the weight of the cake in kilograms
value: the monetary value of the cake in British shillings
For example:
// Weighs 7 kilograms and has a value of 160 shillings
{ weight: 7, value: 160 }
// Weighs 3 kilograms and has a value of 90 shillings
{ weight: 3, value: 90 }
You brought a duffel bag that can hold limited weight, and you want to make off with the most valuable haul possible.
Write a function maxDuffelBagValue() that takes an array of cake type objects and a weight capacity, and returns the maximum monetary value the duffel bag can hold.
For example:
const cakeTypes = [
{ weight: 7, value: 160 },
{ weight: 3, value: 90 },
{ weight: 2, value: 15 },
];
const capacity = 20;
maxDuffelBagValue(cakeTypes, capacity);
// Returns 555 (6 of the middle type of cake and 1 of the last type of cake)
Weights and values may be any non-negative integer. Yes, it's weird to think about cakes that weigh nothing or duffel bags that can't hold anything. But we're not just super mastermind criminals—we're also meticulous about keeping our algorithms flexible and comprehensive.
"""
from typing import List
def get_max_cake_value(cakeTypes: List[dict[int, int]], capacity: int) -> int:
dp = [0] * (capacity + 1)
for i in range(capacity + 1):
for cake in cakeTypes:
if i - cake["weight"] >= 0:
dp[i] = max(dp[i], cake["value"] + dp[i - cake["weight"]])
return dp[len(dp) - 1] | true |
27354066da9bace6280e4c7b6ff9864351c5f97b | nwthomas/code-challenges | /src/hacker-rank/medium/frequency-queries/frequency_queries.py | 2,475 | 4.3125 | 4 | """
You are given q queries. Each query is of the form two integers described below:
- 1:x Insert x in your data structure.
- 2:y Delete one occurence of y from your data structure, if present.
- 3:z Check if any integer is present whose frequency is exactly z. If yes, print 1 else 0.
The queries are given in the form of a 2-D array of size where contains the operation, and contains the data element.
Example
queries = [(1, 1), (2, 2), (3, 2), (1, 1), (1, 1), (2, 1), (3, 2)]
The results of each operation are:
Operation Array Output
(1,1) [1]
(2,2) [1]
(3,2) 0
(1,1) [1,1]
(1,1) [1,1,1]
(2,1) [1,1]
(3,2) 1
Return an array with the output: [0, 1].
Function Description
Complete the freqQuery function in the editor below.
freqQuery has the following parameter(s):
- int queries[q][2]: a 2-d array of integers
Returns
- int[]: the results of queries of type 3
"""
def freqQuery(queries):
valueToCount = {}
countToValues = {}
printQueries = []
for query in queries:
operation, value = query
if operation == 1 and not value in valueToCount:
valueToCount[value] = 1
if not 1 in countToValues:
countToValues[1] = {}
countToValues[1][value] = True
elif operation == 1:
previousCount = valueToCount[value]
nextCount = previousCount + 1
valueToCount[value] = nextCount
del countToValues[previousCount][value]
if not nextCount in countToValues:
countToValues[nextCount] = {}
countToValues[nextCount][value] = True
elif operation == 2 and value in valueToCount and valueToCount[value] > 0:
previousCount = valueToCount[value]
nextCount = valueToCount[value] - 1
valueToCount[value] = nextCount
del countToValues[previousCount][value]
if nextCount == 0:
del valueToCount[value]
else:
countToValues[nextCount][value] = True
elif operation == 3 and value in countToValues and len(countToValues[value].keys()) > 0:
printQueries.append(1)
elif operation == 3:
printQueries.append(0)
return printQueries | true |
bd4b61c1dac3f7071e74c11b2ffa413e8d1e0dac | nwthomas/code-challenges | /src/daily-coding-problem/medium/time-map/time_map.py | 2,090 | 4.1875 | 4 | """
Good morning! Here's your coding interview problem for today.
This problem was asked by Stripe.
Write a map implementation with a get function that lets you retrieve the value of a key at a particular time.
It should contain the following methods:
set(key, value, time): sets key to value for t = time.
get(key, time): gets the key at t = time.
The map should work like this. If we set a key at a particular time, it will maintain that value forever or until it gets set at a later time. In other words, when we get a key at a time, it should return the value that was set for that key set at the most recent time.
Consider the following examples:
d.set(1, 1, 0) # set key 1 to value 1 at time 0
d.set(1, 2, 2) # set key 1 to value 2 at time 2
d.get(1, 1) # get key 1 at time 1 should be 1
d.get(1, 3) # get key 1 at time 3 should be 2
d.set(1, 1, 5) # set key 1 to value 1 at time 5
d.get(1, 0) # get key 1 at time 0 should be null
d.get(1, 10) # get key 1 at time 10 should be 1
d.set(1, 1, 0) # set key 1 to value 1 at time 0
d.set(1, 2, 0) # set key 1 to value 2 at time 0
d.get(1, 0) # get key 1 at time 0 should be 2
"""
class TimeMap:
def __init__(self):
self._map = {}
def set(self, key, value, time):
"""
Sets a new key-value pair in self.map with a corresponding time value
"""
if type(time) is not type(1):
return TypeError("The time value must be an integer")
self._map[key] = {"_value": value, "_time": time}
def get(self, key, time):
"""
Gets the value of a key if the time is greater-than-or-equal-to the
set time, else it returns None
"""
if key in self._map:
info = self._map[key]
return info["_value"] if info["_time"] <= time else None
else:
None
def delete(self, key):
"""
Deletes a key-value pair from self._map
"""
del self._map[key]
def values(self):
"""
Returns all current mapped values in self._map
"""
return self._map
| true |
707c872f0d67bf4c04a063be36efbe496b3ef538 | nwthomas/code-challenges | /src/interview-cake/inflight-entertainment/inflight_entertainment.py | 1,538 | 4.46875 | 4 | """"
You've built an inflight entertainment system with on-demand movie streaming.
Users on longer flights like to start a second movie right when their first one ends, but they complain that the plane usually lands before they can see the ending. So you're building a feature for choosing two movies whose total runtimes will equal the exact flight length.
Write a function that takes an integer flight_length (in minutes) and a list of integers movie_lengths (in minutes) and returns a boolean indicating whether there are two numbers in movie_lengths whose sum equals flight_length.
When building your function:
Assume your users will watch exactly two movies
Don't make your users watch the same movie twice
Optimize for runtime over memory
"""
def find_exact_flight_movie_runtime(flight_length, movie_lengths):
"""Finds the exact combination of movie lengths to match a flight length if possible"""
if type(flight_length) != int:
raise TypeError(
"The first argument of find_exact_flight_movie_runtime must be of type int.")
if type(movie_lengths) != list:
raise TypeError(
"The second argument of find_exact_flight_movie_runtime must be of type list.")
if len(movie_lengths) < 1 or flight_length < 0:
return False
prev_lengths = set()
for length in movie_lengths:
missing_length = flight_length - length
if missing_length in prev_lengths:
return True
else:
prev_lengths.add(length)
return False
| true |
ddbde3d2dec3cf2c347a023d349475221443862d | nwthomas/code-challenges | /src/miscellaneous-code-challenges/stock-prices/stock_prices.py | 2,079 | 4.4375 | 4 | """
You want to write a bot that will automate the task of day-trading for you while you're going through Lambda. You decide to have your bot just focus on buying and selling Amazon stock.
Write a function `find_max_profit` that receives as input a list of stock prices. Your function should return the maximum profit that can be made from a single buy and sell. You must buy first before selling; no shorting is allowed here.
For example, `find_max_profit([1050, 270, 1540, 3800, 2])` should return 3530, which is the maximum profit that can be made from a single buy and then sell of these stock prices.
For this problem, we essentially want to find the maximum difference between the smallest and largest prices in the list of prices, but we also have to make sure that the max profit is computed by subtracting some price by another price that comes _before_ it; it can't come after it in the list of prices.
So what if we kept track of the `current_min_price_so_far` and the `max_profit_so_far`?
Run the test file by executing `python test_stock_prices.py`.
You can also test your implementation manually by executing `python stock_prices.py [integers_separated_by_a_single_space]`
"""
import argparse
def find_max_profit(prices):
if len(prices) <= 1:
return None
prior_smallest = prices[0]
max_profit_so_far = prices[1] - prior_smallest
for i in range(1, len(prices) - 1):
new_profit = prices[i] - prior_smallest
if new_profit > max_profit_so_far:
max_profit_so_far = new_profit
if prices[i] < prior_smallest:
prior_smallest = prices[i]
return max_profit_so_far
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Find max profit from prices.')
parser.add_argument('integers', metavar='N', type=int,
nargs='+', help='an integer price')
args = parser.parse_args()
print("A profit of ${profit} can be made from the stock prices {prices}.".format(
profit=find_max_profit(args.integers), prices=args.integers))
| true |
3f19fa1bfb89903e80c56d69db765d3d02b63e59 | nwthomas/code-challenges | /src/leetcode/medium/daily-temperatures/daily_temperatures.py | 1,068 | 4.28125 | 4 | """
https://leetcode.com/problems/daily-temperatures
Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.
Example 1:
Input: temperatures = [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]
Example 2:
Input: temperatures = [30,40,50,60]
Output: [1,1,1,0]
Example 3:
Input: temperatures = [30,60,90]
Output: [1,1,0]
Constraints:
1 <= temperatures.length <= 105
30 <= temperatures[i] <= 100
"""
from typing import List
def daily_temperatures(temperatures: List[int]) -> List[int]:
stack = []
output = [0 for _ in temperatures]
for i, temp in enumerate(temperatures):
while len(stack) > 0 and temperatures[stack[len(stack) - 1]] < temp:
current = stack.pop()
difference = i - current
output[current] = difference
stack.append(i)
return output | true |
66bbe03dbe57f996d3811e6eca4b290971c24039 | nwthomas/code-challenges | /src/leetcode/medium/word-search/word_search.py | 2,728 | 4.125 | 4 | """
https://leetcode.com/problems/word-search/
Given an m x n grid of characters board and a string word, return true if word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
Example 1:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true
Example 2:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
Output: true
Example 3:
Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
Output: false
Constraints:
m == board.length
n = board[i].length
1 <= m, n <= 6
1 <= word.length <= 15
board and word consists of only lowercase and uppercase English letters.
Follow up: Could you use search pruning to make your solution faster with a larger board?
"""
from typing import List
def does_word_exist(board: List[List[str]], word: str) -> bool:
if type(board) != list:
raise TypeError("First argument for does_word_exist must be of type list")
if type(word) != str:
raise TypeError("Second argument for does_word_exist must be of type string")
def search(y, x, index, cache):
if index == len(word) - 1 and board[y][x] == word[index]:
return True
elif (y, x) in cache:
return False
elif board[y][x] != word[index]:
return False
cache.add((y, x))
results = []
if y - 1 >= 0 and not (y - 1, x) in cache:
results.append(search(y - 1, x, index + 1, cache.copy()))
if y + 1 < len(board) and not (y + 1, x) in cache:
results.append(search(y + 1, x, index + 1, cache.copy()))
if x - 1 >= 0 and not (y, x - 1) in cache:
results.append(search(y, x - 1, index + 1, cache.copy()))
if x + 1 < len(board[y]) and not (y, x + 1) in cache:
results.append(search(y, x + 1, index + 1, cache.copy()))
for result in results:
if result:
return True
return False
for y in range(len(board)):
if type(board[y]) != list:
raise TypeError("First argument of type list must contain only rows of type list")
for x in range(len(board[y])):
if type(board[y][x]) != str:
raise TypeError("Values in lists of list must contain only type string")
if board[y][x] == word[0]:
result = search(y, x, 0, set())
if result:
return True
return False | true |
e33b5c0c12775a3991cbdb1c8cefe4b3c039a780 | nwthomas/code-challenges | /src/daily-coding-problem/medium/peekable-iterator/peekable_iterator.py | 2,532 | 4.28125 | 4 | """
Good morning! Here's your coding interview problem for today.
This problem was asked by Google.
Given an iterator with methods next() and hasNext(), create a wrapper iterator, PeekableInterface,
which also implements peek(). Peek shows the next element that would be returned on next().
Here is the interface:
class PeekableInterface(object):
def __init__(self, iterator):
pass
def peek(self):
pass
def next(self):
pass
def hasNext(self):
pass
"""
class Iterator:
def __init__(self, iterator):
self.iter = iterator
self.peeked_value = None
def next_value(self):
"""
Returns the next value in the iterator
"""
if self.has_next() != None:
temp_val = self.peeked_value
self.peeked_value = None
return temp_val
else:
try:
temp_val = next(self.iter)
return temp_val
except StopIteration:
return False
def has_next(self):
"""
Returns True if there is a next value or False otherwise
"""
if self.peeked_value:
return True
else:
try:
temp_val = next(self.iter)
self.peeked_value = temp_val
return True
except StopIteration:
return False
class PeekableInterface:
def __init__(self, iterator):
self.iter = Iterator(iterator)
self.peeked_value = None
def peek(self):
"""
Returns what the next value in the iterator will be if next_value is called
"""
if self.peeked_value:
return self.peeked_value
elif self.iter.has_next():
self.peeked_value = self.iter.next_value()
return self.peeked_value
else:
return None
def next_value(self):
"""
Returns the next value in the iterator
"""
if self.peeked_value:
temp_val = self.peeked_value
self.peeked_value = None
return temp_val
elif self.iter.has_next():
return self.iter.next_value()
else:
return None
def has_next(self):
"""
Returns True if there's a next value in the iterator or False otherwise
"""
if self.peeked_value:
return True
elif self.iter.has_next():
return True
else:
return False
| true |
819373032f5ed9094e6d42a87c671f643dc9625f | nwthomas/code-challenges | /src/hacker-rank/hard/array-manipulation/array_manipulation.py | 1,634 | 4.3125 | 4 | """
Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array.
Example
n = 10
queries = [[1, 5, 3], [4, 8, 7], [6, 9, 1]]
Queries are interpreted as follows:
a b k
1 5 3
4 8 7
6 9 1
Add the values of k between the indices a and b inclusive:
index-> 1 2 3 4 5 6 7 8 9 10
[0,0,0, 0, 0,0,0,0,0, 0]
[3,3,3, 3, 3,0,0,0,0, 0]
[3,3,3,10,10,7,7,7,0, 0]
[3,3,3,10,10,8,8,8,1, 0]
The largest value is 10 after all operations are performed.
Function Description
Complete the function arrayManipulation in the editor below.
arrayManipulation has the following parameters:
int n - the number of elements in the array
int queries[q][3] - a two dimensional array of queries where each queries[i] contains three integers, a, b, and k.
Returns
int - the maximum value in the resultant array
"""
def array_manipulation(queries):
"""Finds the largest sum of potentially overlapping summation queries on an array"""
tracker = {}
largest_value = 0
for i in range(len(queries)):
start, end, value = queries[i]
if not start in tracker:
tracker[start] = 0;
tracker[start] += value
if not end + 1 in tracker:
tracker[end + 1] = 0
tracker[end + 1] -= value;
current_total = 0
for key in tracker:
current_total += tracker[key]
if current_total > largest_value:
largest_value = current_total
return largest_value
| true |
8dcef8821671cead1528c3c36be66ad47cc45daa | nwthomas/code-challenges | /src/interview-cake/merge-sorted-lists/merge_sorted_lists.py | 1,581 | 4.28125 | 4 | """
In order to win the prize for most cookies sold, my friend Alice and I are going to merge our Girl Scout Cookies orders and enter as one unit.
Each order is represented by an "order id" (an integer).
We have our lists of orders sorted numerically already, in lists. Write a function to merge our lists of orders into one sorted list.
For example:
my_list = [3, 4, 6, 10, 11, 15]
alices_list = [1, 5, 8, 12, 14, 19]
# Prints [1, 3, 4, 5, 6, 8, 10, 11, 12, 14, 15, 19]
print(merge_lists(my_list, alices_list))
"""
def merge_sorted_cookie_lists(listA, listB):
"""Takes in two order lists of cookies and merges them together"""
if type(listA) != list or type(listB) != list:
raise TypeError(
"Both arguments for merge_sorted_cookie_lists must be of type list.")
final_list = []
listA_length = len(listA)
listB_length = len(listB)
if listA_length < 1:
return listB
if listB_length < 1:
return listA
if listB_length < 1 and listA_length < 1:
return final_list
a_index = 0
b_index = 0
while a_index + b_index < listA_length + listB_length:
if a_index >= listA_length:
final_list.append(listB[b_index])
b_index += 1
elif b_index >= listB_length:
final_list.append(listA[a_index])
a_index += 1
elif listB[b_index] < listA[a_index]:
final_list.append(listB[b_index])
b_index += 1
else:
final_list.append(listA[a_index])
a_index += 1
return final_list
| true |
b866fa71fb76291c15d35103c1225afe11513b64 | nwthomas/code-challenges | /src/daily-coding-problem/easy/find-most-valuable-path/find_most_weighted_path.py | 1,499 | 4.25 | 4 | """
Good morning! Here's your coding interview problem for today.
This problem was asked by Google.
You are given an array of arrays of integers, where each array corresponds to a row in a triangle of numbers. For example, [[1], [2, 3], [1, 5, 1]] represents the triangle:
1
2 3
1 5 1
We define a path in the triangle to start at the top and go down one row at a time to an adjacent value, eventually ending with an entry on the bottom row. For example, 1 -> 3 -> 5. The weight of the path is the sum of the entries.
Write a program that returns the weight of the maximum weight path.
"""
def find_most_weighted_path_down(triangle):
"""Takes in a triangle (list of list of integers) and returns path with the most weight on the way down"""
# Tracker stores in pattern of [total_weight, x_index, y_index]
tracker = [[triangle[0][0], 0, 0]]
heaviest_path = tracker[0][0]
while len(tracker) >= 1:
total_weight, x_index, y_index = tracker.pop()
if x_index < len(triangle) - 1:
x_index = x_index + 1
y_index_one = y_index
y_index_two = y_index + 1
total_weight_one = total_weight + triangle[x_index][y_index_one]
total_weight_two = total_weight + triangle[x_index][y_index_two]
tracker.append([total_weight_one, x_index, y_index_one])
tracker.append([total_weight_two, x_index, y_index_two])
elif total_weight > heaviest_path:
heaviest_path = total_weight
return heaviest_path | true |
1b1f9ff84258b71e0f4bd0f672d1683a83997705 | nwthomas/code-challenges | /src/leetcode/medium/maximum-product-subarray/maximum_product_subarray.py | 1,295 | 4.125 | 4 | """
https://leetcode.com/problems/maximum-product-subarray
Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product.
The test cases are generated so that the answer will fit in a 32-bit integer.
A subarray is a contiguous subsequence of the array.
Example 1:
Input: nums = [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: nums = [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
Constraints:
1 <= nums.length <= 2 * 104
-10 <= nums[i] <= 10
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
"""
from typing import List
def max_product(nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]
max_so_far = max(nums)
max_current = 1
min_current = 1
for _, num in enumerate(nums):
if num == 0:
max_current = 1
min_current = 1
continue
temp_max_current = max_current * num
max_current = max(temp_max_current, num * min_current, num)
min_current = min(temp_max_current, num * min_current, num)
max_so_far = max(max_so_far, max_current)
return max_so_far | true |
a86cf51fd9e36f81a440708fe156aaa862121643 | nwthomas/code-challenges | /src/hacker-rank/easy/bubble-sort/bubble_sort.py | 1,468 | 4.3125 | 4 | """
Consider the following version of Bubble Sort:
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1; j++) {
// Swap adjacent elements if they are in decreasing order
if (a[j] > a[j + 1]) {
swap(a[j], a[j + 1]);
}
}
}
Given an array of integers, sort the array in ascending order using the Bubble Sort algorithm above. Once sorted, print the following three lines:
Array is sorted in numSwaps swaps., where numSwaps is the number of swaps that took place.
First Element: firstElement, where firstElement is the first element in the sorted array.
Last Element: lastElement, where lastElement is the last element in the sorted array.
Hint: To complete this challenge, you must add a variable that keeps a running tally of all swaps that occur during execution.
Example
a = [6, 4, 1]
swap a
0 [6,4,1]
1 [4,6,1]
2 [4,1,6]
3 [1,4,6]
The steps of the bubble sort are shown above. It took 3 swaps to sort the array. Output is:
Array is sorted in 3 swaps.
First Element: 1
Last Element: 6
Nathan's Note: This function has been modified to return a tuple for the purposes of making it easier to test.
"""
def countSwaps(a):
numSwaps = 0
for _ in range(0, len(a)):
for j in range (0, len(a) - 1):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
numSwaps += 1
return [numSwaps, a[0], a[len(a) - 1]] | true |
e611c91fdc57a31f9f64a9bfc4e9467478830730 | nwthomas/code-challenges | /src/interview-cake/highest-multiple-of-integers/highest_multiple_of_integers.py | 1,337 | 4.59375 | 5 | """
Given a list of integers, find the highest product you can get from three of the integers.
The input list_of_ints will always have at least three integers.
"""
def find_highest_multiple_of_three_ints(int_list):
"""Takes in a list of integers and finds the highest multiple of three of them"""
if type(int_list) != list:
raise TypeError(
"The argument for find_highest_multiple_of_three_ints must be of type list.")
elif len(int_list) == 3:
one, two, three = int_list
return one * two * three
highest_product_of_3 = int_list[0] * int_list[1] * int_list[2]
highest_product_of_2 = int_list[0] * int_list[1]
lowest_product_of_2 = int_list[0] * int_list[1]
highest = max(int_list[0], int_list[1])
lowest = min(int_list[0], int_list[1])
for i in range(2, len(int_list)):
current = int_list[i]
highest_product_of_3 = max(
highest_product_of_3, highest_product_of_2 * current, lowest_product_of_2 * current)
highest_product_of_2 = max(
highest_product_of_2, current * lowest, current * highest)
lowest_product_of_2 = min(
lowest_product_of_2, current * highest, current * lowest)
highest = max(highest, current)
lowest = min(lowest, current)
return highest_product_of_3
| true |
f5ff60b1380f794c8d19dc465f6e890e8f25becd | Avisikta-Majumdar/Campus-Placement-Coding-Question-And-Answers | /Accenture/FindCount.py | 716 | 4.3125 | 4 | #Question
'''You are given a function FindCount
The function accpets an int array 'arr'
The function will return the no of elements of 'arr' having absolute difference
of less than or equal to 'diff' with ' num'''
#Input:-
'''arr: 12 3 14 56 77 13
num:12
diff:2
'''
#Output : -
# 3
def FindCount(array , length , num , diff):
count = 0
for i in array:
if abs(i-num)<=diff:
count+=1
return -1 if count==0 else count #Ternary Operator
Input = input("Enter the elements of array:- ")
num = int(input("num :-"))
diff = int(input("diff :- "))
Array = Input.split(" ")
array = [int(i) for i in Array]
print(FindCount(array , len(array) , num , diff))
| true |
092b662940b04da299d3bfa5a4acf9c1f2b41042 | Avisikta-Majumdar/Campus-Placement-Coding-Question-And-Answers | /TCS NQT Coding Questions and Answers/Check Palindrome.py | 241 | 4.25 | 4 | '''
Write a Python program to
check whether the given number is Palindrome or not using command line arguments.
'''
def PalinDrome(n):
return n==n[::-1]
for i in range(int(input("Test case:-"))):
print(PalinDrome(input()))
| true |
809196d5563f89ac9dd9a1be28dc4480b850017d | aarthymurugappan101/loops | /pract4_q2.py | 210 | 4.15625 | 4 |
total = 0
count = 0
while count < 5:
usrInput = int(input("Your number please"))
total += usrInput
count += 1 # to add so that it will not become an infinite loop
print("While: Total sum is",total) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.