blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
e2e03bfddd00898d64abc3ec02606d52bf08c088 | sylvesteryiadom/100DaysofPython | /RockPaperScissors.py | 1,708 | 4.25 | 4 | import random
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
options1 = [rock, paper, scissors] # putting image in a list
options2 = ['rock', 'paper', 'scissors'] # string list of options
cRandom = random.randint(0,len(options1)-1) #creating random number generator for computer
computerChoice = options1[cRandom] # selecting computer choice based on random Number
uchoice = int(input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors. ")) #asking for user input
userChoice = options1[uchoice] #selecting options based on user input
print("You chose:\n") #displaying user input
print(userChoice)
userChoice = options2[uchoice] #using the userNumber to select same string option
print("Computer chose:\n") #displaying computer input
print(computerChoice)
computerChoice = options2[cRandom] #using random number to select string option for comparison
# implementing RPS rules
if(userChoice == 'rock') and (computerChoice == 'scissors'):
print("You win")
elif (userChoice == 'scissors') and (computerChoice == 'rock'):
print("You loose")
elif (userChoice == 'scissors') and (computerChoice == 'paper'):
print("You win")
elif (userChoice == 'paper') and (computerChoice == 'scissors'):
print("You loose")
elif (userChoice == 'paper') and (computerChoice == 'rock'):
print("You win")
elif (userChoice == 'rock') and (computerChoice == 'paper'):
print("You loose")
else:
print("Its a tie")
| false |
2d08e5559a47282cb57988b0f279e707d8ccaf5d | desenvolvefacil/SSC0800-2019-02-Introducao-a-Ciencia-de-Computao-I | /SSC0800 (2019-02) - Introdução à Ciência de Computação I/EX 005 - Lista 1 - Dados e Expressões - Conversão de graus para radianos.py | 800 | 4.25 | 4 | '''
Conversão de graus para radianos
Desenvolva um algoritmo que leia um número representando um ângulo qualquer entre 0º e 360º, calcule e escreva seu correspondente em radianos (rad = PI*angulo/180).
Entrada: Um número real (angulo), sendo 0 <= angulo <= 360.
Saída: Um número real representando o valor do ângulo em radianos impresso com 6 casas decimais.
Dica 1: Para PI, utilize math.pi,
Dica 2: inclua import math no início do seu código
Dica 3: arredondar em 6 casas decimais usando round(valor,6)
Exemplos de Entrada e Saída
Entrada:
0
Saída:
0.0
Entrada:
180
Saída:
3.141593
'''
import math
# le o valor do angulo
angulo = float(input())
# calcula o valor do angulo em radianos:
radiano = float(math.pi * angulo / 180)
# impreme o valor:
print(round(radiano,6)) | false |
faf36b43997b837bbdcbee745b57b699bb3d71e0 | desenvolvefacil/SSC0800-2019-02-Introducao-a-Ciencia-de-Computao-I | /SSC0800 (2019-02) - Introdução à Ciência de Computação I/EX 018 - Lista 3 - Funções - Lado do Triângulo.py | 1,541 | 4.59375 | 5 | '''
Lista 3 - Funções - Lado do Triângulo
Desenvolva um programa onde o usuário fornece as medidas dos três lados de um triângulo e o tipo de triângulo (escaleno, isósceles ou equilátero) é escrito na tela. Lembre-se, você deve verificar também o critério de formação de triângulo, onde um lado qualquer não pode ser maior que a soma dos outros dois. Logo, o programa deve ter duas funções: uma função classificatriangulo() que recebe as medidas e imprime o tipo de triangulo, e uma função Ehtriangulo() que recebe as medidas e retorna 1 se for triangulo e 0, caso contrário.
Dica: Use os seguinte formatadores print:
print("Triangulo Equilatero")
print("Triangulo Isosceles")
print("Triangulo Escaleno")
print ("Valores nao formam um triangulo")
Exemplo de Entrada e Saída
Entrada:
2
3
4
Saída:
Triangulo Escaleno
'''
#Define se e ou não um triangulo
def ehTriangulo(ladoA,ladoB,ladoC):
#retorna 1 se for triangulo 0 caso contrario
if (ladoA+ladoC<ladoB or ladoC+ladoB<ladoA or ladoA+ladoB<ladoC):
return 0
return 1
def classificaTriangulo(ladoA,ladoB,ladoC):
if(ladoA == ladoB == ladoC):
return "Triangulo Equilatero"
elif(ladoA==ladoB or ladoA==ladoC or ladoB==ladoC):
return "Triangulo Isosceles"
else:
return "Triangulo Escaleno"
ladoA = int(input())
ladoB = int(input())
ladoC = int(input())
if(ehTriangulo(ladoA,ladoB,ladoC)==1):
print(classificaTriangulo(ladoA,ladoB,ladoC))
else:
print ("Valores nao formam um triangulo") | false |
c5d4cab2d44872f33f0a2a8d0dfedebfbd5f5930 | paralleasty/DSA | /Python/tree.py | 2,319 | 4.15625 | 4 | # 每个节点都是BinaryTree类的一个实例
class BinaryTree:
def __init__(self, rootObj):
self.key = rootObj
self.leftChild = None
self.rightChild = None
def insertLeft(self, newNode):
'''现有leftChild为None, 或存在'''
if self.leftChild is None:
self.leftChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.leftChild = self.leftChild
self.leftChild = t
def insertRight(self, newNode):
if self.leftChild is None:
self.rightChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.rightChild = self.rightChild
self.rightChild = t
def getLeftChild(self):
return self.leftChild
def getRightChild(self):
return self.rightChild
def setRootValue(self, obj):
self.key = obj
def getRootValue(self):
return self.key
# 前序遍历作为类的方法
def preorder(self):
print(self.key)
if self.leftChild:
self.leftChild.preorder()
if self.rightChild:
self.rightChild.preorder()
# 树的遍历
# 前序遍历
def preorder(tree):
'''先访问根节点,然后依次递归地前序遍历左子树和右子树'''
if tree:
print(tree.getRootvalue())
preorder(tree.getLeftChild())
preorder(tree.getRightChild())
# 后序遍历
def postorder(tree):
'''先遍历左右子树, 然后访问根节点'''
if tree is not None:
postorder(tree.getLeftChild())
postorder(tree.getRightChild())
print(tree.getRootvalue)
# 中序遍历
def inorder(tree):
'''先递归遍历左子树,然后访问根节点, 最后递归遍历右子树'''
if tree is not None:
inorder(tree.getLeftChild())
print(tree.getRootvalue())
inorder(tree.getRightChild())
if __name__ == '__main__':
r = BinaryTree('a')
r.insertLeft('b')
r.insertRight('c')
print(r.getRootValue())
print(r.getLeftChild()) # BinaryTree的一个实例
print(r.getRightChild())
print(r.getLeftChild().getRootValue())
print(r.getRightChild().getRootValue())
r.getRightChild().setRootValue('hello')
print(r.getRightChild().getRootValue())
| false |
d9a13c6679160d8ad23b3a5f52a5c0c4327855fb | ravisrhyme/CTCI | /chapter11/11.3.py | 1,359 | 4.15625 | 4 | """
Given a sorted array of n integers that has been rotated an unknown number of
times, write code to find an element in the array. You may assume that the array
was originally in increasing order.
Time Complexity : O(log(n)) if all elements are distinct
Space Complexity : O(1)
"""
__author__ = "Ravi Kiran Chadalawada"
__email__ = "rchadala@usc.edu"
__credits__ = ["Cracking The coding interview"]
__status__ = "Prototype"
def find_element(element_list,element):
start = 0
end = len(element_list) - 1
while (start <= end):
mid = (start + end) // 2 # Integer division in python3
if element == element_list[mid]:
return mid
# Key thought here is either the left or right half is always normal.
# i.e Ascending. Using that observation to decide to move left or right
elif element_list[start] <= element_list[mid]: # Left half is normal and ascending
if element >= element_list[start] and element < element_list[mid]:
#move left
end = mid - 1
else:
# Move right
start = mid + 1
elif element_list[start] > element_list[mid]: #Right half is normal and ascending
if element <= element_list[end] and element > element_list[mid]:
#Move right
start = mid + 1
else :
# Move left
end = mid - 1
return None
if __name__=='__main__':
element_list = [10,15,20,0,5]
print(find_element(element_list,5))
| true |
ccca61b6932881326b2fabcf094d5ff0f22d5795 | ravisrhyme/CTCI | /python_demos/decorators.py | 471 | 4.34375 | 4 | """
Demo to understand decorators in python.
"""
__author__ = "Ravi Kiran Chadalawada"
__email__ = "rchadala@usc.edu"
__credits__ = ["https://www.python-course.eu/python3_decorators.php"]
__status__ = "Prototype"
def our_decorator(func):
def function_wrapper(x):
print("Before calling " + func.__name__)
res = func(x)
print(res)
print("After calling " + func.__name__)
return function_wrapper
@our_decorator
def succ(n):
return n + 1
succ(10)
| false |
a4f160d6668ed485d038ce1ff584272c2fb3d100 | ravisrhyme/CTCI | /IC/find_kth_from_last.py | 1,043 | 4.15625 | 4 | """
You have a linked list and want to find the kth to last node.
Write a function kth_to_last_node() that takes an integer kk and the head_node of
a singly linked list, and returns the kth to last node in the list.
Time Complexity = O(n)
Space Complexity : O(1)
Done in a single pass
"""
__author__ = "Ravi Kiran Chadalawada"
__email__ = "rchadala@usc.edu"
__credits__ = ["Interviewcake.com"]
__status__ = "Prototype"
class linked_list:
def __init__(self,value):
self.data = value
self.next = None
def kth_to_last_node(head,k):
""" Returns the Kth element from last node
"""
first_pointer = head
second_pointer = head
i = 0
while first_pointer :
if ( i > k ):
second_pointer = second_pointer.next
first_pointer = first_pointer.next
i += 1
if (i <= k):
raise Exception("Length of list less than k")
else :
return second_pointer
if __name__=='__main__':
a = linked_list(1)
b = linked_list(2)
c = linked_list(3)
d = linked_list(4)
a.next = b
b.next = c
c.next = d
node = kth_to_last_node(a,0)
print(node.data)
| true |
ab9f4587876f318d28329cf8945be3ecb25ce73f | ravisrhyme/CTCI | /chapter9/9.3.py | 2,253 | 4.1875 | 4 | """
A magic index in an array A[1...n-1] is defined to be an index such that A[i] = i
Given a sorted array of distinct integers, write a method to find a magic index,
if one exists, in an array.
Follow up:
What if the values are not distinct
Time complexity : O(n) in brute force.
O(log(n)) if binary search is applied
Space complexity : O(1)
"""
__author__ = "Ravi Kiran Chadalawada"
__email__ = "rchadala@usc.edu"
__credits__ = ["Cracking The coding interview"]
__status__ = "Prototype"
def find_magic_binary_distinct(sorted_array):
""" Returns the magic number by performing a binary search
"""
start = 0
end = len(sorted_array) - 1
while start <= end:
mid = int((start + end)/2)
if sorted_array[mid] == mid:
return mid
elif sorted_array[mid] < mid : # Search right half if key < index
start = mid + 1
else: # search left half
end = mid - 1
return -1
def find_magic_binary_not_distinct(sorted_array,start,end):
""" If elements are not distinct, we cannot eliminate one half of tree
as in binary search. We traverse both left and right subtree. We can
jump to indices of mid_value as that is the minimum possibility of having
the magic index condition.
"""
if (end < start) or (start < 0) or (end >= len(sorted_array)):
return -1
mid_index = int((start + end)/2)
mid_value = sorted_array[mid_index]
if mid_index == mid_value:
return mid_index
left_index = min(mid_index-1,mid_value)
left_found = find_magic_binary_not_distinct(sorted_array,start,left_index)
if left_found >= 0:
return left_found
right_index = max(mid_index+1,mid_value)
right_found = find_magic_binary_not_distinct(sorted_array,right_index,end)
return right_found
def find_magic_brute_force(sorted_array):
""" Returns the magic index.
Time complexity : O(n)
space complexity : O(1)
"""
for i in range (0,len(sorted_array)):
if i == sorted_array[i]:
return i
if __name__=='__main__':
distinct_sorted_array = [-40,-20,-1,1,2,3,5,7,9,12,13]
not_distinct_sorted_array = [-40,-20,2,2,2,3,5,7,9,12,13]
print(find_magic_brute_force(distinct_sorted_array))
print(find_magic_binary_distinct(distinct_sorted_array))
print(find_magic_binary_not_distinct(not_distinct_sorted_array,0,len(not_distinct_sorted_array)-1))
| true |
697a91dda3ec0dee032779b90c218af7d4979a36 | ravisrhyme/CTCI | /CFI/hash_table.py | 2,823 | 4.25 | 4 | """
Implementation of hashtable
"""
__author__ = "Ravi Kiran Chadalawada"
__email__ = "rchadala@usc.edu"
__credits__ = ["Brian Jordan"]
__status__ = "Prototype"
table_size = 1000
class hash_table:
""" Implementation of simple hash table
"""
def __init__(self):
# made value of table as list to handle collisions
self.table = [[None]] * table_size
def insert(self,string):
""" Inserts a string after getting its hash value in to table.
"""
index = self.shift_and_add_hash(string)
print('index is ', index)
# Appending string to list of values at index
self.table[index].append(string)
def lookup(self,string):
""" Returns a boolean basing on presence or absence of string at index
"""
index = self.shift_and_add_hash(string)
print('index is ', index)
if string in self.table[index]:
return True
else:
return False
def additive_hash(self,string):
"""Implementation of additive hash
"""
h = ord(string[0])
length_of_string = len(string)
for i in range(1,length_of_string):
h += ord(string[i])
return h % table_size
def xor_hash(self,string):
""" Implementation of XOR hashing algorithm
"""
h = ord(string[0])
length_of_string = len(string)
for i in range(1,length_of_string):
h ^= ord(string[i])
return h % table_size
def rotating_hash(self,string):
"""Implementation of rotating hashing algorithm
"""
h = ord(string[0])
length_of_string = len(string)
for i in range(1,length_of_string):
h = (h << 4) ^ (h >> 28) ^ ord(string[i])
return h % table_size
def bernstein_hash(self,string):
"""Implementation of bernstein hashing algorithm
"""
h = ord(string[0])
length_of_string = len(string)
for i in range(1,length_of_string):
h = 33 * h + p[i];
return h % table_size
def modified_bernstein_hash(self,string):
"""Implementation of modified bernstein hashing algorithm
"""
h = ord(string[0])
length_of_string = len(string)
for i in range(1,length_of_string):
h = 33 * h ^ ord(string[i]);
return h % table_size
def shift_add_xor_hash(self,string):
"""Implementation of shift-add-XOR hashing algorithm
"""
h = ord(string[0])
length_of_string = len(string)
for i in range(1,length_of_string):
h ^= (h << 5) + (h >> 2) + ord(string[i]);
return h % table_size
def shift_and_add_hash(self,string):
""" Computes and returns hash index for a given string.
Has two components :
1. calculating hash code(unbounded i.e h)
2. calculating compressed index i.e h % tablesize
Using shift and add algorithm for #1 below
"""
h = ord(string[0])
length_of_string = len(string)
for i in range(1,length_of_string):
h = (h << 4) + ord(string[i])
print('h is', h)
return h % table_size
if __name__=='__main__':
ht = hash_table()
ht.insert('ravi')
print(ht.lookup('ravi'))
| true |
968959850a0d0abd1b60289c0ecc279b18dba4db | nbenlin/beginners-python-examples | /1-Basic Python Objects and Data Structures/2_exapmle.py | 222 | 4.28125 | 4 | # Take the two perpendicular sides (a, b) of a right triangle from the user and try to find the length of the hypotenuse.
a = int(input("a: "))
b = int(input("b: "))
c = (a ** 2 + b ** 2) ** 0.5
print("Hypotenuse: ", c)
| true |
918ea42698dd84acdccd7223f4536a9658f4a5cb | ducc/all-project-1 | /networked/client/src/board.py | 1,597 | 4.1875 | 4 | """Handles the "screen" of a game"""
import os
class Board:
"""Represents a tic-tac-toe board"""
SIZE = 3
def __init__(self):
self.tiles = [[""] * self.SIZE for i in range(self.SIZE)]
self.__create_labels()
self.draw()
def __create_labels(self):
counter = 0
for i in range(self.SIZE):
for j in range(self.SIZE):
counter += 1
self.tiles[i][j] = counter
def __print_devider(self):
print('|'.join(['____' for x in range(self.SIZE)]))
def __print_blank(self):
print('|'.join([' ' for x in range(self.SIZE)]))
def __print_labels(self, counter):
row = ' | '.join(['%2s' % self.tiles[counter][x] for x in range(self.SIZE)])
row = ' ' + row
print(row)
def draw(self):
"""Renders the board"""
for i in range(self.SIZE):
self.__print_blank()
self.__print_labels(i)
if (i == self.SIZE - 1):
self.__print_blank()
else:
self.__print_devider()
def clear(self):
"""Clears the screen ready for the board to be drawn again"""
# command to clear the screen is different depending on the OS
if os.name is "nt": # check if the os is windows
os.system("cls")
else: # clear is used on most unix based systems
os.system("clear")
def set_tile(self, tile, value):
"""Sets the label of the specified tile"""
self.tiles[tile // self.SIZE][tile % self.SIZE] = value | false |
d4603894da27792f66d317d173410e36f83cdbcd | mathiazom/TDT4113 | /P2 Rock, Scissors, Paper/action.py | 918 | 4.1875 | 4 | """
TDT4113 - Computer Science, Programming Project (Spring 2021)
Project 2 Rock, Scissors, Paper
made with ❤ by mathiom
Defines the concept of an action in Rock, Paper, Scissors
"""
from enum import Enum
import random
class Action(Enum):
"""Represents one of the three choices in Rock, Paper, Scissors"""
ROCK = 1
PAPER = 2
SCISSORS = 3
def counter(self):
"""Get the action that beats this action"""
if self is Action.ROCK:
return Action.PAPER
if self is Action.PAPER:
return Action.SCISSORS
if self is Action.SCISSORS:
return Action.ROCK
raise Exception("Action not recognized")
def __gt__(self, other):
return self is other.counter()
def get_random_action():
"""Randomly pick from the available actions"""
return Action(random.randint(1, len(Action)))
| true |
f47fd9f353c7fd42d516224ceb09bbae551a5e77 | Daiani34/learning-python | /Cap2-decisoes/decisao-encadeada.py | 864 | 4.15625 | 4 | nome = input(" Digite o nome do paciente: ")
idade = int(input(" Digite a idade: "))
doenca_infectocontagiosa = input(" O paciente tem sintomas de doenças infectocontagiosas?").upper()
if doenca_infectocontagiosa == "SIM":
print(" Encaminhe o paciente para sala amarela ")
elif doenca_infectocontagiosa == "NAO":
print(" Encaminhe o paciente para a sala branca")
else:
print("Responda a suspeita de doença infectocontagiosa com SIM ou NAO")
if idade >= 65:
print("Paciente COM prioridade ")
else:
genero = input("Qual o gênero do paciente? ").upper()
if genero=="FEMININO" and idade > 10:
gravidez = input("A paciente está grávida?").upper()
if gravidez == "SIM":
print("Paciente COM prioridade")
else:
print("Paciente SEM prioridade")
else:
print("Paciente SEM prioridade")
| false |
dd0dff65bc17462380600cd90d12493c9244bda0 | anhnguyendepocen/introduction_to_python | /src/03_logical_while_if.py | 1,553 | 4.40625 | 4 | # -*- coding: utf-8 -*-
"""
Introduction to Python, 3
Created on Thu Jan 18 20:57:01 2018
@author: Claire Kelling
The purpose of this file is to learn how to do logical operations
and if statements/while loops.
"""
#####
## Basics of logic in Python
#####
2 == 3
2 == 2
2 > 3
2 >= 2 #greater than or equal to
2 != 3 #not equal to
2 != 3 and 2 < 3
2 != 3 or 2 > 3
True
False
True and False
True or False
False and False
# Checking if a string is in another string
str1 = 'hello'
'h' in str1
'hell' in str1
'q' in str1
'q' not in str1
# Checking if a value is in a list
primes = [2, 3, 5, 7, 11, 13, 17]
3 in primes
4 in primes
4 not in primes
#####
## If Statements
#####
a = eval(input("Enter 2 or any other number: ")) # Ask user for some number
if a == 2:
print('a is equal to 2') #doesn't do anything if a not equal 2
a = eval(input("Enter 2 or any other number: ")) # Ask user for some number
if a == 2:
print('a is equal to 2')
else: # ifelse statement
print('a is not equal to 2')
#Also, we can use else if (syntax is elif)
a = eval(input("Enter 2 or any other number: ")) # Ask user for some number
if a == 2:
print('a is equal to 2')
elif a == 3:
print('a is equal to 3')
else: # ifelse statement
print('a is not equal to 2 or 3')
####
## While loops
####
a = 1
while a != 8:
print(a)
a = a + 1
print('...')
print('Congratulations.') # when it is finished
a = 2
while a < 7:
a += 1 #shorthand for the a = a+1
print(a)
a = 1
while a <= 32:
a *= 2 # shorthand for a = 2a
print(a) | true |
cc1f6a75ae90b1c47528d62cc1c982117146cb22 | vyhuholl/42_python | /Day01/ex09/caesar.py | 1,198 | 4.1875 | 4 | import sys
def encode(string, shift):
ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
printable = set(
ascii_lowercase + ascii_uppercase + '0123456789' +
r'!\"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~' + ' \t\n\r\f\v'
)
res = ''
for char in string:
if char not in printable:
raise ValueError(' The script does not support your language yet')
elif char in ascii_lowercase:
res += ascii_lowercase[(ascii_lowercase.index(char) + shift) % 26]
elif char in ascii_uppercase:
res += ascii_uppercase[(ascii_uppercase.index(char) + shift) % 26]
else:
res += char
return res
if __name__ == '__main__':
if len(sys.argv) == 1:
print('usage: python3 caesar.py option string shift')
elif len(sys.argv) == 4:
if sys.argv[1] == 'encode':
print(encode(sys.argv[2], int(sys.argv[3])))
elif sys.argv[1] == 'decode':
print(encode(sys.argv[2], -int(sys.argv[3])))
else:
raise ValueError('Incorrect option')
else:
raise ValueError('Incorrect number of arguments')
| false |
83a1df2c6d8458bdd8869720a9f34a43bd202a4f | AdonisHan/evaluations_ | /src/enumerate.py | 512 | 4.125 | 4 | def enumerate(number,values=0):
n = values
for element in number:
yield n, element
n += 1
seasons = ['Spring','Summer','Fall','Winter']
print(list(enumerate(seasons)))
seasons_per_sequence = ['one','two','three','four']
seasons = ['Spring','Summer','Fall','Winter']
for numbers,values in zip(seasons_per_sequence,seasons):
print('numbers:{},values:{}'.format(numbers,values))
numbers:one,values:Spring
numbers:two,values:Summer
numbers:three,values:Fall
numbers:four,values:Winter | true |
8e38c475ee95e7743a7fb5d145b3c86ee3b6066b | adamcfro/code-abbey-solutions | /modulo_and_time_difference.py | 931 | 4.21875 | 4 | def time_difference(time1, time2):
'''This function takes in days, hours, minutes, and seconds from two days and determines how far apart the two days are.'''
day = 86400 # 60 * 60 * 24
hour = 3600 # 60 * 60
minute = 60 # 60
second = 1 # 1
seconds1 = 0
seconds1 += (time1[0] * day) + (time1[1] * hour) + (time1[2] * minute) + time1[3]
seconds2 = 0
seconds2 += (time2[0] * day) + (time2[1] * hour) + (time2[2] * minute) + time2[3]
difference = seconds2 - seconds1
day_diff = int(difference / day)
difference %= day
hour_diff = int(difference / hour)
difference %= hour
min_diff = int(difference / minute)
difference %= minute
sec_diff = int(difference / second)
difference %= second
return day_diff, hour_diff, min_diff, sec_diff
print(time_difference([1, 0, 0, 0], [2, 3, 4, 5]))
print(time_difference([5, 3, 23, 22], [24, 4, 20, 45])) | true |
4b6a26c53b737986aad9289a88b3deeab0bffd46 | adamcfro/code-abbey-solutions | /smoothing_the_weather.py | 606 | 4.28125 | 4 | def smoothing(lst):
'''This function takes in a list of numbers and returns a list of numbers where the current number, the previous number, and the following number are added together then divided by three. The first and last numbers are untouched.'''
my_list = []
my_list.append(lst[0])
for i in range(1, len(lst) - 1):
number = (lst[i] + lst[i + 1] + lst[i - 1]) / 3
# number = sum(lst[i - 1: i + 2]) / 3
my_list.append(number)
my_list.append(lst[-1])
return my_list
print(smoothing([32.6, 31.2, 35.2, 37.4, 44.9, 42.1, 44.1]))
try this with enumerate | true |
97607519aebc1feb5e200b51a2342193852e4aea | qingxiaoye/python-summary | /a_base/f_oop/a_封装.py | 877 | 4.15625 | 4 | # !/usr/bin/python
# -*- coding:utf-8 -*-
import time
"""
封装性
__speed私有化
私有属性,只能被 Animal3类 内的所有方法引用,如被方法getSpeed方法引用。
但是,不能被其他类引用,也不能被 __str__ 引用
AttributeError: 'Animal2' object has no attribute '_Manager__speed'
"""
class Animal3:
def __init__(self, name, speed):
self.name = name
self.__speed = speed
def getSpeed(self):
print(self.__speed)
class Manager:
def __init__(self, animal):
self.animal = animal
def recordTime(self):
print('feeding time for %s(行走速度为:%s) ' % (self.animal.name, self.animal.__speed))
cat = Animal3('加菲猫', 8)
cat.getSpeed()
xiaoming = Manager(cat)
xiaoming.recordTime()
# AttributeError: 'Animal3' object has no attribute '_Manager__speed'
| false |
70857e7b5f93774929672064ea6dcda6797a117f | jrgosalia/Python | /problem5_posterize.py | 2,055 | 4.15625 | 4 | """
Program : problem5_posterize.py
Author : Jigar R. Gosalia
Verion : 1.0
Course : CSC-520 (Homework 2)
Prof. : Srinivasan Mandyam
Define and test a function named posterize.
This function expects an image and a tuple of RGB values as arguments.
The function modifies the image like the blackAndWhite function, but
uses the given RGB values instead of black.
"""
import os
from PIL import Image
from library import validImageFile
from library import validInt
def blackAndWhite(rgbTuple, image):
""" Converts the image to black and white from given RGB value. """
whitePixel = (255, 255, 255)
for y in range(image.height):
for x in range(image.width):
(r, g, b) = image.getpixel((x, y))
average = (r + g + b)/3
if average < 128:
image.putpixel((x, y), rgbTuple)
else:
image.putpixel((x, y), whitePixel)
def main():
""" Main Method. """
print("\n" * 10)
print("Posterize given image from given RGB value to black and white", end="\n\n");
input("Press ENTER to start execution ... \n");
fileName = input("Enter valid image file path (RELATIVE ONLY and NOT ABSOLUTE): ")
while not validImageFile(os.getcwd() + os.sep + fileName):
fileName = input("Enter valid image file path (RELATIVE ONLY and NOT ABSOLUTE): ")
red = input("Enter value of RED[0-255] in RGB: ")
while not validInt(red):
red = input("Enter value of RED[0-255] in RGB: ")
green = input("Enter value of GREEN[0-255] in RGB: ")
while not validInt(green):
green = input("Enter value of GREEN[0-255] in RGB: ")
blue = input("Enter value of BLUE[0-255] in RGB: ")
while not validInt(blue):
blue = input("Enter value of BLUE[0-255] in RGB: ")
rgbTuple = (int(red), int(green), int(blue))
image = Image.open(fileName)
print("Close the image window to continue.")
image.show()
blackAndWhite(rgbTuple, image)
print("Close the image window to quit.")
image.show()
"""
Starting point
"""
main()
| true |
ae44c75b6eadeaa331ffd3c3cbd09de88c8e3d16 | theJalden/FLS_Python_Tutorial | /merge.py | 1,733 | 4.1875 | 4 | # Recursive sorting
# "Divide and conquer"
# - Take a large list
# - Divide it into 2 or more smaller lists
# - Sort the smaller lists, put the sorted smallers lists
# back together
def merge_sort(nums):
if len(nums) <= 1:
return nums
else:
# choose a pivot point
pv = len(nums) // 2
l1 = nums[:pv]
l2 = nums[pv:]
l1 = merge_sort(l1)
l2 = merge_sort(l2)
print(l1)
print(l2)
# merge two sorted lists
ret_list = []
ii, jj = 0, 0
while ii < len(l1) and jj < len(l2):
if l1[ii] < l2[jj]:
ret_list.append(l1[ii])
ii += 1
else:
ret_list.append(l2[jj])
jj += 1
# if one of the lists has an element remaining
# add it to the end of the list
if ii < len(l1):
ret_list = ret_list + l1[ii:]
elif jj < len(l2):
ret_list = ret_list + l2[jj:]
print(ret_list)
return ret_list
# Take the first number in a list, use as a pivot
# Put every other element into one of two smaller lists
# - One list: list_1 has elements < pv
# - Other list: list_ 2 has elements >= pv
# Recursive quick_sort on list_1 and list_2
# return sorted list_1 + [pv] + sorted list_2
def quick_sort(nums):
if len(nums) <= 1:
return nums
else:
pv = nums[0]
larger = []
smaller = []
for ii in nums[1:]:
if ii >= pv:
larger.append(ii)
else:
smaller.append(ii)
l2 = quick_sort(larger)
l1 = quick_sort(smaller)
return l1 + [pv] + l2
| true |
6894dc6e9f690e0c5dfd602c07a81bf6f066649c | theJalden/FLS_Python_Tutorial | /euler1.py | 380 | 4.1875 | 4 |
# Number -> Boolean
# Return True if given number is a multiple of 3
# False otherwise
def isMultipleOf3(n):
return (n % 3) == 0
# Number -> Boolean
# Return True if given number is a multiple of 5
# False otherwise
def isMultipleOf5(n):
return (n % 5) == 0
summa = 0
for x in range(1000):
if isMultipleOf3(x) or isMultipleOf5(x):
summa += x
print(summa)
| true |
f43731aa5bd97d2e96b2e3ed66bbcc39cb7be6b1 | aye-am-rt/python-practice | /Matrixes/SearchWordIn2DGrid.py | 2,939 | 4.125 | 4 | """
Search a Word in a 2D Grid of characters
Given a 2D grid of characters and a word, find all occurrences of given word in grid. A word can
be matched in all 8 directions at any point. Word is said be found in a direction if all characters
match in this direction (not in zig-zag form).
The 8 directions are, Horizontally Left, Horizontally Right, Vertically Up and 4 Diagonal directions.
Example:
Input: grid[][] = {"GEEKSFORGEEKS",
"GEEKSQUIZGEEK",
"IDEQAPRACTICE"};
word = "GEEKS"
Output: pattern found at 0, 0
pattern found at 0, 8
pattern found at 1, 0
Input: grid[][] = { "GEEKSFORGEEKS",
"GEEKSQUIZGEEK",
"IDEQAPRACTICE"};
word = "EEE"
Output: pattern found at 0, 2
pattern found at 0, 10
pattern found at 2, 2
pattern found at 2, 12
The idea used here is simple, we check every cell. If cell has first character, then we one by one try all
8 directions from that cell for a match. Implementation is interesting though. We use two arrays x[]
and y[] to find next move in all 8 directions.
"""
class SearchInGrid:
def __init__(self):
self.R = None
self.C = None
self.directions = [[-1, 0], [1, 0], [1, 1], [1, -1], [-1, -1], [-1, 1], [0, 1], [0, -1]] # 8 dirs.
# IN JAVA THIS CAN BE DONE LIKE THIS.
# //Rows and columns in given grid
# static int R, C;
# //searching in all 8 direction
# static int[] x = { -1, -1, -1, 0, 0, 1, 1, 1 };
# static int[] y = { -1, 0, 1, -1, 1, -1, 0, 1 };
def patternSearch(self, grid, word):
self.R = len(grid)
self.C = len(grid[0])
for row in range(self.R):
for col in range(self.C):
if self.search8Directions(grid, row, col, word):
print(word, " pattern found at (i,j)=" + str(row) + " " + str(col))
def search8Directions(self, grid, row, col, word):
if grid[row][col] != word[0]:
return False
for x, y in self.directions:
rd, cd = row + x, col + y # int k, rd = row + x[i], cd = col + y[i]; in java
flag = True
# First character is already checked, match remaining characters
for k in range(1, len(word)):
if 0 <= rd < self.R and 0 <= cd < self.C and word[k] == grid[rd][cd]:
# Moving in particular direction
rd += x
cd += y
else: # If out of bound or not matched, break
flag = False
break
if flag:
return True
return False
if __name__ == '__main__':
Grid = ["GEEKSFORGEEKS",
"GEEKSQUIZGEEK",
"IDEQAPRACTICE"]
sig = SearchInGrid()
sig.patternSearch(Grid, 'GEEKS')
print('**********')
sig.patternSearch(Grid, 'EEE')
print('**********')
sig.patternSearch(Grid, 'QSF')
| true |
34d2270de16f77307661c797bd96fda83974aa9c | aye-am-rt/python-practice | /PyCS_CG/oops_CS/DecoratorsGS.py | 1,334 | 4.15625 | 4 | class Employee:
def __init__(self, first, last):
self.first = first
self.last = last
@property
def email(self):
return '{}.{}@email.com'.format(self.first, self.last)
# property decorator allows us to define a method but we can use it as an attribute.
@property
def fullname(self):
return '{} {}'.format(self.first, self.last)
# without setter python throws error coz it doesnt knows how to set full name from a given string.
@fullname.setter
def fullname(self, name):
first, last = name.split(' ')
self.first = first
self.last = last
@fullname.deleter
def fullname(self):
print('Delete Name!')
self.first = None
self.last = None
emp_1 = Employee('John', 'Smith')
emp_1.fullname = "Corey Schafer" # what if we want to set emp name by giving string like this and also want it to
# automatically set first name last name and email of that employee.
# thats why here we use @<any_method_name>.setter or deleter.
print(emp_1.first)
print(emp_1.email) # if we dont make that a property we have to call it like a method emp1.email()
# that is not good coz it will break the code for other people who was using class before this change.
print(emp_1.fullname)
del emp_1.fullname # this is way of calling deleter method.
| true |
44a5302e36e4bddcc1f167c3ca3fe399e7db1989 | aye-am-rt/python-practice | /Strings/KUniquesIntSubs/LexoSmallest1Swap.py | 2,034 | 4.1875 | 4 | # Find lexicographically smallest string in at most one swaps
# Given a string str of length N. The task is to find out the lexicographically smallest
# string when at most only one swap is allowed. That is, two indices 1 <= i, j <= n can be
# chosen and swapped. This operation can be performed at most one time.
#
# Examples:
#
# Input: str = “string”
# Output: gtrins
# Explanation:
# Choose i=1, j=6, string becomes – gtrins. This is lexicographically smallest strings that
# can be formed.
"""
Approach: The idea is to use sorting and compute the smallest lexicographical string possible
for the given string. After computing the sorted string, find the first unmatched character
from the given string and replace it with the last occurrence of the unmatched character in the
sorted string.
For example, let str = “geeks” and the sorted = “eegks”. First unmatched character is in the
first place. This character has to swapped such that this character matches the character with
sorted string. Resulting lexicographical smallest string. On replacing “g” with the last
occurring “e”, the string becomes eegks which is lexicographically smallest."""
def findLexicoSmallest1Swap(strAsList):
if len(strAsList) < 1:
print(" size small ")
return -1
# print(list(zip(strAsList, sorted(strAsList))))
i = 0
while sorted(strAsList)[i] == strAsList[i] and i < len(strAsList):
i += 1
firstMisMatchIndex = i
firstMisMatchChar = sorted(strAsList)[i]
lastMisMatchIndex = i
i += 1
while i < len(strAsList):
if strAsList[i] == firstMisMatchChar:
lastMisMatchIndex = i
i += 1
print(f"{firstMisMatchIndex}, {firstMisMatchChar}, {lastMisMatchIndex}")
strAsList[firstMisMatchIndex], strAsList[lastMisMatchIndex] = \
strAsList[lastMisMatchIndex], strAsList[firstMisMatchIndex]
# print(strAsList)
return "".join(strAsList)
if __name__ == "__main__":
s = "geeks"
print(findLexicoSmallest1Swap(list(s)))
| true |
51158bd49c0c3240efe24372c604a9b14f7a9002 | aye-am-rt/python-practice | /Strings/KUniquesIntSubs/IntelligentSubStringsLin.py | 2,795 | 4.25 | 4 | """Intelligent Substrings:
There are two types of characters in a particular language: special and normal. A character is
special if its value is 1 and normal if its value is 0. Given string s, return the longest
substring of s that contains at most k normal characters. Whether a character is normal is
determined by a 26-digit bit string named charValue. Each digit in charValue corresponds to a
lowercase letter in the English alphabet.
Example:
s = 'abcde'
For clarity, the alphabet is aligned with charValue below:
alphabet = abcdefghijklmnopqrstuvwxyz
charValue = 10101111111111111111111111
The only normal characters in the language (according to charValue) are b and d. The string s
contains both of these characters. For k = 2, the longest substring of s that contains at
most k = 2 normal characters is 5 characters long, abcde, so the return value is 5. If k = 1
instead, then the possible substrings are ['b', 'd', 'ab', 'bc', 'cd', 'de', 'abc', 'cde'].
The longest substrings are 3 characters long, which would mean a return value of 3."""
def FindLongestIntelligentSubStringWithKAlphabets(st, K, alphas, values):
if len(st) == 0 or len(st) < K:
return
charMap = {}
for i in range(len(alphas)):
# charMap.update({alphas[i]: str(values)[i]})
charMap[alphas[i]] = int(str(values)[i])
print(charMap)
normalCount = 0
l = 0
r = len(st) - 1
while l <= r:
if charMap.get(st[l]) == 0:
normalCount += 1
if charMap.get(st[r]) == 0:
normalCount += 1
l += 1
r -= 1
if len(st) % 2 != 0 and st[len(st) // 2] == 0:
normalCount -= 1
print("initial normal characters count in string= ", normalCount)
if normalCount == K:
print("Longest Intelligent Sub String With K normal Alphabets = ", st)
# return
elif normalCount < K:
print(" not possible ")
# return
else:
n = len(st)
ansString = st
c = [0 for i in range(128)]
result = j = -1
for i in range(n):
x = st[i]
if charMap.get(x) == 0:
c[ord(x)] += 1
if c[ord(x)] == 1:
K -= 1
while K < 0:
j += 1
x = st[j]
if charMap.get(x) == 0:
c[ord(x)] -= 1
K += 1
if K == 0:
result = max(result, i - j)
ansString = st[j:i]
print(f"final length result = {result} and String = {ansString}")
if __name__ == '__main__':
alphabet = "abcdefghijklmnopqrstuvwxyz"
charValue = 10101111111111111111111111
s = 'abcde'
k = 1
FindLongestIntelligentSubStringWithKAlphabets(s, k, alphabet, charValue)
| true |
8496f1c2ec64a2f0bdabb7d7204fa58576a0bc42 | mkm3/coding-challenges | /max_of_three.py | 690 | 4.375 | 4 | def maxofthree_v1(num1, num2, num3):
"""Returns the largest of three integers
>>> maxofthree(1, 5, 2)
5
>>> maxofthree(10, 1, 11)
11
"""
return max(num1,num2,num3)
print(maxofthree_v1(1, 5, 2))
print(maxofthree_v1(10, 1, 11))
def maxofthree_v2(num1, num2, num3):
"""Returns the largest of three integers
>>> maxofthree(1, 5, 2)
5
>>> maxofthree(10, 1, 11)
11
"""
max_num = 0
if num1 >= num2:
max_num = num1
else:
max_num = num2
if num2 >= num3:
max_num = num2
else:
max_num = num3
return max_num
print(maxofthree_v2(1, 5, 2))
print(maxofthree_v2(10, 1, 11))
| false |
3792b168bf0669d72f5742c5dc62665f2c0d1050 | yanama123/Crack_Interviews | /Closures/p1.py | 778 | 4.5625 | 5 | """
Nested functions can access outer function variables but not outside of the outside function.
It restricts the access sort of data hiding.
"""
def outer(message):
text = message
def inner():
print("I am inside inner() function and {} is the message you have passed in the function call".format(text))
inner()
#outer("Learning Closures in Python")
#print("#"*30)
#print("Closure returns the function object instead of calling the function")
def outer_closure(message):
text = message
def inner_closure():
print("HEY!!!!!!!!!I am here and {} is your message".format(text))
return inner_closure
if __name__ == "__main__":
outer("Learning Closures")
print("#"*30)
res = outer_closure("How closure works")
res()
| true |
c7b6521697748a0aa2eaa1f9ea1458759e0e99d8 | emre273/GlobalAIHubPythonCourse | /Final Project/Final_Project.py | 1,766 | 4.15625 | 4 | #Creating dictionary for questions and answers.
Qs={"What is the capital of Turkey: ": "Ankara",
"Which planet is closest to the sun: ":"Mercury",
"What is the largest country in the world: ": "Russia",
"Alberta is a province of which country: ":"Canada",
"How many elements are there in the periodic table: ":"118",
"Name the fictional city Batman calls home: ":"Gotham",
"In what year did World War II end: ":"1945",
"Which chess piece can't move in a straight line: ":"Knight",
"In Greek mythology, who is the God of the sea: ":"Poseidon",
"The largest desert of the World is: ": "Sahara"}
checker=[]#"checker" is to check whether the corresponding question is true or not.
answers=[]#This list will store the answer that the user will give.
totalPoints=0#"totalPoints" is representing the the total points that the user gets
for i in Qs: #Asking all the question to the user
ans=str((input("\n"+i))) #Taking the answer
answers.append(ans)#Storing each answer
if ans.lower()==Qs[i].lower():#Checking the answer considering case sensitivity
checker.append(True)
totalPoints += 10
else:
checker.append(False)
print("\nYou can see the answers below: ")
j=0
for i in Qs:#Printing questions and the correct answers.
print("\n"+str(j+1)+"."+i+" Correct answer: "+Qs[i]+"/// Your Answer: "+answers[j])
j += 1
if totalPoints>50:#Checking total points and informing the user
print("\nYou have "+str(checker.count(False))+" wrong answer. Therefore you have "+str(totalPoints)+" Points ==> SUCCESSFUL")
else:
print("\nYou have "+str(checker.count(False))+" wrong answer. Therefore you have "+str(totalPoints)+" Points ==> UNSUCCESSFUL")
| true |
ef9c8100629695f19aa5e72fdfec2baca3e10e61 | AyushKumar20/PythonisEasy | /Homework#2.py | 767 | 4.125 | 4 | # Function for printing song name
def SongName():
Sname = "Kya Tum Naraaz Ho?"
print(Sname)
# Function for printing artist name
def Artist():
Aname = "Tanmaya Bhatnagar"
print(Aname)
# Function for returning genre of the song
def Genre():
Gname = "Rhythm and blues"
return Gname
# Using bool function for returning True/False
Sname = "Kya Tum Naraaz"
def boolean():
if Sname == "Kya Tum Naraaz Ho?" :
return True
else :
return False
# calling function SongName to print Sname
SongName()
# calling function Artist to print Aname
Artist()
# Calling function Genre inside a print statement to print the return value
print(Genre())
# Calling function boolean inside a print statement to print the return value
print(boolean()) | false |
804060db964484b35f4632f3e94587e3e7630520 | Enzoq2202/Paciencia-Acordeao | /main.py | 2,205 | 4.1875 | 4 | #Jogo Paciência Acordeão
from funcoes import*
import colorama
print('Paciência Acordeão ')
print('================== ')
print('')
print('Seja bem-vindo(a) ao jogo de Paciência Acordeão! O objetivo deste jogo é colocar todas as cartas em uma mesma pilha. ')
print('')
print('Existem apenas dois movimentos possíveis: ')
print('')
print('1. Empilhar uma carta sobre a carta imediatamente anterior; ')
print('2. Empilhar uma carta sobre a terceira carta anterior. ')
print('')
print('Para que um movimento possa ser realizado basta que uma das duas condições abaixo seja atendida: ')
print('')
print('1. As duas cartas possuem o mesmo valor ou ')
print('2. As duas cartas possuem o mesmo naipe. ')
print('')
print('Desde que alguma das condições acima seja satisfeita, qualquer carta pode ser movimentada. ')
print('')
input('Aperte [Enter] para iniciar o jogo...')
baralho = cria_baralho()
baralho=list(set(baralho))
while possui_movimentos_possiveis(baralho):
imprime_baralho(baralho)
origem=(input('Escolha uma carta (digite um número entre 1 e {}): '.format(len(baralho))))
if not origem.isdigit():
print('Opção Inválida')
elif int(origem) < 1 or int(origem) > 52:
print('Opção Inválida')
else:
origem = int(origem)
movim = lista_movimentos_possiveis(baralho, origem-1)
if movim == []:
print(f'A carta {baralho[origem-1]} não pode ser movida. Por favor, digite um número entre 1 e {len(baralho)}:')
elif movim == [1]:
baralho = empilha(baralho,origem-1,origem-2 )
elif movim == [3]:
baralho = empilha(baralho,origem-1,origem -4)
else:
print(f'Sobre qual carta você quer empilhar o {baralho[origem-1]}?')
print(f'1. {extrai_cor(baralho[origem-2])}')
print(f'2. {extrai_cor(baralho[origem-4])}')
c = int(input('Digite o número de sua escolha (1-2):'))
if c == 1:
baralho = empilha(baralho,origem-1,origem -2)
if c == 2:
baralho = empilha(baralho,origem-1,origem -4)
if len(baralho) == 1:
print('Você ganhou!')
else:
print('Você Perdeu!')
| false |
2e6237920d00de4d5df77f486b7722f54b871af1 | hieuvoo/python | /python_basics/try_py.py | 1,563 | 4.1875 | 4 | # STRING: capitalize, upper, lower, count, find, index, split, join, replace, format
# LIST: len, max, min, index, append, pop, remove, insert, sort, reverse, (optional) extend, (optional) list
#capitalize, upper
# s = "cotton eye joe"
# print str.capitalize(s)
# print str.upper(s)
# x = 'COTTON EYE JOE'
# print str.lower(x)
# str = 'this is a string example'
# sub = 'i'
# print str.count(sub,0,len(str))
# str = 'this is a string example'
# print str.find('is')
# str = 'this is a string example'
# sub = 'i'
# print str.index(sub,0,len(str))
# d = 'blue,red,green'
# d.split(',')
# a,b,c = d.split(',')
# print a
# print b
# print c
# y = '-'
# seq = ('a','b','c')
# print y.join(seq)
# y = '-'
# str = 'cotton eye joe'
# str = str.replace('eye','i')
# print str
# a = 'cotton'
# b = 'eye'
# c = 'joe'
# print " where did you come from {} {} {}?".format(a,b,c)
# x = 'COTTON EYE JOE'
# print len(x)
# x = '12345'
# print max(x)
# print min(x)
# list1 = [1,2,3,4,5]
# print list1.index(3)
# list1 = [1,2,3,4,5]
# list1.append(666)
# print list1
# list1 = [1,2,3,4,5]
# list1.pop(4)
# print list1
# list1 = [1,2,3,4,5]
# list1.remove(5)
# print list1
# list1 = [1,2,3,4,5,6,7,8,9]
# list1.insert(9,7)
# print list1
# list2 = [3,6,1,9,44,100]
# list2.sort()
# print list2
# list1 = [1,2,3,4,5,6,7,8,9]
# list1.reverse()
# print list1
# aList = [123, 'xyz', 'zara', 'abc', 123];
# bList = [2009, 'manni'];
# aList.extend(bList)
# print "Extended List : ", aList
x = 'cotton is soft'
print list(x) | true |
67642cc6805386fd34b31242cb2fce4bf3ac790c | crystal1509/Day-1 | /D1program10.py | 293 | 4.1875 | 4 | #WAP to find the last position of a substring “Emma” in a given string: "Emma is a data scientist who knows Python. Emma works at google."
string="Emma is a data scientist who knows Python. Emma works at google."
pos=string.rfind("Emma")
print("last position of Emma is:",pos)
| true |
6b78914899847e9e16d40ae2011724797f01febb | aman31kmr/code-data-science | /numpy_newaxis.py | 2,479 | 4.1875 | 4 |
# coding: utf-8
# In[95]:
import numpy as np
# In[96]:
def show_array(y):
print('array:', y)
print('array.ndim:', y.ndim)
print('array.shape:', y.shape)
# ### 0-D
# In[97]:
x = np.array(5)
show_array(x)
# #### 0-D to 1-D
# In[98]:
y = np.array(x)[np.newaxis]
show_array(y)
# In[99]:
y = np.expand_dims(x, axis=0)
show_array(y)
# Any number >= 0 does the same.
# In[100]:
y = np.expand_dims(x, axis=123456)
show_array(y)
# In[101]:
y = x.reshape(-1,)
show_array(y)
# #### 0-D to 2-D
# In[102]:
y = np.array(x)[np.newaxis, np.newaxis]
show_array(y)
# In[103]:
y = np.expand_dims(x, axis=0)
y = np.expand_dims(y, axis=0)
show_array(y)
# In[104]:
y = x.reshape(-1, 1)
show_array(y)
# ### 1-D
# In[105]:
x = np.array([5, 6, 7])
show_array(x)
# #### 1-D to 2-D
# ##### Vector to row matrix
# In[106]:
y = np.array(x)[np.newaxis, :]
show_array(y)
# In[107]:
y = np.array(x)[np.newaxis] # This is short hand of y = np.array(x)[np.newaxis, :]
show_array(y)
# In[108]:
y = np.expand_dims(x, axis=0)
show_array(y)
# In[109]:
y = x.reshape(1, -1)
show_array(y)
# ##### Vector to column matrix
# In[110]:
y = np.array(x)[:, np.newaxis]
show_array(y)
# In[111]:
y = np.expand_dims(x, axis=1)
show_array(y)
# Any number >= 1 does the same.
# In[112]:
y = np.expand_dims(x, axis=123456)
show_array(y)
# In[113]:
y = x.reshape(-1, 1)
show_array(y)
# ### 2-D
# In[114]:
x = np.array([[1, 2, 3], [4, 5, 6]])
show_array(x)
# #### 2-D to 3-D
# ##### Case 1
# In[115]:
y = np.array(x)[np.newaxis, :, :]
show_array(y)
# In[116]:
y = np.array(x)[np.newaxis, :]
show_array(y)
# In[117]:
y = np.array(x)[np.newaxis]
show_array(y)
# In[118]:
y = np.expand_dims(x, axis=0)
show_array(y)
# In[119]:
y = x.reshape(-1, 2, 3)
show_array(y)
# In[126]:
y = x.reshape(-1, *x.shape)
show_array(y)
# ##### Case 2
# In[121]:
y = np.array(x)[:, np.newaxis, :]
show_array(y)
# In[122]:
y = np.array(x)[:, np.newaxis]
show_array(y)
# In[123]:
y = np.expand_dims(x, axis=1)
show_array(y)
# In[124]:
y = x.reshape(2, 1, 3)
show_array(y)
# In[127]:
y = x.reshape(x.shape[0], -1, x.shape[1])
show_array(y)
# ##### Case 3
# In[24]:
y = np.array(x)[:, :, np.newaxis]
show_array(y)
# In[25]:
y = np.expand_dims(x, axis=2)
show_array(y)
# Any number >= 2 does the same.
# In[26]:
y = np.expand_dims(x, axis=123456)
show_array(y)
# In[128]:
y = x.reshape(*x.shape, -1)
show_array(y)
# In[ ]:
| false |
555a5aea8aad2f478d4bce6f4964750874034ccf | Beiriz/UdemyPython | /53POO.py | 1,070 | 4.15625 | 4 | #!/usr/bin/env python
# coding=utf-8
class Line(object):
def __init__(self,coord1,coord2):
self.coord1 = coord1
self.coord2 = coord2
def distance(self):
x1,y1 = self.coord1
x2,y2 = self.coord2
return ((x2-x1)**2 + (y2-y1)**2 )**0.5
def slope(self):
x1,y1 = self.coord1
x2,y2 = self.coord2
return float((y2-y1))/(x2-x1)
#----------------------
class Cylinder(object):
def __init__(self,height=1,radius=1):
self.height = height
self.radius = radius
def volume(self):
return self.height * (3.14) * (self.radius)**2
def surface_area(self):
top = (3.14) * (self.radius)**2
return 2 * top + 2 * 3.14 * self.radius * self.height
#----------------------Problema 1
coordinate1 = (3,2)
coordinate2 = (8,10)
li = Line(coordinate1,coordinate2)
print("distance %.3f" % li.distance())
print("slope %.3f" % li.slope())
#----------------------Problema 2
c = Cylinder(2,3)
print("volume %.3f" % c.volume())
print("surface_area %.3f" % c.surface_area()) | false |
97707156663beeaeeddced69929458cfd95d4434 | bbuyukyuksel/codewithm3 | /problems.5/problem.5.py | 1,104 | 4.125 | 4 | def is_prime(num):
if num <= 3:
return True
for i in range(num//2, 1, -1):
if num % i == 0:
return False
return True
_from, _to = 1, 20
primes = list(filter(lambda x: is_prime(x), range(_from+1, _to+1)))
all_factors_by_value = []
for i in range(_from+1, _to+1):
num = i
factors = []
for prime in primes:
if num>=prime:
while num % prime == 0:
num //= prime
factors.append(prime)
all_factors_by_value.append((factors))
print("\n"*2,"Factors,")
for index, factor_list in enumerate(all_factors_by_value):
print("{:<3} {}".format(index+2, factor_list))
# Max counts of primes in factor lists
print("_"*20, "\n ", "Max primes in factor lists")
count_of_primes = {}
for prime in primes:
count_of_primes[str(prime)] = max(list(map(lambda x: x.count(prime), all_factors_by_value)))
print("{:<3} count: {}".format(prime, count_of_primes[str(prime)]))
product = 1
for prime, count in count_of_primes.items():
product *= int(prime)**count
print("\n>> Smallest multiple is", product)
| false |
6b8e1d963200385db60faf9b38e1d50932e82b04 | IT-Dept-Labs/III-DSA-Lab | /lab8/prog1a.py | 1,141 | 4.125 | 4 | class TrieNode:
def __init__(self):
self.children=[None] * 26
self.end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def getIndex(self,ch):
return ord(ch)-ord('a')
def insert(self,key):
travNode=self.root
keyLen=len(key)
for i in range(keyLen):
index=self.getIndex(key[i])
if not travNode.children[index]:
travNode.children[index]=TrieNode()
travNode=travNode.children[index]
travNode.end=True
def search(self,key):
length=len(key)
trav=self.root
flag=False
for i in range(length):
if trav.children[self.getIndex(key[i])]!=None and trav.end==False:
trav=trav.children[self.getIndex(key[i])]
if trav.end==True:
flag=True
if not flag:
return False
return True
"""def printTrie(self):
trav=self.root
print(self.root.children[0].children)"""
def main():
t=Trie()
t.insert('action')
t.insert('apple')
t.insert('hello')
print(t.search('hello'))
print(t.search('act'))
# print("Press 0 to quit")
# x=input("Enter the word: ")
# while x!='0':
# x=input("Enter the word: ")
# t.insert(x)
if __name__ == '__main__':
main() | false |
d4d7636a87d4eb894e65ac68187cbf0f5305141b | SaturnFromTitan/project_euler_problems | /problem1-multiples_of_3_and_5/naive_solution.py | 498 | 4.125 | 4 | import functools
from utils import timeit
@timeit
def sum_of_multiples_of_3_or_5(below: int) -> int:
is_multiple_of_3 = functools.partial(_is_multiple_of, n=3)
is_multiple_of_5 = functools.partial(_is_multiple_of, n=5)
return sum(n for n in range(1, below) if is_multiple_of_3(n) or is_multiple_of_5(n))
def _is_multiple_of(number: int, n: int) -> bool:
return (number % n) == 0
if __name__ == '__main__':
result = sum_of_multiples_of_3_or_5(below=1000)
print(result)
| false |
a7c703ffe3f743a032205724ca7014253c981e52 | annarider/NanoDA | /IntroDataScience/Project1/Subway2Matplotlib_Luke.py | 2,401 | 4.125 | 4 | import numpy as np
import pandas
import matplotlib.pyplot as plt
def entries_histogram(subway_data_df):
'''
One visualization should contain two histograms: one of ENTRIESn_hourly for
rainy days and one of ENTRIESn_hourly for non-rainy days.
You can combine the two histograms in a single plot or you can use
two separate plots.
If you decide to use to two separate plots for the two histograms,
please ensure that the x-axis limits for both of the plots are identical.
It is much easier to compare the two in that case.
For the histograms, you should have intervals representing the volume of
ridership (value of ENTRIESn_hourly) on the x-axis and the frequency of
occurrence on the y-axis. For example, you might have one interval
(along the x-axis) with values from 0 to 1000. The height of the bar for
this interval will then represent the number of records (rows in our data)
that have ENTRIESn_hourly that fall into this interval.
Remember to increase the number of bins in the histogram
(by having larger number of bars).
The default bin width is not sufficient to capture the variability in the two samples.
Remember to add appropriate titles and axes labels to your plots.
Also, please add a short description below each figure commenting on
the key insights depicted in the figure.
You can read a bit about using matplotlib and pandas to plot histograms here:
http://pandas.pydata.org/pandas-docs/stable/visualization.html#histograms
'''
#All columns, but only rows that had rain
no_rain_df = subway_data_df[subway_data_df['rain'] == 1]
#import pdb; pdb.set_trace()
#plt.figure()
#Histogram of the entries column
pandas.DataFrame.hist(no_rain_df, column = 'ENTRIESn_hourly', bins = 250)
#print no_rain_df
#pandas.DataFrame.hist(no_rain_df, bins = 250)
#no_rain_df.show()
return no_rain_df
# sample code
# P.figure()
# create a new data-set
# x = mu + sigma*P.randn(1000,3)
# n, bins, patches = P.hist(x, 10, normed=1, histtype='bar',
# color=['crimson', 'burlywood', 'chartreuse'],
# label=['Crimson', 'Burlywood', 'Chartreuse'])
# P.legend()
if __name__ == '__main__':
subway_data_df = pandas.read_csv('turnstile_weather_v2.csv')
entries_histogram(subway_data_df)
| true |
2456c848431c45a77275688667d974555de31f3d | simran0963/python | /challenges/factorial.py | 277 | 4.1875 | 4 | def factorial(num: int):
fact = 1
for j in range(1,num+1):
fact *= j
return fact
# if __name__ == "__main__":
number1 = int(input("enter the first number: "))
number2 = int(input("enter the second number: "))
for n in range(number1, number2+1) :
print(factorial(n)) | true |
9856866b1d673544e550cc74fda9ec51a91da166 | VKSi/2019_10_GB_Course_Py_Essential | /les_3/les_3_task_4.py | 1,280 | 4.125 | 4 | # Vasilii Sitdikov
# GeekBrains Courses. Python Essential
# Lesson 3 task 4
# October 2019
# task: 4) Программа принимает действительное положительное число x и целое отрицательное число y.
# Необходимо выполнить возведение числа x в степень y.
# Задание необходимо реализовать в виде функции my_func(x, y).
# При решении задания необходимо обойтись без встроенной функции возведения числа в степень.
# Solution:
def my_func(x, y):
res = 1
try:
for _ in range(abs(y)):
res /= x
except ZeroDivisionError:
print('x должно быть положительным')
return res
my_x = float(input("Введите действительное положительное число x: "))
my_y = int(input("Введите целое отрицательное число y: "))
if my_x > 0 and my_y < 0:
print(f'Результат возведения {my_x} в степень {my_y} = {my_func(my_x, my_y):0.4f}')
else:
print('Проверьте правильность ввода')
| false |
9138beff6a49cc193d969c5b37e17085c30e2cfb | VKSi/2019_10_GB_Course_Py_Essential | /les_2/les_2_task_4.py | 707 | 4.28125 | 4 | # GeekBrains Courses. Python Essential
# Vasilii Sitdikov
# Lesson 2 task 4
# October 2019
# task: 4) Пользователь вводит строку из нескольких слов, разделённых пробелами. Вывести каждое
# слово с новой строки. Строки необходимо пронумеровать. Если в слово длинное, выводить
# только первые 10 букв в слове.
# Solution:
my_tuple = input('Введите строку из нескольких слов, разделенных пробелами: ').split(' ')
for i, word in enumerate(my_tuple, 1):
print(f'{i} {word[:10]}')
| false |
563a1406bfc64d8f789c163dcc4a8ae22ec864ea | VKSi/2019_10_GB_Course_Py_Essential | /les_4/les_4_task_2.py | 849 | 4.1875 | 4 | # Vasilii Sitdikov
# GeekBrains Courses. Python Essential
# Lesson 4 task 2
# October 2019
# task: 2) Представлен список чисел. Необходимо вывести элементы исходного списка, значения которых больше
# предыдущего элемента.
# Подсказка: элементы, удовлетворяющие условию, оформить в виде списка.
# Для формирования списка использовать генератор.
# Solution:
def new_list(old_list):
try:
return [old_list[i] for i in range(1, len(old_list)) if old_list[i] > old_list[i - 1]]
except TypeError:
print('Check type of values')
def test():
my_list = [1, 2, -30, 60, 50, 345]
print(new_list(my_list))
test()
| false |
156dec460c23ed50472beb6844659144faa0ef6d | unixwars/euler | /024.py | 953 | 4.15625 | 4 | #!/usr/bin/env python
# A permutation is an ordered arrangement of objects. For example,
# 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all
# of the permutations are listed numerically or alphabetically, we
# call it lexicographic order. The lexicographic permutations of 0, 1
# and 2 are: 012 021 102 120 201 210
# What is the millionth lexicographic permutation of the digits 0, 1,
# 2, 3, 4, 5, 6, 7, 8 and 9?
# Discussion:
#
# math.factorial(9) = k = 362880 ==> permutations beginning with any
# given number. So k*2 < 10**6 < k*3, so the target is a permutiation
# beggining with the 3rd number of the string (#2). Similar reasoning
# can be followed with 8!, 7!, 6!, etc. Or... just generate all the
# permutations and select the nth one ;)
from itertools import permutations
i = 10**6
for x in permutations(range(10), 10):
i -= 1
if i == 0:
print ''.join(map(str,x))
break
# 2783915460
| true |
83a4cc8c55ff3832a2e8be0d080a7282ce5fa973 | unixwars/euler | /004.py | 564 | 4.125 | 4 | #!/usr/bin/env python
# A palindromic number reads the same both ways. The largest
# palindrome made from the product of two 2-digit numbers is
# 9009 = 91 99. Find the largest palindrome made from the product of
# two 3-digit numbers.
def lp():
k = None
tup = None
for x in range(999,99,-1):
for y in range(999,99,-1):
if x == y: continue
num = str(x*y)
if num == num[::-1]:
if int(num) > k:
k = int(num)
tup = (x,y)
return k, tup
print lp()
| true |
4c3516de69d18a1942f42a78cd194c66193fffa2 | Code-ZYJ/Leecode_everyday | /分糖果.py | 1,005 | 4.40625 | 4 | '''
给定一个偶数长度的数组,其中不同的数字代表着不同种类的糖果,每一个数字代表一个糖果。你需要把这些糖果平均分给一个弟弟和一个妹妹。返回妹妹可以获得的最大糖果的种类数。
示例 1:
输入: candies = [1,1,2,2,3,3]
输出: 3
解析: 一共有三种种类的糖果,每一种都有两个。
最优分配方案:妹妹获得[1,2,3],弟弟也获得[1,2,3]。这样使妹妹获得糖果的种类数最多。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/distribute-candies
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
class Solution(object):
def distributeCandies(self, candyType):
"""
:type candyType: List[int]
:rtype: int
"""
return len(set(candyType)) if len(set(candyType)) < len(candyType) // 2 else len(candyType) // 2
candies = [1,1,2,2,3,3]
Solution().distributeCandies(candies) | false |
9cad882ec8081704ba2abe16cffd7b29b8fc8f55 | Benny1143/ossu-progress | /introcs-mit-edx-2021/ps1/p2.py | 445 | 4.125 | 4 | # Assume s is a string of lower case characters.
# Write a program that prints the number of times the string 'bob' occurs in s.
# For example, if s = 'azcbobobegghakl', then your program should print
# Number of times bob occurs is: 2
# Give
s = 'azcbobobegghakl'
bob = 0
index = 0
for letter in s:
if letter == 'b':
if s[index:index+3] == 'bob':
bob += 1
index += 1
print('Number of times bob occurs is:', bob) | true |
c8edca1a47e7eb601c56cef5c677e1ed33f12a1b | Benny1143/ossu-progress | /introcs-mit-edx-2021/ps3/p1.py | 1,154 | 4.21875 | 4 | # Problem 1 - Is the Word Guessed
# Please read the Hangman Introduction before starting this problem.
# We'll start by writing 3 simple functions that will help us easily code
# the Hangman problem. First, implement the function isWordGuessed that
# takes in two parameters - a string, secretWord, and a list of letters,
# lettersGuessed. This function returns a boolean - True if secretWord has
# been guessed (ie, all the letters of secretWord are in lettersGuessed) and
# False otherwise.
# Example Usage:
# >>> secretWord = 'apple'
# >>> lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's']
# >>> print(isWordGuessed(secretWord, lettersGuessed))
# False
# For this function, you may assume that all the letters in secretWord
# and lettersGuessed are lowercase.
def isWordGuessed(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: boolean, True if all the letters of secretWord are in lettersGuessed;
False otherwise
'''
for a in secretWord:
if a not in lettersGuessed:
return False
return True | true |
ec8ad7cbd405ff9a10d6af8399e1fcf8116d978d | AnkushShetty1/FST-M1 | /Python/Activities/Activity_11.py | 235 | 4.1875 | 4 | fruit_dict = {
"apple" : 70,
"mango" : 50,
"orange" : 55
}
fruit_name = input("Enter a fruit name to check ").lower()
if(fruit_name in fruit_dict):
print("Fruit is available")
else:
print("Fruit is not available") | true |
bd46cfb2c72de5346a46dd3f1265ac589ea8037c | EANimesha/Python | /List/list.py | 2,006 | 4.59375 | 5 | # Python Lists
# used to store multiple items in a single variable.
# created using square brackets
# List items are ordered(items have a defined order, and that order will not change.),
# changeable(can change, add, and remove items in a list after it has been created.),
# and allow duplicate values.
# List items are indexed, the first item has index [0], the second item has index [1] etc.
# If you add new items to a list, the new items will be placed at the end of the list.
iAmList = ["Katness", "Everdeen", "HungerGames"]
print(iAmList)
iAllowDuplicates = ["Katness", "Everdeen", "HungerGames", "Katness"]
print(iAllowDuplicates)
ListLength = ["Katness", "Everdeen", "HungerGames"]
print(len(ListLength))
# Data types: List items can be of any data type.
# String, int and boolean data types
iAmListString= ["Katness", "Everdeen", "HungerGames"]
iAmListInt = [1, 2, 10, 5, 3]
iAmListBoolean = [True, False, False]
print(iAmListString)
print(iAmListInt)
print(iAmListBoolean)
# A list with strings, integers and boolean values:
DifferentDataTypes = ["kate" , 20, 10.0, True]
print(DifferentDataTypes)
print(type(DifferentDataTypes))
# The list() Constructor
# we can use the list() constructor for creating a new list.
iAmConstructor = list(("Katness", "Everdeen", "HungerGames")) # use double round-brackets
print(iAmConstructor)
# List Method
# append() Adds an element at the end of the list
# clear() Removes all the elements from the list
# copy() Returns a copy of the list
# count() Returns the number of elements with the specified value
# extend() Add the elements of a list (or any iterable), to the end of the current list
# index() Returns the index of the first element with the specified value
# insert() Adds an element at the specified position
# pop() Removes the element at the specified position
# remove() Removes the item with the specified value
# reverse() Reverses the order of the list
# sort() Sorts the list | true |
fd6ab0f62eb49e328cef63372005bde1d7151bff | sfitzsimmons/Exercises | /NumberRange.py | 361 | 4.3125 | 4 | # this exercise wants me to test whether a number is within 100 of 1000 or 2000.
given_number = int(input("Enter number: "))
if 900 < given_number < 1100:
print("Your number is within 100 of 1000.")
elif 1900 < given_number < 2100:
print("Your number is within 100 of 2000")
else:
print("Your number is not within 100 of 1000 or 2000.")
| true |
a4a1df85165d2ef8e3a4c921889ebbcf1d8d9247 | Prietoisa/Atividades-1-2-3-4-5 | /atividade5.py | 558 | 4.15625 | 4 | # Faça um programa que leia o raio de um círculo e faça duas
# funções: uma que calcule a área do círculo e outra que calcule
# o comprimento do círculo.
raio_circulo = float(input('qual o raio do circulo '))
pi = 3.14
def area(raio_circulo,pi):
area_circulo = (pi * (raio_circulo ** 2))
print('a sua área é {}m²'.format(area_circulo))
area(raio_circulo,pi)
def comprimento_circulo(pi,raio_circulo):
comprimento = 2 * pi * raio_circulo
print('Seu comprimento é {}'.format(comprimento))
comprimento_circulo(pi, raio_circulo) | false |
f312e2fa0e94e9b271aff92c8a1e820697b87420 | Joshua-Porter-dev/PythonCalculator | /main.py | 558 | 4.375 | 4 | operation = input("Would you like to add, subtract, divide, or multiply? ")
num1 = float(input("Enter a number: "))
num2 = float(input("Enter another number: "))
def add(num1, num2):
print(num1 + num2)
def subtract(num1, num2):
print(num1 - num2)
def divide(num1, num2):
print(num1 / num2)
def multiply(num1, num2):
print(num1 * num2)
if operation == 'add':
add(num1, num2)
if operation == 'subtract':
subtract(num1, num2)
if operation == 'divide':
divide(num1, num2)
if operation == 'multiply':
multiply(num1, num2)
| false |
a2fc7ff637a90344ac6e8948c275c8461e1aa865 | mohaimenhasan/practiceAlgoQuestion | /Online Questions:/q2.py | 1,503 | 4.25 | 4 | '''
You are a renowned thief who has recently switched from stealing precious metals to stealing cakes because of the insane profit margins. You end up hitting the jackpot, breaking into the world's largest privately owned stock of cakes—the vault of the Queen of England.
While Queen Elizabeth has a limited number of types of cake, she has an unlimited supply of each type.
Each type of cake has a weight and a value, stored in a tuple with two indices:
An integer representing the weight of the cake in kilograms
An integer representing the monetary value of the cake in British shillings
For example:
# Weighs 7 kilograms and has a value of 160 shillings
(7, 160)
# Weighs 3 kilograms and has a value of 90 shillings
(3, 90)
You brought a duffel bag that can hold limited weight, and you want to make off with the most valuable haul possible.
Write a function max_duffel_bag_value() that takes a list of cake type tuples and a weight capacity, and returns the maximum monetary value the duffel bag can hold.
For example:
cake_tuples = [(7, 160), (3, 90), (2, 15)]
capacity = 20
# Returns 555 (6 of the middle type of cake and 1 of the last type of cake)
max_duffel_bag_value(cake_tuples, capacity)
Weights and values may be any non-negative integer. Yes, it's weird to think about cakes that weigh nothing or duffel bags that can't hold anything. But we're not just super mastermind criminals—we're also meticulous about keeping our algorithms flexible and comprehensive.
'''
| true |
8d47cbfc9a4650b297ab056559e16b03698f9926 | zmunson85/CodemySelfStudy | /algos/maskify/maskify.py | 1,813 | 4.21875 | 4 | # // // Usually when you buy something, you're asked whether your credit card number, phone number or answer to your most secret question is still correct. However, since someone could look over your shoulder, you don't want that shown on your screen.Instead, we mask it.
# // // Your task is to write a function maskify, which changes all but the last four characters into '#'.
# // Examples
# // maskify("4556364607935616") == "############5616"
# // maskify("64607935616") == "#######5616"
# // maskify("1") == "1"
# // maskify("") == ""
# // // "What was the name of your first pet?"
# // maskify("Skippy") == "##ippy"
# // maskify("Nananananananananananananananana Batman!") == "####################################man!"
#My solution
def maskify(nums):
string = ''
for num in nums[:-4]:
string += '#'
string += nums[-4:]
return string
#other solutions
# #version 2
# def maskify(cc):
# return "#"*(len(cc)-4) + cc[-4:]
# #version 3
# def maskify(cc):
# l = len(cc)
# if l <= 4:
# return cc
# return (l - 4) * '#' + cc[-4:]
# #version 4
# def maskify(cc):
# return '{message:#>{fill}}'.format(message=cc[-4:], fill=len(cc))
# #version 5
# def maskify(cc):
# word = list(cc)
# for i in range(len(word) - 4):
# word[i] = '#'
# return ''.join(word)
# pass
# #version 6
# def maskify(cc):
# width = len(cc)
# return cc[-4:].rjust(width, '#')
# #version 7
# def maskify(cc):
# return cc[-4:].rjust(len(cc), "#")
# #version 8
# def maskify(cc):
# return "#" * len(cc[:-4]) + cc[-4:]
# #version 9
# def maskify(cc):
# if len(cc) < 4:
# return cc
# return "#" * (len(cc)-4) + cc[-4:]
# #version 10
# maskify = (
# lambda c: (
# '#'*(len(
# c)-4)+c
# [-4:])
# )
| true |
b7458d6db84b5d72ce29e02237ad74f5107807d3 | David-Lisboa/Ocean_Python_04_11_2020 | /Exercicio1.py | 664 | 4.1875 | 4 | # Exercicio 1
"""
- Escreva um programa que receba uma string digitada pelo usuário e caso a string seja igual a “medieval”,
exiba no console: “espada”;
- Caso contrário, se a string for igual a “futurista”, exiba no console: “sabre de luz”; - Caso contrário,
exiba no console: “Tente novamente.”.
"""
contador = 1
while contador != 0:
estilo = input("Informe o seu estilo: ").strip().lower() # Tira o espaço e coloca em minusculo
if estilo == "medieval":
print("espada")
contador = 0
elif estilo == "futurista":
print("sabre de luz")
contador = 0
else:
print("tente novamente")
| false |
3d45890bccff1dcd4a375cfcf64ff088d4dbb549 | rawrgulmuffins/ProjectEuler | /Question7.py | 424 | 4.125 | 4 | #!/usr/bin/env python3.2
import math
def IsPrime(num):
if num < 1:
return False
for number in range(2, math.floor(math.sqrt(num) + 1)):
if num % number == 0:
return False
return True
def GetPrime(limit):
count = 0
number = 1
while count < limit:
number += 1
if IsPrime(number):
count += 1
return number
print(GetPrime(10001))
| true |
5ac9298c337eee423f2bd667b0abd5a882af1fb0 | SabraMGrace/itc110 | /mpg.py | 645 | 4.28125 | 4 | #distance.py
def main():
print("Calculate mpg!")
print()
#input
miles = float(input("How many miles are you driving? "))
gallons = float(input("How many gallons of gas did you use? "))
##mpg = miles / gallons
if miles <=0:
print("You haven't driven anywhere! Miles must be greater than zero. Try again.")
elif gallons <=0:
print("Uh oh! You need to get gas! Gallons of gas must be greater than zero.")
else:
#calculate and display mpg.
mpg = round((miles / gallons), 2)
print("Miles per Gallon:", mpg)
print("Goodbye!")
main()
| true |
f30cc4f5f6b60e7a36dee61110041936d7af6e6f | SabraMGrace/itc110 | /circleRadius.py | 255 | 4.15625 | 4 | #find the area of a circle
# pi * r **2
from math import *
def main():
print(circleArea())
#get the area
def circleArea():
r = input("What is the circle's radius? ")
a = pi * float(r)**2
return(a)
main()
| true |
4c1721fd78501f4f668f410a9ba78efcf8347b74 | snehaljadhav7/Data-Science | /Assignment2/RemoveDuplicates.py | 315 | 4.15625 | 4 | #!/bin/python3
def RemoveDuplicates(my_list):
new_list = []
for element in my_list:
if element not in new_list:
new_list.append(element)
return new_list
print(RemoveDuplicates([1, 1, 'a', 'b', 1, 'a', 'd']))
print(RemoveDuplicates([1, 2, 'a', [1, 2, 3], 1, 2, 3,[1, 2, 3]]))
| false |
915bee4e9ad5f90ff490470c05065b97d402209a | snehaljadhav7/Data-Science | /Assignment1/calculatingBMI.py | 236 | 4.21875 | 4 | #!/bin/python3
import math
weight_pounds = int(input("Enter your weight in pounds:"))
height_inches = int(input("Enter your height in inches:"))
BMI=703*(weight_pounds / (height_inches*height_inches))
print("Your BMI is",round(BMI,1))
| true |
c3da26f6563e38f6e8d2aed2c35c6bd10f9973cf | cuthai/Learning-Blackjack | /actions.py | 2,422 | 4.25 | 4 | '''
Functions for player actions
Comes with the following methods:
take_bet - asks the player for a bet and returns it
hit - adds card from deck to player's hand
hit_or_stand - asks the player if they want to continue to hit or to stop
show_some - shows the player's hand and some of the dealer's hand
show_all - shows the player's hand and the dealer's hand
'''
from hand import *
#Method to ask for the player's bet. Takes the player's balance as a paramter. Returns the player's bet
def take_bet(balance):
bet = 0
while True:
try:
bet = int(input(f'How many chips would you like to bet? Balance: {balance} |'))
except ValueError:
print('Please enter a number.')
else:
if bet > balance:
print('Bet is higher than balance. Please enter another number.')
else:
break
return bet
#Method if the player wants to hit to add the card to the hand. Takes in the current deck and player's hand as parameters. add_card comes from the hand class
def hit(deck,hand):
hand.add_card(deck.deal())
hand.adjust_for_ace()
#Method to ask the player if they wants to hit or stay. Takes in the current deck and player's hand as parameters.
#If the player hits, this will call the hit method. Returns true if player continues to hit, and false if the player stops.
def hit_or_stand(deck,hand):
action = input("Would you like to hit? Enter 'y' or 'n' | ")
if action == 'yes' or action == 'y':
hit(deck,hand)
if hand.value > 21:
return False
else:
return True
else:
return False
#Method to show the player and some of dealer's hands. Only shows one card from the dealer's hand. Takes the player hand and the dealer hand as parameters
def show_some(player,dealer):
print("Player's hand. Value: ",player.value)
for card in player.cards:
print(card)
print("Dealer's hand. Value: ",dealer.cards[1].value)
print('<card hidden>')
print(dealer.cards[1])
#Method to show the player and all of the dealer's hands. Takes the player hand and the dealer hand as parameters
def show_all(player,dealer):
print('Printing all Cards')
print("Player's hand. Value: ",player.value)
for card in player.cards:
print(card)
print("Dealer's hand. Value: ",dealer.value)
for card in dealer.cards:
print(card) | true |
36bc7029ca2804b12cf311b1979369e0d88b6527 | raghavatreya/SolutionofhackerearthQuestion | /greedy-motu-patlu.py | 1,122 | 4.125 | 4 | '''
https://www.hackerearth.com/practice/algorithms/greedy/basics-of-greedy-algorithms/practice-problems/algorithm/motu-and-patlu-1-ab612ad8/
In this question the greedy step is take the atleast twice ice cream for motu
then pick the ice cream for patlu
! Be cautious About the list out of Bound Error
'''
# Write your code here
t = int(input())
while t >= 1:
t = t-1
n = int(input())
l = list(map(int,input().split(' ')))
motu = 0
patlu = 0
i = 0
j = len(l) -1
psum = msum = 0
while not i>j:
while msum <= 2*psum and not i>j:
msum += l[i]
i += 1
motu += 1
while msum >= 2*psum and not i>j:
psum += l[j]
j -= 1
patlu += 1
if motu>patlu:
print(motu,patlu,"\nMotu")
elif motu<patlu:
print(motu,patlu,"\nPatlu")
else:
print(motu,patlu,"\nTie")
# This code is not readable
def setdefault_example():
std_dict = dict()
for k, v in enumerate(range(5)):
std_dict.setdefault(k, []).append(v)
return std_dict
setdefault_example()
| false |
d44a48d12d4f627c3616f6505b179fa83585d0be | Carlosterre/Tech_with_Tim | /Python as fast as possible - Learn Python in ~75 minutes/Tech_with_Tim_13-Slice_operator.py | 761 | 4.34375 | 4 | # PYTHON COURSE 13
# Carlos Terreros Sanchez
# Tech with Tim
# Slice operator
x = [0, 1, 2, 3, 4, 5, 6, 7, 8]
y = ['hi', 'hello', 'goodbye', 'cya', 'sure']
s = 'hello'
sliced = x[0:4:2] # [start:stop:step] No incluye el valor final
print(sliced)
sliced2 = x[:4] # Si no hay argumento start comienza por el principio de manera predeterminada
print(sliced2)
sliced3 = x[2:4:]
print(sliced3)
sliced4 = x[4:2:-1]
print(sliced4)
sliced5 = x[::-1] # Invierte una lista
print(sliced5)
sliced6 = s[::2]
print(sliced6)
sliced7 = (2, 2, 3, 4, 5)[::2]
print(sliced7)
| false |
c4f9f82e128c2636d4038a534037130094796c86 | imn00133/PythonSeminar18 | /TeachingMaterials/insert_file/16_lecture_file/infinite_loop.py | 242 | 4.125 | 4 | while True:
answer = input("계속 반복합니까?(yes/no): ")
if answer == "no":
print("종료!")
break
elif answer == "yes":
print("계속 반복!")
else:
print("yes/no를 입력하세요.")
| false |
426a0a28ac8e782bcc92c172404f18484ab4da25 | DhyanilMehta/PC503-Programming-Lab | /Python/Assignment 5/Q3/Question3.py | 1,068 | 4.125 | 4 | STRING = '''You have received first email from abc@gmail.com, You have received second email from def@gmail.com,
You have received third email from pqr@gmail.com, You have received fourth email from qwert@gmail.com,
You have received fifth email from spam@gmail.com'''
# i) Display the word count using dictionary data structure.
wordsList = [word.strip(',') for word in STRING.split()]
uniqueWords = dict()
for word in wordsList:
uniqueWords[word] = uniqueWords.get(word, 0) + 1
print("Displaying counts for each word in STRING: ")
for word, count in uniqueWords.items():
print("Word: " + word + "\tCount: " + str(count))
# ii) Display the list of unique bigrams in the above text and their counts using dictionary data structure.
bigramsList = [wordsList[i]+' '+wordsList[i+1] for i in range(len(wordsList) - 1)]
uniqueBigrams = dict()
for bigram in bigramsList:
uniqueBigrams[bigram] = uniqueBigrams.get(bigram, 0) + 1
print("\nDisplaying counts for each bigram in STRING: ")
for bigram, count in uniqueBigrams.items():
print("Bigram: " + bigram + "\tCount: " + str(count))
| true |
4d606bbf8e36f4d9bb4a974b56f36304efff318e | suncerrae/AFS-200 | /week1/input/input.py | 228 | 4.125 | 4 | city = input("Please provide your current city: ")
code = input("Please provide your current zip code: ")
print("The city you provided is " + city + " and the zip code is " + code)
#print("The zip code you provided is " + code) | true |
c2eb2da9b89248ddeed207ec6e319d4dc7732ffa | MrSaintJCode/100-Days-of-Python | /10-19/19/main.py | 1,959 | 4.40625 | 4 | # https://www.udemy.com/course/100-days-of-code/
# Day - 4 | 21/11/2020
# By - Justin St-Laurent
# Rock, Paper, Scissors Game
import random
def game(player_choice):
# 1 - Rock
# 2 - Paper
# 3 - Scissors
pc_choice = random.randint(1, 3)
if pc_choice == 1:
_rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
print(_rock)
print("PC has played: Rock")
if player_choice.lower() == "paper":
return "Player has won!"
elif player_choice.lower() == "scissors":
return "PC has won!"
elif player_choice.lower() == "rock":
return "It's a tie!"
elif pc_choice == 2:
_paper = '''
_______
---' ____)
______)
_______)
_______)
---.__________)
'''
print(_paper)
print("PC has played: Paper")
if player_choice.lower() == "paper":
return "It's a tie!"
elif player_choice.lower() == "scissors":
return "Player has won!"
elif player_choice.lower() == "rock":
return "PC has won!"
elif pc_choice == 3:
_scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
print(_scissors)
print("PC has played: Scissors")
if player_choice.lower() == "paper":
return "PC has won!"
elif player_choice.lower() == "scissors":
return "It's a tie!"
elif player_choice.lower() == "rock":
return "Player has won!"
return "Not a valid option"
if __name__ == '__main__':
print("Welcome to the Rock, Paper, Scissors Game")
player_choice = input("Player Choice [Rock, Paper, Scissors]:")
print(game(player_choice))
| false |
d72a2be42794202b3138f0bf86258dd0a119325a | denisevaldes/guia2 | /ejercicio6.py | 679 | 4.28125 | 4 | # Denise Valdes
# Ejercicio 6
# Cree un programa que permita concatenar los datos o palabras ingresadas por un usuario. El ingreso
# de palabras debe estar controlado por un ciclo y cuando se escriba la palabra fin termine la ejecución
# y se muestren todos los datos ingresados de forma concatenada.
# se crean dos variables
palabra = None
juntar = ""
#mientras palabra sea diferente de fin, el ciclo se repetira
while palabra != "fin":
# se le pide al usuario ingresar una palabra
palabra = input("ingrese una palabra para concatenar: ")
# en variable juntar se van concatenando las palabras con +
juntar += " " + palabra
print("la frase formada es:", juntar) | false |
b79c004248224f216c4421ed652726771b000776 | kvsrsastry/Docs_and_Code | /Python/python_session_consolidated_scripts/datetime_play.py | 1,352 | 4.125 | 4 | # Datetime
import datetime
# Working with datetime objects
print(datetime.datetime.now())
d1 = datetime.datetime(year=1980, month=5, day=23, hour=18, minute=15, second=34, microsecond=7777)
d2 = datetime.datetime(year=1981, month=2, day=4, hour=18, minute=18, second=25, microsecond=8888)
print(d1)
print(d2)
df = d1 - d2
print(df.days)
print(df.seconds)
print(d1.strftime(format='%Y-%m-%d %H:%M:%S.%f'))
# Working with date objects
print(datetime.date.today())
dt1 = datetime.date(year=1980, month=5, day=23)
dt2 = datetime.date(year=1981, month=2, day=4)
dtf = dt2 - dt1
print(dtf.days)
three_days_before = datetime.date.today() - datetime.timedelta(days=3)
#three_days_before = dt1 - datetime.timedelta(days=3)
print(three_days_before)
seven_days_after = datetime.date.today() + datetime.timedelta(days=7)
print(seven_days_after)
# Working with time objects
datetime.datetime.now().strftime(format='%H:%M:%S')
t1 = datetime.time(hour=23, minute=59, second=59)
t2 = datetime.time(hour=3, minute=9, second=8)
# Subtracting Time Objects
print(datetime.datetime.combine(datetime.date.min, t1) - datetime.datetime.combine(datetime.date.min, t2))
# 3 hours after t1
t1_plus_3 = datetime.datetime.combine(datetime.date.min, t1) + datetime.timedelta(hours=3)
print(t1_plus_3.strftime(format='%H:%M:%S'))
print(datetime.date.min)
print(datetime.date.max)
| false |
0533010e80b67b55321e23d988a01dd929c748e6 | viborotto/pacote-desafios-pythonicos | /07_front_back.py | 1,735 | 4.1875 | 4 | """
07. front_back
Considere dividir uma string em duas metades.
Caso o comprimento seja par, a metade da frente e de trás tem o mesmo tamanho.
Caso o comprimento seja impar, o caracter extra fica na metade da frente.
Exemplo: 'abcde', a metade da frente é 'abc' e a de trás é 'de'.
Finalmente, dadas duas strings a e b, retorne uma string na forma:
a-frente + b-frente + a-trás + b-trás
"""
def front_back(a, b):
# +++ SUA SOLUÇÃO +++
if len(a) % 2 == 0 and len(b) % 2 == 0:
ma = int(len(a) / 2)
mb = int(len(b) / 2)
if len(a) % 2 == 0 and len(b) % 2 != 0:
ma = int(len(a) / 2)
mb = int(len(b) / 2 + 1)
if len(a) % 2 != 0 and len(b) % 2 == 0:
ma = int(len(a) / 2 + 1)
mb = int(len(b) / 2)
if len(a) % 2 != 0 and len(b) % 2 != 0:
ma = int(len(a) / 2 + 1)
mb = int(len(b) / 2 + 1)
fa = a[:ma]
fb = b[:mb]
ta = a[ma:]
tb = b[mb:]
return f'{fa + fb + ta + tb}'
# --- Daqui para baixo são apenas códigos auxiliáries de teste. ---
def test(f, in_, expected):
"""
Executa a função f com o parâmetro in_ e compara o resultado com expected.
:return: Exibe uma mensagem indicando se a função f está correta ou não.
"""
out = f(*in_)
if out == expected:
sign = '✅'
info = ''
else:
sign = '❌'
info = f'e o correto é {expected!r}'
print(f'{sign} {f.__name__}{in_!r} retornou {out!r} {info}')
if __name__ == '__main__':
# Testes que verificam o resultado do seu código em alguns cenários.
test(front_back, ('abcd', 'xy'), 'abxcdy')
test(front_back, ('abcde', 'xyz'), 'abcxydez')
test(front_back, ('Kitten', 'Donut'), 'KitDontenut')
| false |
32c5890c340755c213a3545271b41e68c0ee9299 | camillebear/PythonClass | /HelloWorld.py | 553 | 4.125 | 4 | name = input("enter your name : ")
print ('hello '+ name )
x = 10
print (x)
n = int(input("enter a number : "))
if n < 10:
print('Your number is less than 10!')
elif n > 10:
print('Your number in greater than 10!')
elif n == 10:
print('Your number is equal to 10!')
p = int(input("enter a number : "))
if p% 2 == 1:
print('This number is odd.')
else:
print('This number is even.')
food = ['chocolate', 'water', 'juice']
for index in food:
print(index)
numbers = []
for x in range(0,9):
numbers.append(x)
print(numbers) | true |
168b78242c4af2a80ce57ff20b3fb078311180c0 | jbarragan88/Assingments | /DojoAssingments/Python/Python OOP/OOP_Car.py | 1,811 | 4.125 | 4 | class Car(object): #create class/object car
def __init__(self, price, speed, fuel, mileage): #filling attributes with price, speed, fuel, mileage, and tax of the car
self.price = price
self.speed = speed
self.fuel = fuel
self.mileage = mileage
self.tax = 0.12
def display(self): #method(function) to display all Car info
print "Price:", self.price
print "Max Speed:", self.speed,"mph"
print "Fuel:", self.fuel
print "Mileage:", self.mileage, "mpg"
print "Tax:", self.tax
print ""
return self
def fuelTank(self): #method(function) to set the fuel to wether it's full or empty
if self.fuel > 75:
self.fuel = 'Full'
elif self.fuel >50 and self.fuel <76:
self.fuel = 'Partly Full'
elif self.fuel >25 and self.fuel <51:
self.fuel = 'Half Full'
elif self.fuel >= 0 and self.fuel <26:
self.fuel = 'Needs Fueling'
return self
def fixTax(self): #method(function) to set the tax to 15 percent if the car is greater than 10 000
if self.price > 10000:
self.tax = 0.15
return self
car1 = Car(12000, 120, 20, 35) #creating six instances of the car with its respective information
car1.fuelTank().fixTax().display() #running the methods from the car to display all car information
car2 = Car(1000,100, 74,30)
car2.fuelTank().fixTax().display()
car3 = Car(300123, 320, 87,24)
car3.fuelTank().fixTax().display()
car4 = Car(33432,193, 34, 30)
car4.fuelTank().fixTax().display()
car5 = Car(31000, 200, 67, 34)
car5.fuelTank().fixTax().display()
car6 = Car(500, 100, 34,27)
car6.fuelTank().fixTax().display() | true |
e8b1eb17d9eea38e12d4e2b78eb7aee525151b82 | crampete/full_stack_course | /python/02_code_organisation/02_functions/docstring_example_2.py | 552 | 4.34375 | 4 | def hours_minutes_to_seconds(hours, minutes):
'''
Converts duration from hours and minutes into seconds
Parameters:
hours (int): The number of hours
minutes (int): The number of minutes
Returns:
seconds (int): The hours and minutes converted to seconds.
Example Usage:
hours_minutes_to_seconds(2, 30) -> 9000
'''
hours_in_seconds = hours * 3600
minutes_in_seconds = minutes * 60
return hours_in_seconds + minutes_in_seconds
| true |
d47f9eb0189836f5165abcf8f6bc7e2b42e8d585 | homepeople/PythonLearning | /src/像计算机科学家一样思考Python_Exercise3/Lesson005/Exercise5.3.py | 456 | 4.1875 | 4 | #coding=utf-8
#Exercise5.3
def is_triangle(a,b,c):
if a>b+c:
r = 'No'
else:
r = 'Yes'
print(r)
def is_bigger(a,b,c):
if a>=b>=c:
return is_triangle(a,b,c)
else:
if b>a:
is_bigger(b,a,c)
elif c>b:#如果是if则出现2个yes或no,调用2次is_bigger
is_bigger(a,c,b)
if __name__ == '__main__':
is_bigger(1,3,3) | false |
e94b00646cb9ab2cb75ac8fe9988b3665b259bf4 | ThiyaguE/Ansible | /JaganTraining/day4/hello1.py | 638 | 4.1875 | 4 | #!/usr/bin/python
class Point():
#This is python constructor - this invokes automatically
#when an object of point is created
#self represent current object(this)
def __init__(self):
print ('constructor got invoked...')
self.x = 0
self.y = 0
def setValues(self, x,y):
self.x = x
self.y = y
def printValues(self):
print ('Value of x is ',self.x)
print ('Value of y is ',self.y)
def main():
point1 = Point();
point1.setValues (10,20);
point1.printValues();
point2 = Point();
point2.setValues (30,40);
point2.printValues();
main()
| true |
5345d262a338fc54c7aff3739f54f4d118d301e3 | eyelivermore/pythonlianxi | /ex/ex42.py | 2,148 | 4.125 | 4 | class Animal:
pass
## 继承了动物类
class Dog(Animal):
def __init__(self, name):
## 初始化name属性
self.name = name
## 继承了动物类
class Cat(Animal):
def __init__(self, name):
## 初始化名字
self.name = name
## 定义一个人类
class Person:
name = "Hans"
def __init__(self, name,age,gender):
## 名字属性
self.name = name
self.age = age
self.gender = gender
## 人有一个宠物
self.pet = None
@classmethod #类方法装饰器
def show(cls):
print('我是人类的名字叫{}'.format(cls.name))
@property#这个装饰器可以把方法当属性来用
def Say(self):
print("我是人类,我有说话功能,的名字是:{}".format(self.name))
return self.name
## 定义一个员工类
class Employee(Person):
def __init__(self, name, age, salary, gender):
## 找到父类的name
super(Employee, self).__init__(name,age,gender)
## 人类要有薪水
self.salary = salary
@staticmethod
def word(salary):
print("hello:我是员工类,我的工资是{}".format(salary))
#这是一个静态装饰器 这是装饰器不能有self,只可以被类直接访问,
#没有装饰器不加self 对象是不能请问的
# def show(self):
# print("我的名字叫{}".format(self.name))
## 鱼类
class Fish:
pass
## 三文鱼
class Salmon(Fish):
pass
## 比目鱼继承了鱼类
class Halibut(Fish):
pass
## rover是狗
print("go")
rover = Dog("Rover")
## satan是猫
satan = Cat("Satan")
## mary是人类
mary = Person("Mary",25,'wman')
Person.show()
mary.show()
## 给mary的宠物起一个名字叫satan
mary.pet = satan
## frank是员工,薪水120000
frank = Employee("Frank", 35, 120000,"man")
## frank的宠物起一个名字叫rover
#frank.age = 25
#frank.gender = 'man'
frank.pet = rover
print(frank.name,frank.pet.name,frank.salary)
frank.word(10000)
frank.show()
#把方法当做属性调用
print(frank.Say)
## flipper是鱼
flipper = Fish()
## crouse是三文鱼
crouse = Salmon()
## harry是比目鱼
harry = Halibut()
| false |
d78bac131a7451462902d2402a615263d78dbf76 | namitachaudhari119/coding | /code/code_3.py | 454 | 4.375 | 4 | def find_substring(string):
new_string = ''
for i in string:
if i not in new_string:
new_string += i
print("The substring is: {} and length is {}".format(new_string, len(new_string)))
# find_substring("namita")
# output: The substring is: namit and length is 5
# find_substring("Chaudhari")
# output: The substring is: Chaudri and length is 7
find_substring("abcabcbb")
# output: The substring is: abc and length is 3
| true |
550a017d624e043c77a9a5047841eccaf9ac5db0 | adarshisgg/python | /4th.py | 251 | 4.125 | 4 | print " enter the character"
l= raw_input()
if l in ('a','e','i','o','u','b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'):
print" the character is a letter"
else :
print " the characte is not a letter"
| false |
2deb4dcbca9a53b94ac6d0cddb7348f9093704f8 | harmanbirdi/HackerRank | /10DaysOfStats/day01_quartiles.py | 1,117 | 4.25 | 4 | #!/usr/bin/env python
#
# Problem: https://www.hackerrank.com/challenges/s10-quartiles
# __author__ : Harman Birdi
#
# Gets the median of the list which is the average of the middle
# two numbers of an odd length list, or the middle number of an
# even length list.
def median(l):
l = sorted(l, key=int)
mid = len(l) / 2
if len(l) % 2 == 0:
return (l[mid - 1] + l[mid]) / 2
else:
return l[mid]
# Gets quartile1 by calling median with first half of the list
# to get its median, which is the first quartile value.
def quartile1(l):
l = sorted(l, key=int)
return median(l[0: len(l) / 2])
# Gets quartile3 by calling median with second half of the list
# to get its median, which is the third quartile value.
def quartile3(l):
l = sorted(l, key=int)
if len(l) % 2 == 0:
return median(l[len(l) / 2:])
else:
return median(l[1 + len(l) / 2:])
# Main starts here
n = int(raw_input().strip())
l = map(int, raw_input().strip().split())[:n] # Get only first n elements from the line
print int(quartile1(l))
print int(median(l))
print int(quartile3(l))
| true |
37e3b89745a0693f979004a5e102990a1b50f8f0 | cbgoodrich/Unit2 | /lastname.py | 327 | 4.28125 | 4 | #Charlie Goodrich
#09/14/17
#lastname.py - tells you which half of the alphabet your name is in
last_name = input("Enter your last name: ")
lastName = last_name.lower()
if lastName > "a" and lastName < "m":
print("Your name is in the first half of the alphabet")
else:
print("Your name is the the second half of the alphabet")
| true |
bd926626cbd3a0a72af1025f86ced4b317b407e3 | sydoruk89/pythonic-garage-band | /pythonic_garage_band/pythonic_garage_band.py | 2,586 | 4.40625 | 4 | class Musician:
"""
Super class to all musicians. It has the next methods:
__init__ - creates role and instrument attributes and append it to the list.
__str__ - return a string with an object instance.
__repr__ - return a string readable for the Python interpreter.
play_solo - return a string indicating which musician plays solo.
get_instrument - returns a string with instrument.
"""
members = []
def __init__(self, role, instrument):
self.role = role
self.instrument = instrument
self.__class__.members.append(self)
def __str__(self):
return f'I am a {self.role}'
def __repr__(self):
return self.role
def play_solo(self):
return f'{self.role} is playing solo on the {self.instrument}'
def get_instrument(self):
return self.instrument
class Guitarist(Musician):
"""Subclass that creates a new guitarist and inherits properties from
the Musician super class"""
pass
class Bassist(Musician):
"""Subclass that creates a new bassist and inherits properties from
the Musician super class"""
pass
class Drummer(Musician):
"""Subclass that creates a new drummer and inherits properties from
the Musician super class"""
pass
class Band:
"""
This Class creates a Band instance and has the next class methods:
__init__, __str__, __repr__, play_solos, to_list.
"""
new_band = []
def __init__(self, name, members=[]):
"""
Creates name of the band and its members, and append new object instance to the list new_band
"""
self.name = name
self.members = members
self.__class__.new_band.append(self)
def play_solos(self):
"""
Method that asks each member musician to play a solo, in the order they were added to band.
"""
solo = ''
for mus in self.members:
solo += f'{mus}\n'
return solo
def __str__(self):
"""return string with the the object instance"""
return f'We are the {self.name}'
def __repr__(self):
"""return string with the object instance"""
return ('The band name is ' + self.name)
@classmethod
def to_list(cls):
"""returns a list of previously created Band instances"""
return cls.new_band
guitarist_1 = Guitarist('guitarist', 'guitar')
bassist_1 = Bassist('bassist', 'bass')
drummer_1 = Drummer('drummer', 'drumm')
print(guitarist_1.play_solo())
band_1 = Band('Wild dogs', Musician.members)
| true |
48d81eecd0da591586b42237a23cdb3a90a5333f | aa-fahim/leetcode-problems | /Remove Nth Node from End of List/main.py | 1,306 | 4.125 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
'''
Time Complexity: O(n) where n is the number of nodes in the linked list.
Solution uses two pointer solution. One pointer is fast and other pointer is slow. Fast pointer will start at Nth position of the linked list while slow pointer
will start at the beginning of the linked list. Increment both pointers by 1 until the fast pointer reaches the end of the linked list. At this pointer, we know
the next node of the slow pointer is the Nth node from end of list. We want to skip this next node and change the connection of the slow pointer node to point at
the node two positiosn away thus skipping the Nth node from end of list.
'''
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
dummy = ListNode(next=head)
slow = fast = dummy
print(slow, fast)
for i in range(n):
fast = fast.next
while(True):
if (fast.next == None):
break
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy.next
| true |
3d9bca25b2d4d75b297f1fa35b1b2659f6e0b0d0 | aa-fahim/leetcode-problems | /Symmetric Tree/main.py | 2,139 | 4.1875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
'''
Time Complexity: O(n) where n is the number of nodes in the tree.
Recursion Approach
Make sure left of left node is equal to right of right node and that right of left node and left of right node is the same.
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
if not root:
return True
return self.helper(root.left, root.right)
def helper(self, left, right):
if not left and not right:
return True
if not left or not right:
return False
if left.val != right.val:
return False
return self.helper(left.left, right.right) and self.helper(left.right, right.left)
'''
'''
Time Complexity: O(n) where n is the number of nodes in the tree.
Iterative Approach
The recursive approach basically uses a stack to check which left and right nodes to check next. So in iterative approach, we will manage our own stack.
Popping the latest nodes in our stack and checking if the values are the same then we append the right of the left node and left of the right node to the stack
as a pair and also the left of the left node and right of the right node as a pair too.
'''
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
res = True
stack = [[root.left, root.right]] if root else []
while len(stack) > 0:
left, right = stack.pop(-1)
if not left and not right:
continue
if not left or not right:
res = False
break
if left.val != right.val:
res = False
break
stack.append([left.left, right.right])
stack.append([left.right, right.left])
return res
| true |
7c400e4cc59a3ad71eaff988883165400762df33 | kuswahashish/learningPaython | /exercise7.py | 244 | 4.125 | 4 | #remove the duplicates from list
numbers = [12,11,14,25,12,26,11]
unique = []
for item in numbers:
if item not in unique:
unique.append(item)
print("Before removing duplicates :",numbers)
print("After removing duplicates :",unique) | true |
a3a503c2c45b1b96a622b188297651ce2a7f2a20 | kolozsiszabina/Hazifeldat | /lista.py | 1,520 | 4.125 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
self.before=None
class LinkedList:
head=None
def appendFront(self,data):
new_e=Node(data)
new_e.next=new_e
self.head=new_e
def appendBack(self,data):
new_e=Node(data)
if self.head is None:
self.head=new_e
else:
current_item=self.head
while current_item.next is not None:
current_item=current_item.next
current_item.next=new_e
def remove(self,element):
tmp=self.head
previous=None
while tmp is not None:
if tmp.data==element:
if previous in None:
self.head=self.head.next
else:
previous.next=tmp.next
previous=tmp
tmp=tmp.next
def show(self):
tmp=self.head
print('A lista elemei:')
while tmp is not None:
print(tmp.data, '->', end=' ')
tmp=tmp.next
print('None')
def append(self,data,after):
new_e=Node(data)
if self.head is None:
self.head=new_e
else:
new_e.before=after
new_e.next=after.next
after.next=new_e
new_e.next.before=new_e
s=LinkedList()
s.appendFront(23)
s.appendFront(42)
s.appendBack(11)
s.appendBack(77)
s.show()
s.append(5,23)
s.show() | true |
4ccee55d569ec4343be7fc795dcd93832252c7aa | srad1292/PythonCrashCourse | /Chapter10/learning_python.py | 783 | 4.6875 | 5 | """
Exercise 10-1
Open a blank text file and write a few lines stating
what you have learned in python so far.
Write a program that reads the file and then
prints what you've wrote three times.
Print the contents
1: By reading the entire file
2: By looping over the file object
3: By storing the lines in a list and working with it outside the open block
"""
filename = "learned_in_python.txt"
# Read the entire file
with open(filename) as file_object:
contents = file_object.read()
print(contents)
print("\n")
# Loop over the file object
with open(filename) as file_object:
for line in file_object:
print(line.strip())
print("\n")
# Store the lines in a list
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.strip()) | true |
7f5e8041da6e0d5014d64168336d05cdb48beb22 | srad1292/PythonCrashCourse | /Chapter8/album.py | 713 | 4.6875 | 5 | """
Exercise 8-7
Write a function called make_album() that
builds a dictionary with an artist name and album title.
Use the function to build three dictionaries
and then print them all.
Add an optional parameter to store the number of tracks
Make one new call with the optional parameter
"""
def make_album(artist_name, album_title, number_of_tracks=""):
album = {"artist": artist_name, "album": album_title}
if number_of_tracks:
album['tracks'] = number_of_tracks
return album
album = make_album("Blink-182", "California")
print(album)
album = make_album("Lorde", "Pure Heroine")
print(album)
album = make_album("Drake", "Take Care")
print(album)
album = make_album("Kid Cudi", "Indicud", 18)
print(album) | true |
f458c3053ea99d871fd2e8f70685a27c03bc18f9 | srad1292/PythonCrashCourse | /Chapter4/slices.py | 359 | 4.40625 | 4 | #Exercise 4-10
#Use slices to do the following
#Print the first three items
#Print the middle three items
#Print the last three items
numbers = [value for value in range(1,21)]
print("The first three numbers are ")
print(numbers[:3])
print("\nThree items from the middle are ")
print(numbers[8:11])
print("\nThe last three numbers are ")
print(numbers[-3:]) | true |
a3634a330ffa1ba919d5bb1dcf52506a6e13f038 | srad1292/PythonCrashCourse | /Chapter10/division.py | 276 | 4.125 | 4 | print("Give me two numbers and I'll divide them.")
first_number = int(input("\nFirst Number: "))
second_number = int(input("Second Number: "))
try:
result = first_number / second_number
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print(str(result)) | true |
f7b1de4789321aff490b57ab522ee74db97c994f | srad1292/PythonCrashCourse | /Chapter4/odd_numbers.py | 201 | 4.28125 | 4 | #Exercise 4-6
#Use the third argument in the range function
#to make a list of odd numbers 1-20
#Use a for loop to print them
odd = [value for value in range(1,20,2)]
for number in odd:
print(number) | true |
3a1d8d4cf2db76cde2a7ed502c33f9264bca78a1 | srad1292/PythonCrashCourse | /Chapter8/city_names.py | 539 | 4.5 | 4 | """
Exercise 8-6
Write a function, city_country() that
takes the name of a city and a country
and returns a string formatted as:
"city, country"
Call your function three times and print the result
"""
def city_country(city, country):
"""Takes a city and country and formats them as city, country"""
formatted = city + ", " + country
return formatted.title()
location = city_country("raleigh", "USA")
print(location)
location = city_country("toronto", "canada")
print(location)
location = city_country("tokyo", "japan")
print(location) | true |
b0a8f44a99020e7cb96a1bcafe5a4c4d4826a2d4 | srad1292/PythonCrashCourse | /Chapter5/alien_colors2.py | 474 | 4.125 | 4 | #Exercise 5-4
#Create a variable 'alien_color' and
#assign it green yellow or red
#Write an if/else
#if green they earn 5 otherwise they earn 10
alien_color = 'green'
print("alien color: " + alien_color)
if alien_color == 'green':
print("You earned 5 points")
else:
print("You earned 10 points")
print("\n")
alien_color = 'red'
print("alien color: " + alien_color)
if alien_color == 'green':
print("You earned 5 points")
else:
print("You earned 10 points")
print("\n") | true |
6e3e15e0bc4ad3a7e6a118cc50ba5dc4aa0fbeb8 | srad1292/PythonCrashCourse | /Chapter5/stages_of_life.py | 356 | 4.21875 | 4 | #Exercise 5-6
#Write an ifelifelse chain that
#determines a person's stage of life
age = 25
print("Age: " + str(age))
if age < 2:
print("You are a baby")
elif age < 4:
print("You are a toddler")
elif age < 13:
print("You are a kid")
elif age < 20:
print("You are a teenager")
elif age < 65:
print("You are an adult")
else:
print("You are an elder") | false |
8a30409c27af9a72498f8682f9444489741692ae | srad1292/PythonCrashCourse | /Chapter10/programming_poll.py | 402 | 4.375 | 4 | """
Exercise 10-5
write a while loop that asks people why they like
programming. Each time someone enters a reason,
add that reason to a file that stores the responses
"""
filename = 'programming_responses.txt'
with open(filename, 'w') as file_object:
while True:
response = input("Why do you like programming?('q' to quit) ")
if response == 'q':
break
file_object.write(response + '\n')
| true |
e57c777d816fcc8a35ff97067174429e45d0eebe | srad1292/PythonCrashCourse | /Chapter7/dream_vacation.py | 455 | 4.1875 | 4 | """
Exercise 7-10
Poll users about where they want to visit
then print through the dictionary
"""
vacations = {}
polling = True
while polling:
name = input("\nWhat is your name? ")
place = input("Where would you like to visit? ")
vacations[name] = place
again = input("Poll another person(y/n)? ")
if again == 'n':
polling = False
print("\n")
for person, place in vacations.items():
print(person.title() + " wants to visit " + place.title())
| true |
b68485be680201e3373062e7f9eb2741eda357cc | mauproject/python | /Exo_W3Resource/01_BASIC/015.py | 260 | 4.34375 | 4 | # Write a Python program to get the volume of a sphere with radius 6.
import math
# My Proposal
print (((4 * math.pi) * (6 * 6 * 6)) / 3)
# Another solution
pi = 3.1415926535897931
r= 6.0
V= 4.0/3.0*pi* r**3
print('The volume of the sphere is: ',V) | true |
213fdb7c8dee3fe9f768eaf5077e44c3f4bf6e67 | timothycryals/SmallProjects | /ComputerScience1101/ChaseRyalsA4.py | 1,709 | 4.25 | 4 | #Name: Chase Ryals
#File: Assignment 4
#Date: October 14, 2015
#Description:
import turtle
import random
#This function receives input for the amount of circles that will be drawn
def main():
global amount #'amount' will store the number of circles
amount=int(input("How many circles would you like to draw? "))
while amount<=0:
amount=int(input("Invalid input. The amount must be an integer greater than 0: "))
return amount
#This function receives input for the radius of a circle
def circle_radius():
global userradius #'userradius' will store the radius of the largest circle
userradius=int(input("Please enter the radius of the largest circle (50-300): "))
while userradius<50 or userradius>300:
if userradius<50:
userradius=int(input("Too small. Enter an integer between 50 and 300: "))
if userradius>300:
userradius=int(input("Too large. Enter an integer between 50 and 300: "))
return userradius
print("This program draws circles with decreasing radius sizes.")
print()
main()
print()
circle_radius()
radius=userradius
turtle.title("CPSC1301 Assignment 4 T.Ryals")
for x in range(amount, 0, -1):
turtle.penup()
turtle.goto(0, radius*(-1))
turtle.showturtle()
turtle.begin_fill()
turtle.color(random.random(), random.random(), random.random())
turtle.pendown()
turtle.speed(9)
turtle.circle(radius)
turtle.penup()
turtle.end_fill()
turtle.hideturtle()
radius = radius - 20
#This section creates the caption for the drawing
turtle.goto(0 , userradius+50)
turtle.write("Thank you for using the program.", align='center')
| true |
2d9317d3cae9adfa5b98e936dc540335a89c4f13 | timothycryals/SmallProjects | /ComputerScience1101/Labs/ChaseRyalsLab17.py | 1,192 | 4.15625 | 4 | #Name: Chase Ryals
#File: Lab 17
#Date: September 30, 2015
#Description: Counting wih loops
print("Step 1") #Step 1
i=20
while i>0:
print(i)
i-=2 #i decreases by 2 each time the loop runs
print()
print("Step 2") #Step 2
for a in range(0, 101, 10):
print(a, end=" ")
print()
print()
print("Step 3") #Step 3
print("The answer to number 3 is no.")
print()
print()
print("Step 4") #Step 4
for i in range(1, 4):
if i==1:
for j in range(1, i*11): #Creates a line with 10 asterisks
print("*", end= " ")
print()
if i==2:
for j in range(2, i+5): #Creates a line with 5 asterisks
print("*", end= " ")
print()
if i==3:
for j in range(3, i+20): #Creates a line with 20 asterisks
print("*", end=" ")
print()
print()
print()
print("Step 5") #Step 5
for c in range(10):
for d in range(10): #Adds 9 asterisks to each line
print("*", end=" ")
print()
print()
print()
print("Step 6") #Step 6
for e in range(0, 10):
for g in range(0, e+1): #adds a new number each line
print(g, end=" ")
print()
| false |
473257fec538e526550e9d705299114c8c798e20 | satskyi1991/Stage2_Python_advanced | /class_030/cl_031.py | 220 | 4.125 | 4 | x = int(input("Введите максмальное значение счетчика"))
for i in range(x+1):
if(x<2):
continue
elif(x>5):
break
else:
print(i)
else:
print("Else") | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.