blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
d6192566a5778e4c5ec9536c5f30db470bca7439 | WeeJang/basic_algorithm | /ShuffleanArray.py | 1,260 | 4.28125 | 4 | #!/usr/bin/env python2
#-*- coding:utf-8 -*-
"""
Shuffle a set of numbers without duplicates.
Example:
// Init an array with set 1, 2, and 3.
int[] nums = {1,2,3};
Solution solution = new Solution(nums);
// Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned.
solution.shuffle();
// Resets the array back to its original configuration [1,2,3].
solution.reset();
// Returns the random shuffling of array [1,2,3].
solution.shuffle();
"""
import copy
import random
class Solution(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.origin = nums
def reset(self):
"""
Resets the array to its original configuration and return it.
:rtype: List[int]
"""
return self.origin
def shuffle(self):
"""
Returns a random shuffling of the array.
:rtype: List[int]
"""
nums_c = copy.deepcopy(self.origin)
l = len(nums_c)
for i in range(l):
j = random.randint(0,l-1)
nums_c[i],nums_c[j] = nums_c[j],nums_c[i]
return nums_c
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle()
| true |
023e609eb767a6e0ec588b79fd38567e82c84225 | JakeJaeHyongKim/I211 | /lab 3-4(list comp, combined number in list).py | 549 | 4.15625 | 4 | #lab practical example
#appeal only what I need as output, #1= sort it
nums = ["123", "321", "435", "2468"]
num_order = [num for num in nums if [digit for digit in num] == \
sorted([digit for digit in num])]
print(num_order)
lst1 = [1,2,3]
lst2 = sorted([1,2,3])
#2= only odd numbers as output
nums = ["123", "321", "435", "2468"]
num_odd = [num for num in nums if [digit for digit in num if int(digit) % 2 == 1] == \
sorted([ digit for digit in num if int(digit) % 2 == 1 ])]
print(num_odd)
| true |
5bf0db55a5bc7ca89f4e02cc1d0bbf195629bf45 | JakeJaeHyongKim/I211 | /lab 3-3(list comprehension, word to upper case).py | 378 | 4.1875 | 4 | #word list comprehension
#if word contains less than 4 letters, append as upper case
#if not, leave it as it is
words= ["apple", "ball", "candle", "dog", "egg", "frog"]
word = [i.upper() if len(i) < 4 else i for i in words]
#not proper: word = [word.upper() if len(words) < 4 else word for word in words]
#learn how to take only word less than 4 letters
print(word)
| true |
6168e7579f4d014b666e617f5ff9869cea0d68b4 | mayanksh/practicePython | /largestarray.py | 521 | 4.34375 | 4 | #def largest(array, n):
# max = array[0] #initialize array
# for i in range (1, n):
# if array[i] > max:
# max = array[i]
# return max
#array = [1,2,3,4,5]
#n = len(array)
#answer = largest(array, n)
#print("largest element is: " , answer)
arr=int(input('Enter the element of an array:')
n = len(arr)
def largest(arr,n):
max = arr[0]
for i in range(1, n):
if arr[i] > max:
max = arr[i]
return max
Ans = largest(arr,n)
print ("Largest in given array is",Ans)
| true |
970d5bee4acfe240e4891e348336df5486d9b6a5 | gabrslen/estudos | /EntrevistaEmprego/DataModule.py | 769 | 4.25 | 4 | class Entrevista():
nome = ""
ano_informado = 0
idade = 0
def pergunta_nome(self):
self.nome = input("Nome do candidato: ")
print("O nome é '" + self.nome + "'")
return self.nome
def pergunta_idade(self, ano_atual=2021):
self.ano_informado = int(input("Ano de nascimento de " + self.nome + ":"))
self.idade = ano_atual - self.ano_informado
print(self.nome,"tem",self.idade,"anos.")
#return (self.ano_informado, self.idade)
# Funçoes restritas já estão imbutidas na liguagem py, a primeira recebe os valores e retorna
def __str__(self):
return "{}/{}".format(self.nome, self.idade)
def __repr__(self):
return"Nome: {} - Idade: {}\n".format(self.nome, self.idade) | false |
d663b392d048396983b8e8ed825b1cd8c7ae013b | apktool/LearnPython | /1.12.01.py | 587 | 4.28125 | 4 | #--coding:utf-8---
#元组
tuple1=(1,2,3,4,5,6,7,8)
print(tuple1)
tuple2=(1)
print(tuple2)
tuple3=(1,)
print(tuple3)
tuple4=1
print(tuple4)
tuple5=1,
print(tuple5)
'''
应该注意tuple2和tuple3的区别:tuple2创建的是一个整数,tuple3创建的是一个元祖
tuple4创建的是一个整数,tuple5创建的是一个元组
'''
a=8*(8)
print(a)
a=8*(8,)
print(a)
'''
第一次打印出的a是64
第二次打印出的a是(8, 8, 8, 8, 8, 8, 8, 8)
'''
temp=('a','b','d')
print(temp);
temp=temp[:2]+('c',)+temp[2:]
print(temp);
'''
向已有元组中添加元素
'''
| false |
4a967e2285d09f08261e92df7f719abb0e7d4cf4 | apktool/LearnPython | /3.14.03.py | 1,635 | 4.15625 | 4 | # 命名空间的生命周期
x=1
def fun1():
x=x+1
fun1()
def fun2():
y=123
del y
print(y)
fun2()
'''
UnboundLocalError: local variable 'x' referenced before assignment
UnboundLocalError: local variable 'y' referenced before assignment
'''
'''
不同的命名空间在不同的时刻创建,有不同的生存期。
1、内置命名空间在 Python 解释器启动时创建,会一直保留,不被删除。
2、模块的全局命名空间在模块定义被读入时创建,通常模块命名空间也会一直保存到解释器退出。
3、当函数被调用时创建一个局部命名空间,当函数返回结果 或抛出异常时,被删除。每一个递归调用的函数都拥有自己的命名空间。
Python 的一个特别之处在于其赋值操作总是在最里层的作用域。赋值不会复制数据——只是将命名绑定到对象。删除也是如此:"del y" 只是从局部作用域的命名空间中删除命名y。事实上,所有引入新命名的操作都作用于局部作用域。
'''
'''
A scope is a textual region of a Python program where a namespace is directly accessible. “Directly accessible” here means that an unqualified reference to a name attempts to find the name in the namespace.
the innermost scope, which is searched first, contains the local names
the scopes of any enclosing functions, which are searched starting with the nearest enclosing scope, contains non-local, but also non-global names
the next-to-last scope contains the current module’s global names
the outermost scope (searched last) is the namespace containing built-in names
'''
| false |
617e98aa40ff5d01a7c2e83228c011705de0b928 | timlindenasell/unbeatable-tictactoe | /game_ai.py | 2,347 | 4.3125 | 4 | import numpy as np
def minimax(board, player, check_win, **kwargs):
""" Minimax algorithm to get the optimal Tic-Tac-Toe move on any board setup.
This recursive function uses the minimax algorithm to look over each possible move
and minimize the possible loss for a worst case scenario. For a deeper understanding
and examples see: 'Wikipedia <https://en.wikipedia.org/wiki/Minimax>'_.
:param board: 3x3 numpy ndarray where 0 is empty, 1 is X, 2 is O.
:param player: Determines player: 1 if X, 2 if O.
:param check_win: Function that takes a 'board' and returns: 0 if stale, 1 if X won, 2 if O won.
:param kwargs: Used in the recursion to pass the last move made.
:return: 'score' and index of optimal Tic-Tac-Toe 'move' given a 3x3 board.
:rtype: float, tuple (int, int)
"""
EMPTY = 0
STALE = 0
WIN = 1
PLAYER_X = 1
PLAYER_O = 2
assert isinstance(board, np.ndarray) and board.shape == (3,3), 'board must be a (3,3) numpy.ndarray'
assert player is PLAYER_X or PLAYER_O, 'player must be an int 1 (X) or 2 (O).'
# Get the constant integer value of the opponent.
opponent = PLAYER_X if player == PLAYER_O else PLAYER_O
# Return correct reward if there's a winner.
winner = check_win(board)
if winner == player:
board[kwargs['last_move']] = EMPTY
return WIN
elif winner == opponent:
board[kwargs['last_move']] = EMPTY
return -WIN
move = -1
score = float('-inf')
# Get indices of available moves.
available_moves = np.where(board == EMPTY)
am_indices = list(zip(*available_moves))
# Try each move
for move_index in am_indices:
# Make copy of current board grid.
board_copy = board
# Make move on copy
board_copy[move_index] = player
move_score = -minimax(board_copy, opponent, check_win, last_move=move_index)
if move_score > score:
score = move_score
move = move_index
if move == -1:
board[kwargs['last_move']] = EMPTY
return STALE
# If the keyword-argument is not found, it must be the last recursion and
# should therefore return the best move and its score.
try:
board[kwargs['last_move']] = EMPTY
except KeyError:
return score, move
return score | true |
167b3a56792d0be21f40e0e8d2208fd7943ccddc | Vibhutisavaliya123/DSpractice | /DS practicel 6.py | 1,624 | 4.4375 | 4 | P6#WAP to sort a list of elements. Give user the
option to perform sorting using Insertion sort,
Bubble sort or Selection sort.#
Code:Insertion sort
def insertionSort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
# Driver code to test above
arr = [12, 11, 13, 5, 6]
insertionSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print ("%d" %arr[i])
Code : selection sort
def selection_sort(alist):
for i in range(0, len(alist) - 1):
smallest = i
for j in range(i + 1, len(alist)):
if alist[j] < alist[smallest]:
smallest = j
alist[i], alist[smallest] = alist[smallest], alist[i]
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
selection_sort(alist)
print('Sorted list: ', end='')
print(alist)
Code:Bubble sort
def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n-1):
for j in range(0, n-i-1):
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
arr = [64, 34, 25, 12, 22, 11, 90]
bubbleSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print ("%d" %arr[i]),
| true |
5d7d4bc98ca3fc5b18b7206343bc8da663b29543 | sergady/Eulers-Problems | /Ej1.py | 354 | 4.15625 | 4 |
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
listNums = []
for i in range(1000):
if(i%3 == 0 or i%5 == 0):
listNums.append(i)
sum = 0
for s in (listNums):
sum = sum + s
print(sum)
| true |
a6b5afea50bfb95264937b9a79cb2cd4677d0d45 | aofrigerio/ordenacoes | /heapsort.py | 821 | 4.21875 | 4 | def heapify(A, n, i):
print(A)
largest = i # Initialize largest as root
l = 2 * i + 1 # left = 2*i + 1
r = 2 * i + 2 # right = 2*i + 2
# See if left child of root exists and is
# greater than root
if l < n and A[i] < A[l]:
largest = l
# See if right child of root exists and is
# greater than root
if r < n and A[largest] < A[r]:
largest = r
# Change root, if needed
if largest != i:
A[i], A[largest] = A[largest], A[i] # swap
# Heapify the root.
heapify(A, n, largest)
# The main function to sort an array of given size
def heapSort(A):
n = len(A)
for i in range(n, -1, -1):
heapify(A, n, i)
for i in range(n - 1, 0, -1):
A[i], A[0] = A[0], A[i] # swap
heapify(A, i, 0) | false |
076a1ff1556bf140d838529270121ebd99ecc86f | halljm/murach_python | /exercises/ch02/test_scores.py | 660 | 4.375 | 4 | #!/usr/bin/env python3
# display a welcome message
print("The Test Scores program")
print()
print("Enter 3 test scores")
print("======================")
# get scores from the user
score1 = int(input("Enter test score: "))
score2 = int(input("Enter test score: "))
score3 = int(input("Enter test score: "))
total_score = score1 + score2 + score3
# calculate average score
average_score = round(total_score / 3)
# format and display the result
print("======================")
print("Your Scores: " + " " + str(score1) + " " + str(score2) + " " + str(score3))
print("Total Score: ", total_score,
"\nAverage Score:", average_score)
print() | true |
c2c2bf4bcf47b7a4bc15bbf0b333ff6fe52eda3b | jhertzberg1/bmi_calculator | /bmi_calculator.py | 1,364 | 4.375 | 4 | '''
TODO
Greeting
Create commandline prompt for height
Create commandline prompt for weight
Run calculation
Look up BMI chart
Print results
'''
def welcome():
print('Hi welcome to the BMI calculator.')
def request_height():
height = 0
return height
def request_weight():
'''Commandline user input for weight
Returns:
int: Value representing user inputed weight as an int.
'''
while True:
try:
weight = int(input('What is your weight in pounds? >'))
break
except ValueError:
print('That is not a number')
return weight
def calculate_bmi(height_in_inches, weight_in_pounds):
bmi = 23
# TODO consider your units
return bmi
def look_up_word(bmi): # TODO fix word
if bmi >= 30:
return 'Obese'
if bmi >= 25:
return 'Overweight'
if bmi >= 19:
return 'Normal weight'
return 'Under weight'
def print_results(bmi, word):
'''Prints the results of your BMI.
Args:
bmi (int): calculated body mass index score
word (str):
'''
print(word)# look up string formatting
if __name__ == '__main__':
welcome()
height = request_height()
weight = request_weight()
print(weight)
bmi = calculate_bmi(height, weight)
word = look_up_word(bmi)
print_results(bmi, word)
| true |
a45dc8e608aa095066e98b405fdc4c1719da823a | nealebanagale/python-training | /08_Structured_Data/lists.py | 948 | 4.15625 | 4 | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
# [] - list are imutable
# () - tuple are not mutable
def main():
game = ['Rock', 'Paper', 'Scissors', 'Lizard', 'Spock']
print(game[1]) # access list elements
print(game[1:5:2]) # same with range's start,stop,step\
i = game.index('Paper') # search
game.append('Computer')
game.insert(0, 'Computer')
game.remove('Paper') # omitted form list
x = game.pop() # removed last item and return the value
print(i)
print(x)
del game[3] # delete statement by index
print(', '.join(game)) # join string
print(len(game)) # length
print_list(game)
# tuple
game2 = ('Rock', 'Paper', 'Scissors', 'Lizard', 'Spock') # immutable
print(game2)
def print_list(o):
for i in o:
print(i, end=' ', flush=True)
print()
if __name__ == '__main__':
main()
| false |
7df861ce3467cb871fce042f17a4b839f2193379 | Liam-Hearty/ICS3U-Unit5-05-Python | /mailing_address.py | 1,981 | 4.21875 | 4 | #!/usr/bin/env python3
# Created by: Liam Hearty
# Created on: October 2019
# This program finds your mailing address.
def find_mailing_address(street, city, province, postal_code, apt=None):
# returns mailing_address
# process
mailing_address = street
if apt is not None:
mailing_address = apt + "-" + mailing_address
mailing_address = mailing_address + "\n" + city + " " + province + " " \
+ postal_code
return mailing_address
def main():
# this function gets info from user.
try:
# input
aptNum = str(input("Do you have an Apt. Number? Enter y or n: "))
if aptNum == "y":
aptNum_from_user = str(input("Enter your Apt. Number: "))
elif aptNum == "n":
aptNum_from_user = None
else:
print("Please enter a valid response.")
exit()
except ValueError:
print("Please enter a valid response.")
try:
# input
street_address_from_user = str(input("Enter your street address: "))
city_from_user = str(input("Enter what city: "))
province_from_user = str(input("Enter what province: "))
postal_code_from_user = str(input("Enter postal code: "))
print("")
apt = aptNum_from_user
street = street_address_from_user
city = city_from_user
province = province_from_user
postal_code = postal_code_from_user
# call functions
if apt is not None:
mailing_address = find_mailing_address(street, city, province,
postal_code, apt)
else:
mailing_address = find_mailing_address(street, city, province,
postal_code)
# output
print(mailing_address)
except ValueError:
print("Please enter a valid response.")
if __name__ == "__main__":
main()
| true |
cb7e966781a96121035c9489b410fcc1ace84537 | yashaswid/Programs | /LinkedList/MoveLastToFirst.py | 1,325 | 4.28125 | 4 | # Write a function that moves the last element to the front in a given Singly Linked List.
# For example, if the given Linked List is 1->2->3->4->5, then the function should change the list to 5->1->2->3->4
class Node:
def __init__(self,val):
self.data=val
self.next=None
class Linkedlist:
def __init__(self):
self.head = None
def insert(self,val):
temp=Node(val)
temp.next=self.head
self.head=temp
def print(self):
temp=self.head
while (temp):
print(temp.data)
temp=temp.next
def move(self):
temp=self.head
pre=self.head
# can be done in two ways
# while(temp.next is not None): first method
# pre=temp
# temp=temp.next
# value=temp.data
# pre.next=None
# li.insert(value)
while(temp.next is not None):
# second method
pre=temp
temp=temp.next
pre.next = None
temp.next=self.head
self.head=temp
https://33souththird.activebuilding.com/
li =Linkedlist()
li.insert(6)
li.insert(5)
li.insert(4)
li.insert(3)
li.insert(2)
li.insert(1)
li.print()
print("Removing the duplicate values")
li.move()
li.print()
| true |
4e35112282fbaccdf62d4aea0ae67bd9446e6117 | Viole-Grace/Python_Sem_IV | /3a.py | 1,688 | 4.28125 | 4 | phones=dict()
def addentry():
global phones
name=raw_input("Enter name of the phone:")
price=raw_input("Enter price:")
phones.update({name:price})
def namesearch(name1):
global phones
for key,value in phones.items():
if name1==key:
print "Found, its price is ",value
def pricesearch(price):
global phones
searchlist=[k for k,v in phones.items() if v == price]
print searchlist[0]
def pricegroup():
global phones
pricelist = list(set(sorted(phones.values()))) #sorts and removes removes duplicate values
print "Phones grouped by same prices are :"
for i in range(len(pricelist)):
all_keys=pricelist[i]
print "Price : ",all_keys,"; Group : ",[k for k,v in phones.items() if v == all_keys]
def remove_entry():
global phones
print "Enter name of phone to delete :"
name=raw_input();
try:
del(phones[name])
print "Updated Dict : \n",phones.keys()
except:
print "Entry not found"
def sortdict():
print sorted(phones.items(),key=lambda x : x[1]) #sort by price, for sorting by name use x[0]
while True:
print "MENU : \n1. Add Entry \n2. Search by name \n3. Search by price \n4. Group by price \n5. Sort \n6. Delete Entry \n7. Exit \nEnter your choice :"
choice=int(input())
if choice==1:
addentry()
elif choice==2:
name=raw_input('Enter name of the phone: ')
namesearch(name)
elif choice==3:
price = (raw_input('Enter price of the phone: '))
pricesearch(price)
elif choice==4:
pricegroup()
elif choice == 5:
sortdict()
elif choice==6:
remove_entry()
else:
break
| true |
571c1db047fd45cf9a73414eb1b246f15ce3f3e3 | hickmanjv/hickmanjv | /CS_4085 Python/Book Examples/coin_toss_demo.py | 401 | 4.25 | 4 | import coin
def main():
# create an object of the Coin class
my_coin = coin.Coin()
# Display the side of the coin that is facing up
print('This side is up: ', my_coin.get_sideup())
# Toss the coin 10 times:
print('I am going to toss the coin 10 times:')
for count in range(10):
my_coin.toss()
print(my_coin.get_sideup())
# Call the main function
main()
| true |
94b508503ea89642213964b07b0980ca81e354e2 | lucaslb767/pythonWorkOut | /pythonCrashCourse/chapter6/favorite_languages.py | 567 | 4.375 | 4 | favorite_languages = {
'jen':'python',
'sarah':'C',
'jon':'ruby'
}
print('Jon favorite language is ', favorite_languages['jon'])
friends = ['sarah']
#using a list to sort a dictionary's value
for name in favorite_languages:
print(name.title())
if name in friends:
print('Hi', name.title(),'I see your favorite language is', favorite_languages[name],'!')
#using the value() method to only loop trhough values
print('the following values have been mentioned:')
for language in favorite_languages.values():
print(language.title()) | true |
6c543e8cfcb156f3265e3bbd01b287af45c318f3 | MariaBT/IS105 | /ex3.py | 961 | 4.34375 | 4 | # Only text describing what will be done
print "I will count my chickens:"
# Print the result of the number of hens
print "Hens", 25 + 30 / 6
# Print the result of the number of roosters
print "Roosters", 100 - 25 * 3 % 4
# Plain text explaining what will be done next
print "Now I will count the eggs:"
# The result of the action above
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
# Print a question of plain text
print "Is it true that 3 + 2 < 5 - 7?"
# Print the answer: true or false
print 3 + 2 < 5 - 7
# Print text, followed by an answer
print "What is 3 + 2?", 3 + 2
print "What is 5 - 7?", 5 - 7
# Print text
print "Oh, that's why it's false."
print "How about some more."
# Print text in form of questions, followed by an answer: true og false
print "Is it greater?", 5> -2
print "Is it greater og equal?", 5 >= -2
print "Is it less or equal?", 5 <= -2
# Should add ".0" to every number to get more accurate results (floating point numbers)
| true |
879c5858fa8ab9debf0c78559777687fbd2e2d6f | saikrishna-ch/five_languages | /pyhton/NpowerN.py | 252 | 4.28125 | 4 | Number = int(input("Enter a number to multilply to itself by it's number of times:"))
print("{} power {} is".format(Number, Number), end = "")
Product = 1
for Counter in range(Number):
Product = Product * Number
print(" {}.".format(Product))
| true |
83d64472efeab83b8b86036ebfd02cdb26aa79ea | pinstinct/wps-basic | /day6/practice/p2.py | 612 | 4.21875 | 4 | def what_fruits(color):
'''
문자열 color 값을 매개변수로 받아
문자열이 red면 apple,
yellow면 banana,
green이면 melon을 반환한다.
어떤 경우도 아니라면 I don't know 반환
'''
if color == 'red':
return 'apple'
elif color == 'yellow':
return 'banana'
elif color == 'green':
return 'melon'
else:
return 'I don\'t know'
result1 = what_fruits('red')
print(result1)
result2 = what_fruits('yellow')
print(result2)
result3 = what_fruits('green')
print(result3)
result4 = what_fruits('black')
print(result4)
| false |
eff66e25423e884613d98d1093088ec9a4ae084c | thebishaldeb/ClassAssignments | /Algorithms/Assign7/main.py | 1,710 | 4.25 | 4 | #=============== FUNCTIONS START ===============
# merge function for merge sort algorithm to sort an array
def merge(arr, l, m, r ):
n1 = m - l + 1
n2 = r - m
L = [0] * (n1)
R = [0] * (n2)
for i in range(0 , n1):
L[i] = arr[l + i]
for j in range(0 , n2):
R[j] = arr[m + 1 + j]
i = 0
j = 0
k = l
while i < n1 and j < n2 :
if L[i][1] <= R[j][1]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while i < n1:
arr[k] = L[i]
i += 1
k += 1
while j < n2:
arr[k] = R[j]
j += 1
k += 1
# mergeSort function for merge sort algorithm to sort an array
def mergeSort(arr, l, r):
if l < r:
m = int((l+(r-1))/2)
mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)
#=============== MAIN PROGRAM ===============
db = {} # Dictionary to store values from the text file
with open("values.txt","r") as file: # reading the file
for line in file:
x = line.split(" ")
db[int(x[0])] = (int(x[1]),int(x[2])) # Assignment no and their respective deadline and marks
weightArray = [] # array to store the marks/deadline ratio
for i in range(len(db)):
weightArray.append(( i+1, db[i+1][0] / db[i+1][1] ))
mergeSort( weightArray, 0, len(weightArray)-1 )
count = 1
total = 0
result = []
for i in range( len(weightArray) ):
if( db[weightArray[i][0]][0] >= count ):
result.append(weightArray[i][0])
count += 1
total += db[weightArray[i][0]][1]
print(result)
print("The total marks that'll be obtained is",total) | false |
baf1307dfe88b63e00bebd58aff86921d017e331 | acronoo/lesson1 | /homework1.1.py | 737 | 4.28125 | 4 | # 1. Поработайте с переменными, создайте несколько, выведите на экран,
# запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран.
a = 5
print("a = ", a)
b = 20
print("b = ", b)
value = a + b
print(f"a + b = {a} + {b} = {value}")
user_input1 = input("Что бы получить результат умножения двух чисел, введите первое число: ")
user_input2 = input("Теперь введите второе число: ")
print(f"{user_input1} умножить на {user_input2} равно {int(user_input2) * int(user_input1)}")
| false |
90cb2d16b1457623097c5c0edbe7170b3756e767 | MahadiRahman262523/Python_Code_Part-1 | /practice_problem-28.py | 485 | 4.40625 | 4 | #write a program to print multiplication table of a given number
#using for loop
# num = int(input("Enter any number : "))
# for i in range(1,11):
# # print(str(num) + " X " + str(i) + " = " + str(i*num))
# print(f"{num} X {i} = {i*num}")
#write a program to print multiplication table of a given number
#using while loop
print ("Enter a number")
num = int(input())
i = 1
while i<11:
m = num*i
print (f"{num} × {i} = {m}")
i = i+1
| false |
b4e26837cb1813bb939df3c6f783aea9f0d7eb88 | MahadiRahman262523/Python_Code_Part-1 | /operators.py | 883 | 4.53125 | 5 | # Operators in Python
# Arithmetic Operators
# Assignment Operators
# Comparison Operators
# Logical Operators
# Identity Operators
# Membership Operators
# Bitwise Operators
# Assignment Operator
# print("5+6 is ",5+6)
# print("5-6 is ",5-6)
# print("5*6 is ",5*6)
# print("5/6 is ",5/6)
# print("16//6 is ",16//6)
# print("5**6 is ",5**6)
# print("5%6 is ",5%6)
#Assignment operator
# x = 56
# print(x)
# x += 44
# print(x)
#Comparison operator
# i = 4
# print(i!=7)
#Logical operator
# a = True
# b = False
# print(a and b)
# print(a or b)
#Identity operator
# a = True
# b = False
# print(a is b)
# print(a is not b)
#Membership Operator
# list = [10,44,7,8,44,89,90,100]
# print(12 in list)
# print(10 in list)
# Bitwise operator
print(0 & 0)
print(0 & 1)
print(0 | 0)
print(0 | 1)
print(1 | 1)
| true |
377f7632417faaed3d23bd456f29ec516b5c024c | MahadiRahman262523/Python_Code_Part-1 | /practice_problem-39.py | 231 | 4.25 | 4 | # Write a python function to print first n lines of
# the following pattern :
# * * *
# * * for n = 3
# *
n = int(input("Enter any number to print pattern : "))
for i in range(n):
print("*" * (n-i))
| false |
d5075d4831f900cb4f12665365babefb4ecd098e | MahadiRahman262523/Python_Code_Part-1 | /practice_problem-18.py | 488 | 4.1875 | 4 | # Write a program to input eight numbers from the user and display
# all the unique numbers
num1 = int(input("Enter number 1 : "))
num2 = int(input("Enter number 2 : "))
num3 = int(input("Enter number 3 : "))
num4 = int(input("Enter number 4 : "))
num5 = int(input("Enter number 5 : "))
num6 = int(input("Enter number 6 : "))
num7 = int(input("Enter number 7 : "))
num8 = int(input("Enter number 8 : "))
s = {num1, num2, num3, num4, num5, num6, num7, num8}
print(s)
| false |
6141032532599c2a7f307170c680abff29c6e526 | MahadiRahman262523/Python_Code_Part-1 | /practice_problem-25.py | 340 | 4.34375 | 4 | # Write a program to find whether a given username contaoins less than 10
# characters or not
name = input("Enter your name : ")
length = len(name)
print("Your Name Length is : ",length)
if(length < 10):
print("Your Name Contains Less Than 10 Characters")
else:
print("Your Name Contains greater Than 10 Characters") | true |
e948c889e9443b2d4ded69459a273ad43f72b0c0 | xuelang201201/FluentPython | /03_字典和集合/fp_10_集合论.py | 1,047 | 4.1875 | 4 | # 集合的本质是许多唯一对象的聚集。因此,集合可以用于去重。
my_list = ['spam', 'spam', 'eggs', 'spam']
print(set(my_list))
print(list(set(my_list)))
"""
例如,我们有一个电子邮件地址的集合(haystack),还要维护一个较小
的电子邮件地址集合(needles),然后求出 needles 中有多少地址同时
也出现在了 haystack 里。借助集合操作,我们只需要一行代码就可以了。
"""
# needles 的元素在 haystack 里出现的次数,两个变量都是 set 类型
# found = len(needles & haystack)
# 如果不使用交集操作的话,代码可能就变成了:
# needles 的元素在 haystack 里出现的次数(作用和上面相同)
# found = 0
# for n in needles:
# if n in haystack:
# found += 1
# needles 的元素在 haystack 里出现的次数,这次的代码可以用在任何可迭代对象上
# found = len(set(needles) & set(haystack))
# 另一种写法:
# found = len(set(needles).intersection(haystack))
| false |
b282ba54703d292c9d9a30aebdcf88913905b2a5 | xuelang201201/FluentPython | /02_数据结构/fp_13_一个包含3个列表的列表,嵌套的3个列表各自有3个元素来代表井字游戏的一行方块.py | 589 | 4.125 | 4 | # 建立一个包含3个列表的列表,被包含的3个列表各自有3个元素。打印出这个嵌套列表。
board = [['_'] * 3 for i in range(3)]
print(board)
# 把第1行第2列的元素标记为 X,再打印出这个列表。
board[1][2] = 'X'
print(board)
# 等同于
board = []
for i in range(3):
# 每次迭代中都新建了一个列表,作为新的一行(row)追加到游戏板(board)。
row = ['_'] * 3
board.append(row)
print(board)
board[2][0] = 'X'
# 正如我们所期待的,只有第2行的元素被修改。
print(board)
| false |
9ef906ae918956dbdb2f48ea660293284b719a94 | asselapathirana/pythonbootcamp | /2023/day3/es_1.py | 2,425 | 4.34375 | 4 | import numpy as np
"""Fitness function to be minimized.
Example: minimize the sum of squares of the variables.
x - a numpy array of values for the variables
returns a single floating point value representing the fitness of the solution"""
def fitness_function(x):
return np.sum(x**2) # Example: minimize the sum of squares
"""Evolves a population of candidate solutions using the evolutionary strategy algorithm.
fitness_function - the fitness function to be minimized
num_variables - the number of variables in each candidate solution
population_size - the number of candidate solutions in the population
num_generations - the number of generations to evolve the population
returns the best solution evolved"""
def evolutionary_strategy(fitness_function, num_variables, population_size, num_generations):
# Initialize the population randomly
population = np.random.uniform(low=-5.0, high=5.0, size=(population_size, num_variables))
for generation in range(num_generations):
# Evaluate the fitness of each individual in the population
fitness = np.array([fitness_function(individual) for individual in population])
# Select the best individuals for the next generation
elite_indices = np.argsort(fitness)[:int(population_size/2)]
elite_population = population[elite_indices]
# Create the next generation
next_generation = []
for x in range(population_size):
parent_indices = np.random.choice(range(len(elite_population)), size=2)
parents = elite_population[parent_indices]
child = np.mean(parents, axis=0) + np.random.normal(scale=0.1, size=num_variables)
next_generation.append(child)
population = np.array(next_generation)
print(np.argmin(fitness), np.min(fitness)) # Print the best individual from each generation
# Find the best individual in the final population
fitness = np.array([fitness_function(individual) for individual in population])
best_index = np.argmin(fitness)
best_individual = population[best_index]
return best_individual
# Example usage
num_variables = 5
population_size = 100
num_generations = 500
best_solution = evolutionary_strategy(fitness_function, num_variables, population_size, num_generations)
print("Best solution:", best_solution)
print("Fitness:", fitness_function(best_solution))
| true |
6c375d41e8430694404a45b04819ef9e725db959 | asselapathirana/pythonbootcamp | /archives/2022/day1/quad.py | 781 | 4.15625 | 4 | # first ask the user to enter three numbers a,b,c
# user input is taken as string(text) in python
# so we need to convert them to decimal number using float
a = float(input('Insert a value for variable a'))
b = float(input('Insert a value for variable b'))
c = float(input('Insert a value for variable c'))
# now print the values, just to check
print(a, b, c)
# calculate b^2-4ac as d
d = b**2 - 4 * a * c
if d > 0 : # if d is positive
x1 = (-b + d**0.5)/ (2*a)
x2 = (-b - d**0.5)/ (2*a)
print('You have two real and distincts root')
print(x1, x2)
elif d == 0 : # if d is zero
x1 = (-b / (2*a))
print('You have one real root')
print(x1)
else : # d is niether positive or zeoro, that means negative.
print('No real root can be defined') | true |
cddcfc2c1a2d3177bcf784c7a09fd3fb1f2a69ec | Harini-Pavithra/GFG-11-Week-DSA-Workshop | /Week 1/Problem/Mathematics/Exactly 3 Divisors.py | 1,438 | 4.25 | 4 | Exactly 3 Divisors
Given a positive integer value N. The task is to find how many numbers less than or equal to N have numbers of divisors exactly equal to 3.
Example 1:
Input:
N = 6
Output: 1
Explanation: The only number with
3 divisor is 4.
Example 2:
Input:
N = 10
Output: 2
Explanation: 4 and 9 have 3 divisors.
Your Task:
You don't need to read input or print anything. Your task is to complete the function exactly3Divisors() that takes N as input parameter and returns count of numbers less than or equal to N with exactly 3 divisors.
Expected Time Complexity : O(N1/2 * N1/4)
Expected Auxilliary Space : O(1)
Constraints :
1 <= N <= 109
Solution:
#{
#Driver Code Starts
#Initial Template for Python 3
import math
# } Driver Code Ends
#User function Template for python3
def exactly3Divisors(N):
# code here
def isPrime(i):
i=2
while i<=math.sqrt(N):
if N%i==0:
return False
i +=1
return True
count =0
i=2
while i<N and (i*i)<=N:
if isPrime(i):
count +=1
return count
#{
#Driver Code Starts.
def main():
T=int(input())
while(T>0):
N=int(input())
print(exactly3Divisors(N))
T-=1
if __name__=="__main__":
main()
#} Driver Code Ends | true |
519a1790c47049f2f6a47a6362d45a6821c3252b | Harini-Pavithra/GFG-11-Week-DSA-Workshop | /Week 3/Strings/Problems/Convert to Roman No.py | 1,354 | 4.3125 | 4 | Convert to Roman No
Given an integer n, your task is to complete the function convertToRoman which prints the corresponding roman number of n. Various symbols and their values are given below.
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
Example 1:
Input:
n = 5
Output: V
Example 2:
Input:
n = 3
Output: III
Your Task:
Complete the function convertToRoman() which takes an integer N as input parameter and returns the equivalent roman.
Expected Time Complexity: O(log10N)
Expected Auxiliary Space: O(log10N * 10)
Constraints:
1<=n<=3999
Solution
#Your task is to complete this function
#Your function should return a String
def convertRoman(n):
#Code here
strrom=[["","I","II","III","IV","V","VI","VII","VIII","IX"],
["","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"],
["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"],
["","M","MM","MMM","","","","","",""]]
i = 0
str=""
while(n != 0):
str = strrom[i][n%10] + str
n=n//10
i+=1
return str
#{
# Driver Code Starts
#Your Code goes here
if __name__=='__main__':
t = int(input())
for i in range(t):
n = int(input())
print(convertRoman(n))
# Contributed by: Harshit Sidhwa
# } Driver Code Ends | true |
dab1464351b112f48570a5bf6f23c42912163925 | Harini-Pavithra/GFG-11-Week-DSA-Workshop | /Week 9/Heap/Problems/Nearly sorted.py | 2,018 | 4.1875 | 4 | Nearly sorted
Given an array of n elements, where each element is at most k away from its target position, you need to sort the array optimally.
Example 1:
Input:
n = 7, k = 3
arr[] = {6,5,3,2,8,10,9}
Output: 2 3 5 6 8 9 10
Explanation: The sorted array will be
2 3 5 6 8 9 10
Example 2:
Input:
n = 5, k = 2
arr[] = {4,3,1,2,5}
Output: 1 2 3 4 5
Note: DO NOT use STL sort() function for this question.
Your Task:
You are required to complete the method nearlySorted() which takes 3 arguments and returns the sorted array.
Expected Time Complexity : O(nlogk)
Expected Auxilliary Space : O(n)
Constraints:
1 <= n <= 106
1 <= k <= n
1 <= arri <= 107
Solution
#User function Template for python3
def nearlySorted(a,n,k):
'''
:param a: given array
:param n: size of a
:param k: max absolute distance of value from its sorted position
:return: sorted list
'''
min_heap = [] # our min heap to be used
ans = [] # our resultant sorted array
for num in a:
if len(min_heap)<2*k : # if number of elements in heap is less than 2*k
# we take 2*k as ,distance can be on either side
# insert this element
heapq.heappush(min_heap,num)
else:
# insert the root of the heap to ans, as it must be its position
ans.append(heapq.heappop(min_heap))
# now insert the current value in the heap
heapq.heappush(min_heap,num)
# if heap is non - empty, put all the elements taking from root of heap one by one in ans
while(len(min_heap)):
ans.append(heapq.heappop(min_heap))
return ans
#{
# Driver Code Starts
#Initial Template for Python 3
import atexit
import io
import sys
import heapq
from collections import defaultdict
# Contributed by : Nagendra Jha
if __name__ == '__main__':
test_cases = int(input())
for cases in range(test_cases) :
n,k = map(int,input().strip().split()) | true |
741480f8b2500ef939b9951b4567f5b16172379a | Harini-Pavithra/GFG-11-Week-DSA-Workshop | /Week 1/Problem/Arrays/Find Transition Point.py | 1,237 | 4.1875 | 4 | Find Transition Point
Given a sorted array containing only 0s and 1s, find the transition point.
Example 1:
Input:
N = 5
arr[] = {0,0,0,1,1}
Output: 3
Explanation: index 3 is the transition
point where 1 begins.
Example 2:
Input:
N = 4
arr[] = {0,0,0,0}
Output: -1
Explanation: Since, there is no "1",
the answer is -1.
Your Task:
You don't need to read input or print anything. The task is to complete the function transitionPoint() that takes array and N as input parameters and returns the 0 based index of the position where "0" ends and "1" begins. If array does not have any 1s, return -1. If array does not have any 0s, return 0.
Expected Time Complexity: O(LogN)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 500000
0 ≤ arr[i] ≤ 1
Solution:
def transitionPoint(arr, n):
#Code here
for i in range(0,len(arr)):
if arr[i]==1:
return i
return -1
#{
# Driver Code Starts
#driver code
if __name__=='__main__':
t=int(input())
for i in range(t):
n = int(input())
arr = list(map(int, input().strip().split()))
print(transitionPoint(arr, n))
# } Driver Code Ends | true |
0e9e0bab41e6810a4b6c41d69ae01df699977570 | Harini-Pavithra/GFG-11-Week-DSA-Workshop | /Week 3/Matrix/Transpose of Matrix.py | 1,798 | 4.59375 | 5 | Transpose of Matrix
Write a program to find the transpose of a square matrix of size N*N. Transpose of a matrix is obtained by changing rows to columns and columns to rows.
Example 1:
Input:
N = 4
mat[][] = {{1, 1, 1, 1},
{2, 2, 2, 2}
{3, 3, 3, 3}
{4, 4, 4, 4}}
Output:
{{1, 2, 3, 4},
{1, 2, 3, 4}
{1, 2, 3, 4}
{1, 2, 3, 4}}
Example 2:
Input:
N = 2
mat[][] = {{1, 2},
{-9, -2}}
Output:
{{1, -9},
{2, -2}}
Your Task:
You dont need to read input or print anything. Complete the function transpose() which takes matrix[][] and N as input parameter and finds the transpose of the input matrix. You need to do this in-place. That is you need to update the original matrix with the transpose.
Expected Time Complexity: O(N * N)
Expected Auxiliary Space: O(1)
Constraints:
1 <= N <= 100
-103 <= mat[i][j] <= 103
Solution
#User function Template for python3
def transpose(matrix, n):
# code here
tmp = 0
for i in range(n):
for j in range(i+1,n):
tmp = matrix[i][j]
matrix[i][j] = matrix[j][i]
matrix[j][i] = tmp
#{
# Driver Code Starts
#Initial Template for Python 3
if __name__ == '__main__':
t = int (input ())
for _ in range (t):
n = int(input())
matrix = [[0 for j in range(n)] for i in range(n)]
line1 = [int(x) for x in input().strip().split()]
k=0
for i in range(n):
for j in range (n):
matrix[i][j]=line1[k]
k+=1
transpose(matrix,n)
for i in range(n):
for j in range(n):
print(matrix[i][j],end=" ")
print()
# } Driver Code Ends | true |
48c9c87ca2976207c5f379fd9b42df86faa877b5 | Harini-Pavithra/GFG-11-Week-DSA-Workshop | /Week 4/Linked LIst/Reverse a Linked List in groups of given size.py | 2,725 | 4.25 | 4 | Reverse a Linked List in groups of given size.
Given a linked list of size N. The task is to reverse every k nodes (where k is an input to the function) in the linked list.
Example 1:
Input:
LinkedList: 1->2->2->4->5->6->7->8
K = 4
Output: 4 2 2 1 8 7 6 5
Explanation:
The first 4 elements 1,2,2,4 are reversed first
and then the next 4 elements 5,6,7,8. Hence, the
resultant linked list is 4->2->2->1->8->7->6->5.
Example 2:
Input:
LinkedList: 1->2->3->4->5
K = 3
Output: 3 2 1 5 4
Explanation:
The first 3 elements are 1,2,3 are reversed
first and then elements 4,5 are reversed.Hence,
the resultant linked list is 3->2->1->5->4.
Your Task:
You don't need to read input or print anything. Your task is to complete the function reverse() which should reverse the linked list in group of size k and return the head of the modified linked list.
Expected Time Complexity : O(N)
Expected Auxilliary Space : O(1)
Constraints:
1 <= N <= 103
1 <= k <= N
Solution
"""Return reference of new head of the reverse linked list
The input list will have at least one element
Node is defined as
class Node:
def __init__(self, data):
self.data = data
self.next = None
This is method only submission.
You only need to complete the method.
"""
def reverse(head, k):
# Code here
current = head
prev = None
nextnode = None
count = 0
while(current!=None and count<k):
# print(current.data)
nextnode = current.next
current.next = prev
prev = current
count = count + 1
current = nextnode
if nextnode!=None:
head.next = reverse(nextnode,k)
return prev
#{
# Driver Code Starts
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
# self.tail
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def printList(self):
temp = self.head
while (temp):
print(temp.data, end=" ")
# arr.append(str(temp.data))
temp = temp.next
print()
if __name__ == '__main__':
t = int(input())
while (t > 0):
llist = LinkedList()
n = input()
values = list(map(int, input().split()))
for i in reversed(values):
llist.push(i)
k = int(input())
new_head = LinkedList()
new_head = reverse(llist.head, k)
llist.head = new_head
llist.printList()
t -= 1
# } Driver Code Ends | true |
b1acad41a07b4a5a1b38fdad15619ebeec5dd70d | Harini-Pavithra/GFG-11-Week-DSA-Workshop | /Week 3/Bit Magic/Rightmost different bit.py | 1,708 | 4.15625 | 4 | Rightmost different bit
Given two numbers M and N. The task is to find the position of the rightmost different bit in the binary representation of numbers.
Example 1:
Input: M = 11, N = 9
Output: 2
Explanation: Binary representation of the given
numbers are: 1011 and 1001,
2nd bit from right is different.
Example 2:
Input: M = 52, N = 4
Output: 5
Explanation: Binary representation of the given
numbers are: 110100‬ and 0100,
5th-bit from right is different.
User Task:
The task is to complete the function posOfRightMostDiffBit() which takes two arguments m and n and returns the position of first different bits in m and n. If both m and n are the same then return -1 in this case.
Expected Time Complexity: O(max(log m, log n)).
Expected Auxiliary Space: O(1).
Constraints:
1 <= M <= 103
1 <= N <= 103
Solution
#{
#Driver Code Starts
#Initial Template for Python 3
import math
# } Driver Code Ends
#User function Template for python3
##Complete this function
def posOfRightMostDiffBit(m,n):
#Your code here
if m > n:
m, n = n, m
i=1
while (n > 0):
if (m % 2) == (n % 2):
pass
else:
return i
m = m // 2
n = n // 2
i=i+1
#{
#Driver Code Starts.
def main():
T=int(input())
while(T>0):
mn=[int(x) for x in input().strip().split()]
m=mn[0]
n=mn[1]
print(math.floor(posOfRightMostDiffBit(m,n)))
T-=1
if __name__=="__main__":
main()
#} Driver Code Ends | true |
27f267d66c25e89ed823ddd1f003b33fe09cc3cc | Harini-Pavithra/GFG-11-Week-DSA-Workshop | /Week 1/Problem/Arrays/Remove duplicate elements from sorted Array.py | 1,554 | 4.1875 | 4 | Remove duplicate elements from sorted Array
Given a sorted array A of size N, delete all the duplicates elements from A.
Example 1:
Input:
N = 5
Array = {2, 2, 2, 2, 2}
Output: 2
Explanation: After removing all the duplicates
only one instance of 2 will remain.
Example 2:
Input:
N = 3
Array = {1, 2, 2}
Output: 1 2
Your Task:
You dont need to read input or print anything. Complete the function remove_duplicate() which takes the array A[] and its size N as input parameters and modifies it in place to delete all the duplicates. The function must return an integer X denoting the new modified size of the array.
Note: The generated output will print all the elements of the modified array from index 0 to X-1.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 <= N <= 104
1 <= A[i] <= 106
Solution:
#User function template for Python
class Solution:
def remove_duplicate(self, A, N):
# code here
j=0
if N==0 or N==1:
return N
for i in range(0,N-1):
if A[i] != A[i+1]:
A[j]=A[i]
j +=1
A[j]=A[N-1]
j +=1
return j
#{
# Driver Code Starts
#Initial template for Python
if __name__=='__main__':
t = int(input())
for i in range(t):
N = int(input())
A = list(map(int, input().strip().split()))
ob = Solution()
n = ob.remove_duplicate(A,N)
for i in range(n):
print(A[i], end=" ")
print()
# } Driver Code Ends | true |
4a44a1c4851060d4114ea4ae3d509800781378e0 | Harini-Pavithra/GFG-11-Week-DSA-Workshop | /Week 3/Strings/Problems/Longest Substring Without Repeating Characters.py | 2,507 | 4.125 | 4 | Longest Substring Without Repeating Characters
Given a string S, find the length of its longest substring that does not have any repeating characters.
Example 1:
Input:
S = geeksforgeeks
Output: 7
Explanation: The longest substring
without repeated characters is "ksforge".
Example 2:
Input:
S = abbcdb
Output: 3
Explanation: The longest substring is
"bcd". Here "abcd" is not a substring
of the given string.
Your Task:
Complete SubsequenceLength function that takes string s as input and returns the length of the longest substring that does not have any repeating characters.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
0<= N <= 10^5
here, N = S.length
Solution
#User function Template for python3
def SubsequenceLength(s):
if (len(s) == 0 ):
return 0
count = 1 # length of current substring
answer = 1 # result
''' Define the visited array to represent all
256 ASCII characters and maintain their last
seen position in the processed substring.
Initialize the array as -1 to indicate that
no character has been visited yet. '''
visited = [-1]*256
''' Mark first character as visited by storing the index
of first character in visited array. '''
visited[ord(s[0])]=0;
'''Start from the second character. ie- index 1 as
the first character is already processed. '''
for end in range(1,len(s)):
idx = ord(s[end])
''' If the current character is not present in the
already processed string or it is not part of the
current non-repeating-character-string (NRCS),
increase count by 1 '''
if(visited[idx] == -1 or end-count > visited[idx]):
count+=1
# If current character is already present in NRCS
else:
''' check whether length of the previous
NRCS was greater than answer or not '''
answer = max(count, answer)
''' update NRCS to start from the next
character of the previous instance. '''
count = end - visited[idx]
# update the index of current character in visited array
visited[idx]=end
return max(count,answer)
#{
# Driver Code Starts
#Initial Template for Python 3
for _ in range(0,int(input())):
s = input()
print(SubsequenceLength(s))
# } Driver Code Ends | true |
d3d0dabc882f6021df69bebe4a00e4b97c6878bf | Harini-Pavithra/GFG-11-Week-DSA-Workshop | /Week 9/Heap/Problems/Heap Sort.py | 2,223 | 4.3125 | 4 | Heap Sort
Given an array of size N. The task is to sort the array elements by completing functions heapify() and buildHeap() which are used to implement Heap Sort.
Example 1:
Input:
N = 5
arr[] = {4,1,3,9,7}
Output:
1 3 4 7 9
Explanation:
After sorting elements
using heap sort, elements will be
in order as 1,3,4,7,9.
Example 2:
Input:
N = 10
arr[] = {10,9,8,7,6,5,4,3,2,1}
Output:
1 2 3 4 5 6 7 8 9 10
Explanation:
After sorting elements
using heap sort, elements will be
in order as 1, 2,3,4,5,6,7,8,9,10.
Your Task :
Complete the functions heapify() and buildheap().
Expected Time Complexity: O(N * Log(N)).
Expected Auxiliary Space: O(1).
Constraints:
1 <= N <= 106
1 <= arr[i] <= 106
Solution
#User function Template for python3
def heapify(arr, n, i):
largest = i # Initialize largest as root
l = 2 * i + 1 # left = 2*i + 1
r = 2 * i + 2 # right = 2*i + 2
# See if left child of root exists and is
# greater than root
if l < n and arr[i] < arr[l]:
largest = l
# See if right child of root exists and is
# greater than root
if r < n and arr[largest] < arr[r]:
largest = r
# Change root, if needed
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i] # swap
# Heapify the root.
heapify(arr, n, largest)
# The main function to sort an array of given size
def buildHeap(arr,n):
# Build a maxheap.
for i in range(n, -1, -1):
heapify(arr, n, i)
# One by one extract elements
for i in range(n - 1, 0, -1):
arr[i], arr[0] = arr[0], arr[i] # swap
heapify(arr, i, 0)
#{
# Driver Code Starts
#Initial Template for Python 3
import atexit
import io
import sys
# Contributed by : Mohit Kumara
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER
@atexit.register
def write():
sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
if __name__ == '__main__':
test_cases = int(input())
for cases in range(test_cases):
n = int(input())
arr = list(map(int, input().strip().split()))
buildHeap(arr,n)
print(*arr)
# } Driver Code Ends
| true |
0bb5128f7e3bbd1ee480e189c182cb7933143ae1 | Harini-Pavithra/GFG-11-Week-DSA-Workshop | /Week 3/Strings/Problems/Isomorphic Strings.py | 2,802 | 4.4375 | 4 | Isomorphic Strings
Given two strings 'str1' and 'str2', check if these two strings are isomorphic to each other.
Two strings str1 and str2 are called isomorphic if there is a one to one mapping possible for every character of str1 to every character of str2 while preserving the order.
Note: All occurrences of every character in ‘str1’ should map to the same character in ‘str2’
Example 1:
Input:
str1 = aab
str2 = xxy
Output: 1
Explanation: There are two different
charactersin aab and xxy, i.e a and b
with frequency 2and 1 respectively.
Example 2:
Input:
str1 = aab
str2 = xyz
Output:
Explanation: There are two different
charactersin aab but there are three
different charactersin xyz. So there
won't be one to one mapping between
str1 and str2.
Your Task:
You don't need to read input or print anything.Your task is to complete the function areIsomorphic() which takes the string str1 and string str2 as input parameter and check if two strings are isomorphic. The function returns true if strings are isomorphic else it returns false.
Expected Time Complexity: O(|str1|+|str2|).
Expected Auxiliary Space: O(Number of different characters).
Note: |s| represents the length of string s.
Constraints:
1 <= |str1|, |str2| <= 103
Solution
#User function Template for python3
'''
Your task is to check if the given strings are
isomorphic or not.
Function Arguments: str1 and str2 (given strings)
Return Type: boolean
'''
def areIsomorphic2(str1,str2):
dict1 = {}
len1 = len(str1)
len2 = len(str2)
# print(dict1,len1,len1)
if len1 == len2:
for i in range(len1):
if str1[i] in dict1.keys():
if dict1[str1[i]] == str2[i]:
pass
else:
return False
else:
dict1[str1[i]] = str2[i]
else:
return False
return True
def areIsomorphic(s,p):
first = areIsomorphic2(s, p)
second = areIsomorphic2(p, s)
# print(first, second)
if (first == True and second == True):
return True
else:
return False
#{
# Driver Code Starts
#Initial Template for Python 3
import atexit
import io
import sys
from collections import defaultdict
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER
@atexit.register
def write():
sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
if __name__=='__main__':
t = int(input())
for i in range(t):
s=str(input())
p=str(input())
if(areIsomorphic(s,p)):
print(1)
else:
print(0)
# } Driver Code Ends | true |
261cfa1feb28124e9113c400707c5dedf9e30249 | Technicoryx/python_strings_inbuilt_functions | /string_08.py | 609 | 4.40625 | 4 | """Below Python Programme demonstrate expandtabs
functions in a string"""
#Case1 : With no Argument
str = 'xyz\t12345\tabc'
# no argument is passed
# default tabsize is 8
result = str.expandtabs()
print(result)
#Case 2:Different Argument
str = "xyz\t12345\tabc"
print('Original String:', str)
# tabsize is set to 2
print('Tabsize 2:', str.expandtabs(2))
# tabsize is set to 3
print('Tabsize 3:', str.expandtabs(3))
# tabsize is set to 4
print('Tabsize 4:', str.expandtabs(4))
# tabsize is set to 5
print('Tabsize 5:', str.expandtabs(5))
# tabsize is set to 6
print('Tabsize 6:', str.expandtabs(6))
| true |
cf11c056ca6697454d3c585e6fa6eea6a153deae | Technicoryx/python_strings_inbuilt_functions | /string_06.py | 204 | 4.125 | 4 | """Below Python Programme demonstrate count
functions in a string"""
string = "Python is awesome, isn't it?"
substring = "is"
count = string.count(substring)
# print count
print("The count is:", count)
| true |
da915e308927c3e5ed8eb0f96937f10fd320c8ab | Technicoryx/python_strings_inbuilt_functions | /string_23.py | 360 | 4.46875 | 4 | """Below Python Programme demonstrate ljust
functions in a string"""
#Example:
# example string
string = 'cat'
width = 5
# print right justified string
print(string.rjust(width))
#Right justify string and fill the remaining spaces
# example string
string = 'cat'
width = 5
fillchar = '*'
# print right justified string
print(string.rjust(width, fillchar))
| true |
68285e9fdf5413e817851744d716596c0ff2c926 | anton515/Stack-ADT-and-Trees | /queueStackADT.py | 2,893 | 4.25 | 4 |
from dataStructures import Queue
import check
# Implementation of the Stack ADT using a single Queue.
class Stack:
'''
Stack ADT
'''
## Stack () produces an empty stack.
## __init__: None -> Stack
def __init__(self):
self.stack = Queue ()
## isEmpty(self) returns True if the Stack is empty, False otherwise
## isEmpty: Stack -> Bool
def isEmpty(self):
return self.stack.isEmpty ()
## len(self) returns the number of items in the stack.
## __len__: Stack -> Int
def __len__(self):
return self.stack.__len__()
## peek(self) returns a reference to the top item of the Stack without
## removing it. Can only be done on when Stack is not empty and does
## not modify the stack contents.
## peek: Stack -> Any
## Requires: Stack cannot be empty
def peek(self):
assert len(self.stack) > 0, "Cannot peek from empty Stack"
delta = len(self.stack) - 1
while delta != 0:
item = self.stack.dequeue()
self.stack.enqueue(item)
delta -= 1
item = self.stack.dequeue()
self.stack.enqueue(item)
return item
## pop(self) removes and returns the top (most recent) item of the Stack,
## if the Stack is not empty. The next (2nd most recent) item on the
## Stack becomes the new top item.
## pop: Stack -> Any
## Requires: Stack cannot be empty
## Effects: The next (2nd most recent) item on the Stack becomes the new
## top item.
def pop(self):
assert len(self.stack) > 0, "Cannot pop from Empty Stack."
delta = len(self.stack) - 1
while delta != 0:
item = self.stack.dequeue()
self.stack.enqueue(item)
delta -= 1
return self.stack.dequeue()
## push(self,item) adds the given item to the top of the Stack
## push: Stack Any -> None
## Effects: adds the given item to the top of the Stack
def push(self, item):
self.stack.enqueue(item)
## print(self) prints the items in the Stack (for testing purposes)
## __str__: Stack -> Str
## Requires: Stack cannot be empty
def __str__(self):
assert not self.isEmpty(), "Cannot print from an empty Stack."
return self.stack.__str__()
## Test
t1 = Stack()
check.expect("Q1T1",t1.isEmpty(),True)
check.expect("Q1T2",len(t1),0)
t1.push(1)
check.expect("Q1T3",t1.isEmpty(),False)
check.expect("Q1T4",t1.peek(),1)
check.expect("Q1T5",len(t1),1)
t1.push(100)
check.expect("Q1T6",t1.isEmpty(),False)
check.expect("Q1T7",t1.peek(),100)
check.expect("Q1T8",len(t1),2)
check.expect("Q1Ta",t1.pop(),100)
check.expect("Q1T9",t1.isEmpty(),False)
check.expect("Q1T10",t1.peek(),1)
check.expect("Q1T11",len(t1),1)
check.expect("Q1Tb",t1.pop(),1)
check.expect("Q1T12",t1.isEmpty(),True)
check.expect("Q1T13",len(t1),0)
| true |
ce6d86586bb5d7030312ade00c8fc3ca7a0d2273 | vamsi-kavuru/AWS-CF1 | /Atari-2.py | 1,182 | 4.28125 | 4 | from __future__ import print_function
print ("welcome to my atari adventure game! the directions to move in are defined as left, right, up, and down. Enjoy.")
x = 6
y = -2
#move = str(input('Make your move! Type in either "Left", "Right", "Up", "Down" or type "Exit" to exit the game:')).lower()
def game():
global x
global y
move = str(input('Make your move! Type in either "Left", "Right", "Up", "Down" or type "Exit" to exit the game:')).lower()
if move == ('left'):
x = x-3
print ('your x position is', x, '.' 'your y position is', y, '.')
game()
elif move == ('up'):
y = y+3
print ('your x position is', x, '.' 'your y position is', y, '.')
game()
elif move == ('right'):
x = x+2
print ('your x position is', x, '.' 'your y position is', y, '.')
game()
elif move == ('down'):
y = y-2
print ('your x position is', x, '.' 'your y position is', y, '.')
game()
elif move == ('exit'):
exit()
else:
print ("Oops!!! You have entered a wrong input, please enter either up, down, left, right or exit only.")
game()
game() | true |
562c78526d055d1ca782cc39096decf79a585bb6 | AmbyMbayi/CODE_py | /Pandas/Pandas_PivotTable/Question1.py | 310 | 4.125 | 4 | """write a pandas program to create a pivot table with multiple indexes from a given excel sheet
"""
import pandas as pd
import numpy as np
df = pd.read_excel('SaleData.xlsx')
print(df)
print("the pivot table is shown as: ")
pivot_result = pd.pivot_table(df, index=["Region", "SalesMan"])
print(pivot_result) | true |
16e1a288f8866c3c82b6bba997753cab5ff085c2 | harshitmanek/savc | /index.py | 1,083 | 4.1875 | 4 |
def main():
print "**************MENU*******************"
print "1]VOLUME OF CUBE"
print "2]SURFACE AREA OF CUBE"
print "3]VOLUME OF CUBOID"
print "4]SURFACE AREA OF CUBOID"
e=int(raw_input("\n\t\tenter your choice:"))
if(e==1):
cube_volume()
elif(e==2):
cube_surface_area()
elif(e==3):
cuboid_volume()
else:
cuboid_surface_area()
def cube_volume():
s=int(raw_input("Enter side: "))
volume=s*s*s*1.0
print volume
def cube_surface_area():
s=int(raw_input("Enter side: "))
surfacearea=6.0*s*s
print surfacearea
def cuboid_surface_area():
length=float(raw_input("enter the length"))
breadth=float(raw_input("enter the breadth"))
height=float(raw_input("enter the height"))
area=2*(length*breadth + breadth*height + length*height)
print area
def cuboid_volume():
length=float(raw_input("enter the length"))
breadth=float(raw_input("enter the breadth"))
height=float(raw_input("enter the height"))
volume=length*breadth*height
print volume
main()
| false |
8b0716fd554604776390c6f6ab40619d19fc5e12 | KWinston/PythonMazeSolver | /main.py | 2,559 | 4.5 | 4 | # CMPT 200 Lab 2 Maze Solver
#
# Author: Winston Kouch
#
#
# Date: September 30, 2014
#
# Description: Asks user for file with maze data. Stores maze in list of lists
# Runs backtracking recursive function to find path to goal.
# Saves the output to file, mazeSol.txt. If no file given, it will
# default to using maze.txt. It then checks if the file exists.
# if it does, it will proceed with solving the maze. If it
# doesn't exist it will print an error message and stop.
#
# Syntax: getMaze() - Asks user for file with maze data
#
#
# import my Maze class
from Maze import *
# To load the maze, this function is used to ask user for maze filename
# After it is entered, it will load the maze or
def getMaze():
# Ask user to input maze file name
filename = input("Please enter the maze file name: ")
# if user enters nothing during input, it will default to maze.txt and try to open it.
if (filename == ""):
filename = "maze.txt"
# try to open the file
try:
inputFile = open(filename, 'r')
except FileNotFoundError:
# If it doesnt exist, prints error message and stops
print ("Error, The file", filename, "does not exist.")
return None
# Read the map data into theMaze
theMaze = inputFile.readlines()
# close the file
inputFile.close()
# Set up the map size, start point, end point
# Grab from first line of map data
mapSize = theMaze[0].split()
# Split the 2 numbers into rows, cols
mapSize[0] = 2*int(mapSize[0])+1
mapSize[1] = 2*int(mapSize[1])+1
# Grab start and end point from line 2 and 3 of file
startPoint = theMaze[1].split()
endPoint = theMaze[2].split()
# Set up a display window for graphics.py
win = GraphWin ("Maze Path", 10 * (mapSize[1]), 10 * (mapSize[0]))
# Generate the board in a list of lists
generatedMaze = Maze(mapSize[0],mapSize[1])
# Map the maze into my list of lists
generatedMaze.mappingMaze(theMaze, mapSize)
# Place the start and end points onto the board
generatedMaze.setPositions(startPoint, endPoint, mapSize)
# Display translated Maze
generatedMaze.display(generatedMaze, 10, win)
# Solve the maze
generatedMaze.solveMaze()
# Display the solution in graphics
generatedMaze.displaysol(generatedMaze, 10, win)
# Run getMaze
getMaze() | true |
7505b339bb908d006e9d2b7ee8eb8dbc43140bdc | baidongbin/python | /疯狂Python讲义/codes/05/5.2/default_param_test2.py | 448 | 4.25 | 4 | # 定义一个打印三角形的函数,有默认值的参数必须放在后面
def printTriangle(char, height=5):
for i in range(1, height + 1):
# 先打印一排空格
for j in range(height - 1):
print(' ', end='')
# 再打印一排特殊字符
for j in range(2 * i - 1):
print(char, end='')
print()
printTriangle('@', 6)
printTriangle('#', height=7)
printTriangle(char='*')
| false |
b37a727c6653dafcfa480283e68badbd87c408f2 | skynette/Solved-Problems | /Collatz.py | 1,737 | 4.3125 | 4 | question = """The Collatz Sequence
Write a function named collatz() that has one parameter named number. If
number is even, then collatz() should print number // 2 and return this value.
If number is odd, then collatz() should print and return 3 * number + 1. Then write a program that
lets the user type in an integer and that keeps calling collatz() on
that number until the function returns the value 1.
(Amazingly enough, this sequence actually works for any integer—sooner
or later, using this sequence, you’ll arrive at 1! Even mathematicians aren’t
sure why. Your program is exploring what’s called the Collatz sequence, sometimes called “the simplest impossible math problem.”)
Remember to convert the return value from input() to an integer with the int() function; otherwise, it will be a string value.
Hint: An integer number is even if number % 2 == 0, and it’s odd if
number % 2 == 1."""
output = """The output of this program could look something like this:
Enter number:
3
10
5
16
8
4
2
1
"""
def collatz(number):
if number%2 == 0:
result = number//2
else:
result = 3*number+1
return result
number = int(input("Enter a starting number: "))
print(number)
while collatz(number) != 1:
print(collatz(number))
number = collatz(number)
print(1)
times = int(input())
nums = []
len_of_nums = []
for i in range(times):
nl = []
n = int(input())
n = n-1
nums.append(n)
count = 0
while count < len(str(n)):
while n!=1:
n = collatz(n)
nl.append(n)
count+=1
len_of_nums.append(len(nl))
d = list(zip(len_of_nums, nums))
m = (max(d))
print(m[-1])
| true |
0081eac284bb86e948aeef7e933796385df12000 | ddbs/Accelerating_Dual_Momentum | /functions.py | 374 | 4.15625 | 4 | from datetime import datetime, date
def start_of_year(my_date):
"""
Gives the starting date of a year given any date
:param my_date: date, str
:return: str
"""
my_date = datetime.strptime(my_date, '%Y-%m-%d')
starting_date = date(my_date.year, my_date.month, 1)
starting_date = starting_date.strftime('%Y-%m-%d')
return starting_date
| true |
d545e90149dfca91045aed7666b8456644c8f9a8 | jyotisahu08/PythonPrograms | /StringRev.py | 530 | 4.3125 | 4 | from builtins import print
str = 'High Time'
# Printing length of given string
a = len(str)
print('Length of the given string is :',a)
# Printing reverse of the given string
str1 = ""
for i in str:
str1 = i + str1
print("Reverse of given string is :",str1)
# Checking a given string is palindrome or not
str2 = 'abba'
str3 = ''
for i in str2:
str3 = i + str3
assert str2==str3,"given string is not a palindrome"
print("given string is a palindrome")
# Displaying the string multiple times
for i in range(0,3):
print(str)
| true |
d5e49df7f61a6e15cf1357aa09e33a81e186627b | Botany-Downs-Secondary-College/password_manager-bunda | /eason_loginV1.py | 2,002 | 4.4375 | 4 | #password_manager
#store and display password for others
#E.Xuan, February 22
name = ""
age = ""
login_user = ["bdsc"]
login_password = ["pass1234"]
password_list = []
def menu(name, age):
if age < 13:
print("Sorry, you do not meet the age requirement for this app")
exit()
else:
print("Welcome", name)
mode = input("Choose a mode by entering the number: \n"
"1: Add passwords 2: Veiw passwords 3: Exit \n"
"").strip()
return mode
def login():
while True:
username = input("Please enter your username: ")
password = input("Please enter your password: ")
if username in login_user and password in login_password:
print("Welcome back,", username)
else:
print("do it again")
print("Welocome to the password manager")
while True:
user_login = input("Please enter, L to login or, N to sign up: ").strip().title()
if user_login == "L":
login()
break
elif user_login == "N":
print("make account")
break
else:
print("enter either L or N")
print("If you are over the age of 12, you are able to store your passwords on this app")
name = input("What is your name?: ")
while True:
try:
age = float(input("How old are you?: "))
option = menu(name, age)
if option == "1":
new_password = input("please enter a password: ")
password_list.append(new_password)
elif option == "2":
print("Here are your passwords")
for password in password_list:
print(password)
elif option == "3":
print("Goodbye")
break
else:
print("That is not a valid number please enter a valid value")
except ValueError:
print("Please enther numbers")
print("Thank you for using the password manager") | true |
baa45a884596594e89c2ca311973bf378c756e77 | SinCatGit/leetcode | /00122/best_time_to_buy_and_sell_stock_ii.py | 1,574 | 4.125 | 4 | from typing import List
class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions
as you like (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock
before you buy again).
Parameters
----------
prices: List[int]
Returns
-------
int
Examples
--------
>>> solution = Solution()
>>> solution.maxProfit([7, 1, 5, 3, 6, 4])
7
>>> solution.maxProfit([1, 2, 3, 4, 5])
4
>>> solution.maxProfit([7, 6, 4, 3, 1])
0
Notes
-----
References
---------
"""
return sum([max(0, prices[i]-prices[i-1]) for i in range(1, len(prices))])
def maxProfitV01(self, prices: List[int]) -> int:
i, profit, prices_len = 0, 0, len(prices)
while i < prices_len:
while i < prices_len - 1 and prices[i] > prices[i+1]:
i += 1
min_val = prices[i]
i += 1
while i < prices_len - 1 and prices[i] <= prices[i+1]:
i += 1
if i < prices_len:
profit += prices[i] - min_val
return profit
| true |
c5eadaf692c43bc0ad5acf88104403ca6b7266dc | HarryVines/Assignment | /Garden cost.py | 323 | 4.21875 | 4 | length = float(input("Please enter the length of the garden in metres: "))
width = float(input("Please enter the width of the garden in metres: "))
area = (length-1)*(width-1)
cost = area*10
print("The area of your garden is: {0}".format(area))
print("The cost to lay grass on your garden is : £{0}".format(cost))
| true |
c9dadcd37ac16013e6a9c23aa3afe411bacd400e | jhuang09/GWC-2018 | /Data Science/attack.py | 2,488 | 4.34375 | 4 | # This project checks to see if your password is a strong one
# It works with longer passwords, but not really short ones.
# That's because since each letter is considered a word in the dictionary.txt file,
# any password that contains just letters will be considered as a word/not a strong password.
# To alleviate this, I've split it so that it will break the string into substrings of length 3,
# because there are a lot of combinations of two letter words in the dictionary.txt as well.
# doesn't work for "I", "am", etc. etc.
# longer words should work
def is_secure(password, word_list):
# make a list of letters of word
if (password in word_list):
print(password)
return False
# char_list = list(password)
if (len(password) < 3):
if (not password in word_list):
return True
# iterate through letters in password
# start with one letter and then keep incresing letters
# to check if the substring of password is an actual word
for i in range(3, len(password)):
sub_pw = password[0:i]
if(sub_pw in word_list):
print("i=", i, "sub=", sub_pw)
secure = is_secure(password[i:], word_list)
# print(secure)
if (not secure):
return False
if(i == len(password) - 1):
return True
# goes through each word in the dictionary and checks if it appears in the password
# doesn't work too well because each letter counts as a word in the dictionary.txt
# for word in word_list:
# if (word in password):
# index = password.find(word) #first index of word appearing
# left_pw = password[0:index]
# right_pw = password[index + len(word):]
# security = [is_secure(left_pw, word_list), is_secure(right_pw, word_list)]
# # only if both left and right sides are actual words, then return false
# if (security[0] == False and security[1] == False):
# return False
return True
# open and read in words from text file
file = open("dictionary.txt", "r")
text = file.read()
file.close()
# will automatically create a list of all the words
split = text.split()
# print(type(split))
# prompt user for input
password = input("What's your password?\n").lower()
secure = is_secure(password, split)
# keep prompting user if the password is a word
while (len(password) < 3 or not secure): #any(word in password for word in split)
password = input("Password is a word! Enter a new one.\n").lower()
secure = is_secure(password, split)
print("Congratulations! Your password is very secure!") | true |
32c4a398d4cc157611fb6827fce531ecbb82f431 | GeraldShin/PythonSandbox | /OnlineCode.py | 1,851 | 4.28125 | 4 | #This will be snippets of useful code you find online that you can copy+paste when needed.
#Emoji Package
#I don't know when this will ever be helpful, but there is an Emoji package in Python.
$ pip install emoji
from emoji import emojize
print(emojize(":thumbs_up:")) #thumbs up emoji, check notes for more.
#List comprehensions
#You could probably get better at these... here is an easy example for reference
numbers = [1,2,3,4,5,6,7]
evens = [x for x in numbers if x % 2 is 0]
odds = [y for y in numbers if y not in evens]
cities = ['London', 'Dublin', 'Oslo']
def visit(city):
print("Welcome to "+city)
for city in cities:
visit(city)
def split_lines(s): #split a string into pieces using a separator
return s.split('\n')
split_lines('50\n python\n snippets')
language = "python" #reverse the order of the letters in a word
reversed_language = language[::-1]
print(reversed_language)
def union(a,b): #find elements that exist in both lists
return list(set(a + b))
union([1, 2, 3, 4, 5], [6, 2, 8, 1, 4])
def unique(list): #finds if all elements in a list are unique
if len(list)==len(set(list)):
print("All elements are unique")
else:
print("List has duplicates")
unique([1,2,3,4,5]) # All elements are unique
from collections import Counter #counts freq of appearance of elements
list = [1, 2, 3, 2, 4, 3, 2, 3]
count = Counter(list)
print(count) # {2: 3, 3: 3, 1: 1, 4: 1}
def most_frequent(list): #piggy-backing, finds most freq appearance of elements
return max(set(list), key = list.count)
numbers = [1, 2, 3, 2, 4, 3, 1, 3]
most_frequent(numbers) # 3
def multiply(n): #mapping applies the function in the parens to the data element in the parens
return n * n
list = (1, 2, 3)
result = map(multiply, list)
print(list(result)) # {1, 4, 9}
| true |
9e304793cd98bac00cc967be51c1c3da49dd8639 | Isaac-D-Dawson/Homework-Uploads | /PyCheckIO/ReverseEveryAscending.py | 2,396 | 4.46875 | 4 | # Create and return a new iterable that contains the same elements as the argument iterable items, but with the reversed order of the elements inside every maximal strictly ascending sublist. This function should not modify the contents of the original iterable.
# Input: Iterable
# Output: Iterable
# Precondition: Iterable contains only ints
# The mission was taken from Python CCPS 109 Fall 2018. It’s being taught for Ryerson Chang School of Continuing Education by Ilkka Kokkarinen
def reverse_ascending(items):
#stage one: sanity checker:
if len(items) <= 2: #if there are two items in the list
return(items) #don't make changes, it shouldn't matter.
else: #otherwise, run the program normally.
#allocate variables now that we know we need them.
outval = [] #outpt variable
midval = [[]] #the variable we perform all out operations in.
h = 0 #What was the last number we looked at?
for i in items:
if i > h: #if I is more than the last thing we looked at,
midval[-1].append(i) #it goes in the existing sublist
else: #otherwise
midval.append([i]) #it goes in a new sublist
h = i #Here's the last thing we checked
#print(midval) #Debug call
#print(midval) #Debug call
for i in midval:
for j in reversed(i): #For each item in a reversed sublist
outval.append(j) #Add it to the output
#print(outval) #Debug call
return(outval)
# if __name__ == '__main__':
# print("Example:")
# print(reverse_ascending([1, 2, 3, 4, 5]))
# # These "asserts" are used for self-checking and not for an auto-testing
# assert list(reverse_ascending([1, 2, 3, 4, 5])) == [5, 4, 3, 2, 1]
# assert list(reverse_ascending([5, 7, 10, 4, 2, 7, 8, 1, 3])) == [10, 7, 5, 4, 8, 7, 2, 3, 1]
# assert list(reverse_ascending([5, 4, 3, 2, 1])) == [5, 4, 3, 2, 1]
# assert list(reverse_ascending([])) == []
# assert list(reverse_ascending([1])) == [1]
# assert list(reverse_ascending([1, 1])) == [1, 1]
# assert list(reverse_ascending([1, 1, 2])) == [1, 2, 1]
# print("Coding complete? Click 'Check' to earn cool rewards!") | true |
b440d0252e9ed8a9bc3f84b569a31f819225302a | Isaac-D-Dawson/Homework-Uploads | /PyCheckIO/DateTimeConverter.py | 1,685 | 4.5 | 4 | # Computer date and time format consists only of numbers, for example: 21.05.2018 16:30
# Humans prefer to see something like this: 21 May 2018 year, 16 hours 30 minutes
# Your task is simple - convert the input date and time from computer format into a "human" format.
# example
# Input: Date and time as a string
# Output: The same date and time, but in a more readable format
# Precondition:
# 0 < date <= 31
# 0 < month <= 12
# 0 < year <= 3000
# 0 < hours < 24
# 0 < minutes < 60
def date_time(time: str) -> str:
date = time.split(" ")[0]
clock = time.split(" ")[1]
months = "January,Febuary,March,April,May,June,July,August,Septermber,October,November,December".split(",")
date = date.split(".")
clock = clock.split(":")
if int(clock[0]) == 1:
hours = "hour"
else:
hours = "hours"
if int(clock[1]) == 1:
minutes = "minute"
else:
minutes = "minutes"
outval = f"{int(date[0])} {months[int(date[1])-1]} {date[2]} year {int(clock[0])} {hours} {int(clock[1])} {minutes}"
#print(outval)#Debug output
return(outval)
# if __name__ == '__main__':
# print("Example:")
# print(date_time('01.01.2000 00:00'))
# #These "asserts" using only for self-checking and not necessary for auto-testing
# assert date_time("01.01.2000 00:00") == "1 January 2000 year 0 hours 0 minutes", "Millenium"
# assert date_time("09.05.1945 06:30") == "9 May 1945 year 6 hours 30 minutes", "Victory"
# assert date_time("20.11.1990 03:55") == "20 November 1990 year 3 hours 55 minutes", "Somebody was born"
# print("Coding complete? Click 'Check' to earn cool rewards!")
| true |
239f81592f5c85411d53ced66e13b7ec94218b97 | Isaac-D-Dawson/Homework-Uploads | /PyCheckIO/MedianOfThree.py | 1,536 | 4.375 | 4 | # Given an iterable of ints , create and return a new iterable whose first two elements are the same as in items, after which each element equals the median of the three elements in the original list ending in that position.
# Wait...You don't know what the "median" is? Go check out the separate "Median" mission on CheckiO.
# Input: Iterable of ints.
# Output: Iterable of ints.
# The mission was taken from Python CCPS 109 Fall 2018. It’s being taught for Ryerson Chang School of Continuing Education by Ilkka Kokkarinen
from typing import Iterable
def median_three(els: Iterable[int]) -> Iterable[int]:
if len(els) <= 2: #if there are two or less items in els
return(els) #return it
else: #otherwise
outval = els[0:2] #set the output variable to be the first two items in els
for i in range(2, len(els)): #Then, for every number other than the first two...
outval.append(sorted([els[i-2], els[i-1], els[i]])[1]) #Get the median ending at that position.
#print(outval) #Debug call
return(outval) #Output the output variable
# if __name__ == '__main__':
# print("Example:")
# print(list(median_three([1, 2, 3, 4, 5, 6, 7])))
# # These "asserts" are used for self-checking and not for an auto-testing
# assert list(median_three([1, 2, 3, 4, 5, 6, 7])) == [1, 2, 2, 3, 4, 5, 6]
# assert list(median_three([1])) == [1]
# print("Coding complete? Click 'Check' to earn cool rewards!") | true |
f4fc59d24310afd8a4fb778ad743d194cc0c1e2a | Isaac-D-Dawson/Homework-Uploads | /PyCheckIO/MorseDecoder.py | 2,122 | 4.125 | 4 | # Your task is to decrypt the secret message using the Morse code.
# The message will consist of words with 3 spaces between them and 1 space between each letter of each word.
# If the decrypted text starts with a letter then you'll have to print this letter in uppercase.
# example
# Input: The secret message.
# Output: The decrypted text.
# Precondition:
# 0 < len(message) < 100
# The message will consists of numbers and English letters only.
MORSE = {'.-': 'a', '-...': 'b', '-.-.': 'c',
'-..': 'd', '.': 'e', '..-.': 'f',
'--.': 'g', '....': 'h', '..': 'i',
'.---': 'j', '-.-': 'k', '.-..': 'l',
'--': 'm', '-.': 'n', '---': 'o',
'.--.': 'p', '--.-': 'q', '.-.': 'r',
'...': 's', '-': 't', '..-': 'u',
'...-': 'v', '.--': 'w', '-..-': 'x',
'-.--': 'y', '--..': 'z', '-----': '0',
'.----': '1', '..---': '2', '...--': '3',
'....-': '4', '.....': '5', '-....': '6',
'--...': '7', '---..': '8', '----.': '9'
}
def morse_decoder(code):
inval = code.split(" ")#get it as individual words)
#We do the first word maually to ensure valid capitaliseation
currentWord = inval[0].split(" ")
outval = MORSE[currentWord[0]].upper()
for i in currentWord[1:]:
outval = f"{outval}{MORSE[i]}"
#Now we decode the rest normally
for i in inval[1:]:
outval = f"{outval} "
for j in i.split(" "):
outval = f"{outval}{MORSE[j]}"
print(outval)#Debug call
return(outval)
# if __name__ == '__main__':
# print("Example:")
# print(morse_decoder('... --- ...'))
# #These "asserts" using only for self-checking and not necessary for auto-testing
# assert morse_decoder("... --- -- . - . -..- -") == "Some text"
# assert morse_decoder("..--- ----- .---- ---..") == "2018"
# assert morse_decoder(".. - .-- .- ... .- --. --- --- -.. -.. .- -.--") == "It was a good day"
# print("Coding complete? Click 'Check' to earn cool rewards!")
| true |
50deb4603696cf2de54543fdc813df491944525c | BerkeleyPlatte/competitiveCode | /weird_string_case.py | 958 | 4.4375 | 4 | #Write a function toWeirdCase (weirdcase in Ruby) that accepts a string, and returns the same string with all even indexed characters in each word upper cased, and all odd
#indexed characters in each word lower cased. The indexing just explained is zero based, so the zero-ith index is even, therefore that character should be upper cased.
#The passed in string will only consist of alphabetical characters and spaces(' '). Spaces will only be present if there are multiple words. Words will be separated by a
#single space(' ').
def to_weird_case(string):
string_list = list(string)
altered_list = []
for index, value in enumerate(string_list):
if value.isalpha():
if index % 2 == 0:
altered_list.append(value.upper())
else:
altered_list.append(value.lower())
else:
altered_list.append(value)
return ''.join(altered_list)
print(to_weird_case('This')) | true |
89708757e3ec29b31feef559b24ff8b3a336c6e5 | gab-umich/24pts | /fraction.py | 1,979 | 4.1875 | 4 | from math import gcd
# START OF CLASS DEFINITION
# EVERYTHING IS PUBLIC
class Fraction:
"""A simple class that supports integers and four operations."""
numerator = 1
denominator = 1
# Do not modify the __init__ function at all!
def __init__(self, nu, de):
"""Assign numerator and denominator, then simplify"""
self.numerator = nu
self.denominator = de
self.simplify()
# Do not modify the simplify function at all!
def simplify(self):
"""_________Require: self.numerator is an int,
self.denominator is an int,
Modify: Simplify numerator and denominator,
Effect: GCD(numerator, denominator) == 1"""
try:
if self.denominator == 0:
raise ValueError("denominator is zero ")
gcd_ = gcd(self.numerator, self.denominator)
self.numerator /= gcd_
self.denominator /= gcd_
except ValueError as err:
print(err)
# Do not modify the print function at all!
def print(self):
print("{}/{}".format(self.numerator, self.denominator))
# END OF CLASS DEFINITION
def add(frac1, frac2):
"""________Require: frac1 and frac2 are simplified
Modify: nothing
Effect: return frac1 added by frac2 and simplified"""
def sub(frac1, frac2):
"""________Require: frac1 and frac2 are simplified
Modify: nothing
Effect: return frac2 subtracted from frac1 and simplified"""
def mul(frac1, frac2):
"""________Require: frac1 and frac2 are simplified
Modify: nothing
Effect: return frac1 multiplied by frac2 and simplified"""
def div(frac1, frac2):
"""________Require: frac1 and frac2 are simplified
Modify: nothing
Effect: return frac1 divided by frac2 simplified"""
# this is tricky! What can go wrong in div??
| true |
1fb18bf77b33d4e911364ff771b8ea1bb11c20cc | Luoxsh6/CMEECourseWork | /Week2/code/tuple.py | 980 | 4.5625 | 5 | #!/usr/bin/env python
"""Practical of tuple with list comprehension"""
__author__ = 'Xiaosheng Luo (xiaosheng.luo18@imperial.ac.uk)'
__version__ = '0.0.1'
birds = (('Passerculus sandwichensis', 'Savannah sparrow', 18.7),
('Delichon urbica', 'House martin', 19),
('Junco phaeonotus', 'Yellow-eyed junco', 19.5),
('Junco hyemalis', 'Dark-eyed junco', 19.6),
('Tachycineata bicolor', 'Tree swallow', 20.2),
)
# Birds is a tuple of tuples of length three: latin name, common name, mass.
# write a (short) script to print these on a separate line or output block by species
# Hints: use the "print" command! You can use list comprehension!
# ANNOTATE WHAT EVERY BLOCK OR IF NECESSARY, LINE IS DOING!
# ALSO, PLEASE INCLUDE A DOCSTRING AT THE BEGINNING OF THIS FILE THAT
# SAYS WHAT THE SCRIPT DOES AND WHO THE AUTHOR IS
# use traditional loops
for i in range(len(birds)):
print(birds[i])
# use list comprehension
[print(birds[i]) for i in range(len(birds))]
| true |
9b6ec7f52421503518ec981ff9b61145fbe03e6b | Ishani2627/PythonAssignment11 | /Class11.py | 555 | 4.15625 | 4 | #Que1
print("1. find valid email address")
import re
email = input("enter an email address : ")
if re.match('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$', email):
print("valid email address")
else:
print("invalid email address")
print("\n")
#Que2
print("2. find valid indian phone number")
import re
phone_no = input("enter a phone number : ")
if re.match("(?:(?:\\+|0{0,2})91(\\s*[\\-]\\s*)?|[0]?)?[6789]\\d{9}", phone_no) and len(phone_no) == 13 :
print("valid phone number")
else:
print("invalid phone number") | false |
8e11531642b2dfb6460f5240499eba2c1fd7e8d9 | YuvalSK/curexc | /cod.py | 1,872 | 4.3125 | 4 | import exrates
import datetime
import sys
def inputdate(date_text):
'''function that inputs a date, and verified if the date is in a vaild format, else return False
'''
try:
datetime.datetime.strptime(date_text, '%Y-%m-%d')
return True
except ValueError:
return False
def main():
'''main to test the program: inputs a date,
and prints the list of currencies for which there is a date, in format requested
'''
datetext = input("Greetings User! please enter a date:" )
#value vaildation using the function above, loop untill correct format, with mentioning problem
while inputdate(datetext)== False:
#printing error!
sys.stderr.write("\Value Error! invalid input-choose an available date\n")
datetext = input(" Let's give it another try! " + "\n" +" please enter a date:" + '\n'
+ " i.e. 'YYYY-MM-DD' stracture, an exsample for a vaild format is 2017-03-11" + '\n')
inputdate(datetext)
#using the date the user entered, to withdraw the dictionery from exrates file, get_exrate fuction and sorted by code.
date_Rates = sorted(exrates.get_exrates(datetext))
#marging two dictionery, to get the name and code in one dictionery
curlist = exrates.get_currencies()
#the format requested
format_list = '{name} ({code})'
#creating the list, using the format above, while check every code in the updated code list
Final_list = [format_list.format(name=curlist.get(code, "<unknonwn>"),code=code) for code in date_Rates]
print('\nHere is a list of correncies available to ' + datetext + " : \n")
#print the values of the list
print('\n'.join(Final_list))
main()
| true |
1114c211c01850695d172cab82d0d544640e2f91 | AdarshRise/Python-Nil-to-Hill | /1. Nil/6. Function.py | 1,618 | 4.53125 | 5 | # Creating Function
# function are created using def
def fun():
print(" function got created ")
def fun2(x):
print("value of x is :",x)
# a bit complex use of function
def fun3(x):
x=x*x
print("value of x*x is ",x)
# above code will execute from here
x=2
fun()
fun2(x)
fun3(x)
print(x) # the value of x is unaffected by fun3()
#--------------------------------------------------
# Variable present in the function call are called -: Actual parameters
# Variable present in the function defintion are called -: Formal parameters
#--------------------------------------------------
# passing parameter in functions
def par(x,y): # function without default value of y
print(" value of x ",x,"value of y ",y)
def par2(x,y=10): # function with default value of y
print(" value of x ",x," value of y ",y)
# this will execute the code above
x=3
y=4
par(x,y) # passing 2 parameter to a function without default value
par2(x) # passing 1 parameter to a function with a default value
par2(x,y) # passing 2 parameter to a function with a default value
par2(y=50,x=90) # passing values in different order but with the names of Formal parameters
# code below is invalid
#-----------------------
# def fun(x=10,y):
# some code....
#-----------------------
#------------------------------------------------------------
# there is No exact main funtion, but we can make one
def main():
print(" all the exectue statements should go here ")
if __name__="__main__":
main()
# the above code works as a sudo-main funtion in python, learn more about __name__
| true |
a9917be09fdd70e78780145231214f1bc833ef95 | mpwesthuizen/eng57_python | /dictionairies/dictionairies.py | 1,292 | 4.46875 | 4 | # Dictionairies
# definitions
# a dictionary is a data structure, like a list, but organised with a key and not indexes
# They are organised with key: 'value' pairs
# for example 'zebra': "an african wild animal that looks like a horse but has stripes on its body."
# this means you can search data using keys, rather than index.
# syntax
my_dictionary ={'key':'value'}
print(type(my_dictionary))
# Defining a dictionary
# looking at our stringy landlords we need more info.. like the houses they have and contact detail.
stingy_dict = {
'name': 'giggs',
'phone_number' : '0745 678 910',
'property_type': 'flat'
}
# printing dictionary
print(stingy_dict)
print(type(stingy_dict))
# getting one value out
print(stingy_dict['name'])
print(stingy_dict['phone_number'])
# re-assigning one value
stingy_dict['name'] = "alfredo de medo"
print(stingy_dict)
# new key value pair
stingy_dict['property_type'] = "house 2, Unit 29 Watson Rd"
print(stingy_dict)
stingy_dict['number_of_victims'] = 0
stingy_dict['number_of_victims'] += 1
print(stingy_dict)
# Get all the values out
# special dictionary methods
# (methods are functions that belong to specific data types)
# .keys()
print(stingy_dict.keys())
# .values()
print(stingy_dict.values())
# .items()
print(stingy_dict.items())
| true |
89f05b07503462748e7cf512d7132e6dcd901390 | yingchuanfu/Python | /com/python7/FunctionClass.py | 856 | 4.28125 | 4 | # -*- coding: UTF-8 -*-
#抽象函数:类(在Python中,类具有封装,继承,多态,但是没有重载)
#self参数
class Person:
#定义类的数据成员:姓名,年龄
name = ''
age = 0
#定义构造函数,用于创建一个类实例,也就是类的具体对象
#通过参数传递,可以赋予对象初始状态
def __init__(self, name, age):
self.name = name
self.age = age
#定义一个函数:打印类实例的基本信息
def printPersionInfo(self):
print('person-info:{name:%s, age:%d}'%(self.name, self.age))
#实例化,创建二个对象,默认调用构造函数: _init_
p1 = Person("ZhangSan", 12)
p2 = Person("Li Si", 18)
#访问类的属性: 数据成员,访问语法obj.x
print("name:", p1.name)
print("age:", p1.age)
#调用类的函数
p1.printPersionInfo()
p2.printPersionInfo()
| false |
c0901965ca658c1eb3a7c93624513527f4559564 | Mayank-Chandra/LinkedList | /LinkedLIst.py | 1,135 | 4.28125 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def push(self,new_data):
new_node=Node(new_data)
new_node.next=self.head
self.head=new_node
def insertAfter(self,prev_node,new_data):
if prev_node is None:
print('The Given Previous node must be in LinkedList:')
return
new_node=Node(new_data)
new_node.next=prev_node.next
prev_node.next=new_node
def append(self,new_data):
new_node=Node(new_data)
if self.head is None:
self.head=new_node
return
last=self.head
while(last.next):
last=last.next
last.next=new_node
def printList(self):
temp=self.head
while(temp):
print(temp.data)
temp=temp.next
if __name__=='__main__':
list1=LinkedList()
list1.append(6)
list1.push(7)
list1.push(1)
list1.append(4)
list1.insertAfter(list1.head.next,8)
print("The Created List is:",list1.printList())
| true |
fc78e85199164a95411cfb14411be9128603366e | JeweL645/restart | /slicing.py | 473 | 4.125 | 4 |
fav_food = ["pizza","pasta","bbq_rice","nachos","milk_shakes","ice_cream"]
#print(fav_food)
for food in fav_food:
print(food.title()+"!!")
print("First three items in the list are:\n")
for food in fav_food[:3]:
print(food.title())
print("The three item in the middle of the list are :")
for food in fav_food[2:5]:
print(food.title())
print("The three item in the last of the list are :")
for food in fav_food[3:]:
print(food.title()) | false |
461085bffe23b8dd9873de328d4a859beb12e3ab | jcjc2019/edX-MIT6.00.1x-IntroToComputerScience-ProgrammingUsingPython | /Program2-ndigits.py | 405 | 4.125 | 4 | # below is the function to count the number of digits in a number
def ndigits(x):
# when x is more than 0
if x > 0:
#change type to string, count the length of the string
return len(str(int(x)))
# when x is less than 0
elif x < 0:
#get the absolute value, change type to string, and count the length
return len(str(abs(x)))
else:
return 0
| true |
04623021d338f1b390d12cb951a37b86a828ab30 | SouzaCadu/guppe | /Secao_12_Modulos/12_80_Oq_sao_modulos_Random.py | 1,413 | 4.34375 | 4 | """
Módulos e módulo Random
Em Python módulos são outros arquivos Python com funções. Devem ser instalados e/ou importados.
O módulo Random possui diversas funções para gerar números pseudo aleatórios.
Existem duas formas de utilizar um módulo:
Importando todo o módulo todas as funções, atributos, classes e propriedades que estiverem
dentro do módulo ficaram disponíveis em memória. O ideal é importar apenas as funções necessárias do módulo.
Por exemplo: import random
print(random.random())
Está indicado o módulo (random) e depois do ponto a função do módulo(random()).
Importando uma função específica de um módulo. Forma recomendada. O acesso a função é direto.
from random import random, uniform, randint, choice, shuffle
random: gera números reais pseudo aleatórios entre 0 e 1.
uniform: gera números reais pseudo aleatórios entre um intervalo estabelecido
randint: gera números inteiros pseudo aleatórios entre um intervalo estabelecido
choice: mostra um valor aleatório em um iterável
shuffle: embaralha dados em um iterável
for i in range(10):
print(random())
for i in range(10):
print(uniform(3, 7))
for i in range(6):
print(randint(1, 61), end=", ")
jogadas = ["papel", "pedra", "tesoura"]
print(choice(jogadas))
cartas = ["k", "Q", "J", "A", "2", "3", "4", "5", "6", "7" ]
print(cartas)
shuffle(cartas)
print(cartas)
"""
| false |
f7abd2c7092c7e148e47391dc2b9e78d7cb2fc72 | SouzaCadu/guppe | /Secao_08_Funcoes/08_47_funcoes_com_parâmetro_padrão.py | 1,916 | 4.65625 | 5 | """
Funções com parâmetro padrão
- funções onde a passagem de parâmetro seja opcional, ou seja, quando eu
estabeleço um valor padrão para o parâmetro, se o usuário informar um valor
como argumento será usado o valor do argumento passado pelo usuário
- ao usar valores padrão eles DEVEM estar no final da declaração da função, do contrário
há um erro na execução
- permite mais flexibilidade na hora de criar uma função
- qualquer tipo de dado pode ser usado como parâmetro padrão
- quanto ao escopo das variáveis, será dada preferência as variáveis locais
em detrimento das globais de mesmo nome
- as variáveis criadas dentro da função só serão acessadas dentro do escopo da
função, as variáveis criadas fora do escopo da função não podem ser acessadas
para realizar operações dentro da função
- funções podem ser declaradas dentro de outras funções
# exemplo
print("Geek University")
print()
def exponencial(base, potencia=2):
return base ** potencia
print(exponencial(2, 3))
print(exponencial(2))
print(exponencial(5))
print(exponencial(5, 2))
def mostra_informacao(nome="Geek", instrutor=False):
if nome == "Geek" and instrutor:
return "Bem vindo instrutor Geek!"
elif nome == "Geek":
return "Eu pensei que você era o instrutor!"
return f"Olá {nome}!"
print(mostra_informacao())
print(mostra_informacao(instrutor=True))
print(mostra_informacao("Lars Ulrich"))
print(mostra_informacao(nome="Paul Richardson"))
def soma(a, b):
return a + b
def subtracao(a, b):
return a - b
def mat(a, b, func=soma):
return func(a, b)
print(soma(3, 8))
print(subtracao(12, 19))
print(mat(20, 14, subtracao))
# exemplo de funções aninhadas, não usual
def fora():
contador = 0
def dentro():
nonlocal contador
contador += 1
return contador
return dentro()
print(fora())
"""
| false |
c9db169a66d3166f20fc1aed6fa32b144b941990 | SouzaCadu/guppe | /Secao_11_Debugando_tratando_erros/11_76_Try_except_else_finally.py | 1,367 | 4.1875 | 4 | """
Try / Except / Else / Finally
Toda a entrada de dados, principalmente do usuário, deve ser tratada!
Else: É executado apenas se não acontecer o erro
try:
num = int(input("Informe um número: "))
except ValueError:
print("Valor incorreto.")
else:
print(f"Você digitou {num}.")
Finally: É sempre executado, ocorrendo a exceção ou não. Geralmente é utilizado para
fechar uma conexão com banco de dados, um arquivo lido durante o código.
try:
num = int(input("Informe um número: "))
except ValueError:
print("Você não digitou um valor válido.")
else:
print(f"Você digitou {num}.")
finally:
print("Executando o finally")
Tratamento individual das entradas em uma função
def dividir(a, b):
try:
return int(a) / int(b)
except ValueError:
return "O valor deve ser numérico."
except ZeroDivisionError:
return "Não é possível dividir por zero."
num1 = input("Informe o primeiro número: ")
num2 = input("Informe o segundo número: ")
print(dividir(num1, num2))
Tratamento semi-genérico
def dividir(a, b):
try:
return int(a) / int(b)
except (ValueError, ZeroDivisionError) as err:
return f"Ocorreu um erro {err}."
num1 = input("Informe o primeiro número: ")
num2 = input("Informe o segundo número: ")
print(dividir(num1, num2))
"""
| false |
b51cf9502c680d0c5f6c42c71cff8e8611151c84 | SouzaCadu/guppe | /Secao_13_Lista_Ex_29e/ex_22.py | 2,572 | 4.3125 | 4 | """
22) Faça um programa que recebe como entrada o nome de um arquivo de entrada e o nome de um arquivo saída.
O arquivo de entrada contém o nome de um aluno ocupando 40 caracteres e três inteiros que indicam suas notas.
O programa deverá ler o arquivo de entrada e gerar um arquivo de saída onde aparece o nome do aluno e as suas notas
em ordem crescente.
"""
print("Informe o caminho do arquivo de entrada contendo o nome de cada aluno e suas três notas.\n"
"A seguir informe o caminho do arquivo de saída, onde serão armazenados os dados em ordem crescente.")
import os
path1 = input("Informe o caminho do arquivo de entrada contendo o nome dos alunos e as notas: ")
while True:
path2 = input("Informe o caminho do arquivo de saída onde serão salvos os dados ordenados: ")
if os.path.isfile(path2):
print("O arquivo já existe!")
else:
break
def organizar(dados):
"""
Função que recebe uma lista no formato 'nome nota1 nota2 nota3' e retorna um map iterator
com nota1, nota2 e nota3 em ordem crescente.
:param dados: Arquivo contendo uma lista no formato 'nome nota1 nota2 nota3'
:return: map iterator com nota1, nota2 e nota3 em ordem crescente.
"""
alunos = [dado.split()[0] for dado in dados]
notas = [[float(nota) for nota in dado.split()[1:]] for dado in dados]
for nota in notas:
if any(filter(lambda n: n > 10 or n < 0, nota)) or len(nota) != 3:
raise ValueError()
nota.sort()
notas = [[str(n) for n in nota] for nota in notas]
return map(lambda tupla: tupla[0] + ' ' + ' '.join(tupla[1]), zip(alunos, notas))
def gerar_notas(entrada, saida):
"""
Função que recebe um arquivo como entrada com o nome do aluno e notas, e retorna as notas em ordem
crescente em outro arquivo.
:param entrada: Arquivo com as notas por aluno
:param saida: Arquivo com as notas por aluno em ordem crescente
:return: Notas por aluno em ordem crescente
"""
try:
with open(entrada) as arq_in:
dados = arq_in.readlines()
except (FileNotFoundError, OSError):
return print('Arquivo inexistente. Favor conferir.')
else:
try:
alunos_notas = organizar(dados)
except (ValueError, IndexError):
return print('Formato inválido')
else:
with open(saida, 'a') as arq_out:
for aluno in alunos_notas:
arq_out.write(f'{aluno}\n')
print('Concluído!')
gerar_notas(path1, path2)
| false |
a91cf7747fcd974eae0a0ea95261d82b8aaac1d7 | SouzaCadu/guppe | /Secao_08_Lista_Ex_73e/ex_23.py | 346 | 4.25 | 4 | """
escreva uma função que gere um triângulo lateral de
altura 2*n-1 e n de largura
"""
def triangulo_lateral(num):
linha = ""
for i in range (2 * num - 1):
if i < num:
linha += "*" * (i + 1) + "\n"
else:
linha += (2 * num - (i + 1)) * "*" + "\n"
return linha
print(triangulo_lateral(12)) | false |
1c5fb28c1c667af22fc2c1737d1113856a7b1b5c | SouzaCadu/guppe | /Secao_07_Lista_Ex_25e/ex_25.py | 2,415 | 4.15625 | 4 | """
faça um programa para determinar a próxima jogada em jogo da velha
o tabuleiro é uma matriz 3 x 3
"""
from collections import Counter
print('Jogo da velha')
def linha_check(matriz, i):
"""Função para conferir o número de X/O na linha i de matriz.
Retorna 1 se há 3 X's, -1 se há 3 O's, e 0 caso contrário."""
if Counter(matriz[i]).get('X') == 3:
return 1
elif Counter(matriz[i]).get('O') == 3:
return -1
return 0
def coluna_check(matriz, j):
"""Função para conferir o número de X/O na coluna j de matriz.
Retorna 1 se há 3 X's, -1 se há 3 O's, e 0 caso contrário."""
m_trans = [[matriz[j][i] for j in range(3)] for i in range(3)]
return linha_check(m_trans, j)
def diag_check(matriz):
"""Função para conferir o número de X/O na duas diagonais de matriz.
Retorna 1 se há 3 X's, -1 se há 3 O's, e 0 caso contrário."""
diag1 = [matriz[i][i] for i in range(3)]
for linha in matriz:
linha.reverse()
diag2 = [matriz[i][i] for i in range(3)]
if Counter(diag1).get('X') == 3 or Counter(diag2).get('O') == 3:
return 1
elif Counter(diag1).get('X') == 3 or Counter(diag2).get('O') == 3:
return -1
return 0
jogo = [[0 for _ in range(3)] for _ in range(3)]
for linha in jogo:
print(linha)
jogada = 1
while True:
if jogada % 2:
print('Jogador 1 - Insira a posição')
else:
print('Jogador 2 - Insira a posição')
jogada_check = True
i = int(input('Linha (0 a 2): '))
j = int(input('Coluna (0 a 2): '))
if jogo[i][j] != 0:
jogada_check = False
while not jogada_check:
print('Jogada inválida.')
i = int(input('Linha (0 a 2): '))
j = int(input('Coluna (0 a 2): '))
if jogo[i][j] == 0:
jogada_check = True
if jogada % 2:
jogo[i][j] = 'X'
else:
jogo[i][j] = 'O'
for linha in jogo:
print(linha)
if linha_check(jogo, i) == 1 or coluna_check(jogo, j) == 1 or diag_check(jogo) == 1:
print(f'Jogador 1 venceu! Número de jogadas: {jogada}')
break
elif linha_check(jogo, i) == -1 or coluna_check(jogo, j) == -1 or diag_check(jogo) == -1:
print(f'Jogador 2 venceu! Número de jogadas: {jogada}')
break
else:
jogada += 1
if jogada > 9:
print('Empate!')
break | false |
54d1eb3bad846f3eeb01994f308b6f732456b15a | SouzaCadu/guppe | /Secao_13_Lista_Ex_29e/ex_11.py | 1,204 | 4.15625 | 4 | """
11) Faça um programa no qual o usuário informa o nome do arquivo e uma palavra, e retorne o número de vezes que aquela
palavra aparece no arquivo.
"""
from collections import Counter
def cont_palavra(texto, palavra):
"""
Conta quantas vezes uma palavra aparece em um texto extamente como o usuário informar
:param texto: Qualquer texto
:param palavra: Palavra que se deseja contar
:return: quantidade de vezes que a palavra aparece no texto
"""
palavras = Counter(texto)
return int(palavras[palavra])
print("Digite o caminho do arquivo e uma palavra para saber quantas vezes a palavra aparece no arquivo selecionado\n"
"com a correspondencia exata.")
path = str(input("Informe o caminho do arquivo: "))
palavra = str(input("Informe a palavra para saber quantas vezes ele aparece no arquivo: "))
try:
with open(path, "r") as arquivo:
texto = arquivo.readlines()
total = 0
for frase in texto:
qtde = cont_palavra(frase.split(), palavra)
total += qtde
print(f"Em {path} a palavra {palavra} aparece {total} vezes.")
except FileNotFoundError:
print("\nArquivo informado não encontrado!")
| false |
4a256bfa77951822529589070833c54141adafc5 | SouzaCadu/guppe | /Secao_10_Expressoes_Lambdas_Funcoes_Integradas/10_64_Any_All.py | 999 | 4.125 | 4 | """
Any e All
all(): retorna True se todos os elementos do iterável são verdadeiros ou ainda se o iterável está vazio
Exemplos
print(all([0, 1, 2, 3, 4]), all([1, 2, 3, 4]), all({}),
all("Geek University"))
nomes = ["carlos", "cristiano", "castro", "cassiano", "carina", "camilla"]
print(all([nome[0] == "c" for nome in nomes]))
print(all([letra for letra in "klmnop" if letra in "abcdefghij"]))
# caso em que o iterável é vazio, e considerado como True pelo all
print(all([num for num in range(50, 100) if num % 2 == 0]), all([num for num in range(50, 100) if num % 2 != 0]))
any(): retorna True se qualquer elemento do iterável for verdadeiro. Se o iterável estiver vazio retorna falso
Exemplos
print(any([0, 1, 2, 3, 4]), any([1, 2, 3, 4]), any({}),
any("Geek University"))
nomes = ["carlos", "cristiano", "castro", "cassiano", "carina", "camilla"]
print(any([nome[0] == "c" for nome in nomes]))
print(any([num for num in range(2, 25, 2) if num % 2 == 0]))
"""
| false |
77bf5f64defe7712ddaff8000265bd881a7240bb | SouzaCadu/guppe | /Secao_06_Lista_Ex_62e/ex_40.py | 604 | 4.125 | 4 | """
Faça um programa que leia vários números inteiros positivos
se um número negativo for digitado o programa deve ser encerrado
e exibir o maior e o menor valor
"""
i = 1
menor = maior = 0
print("Digite quantos números inteiros positivos desejar\n"
"ao digitar um inteiro negativo serão exibidos\n"
"o maior e o menor valor digitados.")
n = int(input("Digite um número: "))
while n >= 0:
n = int(input("Digite um número: "))
if n <= menor:
menor = n
if n >= maior:
maior = n
else:
print(f"O maior número é {maior} e o menor número é {menor}.") | false |
3601cd2ab4dbfcb4671215627f24a815381a9db2 | SouzaCadu/guppe | /Secao_19_Manipulando_data_hora/19_136_Manipulando_data_hora.py | 891 | 4.125 | 4 | """
Manipulando data e hora
import datetime
print(dir(datetime))
print(datetime.MINYEAR, datetime.MAXYEAR)
print(datetime.datetime, datetime.datetime.now()) # <class 'datetime.datetime'>, 2021-02-12 19:12:35.202509
print(repr(datetime.datetime.now())) # datetime.datetime(2021, 2, 12, 19, 13, 56, 852411)
inicio = datetime.datetime.now()
print(inicio)
# alterar o horário
inicio = inicio.replace(hour=20, minute=0, second=0, microsecond=0)
print(inicio)
# criando um evento
evento = datetime.datetime(2021, 2, 15, 0)
print(evento)
print(evento.year)
print(evento.month)
print(evento.day)
print(evento.second)
print(evento.microsecond)
# data Python
nascimento = input("Informe sua data de nascimento no formato dd/mm/yy: ")
nascimento = nascimento.split("/")
nascimento = datetime.datetime(int(nascimento[2]), int(nascimento[1]), int(nascimento[0]))
print(nascimento)
"""
| false |
ae2be8154746d3a5a62fb76e92f6e1d1b6e7932a | SouzaCadu/guppe | /Secao_06_Lista_Ex_62e/ex_32.py | 735 | 4.21875 | 4 | """
faça um programa que simula o lançamento de dois dados n
vezes e tenha como saída:
- o número de cada dado
- a relação entre eles (>, <, =) de cada lançamento
"""
from random import randint
n = int(input("Digite 1 para girar os dados ou 2 para sair: "))
while n != 2:
d1 = randint(1, 6)
d2 = randint(1, 6)
if d1 > d2:
print(f"O resultado é {d1} > {d2}.")
n= int(input("Digite 1 para girar os dados ou 2 para sair: "))
elif d1 < d2:
print(f"O resultado é {d1} < {d2}.")
n = int(input("Digite 1 para girar os dados ou 2 para sair: "))
elif d1 == d2:
print(f"O resultado é {d1} = {d2}.")
n = int(input("Digite 1 para girar os dados ou 2 para sair: "))
| false |
265ce887362d8f699b0bc7a41d508d03c699689d | SouzaCadu/guppe | /Secao_07_Colecoes/07_40_module_collections_named_tuple.py | 627 | 4.21875 | 4 | """
Módulo Collections - Named Tuple
São tuplas para as quais especificamos um nome, para a tupla e para os parametros
facilitando o acesso a informação.
Aceita os mesmo métodos usados em tuplas
"""
from collections import namedtuple
cachorro1 = namedtuple("cachorro", "raça idade origem")
cachorro2 = namedtuple("cachorro", "raça, idade, origem")
cachorro3 = namedtuple("cachorro", ["raça", "idade", "origem"])
ray = cachorro3(raça="Akita", idade=2, origem="Japão")
print(ray)
print(ray[0])
print(ray[1])
print(ray[2])
# ou
print(ray.raça)
print(ray.idade)
print(ray.origem)
# ou
print(ray.index("Japão")) | false |
f3adc9411761ca5836799f1ae448c4e80f5ab983 | SouzaCadu/guppe | /Secao_06_Lista_Ex_62e/ex_47.py | 1,779 | 4.375 | 4 | """
Dadas as operações fundamentais da matemática,
faça um programa que permita ao usuário escolher
a operação obter o resultado e voltar ao menu
"""
print("Selecione uma das opções para o cálculo das operações\n"
"entre 2 números:\n"
"1 - adição\n"
"2 - subtração\n"
"3 - multiplicação\n"
"4 - divisão\n"
"5 - saída")
opcao = int(input("Digite a opção desejada: "))
if opcao == 5:
exit(print("Programa encerrado."))
if opcao not in (1, 2, 3, 4, 5):
print("Opção inválida.")
n1 = float(input("Digite o primeiro valor: "))
n2 = float(input("Digite o segundo valor: "))
if opcao == 4 and n2 == 0:
print("Não existe divisão por zero.")
n2 = float(input("Digite o segundo valor: "))
while True:
if opcao == 1:
print(f"O resultado da soma é {n1 + n2:.2f}")
elif opcao == 2:
print(f"O resultado da substração é {n1 - n2:.2f}")
elif opcao == 3:
print(f"O resultado da multiplicação é {n1 * n2:.2f}")
elif opcao == 4:
print(f"O resultado da divisão é {n1 / n2:.2f}")
print("Selecione uma das opções para o cálculo das operações\n"
"entre 2 números:\n"
"1 - adição\n"
"2 - subtração\n"
"3 - multiplicação\n"
"4 - divisão\n"
"5 - saída")
opcao = int(input("Digite a opção desejada: "))
if opcao == 5:
exit(print("Programa encerrado."))
if opcao not in (1, 2, 3, 4, 5):
print("Opção inválida.")
n1 = float(input("Digite o primeiro valor: "))
n2 = float(input("Digite o segundo valor: "))
if opcao == 4 and n2 == 0:
print("Não existe divisão por zero.")
n2 = float(input("Digite o segundo valor: "))
| false |
2a95d388f5dfde00a6d5f6c7eeb3c04ee54954ae | SouzaCadu/guppe | /Secao_08_Lista_Ex_73e/ex_14.py | 921 | 4.15625 | 4 | """
faça uma função que receba a distância em KM e a quantidade de litros
de gasolina consumidos por um carro e calcule o consumo em
KM / L e escreva a mensagem de acordo com a tabela
- se menor que 8: venda o carro
- entre 8 e 14 econômico
- maior que 14 super econômico
"""
def avalia_consumo(km, litros):
"""
Calcule o consumo em KM / L e escreva a mensagem de acordo com a tabela
- se menor que 8: venda o carro
- entre 8 e 14 econômico
- maior que 14 super econômico
:param km: Distância percorrida em km
:param litros: Quantidade de gasolina utilizada em litros
:return: Consumo no trajeto percorrido
"""
consumo = km / litros
if consumo < 8:
return "Venda o carro!"
elif 8 <= consumo <= 14:
return "Econômico!"
return f"Super econômico!"
print(avalia_consumo(125, 10))
print(avalia_consumo(250, 32))
print(avalia_consumo(375, 11))
| false |
8952a219e349498121e00fc45c06c53b19e92b65 | earl-grey-cucumber/Algorithm | /353-Design-Snake-Game/solution.py | 1,815 | 4.1875 | 4 | class SnakeGame(object):
def __init__(self, width,height,food):
"""
Initialize your data structure here.
@param width - screen width
@param height - screen height
@param food - A list of food positions
E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].
:type width: int
:type height: int
:type food: List[List[int]]
"""
self.width, self.height, self.food = width, height, food
self.foodCount = 0
self.body = [0]
self.directions = {'U': [-1, 0], 'L': [0, -1], 'R': [0, 1], 'D': [1, 0]}
def move(self, direction):
"""
Moves the snake.
@param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down
@return The game's score after the move. Return -1 if game over.
Game over when snake crosses the screen boundary or bites its body.
:type direction: str
:rtype: int
"""
head = self.body[0]
tail = self.body.pop()
x = head / self.width
y = head % self.width
newx = x + self.directions[direction][0]
newy = y + self.directions[direction][1]
newHead = newx * self.width + newy
if (newx < 0 or newx >= self.height or newy < 0 or newy >= self.width
or newHead in self.body):
return -1
self.body.insert(0, newHead)
if (self.foodCount < len(self.food) and newx == self.food[self.foodCount][0] and
newy == self.food[self.foodCount][1]):
self.foodCount += 1
self.body.append(tail)
return len(self.body) - 1
# Your SnakeGame object will be instantiated and called as such:
# obj = SnakeGame(width, height, food)
# param_1 = obj.move(direction) | true |
934d86b9bb48d249c79c5a85d053c62a2b6b5775 | prokarius/hello-world | /Python/BellRinging.py | 714 | 4.125 | 4 | # n = 2: [(1, 2), (2, 1)]
# n = 3:
# ( 1 , 2 ,*3*)
# ( 1 ,*3*, 2 )
# (*3*, 1 , 2 )
# (*3*, 2 , 1 )
# ( 2 ,*3*, 1 )
# ( 2 , 1 ,*3*)
# Solution to recurse
def recurse(n):
if n == 1:
return [["1"]]
out = []
flag = False
for i in recurse(n-1):
if flag:
for j in range(n):
toadd = list(i)
toadd.insert(j, str(n))
out.append(toadd)
else:
for j in range(n-1, -1, -1):
toadd = list(i)
toadd.insert(j, str(n))
out.append(toadd)
flag = not flag
return out
def main():
n = int(input())
for i in recurse(n):
print (" ".join(i))
main()
| false |
0b4692180343e2d59f6eecc315b8886072b07dd9 | Laxaria/LearningPyth3 | /PracticePython/Fibonacci.py | 987 | 4.5625 | 5 | # Write a program that asks the user how many Fibonnaci numbers to generate and then generates them.
# Take this opportunity to think about how you can use functions. Make sure to ask the user to enter the number
# of numbers in the sequence to generate.
# (Hint: The Fibonnaci seqence is a sequence of numbers where the next number in the sequence is
# the sum of the previous two numbers in the sequence. The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …)
# http://www.practicepython.org/exercise/2014/04/30/13-fibonacci.html
def Fib_Generator(userInput):
fibList = [0, 1,1]
userInput = int(userInput)
if userInput == 0:
print(fibList[0])
elif userInput == 1:
print(fibList[0:2])
elif userInput == 2:
print(fibList[0:3])
else:
for _i in range(userInput-3):
fibList.append(fibList[-1] + fibList[-2])
print(fibList)
Fib_Generator(input("How many Fibonnaci numbers do you want to generate? Input: "))
| true |
6d288b804d2b5cc07008fd53cf4ff7352052e458 | MelindaD589/Programming-Foundations-Fundamentals | /practice.py | 448 | 4.125 | 4 | # Chapter 1
print("Hello world!")
# Chapter 2
# Exercise 1
name = input("Hi, what's your name? ")
age = int(input("How old are you? "))
if (age < 13):
print("You're too young to register", name)
else:
print("Feel free to join", name)
# Exercise 2
print("Hello world!")
print("Goodbye world!")
# Exercise 3
# syntax error
print("Hello world")
# runtime error
10 * (2/0)
# semantic error
name = "Alice"
print("Hello name")
| true |
fc7376086c6c59f67ab1009af30a49a5491079f1 | debdutgoswami/python-beginners-makaut | /day-6/ascendingdescending.py | 344 | 4.34375 | 4 | dictionary = {"Name": "Debdut","Roll": "114", "Dept.": "CSE"}
ascending = dict(sorted(dictionary.items(), key=lambda x: x[1]))
descending = dict(sorted(dictionary.items(), key=lambda x: x[1], reverse=True))
print("the dictionary in ascending order of values is",ascending)
print("the dictionary in descending order of values is",descending) | true |
9b2e6ada5318d7eecc9797368fa73b53fef11943 | MikeWooster/reformat-money | /reformat_money/arguments.py | 1,405 | 4.125 | 4 |
class Argument:
"""Parses a python argument as string.
All whitespace before and after the argument text itself
is stripped off and saved for later reformatting.
"""
def __init__(self, original: str):
original.lstrip()
start = 0
end = len(original) - 1
while original[start].isspace():
start += 1
while original[end].isspace():
end -= 1
# End requires +1 when used in string slicing.
end += 1
self._leading_whitespace = original[:start]
self._trailing_whitespace = original[end:]
self.set_text(original[start:end or None])
def get_leading_whitespace(self):
return self._leading_whitespace
def get_trailing_whitespace(self):
return self._trailing_whitespace
def set_text(self, text):
self._text = text
def get_text(self):
return self._text
def __str__(self):
return f"{self.get_leading_whitespace()}{self.get_text()}{self.get_trailing_whitespace()}"
def __repr__(self):
return f"'{self}'"
def __eq__(self, other):
return (
isinstance(other, Argument) and
self.get_leading_whitespace() == other.get_leading_whitespace() and
self.get_text() == other.get_text() and
self.get_trailing_whitespace() == other.get_trailing_whitespace()
) | true |
6efeb3345f8eb779f5dbc797ba6d5ed195966330 | dyhmzall/geekbrains_python | /lesson3/task3.py | 1,276 | 4.21875 | 4 | # 3. Реализовать функцию my_func(), которая принимает три позиционных аргумента,
# и возвращает сумму наибольших двух аргументов.
def my_func(*args):
"""
Принимает любое количество аргументов (в том числе три)
и возвращает сумму наибольших двух из них
:param args: list любое количество аргументов
:return:float
"""
return sum(get_max_from_list(list(args), 2))
def get_max_from_list(number_list, number_count=1):
"""
Получить максимальные элементы из списка
:param number_list: list
:param number_count: int (по-умолчанию 1)
:return: list
"""
# если передали список с количество, меньшим,
# чем нужно максимальных значений - вернем исходный
if len(number_list) <= number_count:
return number_list
max_values = sorted(number_list, reverse=True)[0:number_count]
return max_values
print(my_func(100, 50, 200))
print(my_func(1, 2, 3))
print(my_func(1000, 100, 1))
| false |
490ecf5f4f7847afa1bbb5cebecc47843b3d541a | florian-corby/Pylearn | /hangman/hangman.py | 2,469 | 4.21875 | 4 | #!/usr/bin/env python3
import word_manipulations
import get_random_word
import hangman_ascii
import sys
import os
def print_ends(hangman_end, guess_word):
if hangman_end == "defeat":
print("")
print("You lost! Hangman is now dead...")
print("Guess word was: " + "".join(guess_word))
else:
print("")
print("You won! Hangman survived thanks to you!")
def is_hidden_word_revealed(hidden_word):
is_it_revealed = True
for i in range(0, len(hidden_word)):
if hidden_word[i] == "*":
is_it_revealed = False
return is_it_revealed
# Why string comparison doesn't work here
# with == operator when they are equal???
def is_it_the_end(hangman_state, hidden_word, guess_word):
if hangman_state == 8:
print_ends("defeat", guess_word)
return True
elif is_hidden_word_revealed(hidden_word):
print_ends("victory", guess_word)
return True
else:
return False
def hangman():
hangman_state = 0
end_of_game = False
rand_word = get_random_word.get_random_word()
hidden_word = word_manipulations.create_hidden_word(rand_word)
user_input_saves = []
while not end_of_game:
print("")
user_letter = input("Entrez une lettre: ")
print("")
pos_list = word_manipulations.search_letter(user_letter, rand_word)
if len(pos_list) != 0:
hidden_word = word_manipulations.reveal_letters(pos_list, user_letter, hidden_word)
print("".join(hidden_word))
else:
user_input_saves.append(user_letter)
hangman_state += 1
os.system("clear")
hangman_ascii.hangman_states(hangman_state)
print("")
print("".join(user_input_saves))
print("".join(hidden_word))
end_of_game = is_it_the_end(hangman_state, hidden_word, rand_word)
while True:
try:
keep_playing = input("\nDo you want to keep playing? ")
if keep_playing in ("1", "o", "O", "y", "Y",
"oui", "yes", "Oui", "Yes"):
os.system("clear")
hangman()
elif keep_playing in ("2", "n", "N", "non", "no", "Non", "No"):
os.system("clear")
sys.exit(0)
else:
raise ValueError("Input must be either 'y' or 'n'")
except ValueError:
pass
| false |
3adffc3289a2bbc46051b618b644bce205bd3624 | sdamico23/sort-methods | /mergeSort.py | 923 | 4.125 | 4 | #LAB 13
#Due Date: 11/18/2018, 11:59PM
########################################
#
# Name:Collin Michaels
# Collaboration Statement:
#
########################################
def merge(list1, list2):
#write your code here
newList = []
z = 0
y = 0
while z < len(list1) and y < len(list2): #loop through lists and append them into newlist according to value
if list1[z] < list2[y]:
newList.append(list1[z])
z += 1
else:
newList.append(list2[y])
y += 1
newList += list1[z:]
newList += list2[y:]
return newList
def mergeSort(numList):
#write your code here
if len(numList) <= 1:
return numList
midpt = len(numList)//2
lefthalf = mergeSort(numList[:midpt])
rightHalf = mergeSort(numList[midpt:])
return merge(lefthalf,rightHalf)
| false |
2d75c379c24fc87753ab6d92fd84c1ba0518eec2 | edu-athensoft/ceit4101python | /stem1400_modules/module_6_datatype/m6_4_string/string_demo/string_21_strip.py | 620 | 4.5 | 4 | """
string method - strip()
returns a copy of the string by removing both the leading and the trailing characters
"""
# case 1.
s = ' xoxo python xoxo '
print(f"|{s}|")
print(f"|{s.strip()}|")
# case 2.
s = ' xoxo python xoxo '
print(f"|{s}|")
print(f"|{s.strip('xo')}|")
print(f"|{s.strip(' xo')}|")
s = ' oxoxoxoab python abxoxoxoo '
print(f"|{s.strip(' xo')}|")
# case 3.
s = 'android is awesome'
print(f"|{s.strip('an')}|")
# application
name = input("Enter your name:")
print(f"|{name}|")
if name.strip() == 'peter':
# if name == 'peter':
print("correct username!")
else:
print("incorrect!")
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.