blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
8b4d477363cd34ce76d63351d2eccb639f5cdf29 | xiu-du-du/ggpy | /Day02/输出.py | 251 | 4.15625 | 4 | # 普通输出
print('Hello,Python!')
# 格式化输出
# %s --> 字符串
# %d --> 数值
name='Tom'
age=18
print('我的名字是%s,我的年龄是%d' % (name,age))
# 占位符
name='Tom'
age=18
print(f'我的名字是{name},我的年龄是{age}') | false |
cb9a905b7a4dc680f3ae4a0bc7ba8fc0b80ef13b | praveenhyalij/Basic_Py_Program | /avg_from_numbers.py | 313 | 4.28125 | 4 | #get three number from user and find avg
Number_1, Number_2, Number_3 = input("Enter three number comma seperated ").split(",")
avg = (int(Number_1)+int(Number_2)+int(Number_3))/3
print(avg)
#num1, num2, num3 = input(int("Enter three number comma seperated ")) .split(",")
# Avg = (num1+num2+num3)/3
# print(Avg) | false |
c222a844ff2898a7d43403f70c34b9cd6af23409 | KHATRIVINAY1/Data-Structures | /Stack,QUEUE,DQUEUE/queue.py | 793 | 4.3125 | 4 | class Queue():
def __init__(self):
self.items = []
def is_empty(self):
if self.items == []:
print("Queue is Empty")
else:
print("There are some elemetns in the Queue")
def en_queue(self,data):
self.items.insert(0,data)
print(data,"has been added to the rear part of the Queue")
def de_queue(self):
self.items.pop()
print("Front element of the Queue has been deleted")
def size(self):
print("The size of the Queue is:",len(self.items))
def peek(self):
print("The current Front element is:", self.items[len(self.items)-1])
def show_queue(self):
print("rear-->|",end="")
for i in self.items:
print(str(i)+"|",end="")
print("<--Front")
q = Queue()
q.is_empty()
q.en_queue(4)
q.en_queue(10)
q.de_queue()
q.en_queue(12)
q.en_queue(13)
q.en_queue(14) | false |
8412db3f75e136fe99676b4198a761b9dcf53114 | retzkek/projecteuler | /python/eu017.py | 1,899 | 4.15625 | 4 | #!/usr/bin/python
# encoding: utf-8
def numToWords(num, spaces=True):
"""
returns the word representation of num.
e.g. 225 would return "two hundred and twenty-five"
if spaces=False spaces, 'and', and hyphens are ommitted
e.g. "twohundredandtwentyfive"
"""
digits = ['zero','one','two','three','four','five','six','seven','eight','nine','ten',
'eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen']
tens = ['zero','ten','twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety']
string = ''
if num < 20:
string += digits[num]
elif num < 100:
string += tens[int(num / 10)]
if num % 10 > 0 :
if spaces: string += '-'
string += digits[num % 10]
elif num < 1000:
string += digits[int(num / 100)]
if spaces: string += ' '
string += 'hundred'
if num % 100 > 0:
if spaces: string += ' '
string += 'and'
if spaces: string += ' '
string += numToWords(num % 100, spaces)
elif num < 1000000:
string += numToWords(int(num / 1000))
if spaces: string += ' '
string += 'thousand'
if num % 1000 > 0:
if spaces: string += ' '
string += 'and'
if spaces: string += ' '
string += numToWords(num % 1000)
return string
def main():
# test cases
n = 342
ns = numToWords(n, False)
print n, ns
print "%i letters" % len(ns)
if len(ns) == 23:
print "okay"
n = 115
ns = numToWords(n, False)
print n, ns
print "%i letters" % len(ns)
if len(ns) == 20:
print "okay"
# problem
cnt = 0
for i in range(1,1001):
str = numToWords(i, False)
cnt += len(str)
print cnt
if __name__ == "__main__":
main()
| false |
407d13489bb9498c91475503eff230748e691bfb | kamrulhasan0101/learn_python | /set.py | 607 | 4.46875 | 4 | fruits = {"apple", "banana", "lemon", "orange", "mango"}
# checking type of fruits variable
print(type(fruits))
# checking item is in the set or not
print("banana" in fruits)
# printing whole set as a loop
for x in fruits:
print(x)
# Adding new items into set
fruits.add("added")
print(fruits)
# adding multiple items into set by update function
fruits.update(["orange", "new fruits", "grapes"])
print(fruits)
fruits.discard("banana") # can use pop(delete last) or clear to empty set
print(fruits)
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
set1.update(set2)
print(set1) | true |
1d8f1ee074a54d8a7e58549042bb1fc19d43a626 | DSXiangLi/Leetcode_python | /script/[143]重排链表.py | 2,020 | 4.25 | 4 | # 给定一个单链表 L 的头节点 head ,单链表 L 表示为:
#
#
# L0 → L1 → … → Ln - 1 → Ln
#
#
# 请将其重新排列后变为:
#
#
# L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
#
# 不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
#
#
#
# 示例 1:
#
#
#
#
# 输入:head = [1,2,3,4]
# 输出:[1,4,2,3]
#
# 示例 2:
#
#
#
#
# 输入:head = [1,2,3,4,5]
# 输出:[1,5,2,4,3]
#
#
#
# 提示:
#
#
# 链表的长度范围为 [1, 5 * 104]
# 1 <= node.val <= 1000
#
# Related Topics 栈 递归 链表 双指针
# 👍 969 👎 0
# leetcode submit region begin(Prohibit modification and deletion)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
if not head:
return None
def reverse(head):
newnode = None
cur = head
while cur:
nextnode = cur.next
cur.next=newnode
newnode = cur
cur = nextnode
return newnode
def getmid(head):
slow, fast = head, head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
return slow
def merge(l1, l2):
while l1 and l2:
l1_tmp = l1.next
l2_tmp = l2.next
l1.next = l2
l1 = l1_tmp
l2.next = l1
l2 = l2_tmp
ptr1 = head
left_mid = getmid(head)
mid = left_mid.next
left_mid.next=None
ptr2 = reverse(mid)
merge(ptr1, ptr2)
# leetcode submit region end(Prohibit modification and deletion)
| false |
927751eb4c4f02070516b012d7efe0a02efed428 | ifrost2/Homework-Projects | /hw5/rod.py | 1,872 | 4.125 | 4 | ############################################################
#********************Rod Class*****************************
############################################################
"""
Abstraction representing a single game rod. Disks are stored
as integers (larger disks are larger integers).
Disks are stored in lists from bottom to top. In other words,
the top disk is the last element.
You should NOT edit ANYTHING in this class.
"""
class Rod:
def __init__(self, height):
self.disks = []
self.height = height
#adds specified disk to the rod
#NOTE: Validation checking is completed in
#the games makeMove function of the Game class
def add(self, disk):
self.disks.append(disk)
#Removes a disk from rod
def remove(self):
return self.disks.pop()
#Removes all disks from rod
def removeAll(self):
self.disks = []
#returns true if the rod is empty
def isEmpty(self):
return len(self.disks) == 0
#validates disk addition
def isValidAddition(self,disk):
return self.isEmpty() or self.disks[len(self.disks) - 1] > disk
#returns number of disks on the rod
def numDisks(self):
return len(self.disks)
#returns a string representation of the rod
def toString(self):
output = "| "
for disk in self.disks:
output += str(disk) + " "
for i in range(self.height -self.numDisks()):
output += "--" + " "
return output
#helper function for the game hash
def hash(self, rod):
output = 0
for disk in self.disks:
output += rod * pow(8, (disk - 1))
return output
#helper function for the game copy function
def makeCopy(self):
new = Rod(self.height)
for disk in self.disks:
new.add(disk)
return new | true |
8ce4c0cb3b53d741477ab22c0c620d9e9a50dd42 | anis-byanjankar/python-leetcode | /balanced-binary-tree.py | 1,183 | 4.28125 | 4 | # Given a binary tree, determine if it is height-balanced.
# For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of
# every node never differ by more than 1.
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# The expected result is to return a bool ; True -> if its balanced & False -> if not balanced
#Solution
#========
# (1) We make use of an extra function that calculates the height of a given Node ; with a simple twist -
# (2) return -1 in case, the difference between the height of left and right is > 1
class Solution:
# @param root, a tree node
# @return a boolean
def isBalanced(self, root):
return (self.getHeight(root) >=0 )
def getHeight(self,root):
if root is None:
return 0
left_height, right_height = self.getHeight(root.left),self.getHeight(root.right)
if left_height < 0 or right_height < 0 or abs(left_height - right_height) > 1:
return -1
return max(left_height,right_height) + 1 | true |
bef146d5381b41088d52e7f50d89d74c6b304267 | wunnox/python_advanced | /Musterloesungen/Kartenspiel.py | 913 | 4.15625 | 4 | #!/usr/bin/env python3
"""
Wir haben folgende Karten
werte = ['Ass', 'König', 'Dame', 'Bube', '10', '9', '8', '7', '6']
farben = ['Herz', 'Ecke', 'Schaufel', 'Kreuz']
Erstellen Sie ein gesamtes Kartenspiel
- mit einem Generator cards()
- mit einer Generator Expression
- mit Hilfe der itertools-Methode product()
"""
werte = ['Ass', 'König', 'Dame', 'Bube', '10', '9', '8', '7', '6']
farben = ['Herz', 'Ecke', 'Schaufel', 'Kreuz']
# der Generator
def karten_generator():
for wert in werte:
for farbe in farben:
yield wert, farbe
# Generator Ausdruck
karten = ((wert, farbe) for wert in werte for farbe in farben)
# mit den itertools
import itertools as it
karten_it = it.product(werte, farben)
# Anwendung
for k in karten_generator():
print(k, end=' ')
print('')
for k in karten:
print(k, end=' ')
print('')
for k in karten_it:
print(k, end=' ')
print('')
| false |
450566170eae6dc39dcd94394e8ea97e574b7dde | andreinaoliveira/Exercicios-Python | /Exercicios/083 - Validando expressões matemáticas.py | 444 | 4.21875 | 4 | # Exercício Python 083 - Validando expressões matemáticas
# Crie um programa onde o usuário digite uma expressão qualquer que use parênteses.
# Seu aplicativo deverá analisar se a expressão passada está com os parênteses abertos e fechados na ordem correta.
exp = str(input('Dgite a expressão: '))
if exp.count('(') == exp.count(')'):
print("Sua expressão está válida!")
else:
print("Sua expressão está errada!")
| false |
628952699e3cca142f88915a6ab10a3d3b839252 | andreinaoliveira/Exercicios-Python | /Exercicios/100 - Funções para sortear e somar.py | 630 | 4.25 | 4 | # Exercício Python 099 - Função que descobre o maior
# Faça um programa que tenha uma lista chamada números e duas funções chamadas sorteia() e somaPar().
# A primeira função vai sortear 5 números e vai colocá-los dentro da lista e a segunda função vai mostrar
# a soma entre todos os valores pares sorteados pela função anterior.
from random import randint
def sorteia(lista):
for i in range(0, 5):
lista.append(randint(1, 10))
print(f'Lista: {lista}')
def soma(lista):
print(f'A soma entre os itens da lista é: {sum(lista)}')
numeros = list()
sorteia(numeros)
soma(numeros)
| false |
dde2991f0c4a9bb1333f35114cdf3a2db5619ff8 | andreinaoliveira/Exercicios-Python | /Exercicios/036 - Aprovando Empréstimo.py | 797 | 4.1875 | 4 | # Exercício Python 036 - Aprovando Empréstimo
# Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa.
# Pergunte o valor da casa, o salário do comprador e em quantos anos ele vai pagar.
# A prestação mensal não pode exceder 30% do salário ou então o empréstimo será negado.
casa = float(input("Informe o valor do imóvel: "))
salario = float(input("Informe sua renda mensal: "))
anos = int(input("Informe em quantos anos de financiamento: "))
prestacao = casa / (anos * 12)
if prestacao > (salario*30/100):
print("Infelizmente, o empréstimo foi negado pois a porestação é superior a 30% de sua renda mensal.")
else:
print("Empréstimo aceito. A prestação será de R${:.2f}. Para pagemtno em {} meses.".format(prestacao, anos * 12))
| false |
198984adc7f9cfcc50ffc9b6d654a2953344473e | andreinaoliveira/Exercicios-Python | /Exercicios/108 - Formatando Moedas.py | 482 | 4.125 | 4 | # Exercício Python 108 - Formatando Moedas
# Adapte o código do desafio #107, criando uma função adicional chamada moeda() que consiga mostrar os
# números como um valor monetário formatado.
from pacote import moeda
num = float(input('Informe um valor: '))
print(f'''Aumento de 10%: {moeda.moeda(moeda.aumentar(num, 10))}
Subtração de 10%: {moeda.moeda(moeda.diminuir(num, 10))}
Dobro: {moeda.moeda(moeda.dobro(num))}
Metade: {moeda.moeda(moeda.metade(num))}''')
| false |
15180baa0c2dc433e6e9d2a1266422c714b3b692 | andreinaoliveira/Exercicios-Python | /Exercicios/039 - Alistamento Militar.py | 990 | 4.28125 | 4 | # Exercício Python 039 - Alistamento Militar
# Faça um programa que leia o ano de nascimento de um jovem
# e informe, de acordo com a sua idade, se ele ainda vai se alistar ao serviço militar,
# se é a hora exata de se alistar ou se já passou do tempo do alistamento.
# Seu programa também deverá mostrar o tempo que falta ou que passou do prazo.
from datetime import date
ano_atual = date.today().year
ano = int(input("Infome seu ano de nascimento: "))
idade = ano_atual - ano
print("Quem naceu em {} tem {} anos no ano de {}.".format(ano, idade, ano_atual))
if idade < 18:
print("VocÊ irá se alistar em {} ano(s)".format(18 - idade))
print("Você deverá se alistar em {} ".format(ano_atual + (18-idade)))
elif idade == 18:
print("Você irá se alistar nesse ano de {}".format(ano_atual))
elif idade > 18:
print("Você deveria ter se alistado há {} anos".format(idade-18))
print("Seu alistamento foi em {}".format(ano_atual - (idade - 18)))
| false |
a17a34260ed8e3c6c82f9782c7ff7233fca7ae22 | OperaPRiNCE/PRiNCE | /15155151.py | 227 | 4.15625 | 4 | def factorial(n):
if n==0 or n==1:
return 1
else:
return n*factorial(n-1)
num=int(input("Enter fast number="))
if num<0:
print("Enter positive number")
else:
print("Result=",factorial(num))
| true |
7921581d7c8fd02b776279c1aa70a03a10100bae | fuji-ha/AtCoder_TIPS | /filter.py | 509 | 4.21875 | 4 | def even_evaluator(x:int)->bool:
"""この関数は引数が偶数ならばTrue,
奇数ならばFalseを返します
"""
return x % 2 ==0
#関数の確認
for i in range(5):
print(i,even_evaluator(i))
#ベースとなるリスト
num_list = list(range(10)) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#関数でフィルター
even_list = filter(even_evaluator, num_list)
print(list(even_list))
#lambda でフィルター
even_list2 = filter(lambda x:x % 3 ==0, num_list)
print(list(even_list2))
| false |
573220bcbaaca37a160611a46177598e29b08449 | arvin1384/Arvin | /Arvin_2/problem-input.py | 332 | 4.21875 | 4 | first_input = input("Enter your number")
input_list = []
while(first_input):
input_list.append(int(first_input))
first_input = input("Enter your number")
total = 0
for number in input_list:
total += number
count = len(input_list)
average = total/count
print(f"Sum of my numbers: {total}")
print(average) | true |
f5cf301586745ef534ac55b55927a62c6b783098 | yogitakumar/PythonProg1 | /Pallindrome.py | 203 | 4.34375 | 4 | n = str(input("Enter string : "))
n_in_reverse = n[::-1]
print(n_in_reverse)
if(n == n_in_reverse) :
print("Given string is pallindrome")
else :
print("Given dtring is not pallindrome")
| false |
260f070e6e69baa2121a95fb8c371d2fb1313fad | EmmaTrann/Matrix-Multiplication | /matrix_mult.py | 1,167 | 4.3125 | 4 |
import numpy as np
def matrixmultiply(a, b, result):
for i in range(len(a)):
for j in range(len(b[0])):
for k in range(len(b)):
result[i][j] += a[i][k] * b[k][j]
return result
import time
def main():
print("Please enter same number for ")
row_a = int(input("Enter the number of rows in matrix A: "))
col = int(input("Enter the number of columns in matrix A: "))
col_b = int(input("Enter the number of columns in matrix B: "))
a = np.random.randint(10, size=(row_a,col))
b = np.random.randint(10, size=(col,col_b))
result = np.zeros((row_a, col_b))
start = time.time()
result = matrixmultiply(a, b, result)
end = time.time()
computeTime= end-start
print("\nThe compute time using non built-in is %.3f seconds." % computeTime)
start = time.time()
res = np.dot(a,b)
end = time.time()
computeTime= end-start
print("\nThe compute time using built-in is %.3f seconds." % computeTime)
if (result==res).all():
print("\nThe matrix product got from non built-in routine is the same as the result we use numpy to calculate.")
main()
| true |
164e57f9e7d411f809255cfe2fc42a2d60b828da | quodeabc/Demo | /act2.py | 225 | 4.1875 | 4 | """Coding Activity 2: Integer Input from keyboard**
Print 'Enter a Number'
Take integer input from the keyboard and Store it in a variable num
Print 'The number you entered is' and value in the container num
Code Below """
| true |
6ac4ae87f6a381b27e1a6b372b6a62a32c79e3f2 | agzsoftsi/holbertonschool-web_back_end | /0x05-personal_data/encrypt_password.py | 1,084 | 4.21875 | 4 | #!/usr/bin/env python3
'''
5. Encrypting passwords
6. Check valid password
'''
import bcrypt
def hash_password(password: str) -> bytes:
''' Description: Implement a hash_password function that expects one string
argument name password and returns a salted, hashed
password, which is a byte string.
Use the bcrypt package to perform the hashing (with hashpw).
'''
pass_encoded = password.encode()
pass_hashed = bcrypt.hashpw(pass_encoded, bcrypt.gensalt())
return pass_hashed
def is_valid(hashed_password: bytes, password: str) -> bool:
'''
Description: Implement an is_valid function that expects 2 arguments and
returns a boolean.
Arguments: hashed_password: bytes type
password: string type
Use bcrypt to validate that the provided password matches the hashed
password.
'''
valid = False
pass_encoded = password.encode()
if bcrypt.checkpw(pass_encoded, hashed_password):
valid = True
return valid
| true |
b0763434933f01cba7a0816df426fee3ad05b9a7 | minicloudsky/leetcode_solutions | /data_structures/python/reverse_linkedlist.py | 754 | 4.125 | 4 | #!/usr/bin/env python
# coding=utf-8
class ListNode:
def __init__(self,x):
self.next = None
self.val = x
def build_list(arr):
head = ListNode(0)
p = head
for n in arr:
p.next = ListNode(n)
p = p.next
return head.next
def print_list(head):
while head:
print("{} {}".format(head, head.val))
head = head.next
def reverse_list(head):
pre = None
cur = head
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return pre
if __name__ == '__main__':
list_ = [x for x in range(1,8)]
l = build_list(list_)
print("before reverse: ")
print_list(l)
l = reverse_list(l)
print("after reverse: ")
print_list(l)
| false |
d15521f8c65a698063b84db552169060b23f6b4c | ergarrity/Markov-Chains | /markov.py | 2,463 | 4.125 | 4 | """Generate Markov text from text files."""
from random import choice
import sys
file_name = sys.argv[1]
words_list = []
def open_and_read_file(file_path):
"""Take file path as string; return text as string.
Takes a string that is a file path, opens the file, and turns
the file's contents as one string of text.
"""
with open (file_name) as file:
for line in file:
#why can't we just call line.rstrip() without setting it equal to itself?
line = line.rstrip()
word = line.split(" ")
global words_list
words_list = words_list + word
#alternative to line 19
#words_list.extend(word)
words_list.append(None)
return words_list
# open_and_read_file(file_name)
# your code goes here
# return "Contents of your file as one long string"
def make_chains(lst):
"""Take input text as string; return dictionary of Markov chains.
A chain will be a key that consists of a tuple of (word1, word2)
and the value would be a list of the word(s) that follow those two
words in the input text.
For example:
>>> chains = make_chains("hi there mary hi there juanita")
Each bigram (except the last) will be a key in chains:
>>> sorted(chains.keys())
[('hi', 'there'), ('mary', 'hi'), ('there', 'mary')]
Each item in chains is a list of all possible following words:
>>> chains[('hi', 'there')]
['mary', 'juanita']
>>> chains[('there','juanita')]
[None]
"""
chains = {}
for x in range(len(words_list) - 2):
key = (words_list[x], words_list[x+1])
if key not in chains:
chains[key] = []
# for i in words_list:
# if i == words_list[x + 1]:
chains[key].append(words_list[x + 2])
# for key in chains.items():
# print('{}: {}'.format(key[0], key[1]))
return chains
def make_text(chains):
# """Return text from chains."""
key = choice(list(chains))
#x_string = '{} {}'.format(x[0], x[1])
word = choice(chains[key])
words = []
while word is not None:
key = (key[1], word)
words.append(word)
word = choice(chains[key])
return " ".join(words)
# input_path = "green-eggs.txt"
# Open the file and turn it into one long string
input_text = open_and_read_file(file_name)
# # Get a Markov chain
chains = make_chains(input_text)
# # Produce random text
random_text = make_text(chains)
print(random_text)
| true |
169bd2b60ef17ab4731797bde107d712035a0b2f | sharlenechen0113/sc-projects | /stanCode Projects/boggle_game_solver/largest_digit.py | 1,480 | 4.71875 | 5 | """
File: largest_digit.py
Name: Sharlene Chen
----------------------------------
This file recursively prints the biggest digit in
5 different integers, 12345, 281, 6, -111, -9453
If your implementation is correct, you should see
5, 8, 6, 1, 9 on Console.
"""
def main():
print(find_largest_digit(12345)) # 5
print(find_largest_digit(281)) # 8
print(find_largest_digit(6)) # 6
print(find_largest_digit(-111)) # 1
print(find_largest_digit(-9453)) # 9
def find_largest_digit(n):
"""
:param n: the number to be processed and compared with
:return: the largest digit in the number
"""
num = abs(n)
initial_largest_digit = num % 10 # set largest digit to the last digit of the number
return helper(num, initial_largest_digit)
def helper(num,largest_digit):
"""
This is a helper function that helps find the largest digit with extra variables to assist
calculation. The calculation loops through the number by dividing it by 10 repeatedly to
separate out each digit, then compares recursively to find the largest digit.
:param num: the number to be checked
:param largest_digit: the current largest digit
:return: the most recent largest digit
"""
if num == 0:
return largest_digit
else:
last_digit = int(num % 10) #compare from the last digit
num = int((num - last_digit) / 10)
if last_digit >= largest_digit:
return helper(num,last_digit)
else:
return helper(num,largest_digit)
if __name__ == '__main__':
main()
| true |
bbf7f1dce30c150127d1b1f129f4fb7e92c27e03 | Spacha/SuperClient | /doc/assignment/template.py | 2,137 | 4.125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# The modules required
import sys
import socket
'''
This is a template that can be used in order to get started.
It takes 3 commandline arguments and calls function send_and_receive_tcp.
in haapa7 you can execute this file with the command:
python3 CourseWorkTemplate.py <ip> <port> <message>
Functions send_and_receive_tcp contains some comments.
If you implement what the comments ask for you should be able to create
a functioning TCP part of the course work with little hassle.
'''
def send_and_receive_tcp(address, port, message):
print("You gave arguments: {} {} {}".format(address, port, message))
# create TCP socket
# connect socket to given address and port
# python3 sendall() requires bytes like object. encode the message with str.encode() command
# send given message to socket
# receive data from socket
# data you received is in bytes format. turn it to string with .decode() command
# print received data
# close the socket
# Get your CID and UDP port from the message
# Continue to UDP messaging. You might want to give the function some other parameters like the above mentioned cid and port.
send_and_receive_udp(address, port)
return
def send_and_receive_udp(address, port):
'''
Implement UDP part here.
'''
print("This is the UDP part. Implement it yourself.")
return
def main():
USAGE = 'usage: %s <server address> <server port> <message>' % sys.argv[0]
try:
# Get the server address, port and message from command line arguments
server_address = str(sys.argv[1])
server_tcpport = int(sys.argv[2])
message = str(sys.argv[3])
except IndexError:
print("Index Error")
except ValueError:
print("Value Error")
# Print usage instructions and exit if we didn't get proper arguments
sys.exit(USAGE)
send_and_receive_tcp(server_address, server_tcpport, message)
if __name__ == '__main__':
# Call the main function when this script is executed
main()
| true |
140369335313ecaf6f7afd16dd14d63d4cb7e084 | gvu0110/learningPython | /learning_python/1.python_basics/functions.py | 762 | 4.25 | 4 | #
# Example file for working with functions
#
# Define a basic function
def function1():
print("I am a function")
function1()
print(function1())
# Function that takes arguments
def function2(arg1, arg2):
print(arg1, " and ", arg2)
function2(10, 20)
print(function2(10, 20))
# Function that returns a value
def cube(x):
return x*x*x
print(cube(5))
# Function with default value for an argument
def power(num, x = 1):
result = 1
for i in range(x):
result = result * num
return result
print(power(2))
print(power(2,4))
print(power(x = 4, num = 2))
# Function with variable number of arguments
def multiAdd(*x):
result = 0
for i in x:
result = result + i
return result
print(multiAdd(10, 20, 30, 40))
| true |
a173a4d89daa10020678e41efdfa7d4b8a725c9c | gvu0110/learningPython | /python_essential_training/8.strutured_data/dict.py | 770 | 4.25 | 4 | #!/usr/bin/env python3
def main():
animals = { 'kitten': 'meow', 'puppy': 'ruff!', 'lion': 'grrr',
'giraffe': 'I am a giraffe!', 'dragon': 'rawr' }
# animals = dict(kitten = 'meow', puppy = 'ruff!', lion = 'grrr', giraffe = 'I am a giraffe!', dragon = 'rawr')
for k in animals.keys():
print(k, end=' ', flush=True)
print()
for v in animals.values():
print(v, end=' ',flush=True)
print()
print_dict(animals)
# Insert a value into a dictionary
animals['monkey'] = 'haha'
print_dict(animals)
# Search a key in a dictionary
print('Yes!' if 'lion' in animals else 'No!')
print(animals.get('chimpanzee'))
def print_dict(o):
for x in o: print(f'{x}: {o[x]}')
if __name__ == '__main__':
main()
| false |
fe5bf71f371b6570303e0136d40b315dfa64afa5 | gvu0110/learningPython | /python_essential_training/6.loops/while.py | 464 | 4.125 | 4 | #!/usr/bin/env python3
secret = 'admin'
password = ''
auth = False
count = 0
max_attemp = 5
while password != secret:
count += 1
if count == 3:
continue
if count > max_attemp:
break
password = input(f"{count}: What's the secret word? ")
else: # not "else" statement. This "else" executes only if the loop ends normally, not execute there is a break
auth = True
print('Authorized' if auth else 'Calling the police ...') | true |
59e3e89537a100eb3b6baace1e006ac0623be2a2 | matyuhin/Task_1 | /calc.py | 1,574 | 4.34375 | 4 | def computation(num1):
try:
result = num1
lst = input("Для дальнейшего вычисления введите выражение в формате: <операция> <число> \nДля получения результата введите '=': ").split()
if len(lst) == 2:
operation, num2 = lst
if operation == '+':
result = num1 + float(num2)
elif operation == '-':
result = num1 - float(num2)
elif operation == '*':
result = num1 * float(num2)
elif operation == '/':
result = num1 / float(num2)
elif operation == '**':
result = num1 ** float(num2)
elif operation == '//':
result = num1 // float(num2)
elif operation == '%':
result = num1 % float(num2)
else:
raise Exception
return computation(result)
elif lst[0] == '=':
if result % 1 == 0.0:
result = int(result)
return print(result)
else:
raise ValueError
except ValueError:
print("Неверный формат ввода")
except ZeroDivisionError:
print("Деление на ноль!")
except Exception:
print("Неподдерживаемая операция")
try:
num1 = float(input("Введите число: "))
computation(num1)
except ValueError:
print("Неверный формат ввода")
| false |
9e4845039d9c0424c8d60419abfc8c09f1292d2f | Amartya-Srivastav/Python-Basic-programs | /BasicProgram/Factorial.py | 259 | 4.1875 | 4 | num1 = int(input("Enter First Number = "))
fact = 1
if num1 == 0:
print("Enter Positive value")
elif num1 == 1:
print("Factorial of 1 is 0")
else:
for i in range(1, num1+1):
fact = fact * i
print("The Factorial of", num1, "is", fact)
| true |
b0b466b4d519392f6a83074ca94a854594bb2e68 | Amartya-Srivastav/Python-Basic-programs | /BasicProgram/calculator.py | 766 | 4.15625 | 4 | def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
return a / b
print("Select operation")
print("1. Add")
print("2. subtract")
print("3. Multiply")
print("4. Divide")
choice = int(input("Enter Your Choice = "))
num1 = int(input("Enter First Number = "))
num2 = int(input("Enter Second Number = "))
if choice == 1:
print("Addition of", num1, "+", num2, " is = ", num1+num2)
elif choice == 2:
print("Subtraction of", num1, "-", num2, " is = ", num1 - num2)
elif choice == 3:
print("Multiplication of", num1, "*", num2, " is = ", num1 * num2)
elif choice == 4:
print("Division of", num1, "/", num2, " is = ", num1 / num2)
else:
print("Invalid Input! \n Try Again") | false |
7d99b5e1d976ce9b8152be08c29bc5675b23b66d | Amartya-Srivastav/Python-Basic-programs | /String_Program/adding_something_at_end.py | 435 | 4.5625 | 5 | # Write a Python program to add 'ing' at the end of a given string (length should be at least 3).
# If the given string already ends with 'ing' then add 'ly' instead.
# If the string length of the given string is less than 3, leave it unchanged
string = input("Enter String = ")
length = len(string)
if length > 2:
if string[-3:] == "ing":
string = string + "ly"
else:
string = string + "ing"
print(string)
| true |
1a3372ce63e3e5a6a9e4b339fec73dd4060a29b6 | RMWarner9/CIS-1101 | /RachelWarnerCopyFile.py | 665 | 4.4375 | 4 | """
Rachel Warner
November 27th, 2020
Program Name: Copy File
Program Purpose:
Write a script that will ask the user for two txt files.
The script will then take the input from one txt file and
output it to the other as a copy.
Inputs:
file name
Outputs:
A copy of the file
"""
# Open a file for txt input
# Ask user for input of the file and reads the text from the file
f = open((input("Please enter a text file to be copied: ")), 'r')
text = f.read()
# Input a file name for the original file to be copied
# Writes the last txt file to a new txt file
c = open((input("Please enter a name for the file to be copied: ")), 'w')
c.write(text)
c.close() | true |
525ed7a9c1b2266f54216cdf831d54cb6fa9b06d | Jhonathan-Pizarra/Deberes_2018 | /OperadoresLogicos.py | 720 | 4.21875 | 4 | print("*** OPERADORES LÓGICOS ***")
print("AND")
usuario1 = "Crhistian"
usuario2 = "Cristhiam"
usuario3 = "Crhistian"
if usuario1 and usuario2 == usuario3:
print("Ambos se llaman Crhistian")
else:
print("El nombre de uno de ellos no es Crhistian")
print("")
print("OR")
usuario4 = "Jhon"
usuario5 = "Jhonathan"
usuario6 = "Jhon"
if usuario4 or usuario5 == usuario6:
print("Al menos uno de los dos se llama Jhon")
else:
print("Ninguno de los dos se llama Jhon")
print("")
print("NOT")
estaLloviendo = True
if not estaLloviendo: #Si no es verdad que está lloviendo
print("Vamos afuera")
else:
print("Nos quedamos en casa!") #Porque está lloviendo es: True | false |
d686197a9a82d6526d44c959f00ca7f99600c702 | mikaelbeat/Complete_Python_Developer_2020 | /Complete_Python_Developer_2020/Functional_programming/List_comprehension.py | 677 | 4.25 | 4 |
print("\n********** Using for loop **********\n")
data = []
for char in "Hello":
data.append(char)
print(data)
print("\n********** Using list comprehension **********\n")
data = [char for char in "Hello again!"]
print(data)
print("\n********** Using list comprehension example 2 **********\n")
data = [num for num in range(0 , 21)]
print(data)
print("\n********** Using list comprehension example 3 **********\n")
data = [num * 2 for num in range(0, 21)]
print(data)
print("\n********** Using list comprehension example 4 **********\n")
data = [num * 2 for num in range(0, 21) if num % 2 ==0]
print(data)
| false |
a13824dea243b4d3939f8b578492bc690752a9c1 | mannygomez19/tic-tac-toe-C | /car_dealer.py | 2,054 | 4.34375 | 4 | car = {'honda':4000, 'toyota':3000, 'ford': 2000, 'acura': 7000}
print car
class account:
def __init__(self, balance=0):
self.balance = balance
def withdraw(self, amount):
self.balance -= amount
my_account = account(3500)# Object called my_account is = to the class called account where
print my_account.balance # you want to use stuff from (like balance).
# the for loop allows the appendage of a new key:value (car:price) to the dictionary w/o
#having to create an entire new set of conditional statements.car[brand] is the cost of a specific car.
for brand in car.keys():
if my_account.balance >= car[brand]:
print "I can afford the " + brand
else:
print "I need to make $" + str(car[brand] - my_account.balance) + " more to buy the " + brand
def qstn():
answer = raw_input("Would you be interested in buying a car?")
print answer
# answer = 'no' or 'yes'
if answer == "yes":
print raw_input("Here are the cars and their assigned prices ('Press Enter'):")
for brand in car.keys():
print "The " + brand + " costs $" + str(car[brand]) + "."
answer2 = None # its called None bc the buyer cannot purchase a car that DNE or that is too expensive for them.
while answer2 == None:
answer2 = raw_input("Which one would you want?")
if answer2 not in car.keys():
print "Sorry, we don't have that here, please try again."
answer2 = None
elif car[answer2] > my_account.balance:
print "Sorry, you cannot afford the car."
answer2 = None
else:
my_account.withdraw(car[answer2])
print "You have a " + str(answer2)
print "You have " + str(my_account.balance) + " left."
print "Thank you! Drive safely!"
elif answer == "no":
print raw_input("Good bye! Have a nice day!")
print qstn()
| true |
efb985141e6acbdccb59ea18d9c192afc6ca8ab1 | ozthegnp/ozthegnp | /1 - python/areaCalculator.py | 884 | 4.40625 | 4 | #This program is intended to calculate the area of circle or triangle.
#The shape and dimensions are defined by the input of a user from bash
print """ Welcome to Area calculator
This program will calculate the area of a shape of your choice.
"""
option = raw_input('Enter C for Circle or T for Triangle: ')
option = option.upper()
if option == 'C':
radius = raw_input('Please enter radius: ')
radius = float(radius)
area = radius ** 2 * 3.14
print 'The are of a %.1f radius circle is %.1f' % (radius, area)
elif option == 'T':
base = raw_input
('Enter the base of the triangle: ')
base = float(base)
height = raw_input('Enter the height of triangle: ')
height = float(height)
area = base * height / 2
print ('The area of of the triangle is %.1f') % height
else:
print 'Invalid character'
print 'Calculation completed, Goodbye!'
| true |
bd572b4b916cf6449a18a41b7ac7cbefa163e2b8 | harinjoshi/MyPythonPrograms | /PythonPrograms/firstandlast.py | 249 | 4.1875 | 4 | #program to exchange first and last character of string
def firstlast(string):
print(string [-1:])
print(string [1:-1])
print(string [:1])
return string [-1:] + string [1:-1] + string [:1]
string = input()
print(firstlast(string)) | true |
8dc0846e5b71eda85b633048e007b0895ad3c320 | SensumVitae13/PythonGB | /LS1_5.py | 1,491 | 4.1875 | 4 | # Запросите у пользователя значения выручки и издержек фирмы. Определите, с каким финансовым результатом работает фирма
# (прибыль — выручка больше издержек, или убыток — издержки больше выручки). Выведите соответствующее сообщение.
# Если фирма отработала с прибылью, вычислите рентабельность выручки (соотношение прибыли к выручке). Далее запросите
# численность сотрудников фирмы и определите прибыль фирмы в расчете на одного сотрудника.
profit = float(input("Введите общий доход фирмы: "))
costs = float(input("Введите издержки фирмы: "))
if profit > costs:
print(f"Фирма работает с прибылью. Рентабельность выручки составила {profit / costs}")
workers = int(input("Введите количество сотрудников фирмы: "))
print(f"Прибыль в расчете на одного сторудника сотавила: {(profit - costs) / workers}")
elif profit == costs:
print("Фирма работает в ноль.")
else:
print("Фирма работает в убыток.")
| false |
45b4b135be7b050f402ad2604c7d000a5f1d0a79 | rachel619/paths-to-cs-public | /m4/enumerate.py | 400 | 4.15625 | 4 | foods = ['peaches', 'apples', 'grapes']
def print_foods1():
index = 0
for food in foods:
print str(index) + ": " + food
index = index + 1
def print_foods2():
index = 0
for food in foods:
print str(index) + ": " + food
index += 1
def print_foods3():
for index, food in enumerate(foods):
print str(index) + ": " + food
print_foods3() | true |
143281c06e46bb4f1e4bff644974a1959b9ab1b9 | mmononen/Director-Ranking-Tool | /directors.py | 2,207 | 4.21875 | 4 | # Director Ranking Tool
# by Mikko Mononen
# Analyzes ratings.csv exported from IMDb.com and prints out the list of user's favorite movie directors.
# Usage: python directors.py >output.csv
# Import output.csv in Excel or equivalent and sort by weighted rating
import csv
# opens a csv file and returns it as a list
def open_csv(filename):
with open(filename, 'r') as f:
reader = csv.reader(f)
return list(reader)
# populate and return a dict of directors with names and ratings
# output dict: director name : a list of ratings
def populate_directors_dict(movies, directors):
for m in movies:
if m[5] == 'movie':
dirs = m[12].split(", ")
for d in dirs:
if d in directors:
directors[d] += [int(m[1])]
directors[d].sort(reverse=True)
else:
directors[d] = [int(m[1])]
return directors
# returns the number of movies in a movie list
def num_of_movies(movies):
i = 0
for m in movies:
if m[5] == 'movie':
i += 1
return i
# returns the sum of all movie ratings in a movie list
def sum_of_ratings(movies):
i = 0
for m in movies:
if m[5] == 'movie':
i += int(m[1])
return i
# calculate a weighted average for directors dict
# input: directors (dict), required amount of movies (int)
def calculate_weighted_average(directors, req_movies):
for xd in directors:
if (len(directors[xd]) >= req_movies):
tempsum = 0
for t1 in directors[xd]:
tempsum += int(t1)
R = tempsum / len(directors[xd]) # average rating for director's movies
v = len(directors[xd]) # number of director's movies
C = sum_of_ratings(movies) / num_of_movies(movies) # the average rating of every film
m = req_movies # minimum of films required (default = 3)
W = (R*v + C*m) / (v + m) # weighted average
print(xd + ";" + str(W) + ";" + str(v) + ";" + str(directors[xd]))
directors = {}
movies = open_csv('ratings.csv')
populate_directors_dict(movies, directors)
calculate_weighted_average(directors, 3) | true |
d37eadd05db0f1beff6bd10f26d480b6e291b7f8 | dattnguyen/Intro-to-Python | /Python for everyone/def_compute_pay.py | 656 | 4.125 | 4 |
while True:
try :
hours = float ( input ('please enter hours:'))
rate = float ( input ('please enter rate:'))
except ValueError :
print ('please enter a number')
continue
if hours < 0:
print ('please enter hours as a positive number')
if rate < 0:
print ('please enter rate as a positive number')
continue
else:
break
def computepay(hours, rate):
if hours <=40:
pay = hours * rate
else:
pay = 40 * rate + (hours - 40)* rate * 1.5
return pay
p = computepay(hours, rate)
print ('Pay' ,p) | true |
d2e680e64a5dd416378edf3eb3134052a9cf4324 | lcolli111/fact.py | /fib.py | 773 | 4.25 | 4 | def Fibonacci(n):
a = 0
b = 1
if n<=0:
print("Try again")
# First Fibonacci number is 0
elif n==1:
return 0
# Second Fibonacci number is 1
elif n==2:
return b
else:
for i in range(2, n):
c = a + b
a = b
b = c
return b
n_terms = int(input("How many terms? "))
n1, n2 = 0, 1
count = 0
if n_terms<=0:
print("Enter a positive integer: ")
elif n_terms == 1:
print("Fibonacci sequence up to", n_terms, ":") #User determines the first few terms
print(n1)
else:
print("Fibonacci sequence: ")
while count < n_terms:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
# Driver Program
#print(Fibonacci(n))
| false |
fb731bcf25c227996390b25bad857ba5c8b357e0 | SDasman/Python_Learning | /GamesNChallenges/Factorial.py | 709 | 4.25 | 4 | import time
def factorial_iterative(n):
f = 1
while n>0:
f = f * n
n -= 1
return f
#Factorial here is done iteratively.
#To do this recursively
def factorial_recursive(n):
if n < 2:
return 1
return n * factorial_recursive(n-1)
times = 10000
factorial_value = 900
before_time = time.time()
for _ in range(times):
factorial_iterative(factorial_value)
print(f'This is how long the iterative took for {factorial_value}, {times} times', time.time()-before_time)
before_time = time.time()
for _ in range(times):
factorial_recursive(factorial_value)
print(f'This is how long the recursive took for {factorial_value}, {times} times', time.time()-before_time)
| true |
4c4d46462b0a3654b2aea5375f3c3923be2a967b | SDasman/Python_Learning | /GamesNChallenges/Calculator.py | 973 | 4.34375 | 4 | x = int(input('Please enter x: '))
y = int(input('Please enter y: '))
operator = input('Do you want to add(+), subtract(-), multiply(*), or divide(/)?: ')
add = lambda x, y: x+y
subtract = lambda x, y: x - y
multiply = lambda x, y: x * y
divide = lambda x, y: x / y
# Now that we have defined our relative functions. This is the operational logic of our program.
if operator == 'add' :
print('Addition of ', x, ' and ', y, ' is ', add(x, y))
elif operator == 'subtract' :
print('Subtraction of ', x, ' and ', y, ' is ', subtract(x, y))
elif operator == 'multiply' :
print('Multiplication of of ', x, ' and ', y, ' is ', multiply(x, y))
elif operator == 'divide':
print('Addition of ', x, ' and ', y, ' is ', divide(x, y))
else:
print('Operator Gonzo! Try Again')
# print('Addition is ' , addition(4, 4))
# print('Subtraction is ' , subtraction(4, 4))
# print('Multiplication is ' , multiplication(4, 4))
# print('Division is ' , division(4, 4))
| true |
7e43d4a09d5940f161e7176476bbccad73a42a6f | mohitsaroha03/The-Py-Algorithms | /src/3.9Stringalgorithms/number-subsequences-form-ai-bj-ck.py | 1,860 | 4.375 | 4 | # Link: https://www.geeksforgeeks.org/number-subsequences-form-ai-bj-ck/
# IsDone: 0
# Python 3 program to count
# subsequences of the form
# a ^ i b ^ j c ^ k
# Returns count of subsequences
# of the form a ^ i b ^ j c ^ k
def countSubsequences(s):
# Initialize counts of different
# subsequences caused by different
# combination of 'a'
aCount = 0
# Initialize counts of different
# subsequences caused by different
# combination of 'a' and different
# combination of 'b'
bCount = 0
# Initialize counts of different
# subsequences caused by different
# combination of 'a', 'b' and 'c'.
cCount = 0
# Traverse all characters
# of given string
for i in range(len(s)):
# If current character is 'a',
# then there are following
# possibilities :
# a) Current character begins
# a new subsequence.
# b) Current character is part
# of aCount subsequences.
# c) Current character is not
# part of aCount subsequences.
if (s[i] == 'a'):
aCount = (1 + 2 * aCount)
# If current character is 'b', then
# there are following possibilities :
# a) Current character begins a
# new subsequence of b's with
# aCount subsequences.
# b) Current character is part
# of bCount subsequences.
# c) Current character is not
# part of bCount subsequences.
elif (s[i] == 'b'):
bCount = (aCount + 2 * bCount)
# If current character is 'c', then
# there are following possibilities :
# a) Current character begins a
# new subsequence of c's with
# bCount subsequences.
# b) Current character is part
# of cCount subsequences.
# c) Current character is not
# part of cCount subsequences.
elif (s[i] == 'c'):
cCount = (bCount + 2 * cCount)
return cCount
# Driver code
if __name__ == "__main__":
s = "abbc"
print(countSubsequences(s)) | true |
ca250e5e65cc9c3368011afd6360b84659057fc1 | mohitsaroha03/The-Py-Algorithms | /src/3.1Array/check for pair in A[] with sum as x.py | 597 | 4.15625 | 4 | # Link: https://www.geeksforgeeks.org/given-an-array-a-and-a-number-x-check-for-pair-in-a-with-sum-as-x/
# Python program to find if there are
# two elements wtih given sum
# function to check for the given sum
# in the array
def printPairs(arr, arr_size, sum):
# Create an empty hash set
s = set()
for i in range(0, arr_size):
temp = sum-arr[i]
if (temp in s):
print "Pair with given sum "+ str(sum) + " is (" + str(arr[i]) + ", " + str(temp) + ")"
s.add(arr[i])
# driver program to check the above function
A = [1, 4, 45, 6, 10, 8]
n = 16
printPairs(A, len(A), n) | true |
98cf403c752a89276c8d0ba58d3c0a52b8459bfa | mohitsaroha03/The-Py-Algorithms | /src/5.2Graphs/CountConnectedComponentsWithDFS.py | 1,323 | 4.34375 | 4 | # Link: https://www.geeksforgeeks.org/connected-components-in-an-undirected-graph/
# IsDone: 0
# Python program to print connected
# components in an undirected graph
class Graph:
# init function to declare class variables
def __init__(self, V):
self.V = V
self.adj = [[] for i in range(V)]
def DFSUtil(self, temp, v, visited):
# Mark the current vertex as visited
visited[v] = True
# Store the vertex to list
temp.append(v)
# Repeat for all vertices adjacent
# to this vertex v
for i in self.adj[v]:
if visited[i] == False:
# Update the list
temp = self.DFSUtil(temp, i, visited)
return temp
# method to add an undirected edge
def addEdge(self, v, w):
self.adj[v].append(w)
self.adj[w].append(v)
# Method to retrieve connected components
# in an undirected graph
def connectedComponents(self):
visited = []
cc = []
for i in range(self.V):
visited.append(False)
for v in range(self.V):
if visited[v] == False:
temp = []
cc.append(self.DFSUtil(temp, v, visited))
return cc
# Driver Code
if __name__ == "__main__":
# Create a graph given in the above diagram
# 5 vertices numbered from 0 to 4
g = Graph(5)
g.addEdge(1, 0)
g.addEdge(2, 3)
g.addEdge(3, 4)
cc = g.connectedComponents()
print("Following are connected components")
print(cc) | true |
5305b5d0f62fdcffc1e747ff6202428e8b81497f | mohitsaroha03/The-Py-Algorithms | /src/3.9Stringalgorithms/zig-zag-string-form-in-n-rows.py | 1,151 | 4.5625 | 5 | # Link: https://www.geeksforgeeks.org/print-concatenation-of-zig-zag-string-form-in-n-rows/
# IsDone: 0
# Python 3 program to print
# string obtained by
# concatenation of different
# rows of Zig-Zag fashion
# Prints concatenation of all
# rows of str's Zig-Zag fasion
def printZigZagConcat(str, n):
# Corner Case (Only one row)
if n == 1:
print(str)
return
# Find length of string
l = len(str)
# Create an array of
# strings for all n rows
arr=["" for x in range(l)]
# Initialize index for
# array of strings arr[]
row = 0
# Travers through
# given string
for i in range(l):
# append current character
# to current row
arr[row] += str[i]
# If last row is reached,
# change direction to 'up'
if row == n - 1:
down = False
# If 1st row is reached,
# change direction to 'down'
elif row == 0:
down = True
# If direction is down,
# increment, else decrement
if down:
row += 1
else:
row -= 1
# Print concatenation
# of all rows
for i in range(n):
print(arr[i], end = "")
# Driver Code
str = "GEEKSFORGEEKS"
n = 3
printZigZagConcat(str, n)
| true |
e551b4f06f2eb3cf46cad940ea0100f7ede6ac43 | mohitsaroha03/The-Py-Algorithms | /src/3.4Stacks/prefix-postfix-conversion.py | 674 | 4.1875 | 4 | # Link: https://www.geeksforgeeks.org/prefix-postfix-conversion/
# IsDone: 0
# Write Python3 code here
# -*- coding: utf-8 -*-
# Example Input
s = "*-A/BC-/AKL"
# Stack for storing operands
stack = []
operators = set(['+', '-', '*', '/', '^'])
# Reversing the order
s = s[::-1]
# iterating through individual tokens
for i in s:
# if token is operator
if i in operators:
# pop 2 elements from stack
a = stack.pop()
b = stack.pop()
# concatenate them as operand1 +
# operand2 + operator
temp = a+b+i
stack.append(temp)
# else if operand
else:
stack.append(i)
# printing final output
print(*stack) # learn
| true |
e9a690c16c9f41e44017d6ca7f2548fca0ad6d28 | mohitsaroha03/The-Py-Algorithms | /src/3.1Array/print-unique-rows.py | 593 | 4.28125 | 4 | # Link: https://www.geeksforgeeks.org/print-unique-rows/
# Python3 code to print unique row in a
# given binary matrix
def printArray(matrix):
rowCount = len(matrix)
if rowCount == 0:
return
columnCount = len(matrix[0])
if columnCount == 0:
return
row_output_format = " ".join(["%s"] * columnCount)
printed = {}
for row in matrix:
routput = row_output_format % tuple(row)
if routput not in printed:
printed[routput] = True
print(routput)
# Driver Code
mat = [[0, 1, 0, 0, 1],
[1, 0, 1, 1, 0],
[0, 1, 0, 0, 1],
[1, 1, 1, 0, 0]]
printArray(mat) | true |
7459397b4045f5cceb44b2e33a1acd207c5f3abf | mohitsaroha03/The-Py-Algorithms | /src/3.4Stacks/2 stack using array.py | 1,477 | 4.15625 | 4 | # Link: https://www.geeksforgeeks.org/implement-two-stacks-in-an-array/
# Python Script to Implement two stacks in a list
class twoStacks:
def __init__(self, n): # constructor
self.size = n
self.arr = [None] * n
self.top1 = -1
self.top2 = self.size
# Method to push an element x to stack1
def push1(self, x):
# There is at least one empty space for new element
if self.top1 < self.top2 - 1 :
self.top1 = self.top1 + 1
self.arr[self.top1] = x
else:
print("Stack Overflow ")
exit(1)
# Method to push an element x to stack2
def push2(self, x):
# There is at least one empty space for new element
if self.top1 < self.top2 - 1:
self.top2 = self.top2 - 1
self.arr[self.top2] = x
else :
print("Stack Overflow ")
exit(1)
# Method to pop an element from first stack
def pop1(self):
if self.top1 >= 0:
x = self.arr[self.top1]
self.top1 = self.top1 -1
return x
else:
print("Stack Underflow ")
exit(1)
# Method to pop an element from second stack
def pop2(self):
if self.top2 < self.size:
x = self.arr[self.top2]
self.top2 = self.top2 + 1
return x
else:
print("Stack Underflow ")
exit()
# Driver program to test twoStacks class
ts = twoStacks(5)
ts.push1(5)
ts.push2(10)
ts.push2(15)
ts.push1(11)
ts.push2(7)
print("Popped element from stack1 is " + str(ts.pop1()))
ts.push2(40)
print("Popped element from stack2 is " + str(ts.pop2())) | false |
d6c9c1d5056f3a3fde6dea01d26bbbd54303def7 | mohitsaroha03/The-Py-Algorithms | /src/3.1Array/Printing Matrix Chain Multiplication.py | 1,762 | 4.5625 | 5 | # Link: https://www.geeksforgeeks.org/printing-brackets-matrix-chain-multiplication-problem/
# https://www.geeksforgeeks.org/printing-matrix-chain-multiplication-a-space-optimized-solution/
# A space optimized python3 program to
# print optimal parenthesization in
# matrix chain multiplication.
def printParenthesis(m, j, i ):
# Displaying the parenthesis.
if j == i:
# The first matrix is printed as
# 'A', next as 'B', and so on
print(chr(65 + j), end = "")
return;
else:
print("(", end = "")
# Passing (m, k, i) instead of (s, i, k)
printParenthesis(m, m[j][i] - 1, i)
# (m, j, k+1) instead of (s, k+1, j)
printParenthesis(m, j, m[j][i])
print (")", end = "" )
def matrixChainOrder(p, n):
# Creating a matrix of order
# n*n in the memory.
m = [[0 for i in range(n)]
for i in range (n)]
for l in range (2, n + 1):
for i in range (n - l + 1):
j = i + l - 1
# Initializing infinity value.
m[i][j] = float('Inf')
for k in range (i, j):
q = (m[i][k] + m[k + 1][j] +
(p[i] * p[k + 1] * p[j + 1]));
if (q < m[i][j]):
m[i][j] = q
# Storing k value in opposite index.
m[j][i] = k + 1
return m;
# Driver Code
arr = [40, 20, 30, 10, 30]
n = len(arr) - 1
m = matrixChainOrder(arr, n) # Forming the matrix m
print("Optimal Parenthesization is: ", end = "")
# Passing the index of the bottom left
# corner of the 'm' matrix instead of
# passing the index of the top right
# corner of the 's' matrix as we used
# to do earlier. Everything is just opposite
# as we are using the bottom half of the
# matrix so assume everything opposite even
# the index, take m[j][i].
printParenthesis(m, n - 1, 0)
print("\nOptimal Cost is :", m[0][n - 1])
| true |
951ae31865210a9c0368fd418686c81971f2558b | mohitsaroha03/The-Py-Algorithms | /src/3.1Array/pair-swapping-which-makes-sum-of-two-arrays-same.py | 1,013 | 4.3125 | 4 | # Link: https://www.geeksforgeeks.org/find-a-pair-swapping-which-makes-sum-of-two-arrays-same/
# Python code for optimized implementation
#Returns sum of elements in list
def getSum(X):
sum=0
for i in X:
sum+=i
return sum
# Finds value of
# a - b = (sumA - sumB) / 2
def getTarget(A,B):
# Calculations of sumd from both lists
sum1=getSum(A)
sum2=getSum(B)
# Because that target must be an integer
if( (sum1-sum2)%2!=0):
return 0
return (sum1-sum2)/2
# Prints elements to be swapped
def findSwapValues(A,B):
# Call for sorting the lists
A.sort()
B.sort()
#Note that target can be negative
target=getTarget(A,B)
# target 0 means, answer is not possible
if(target==0):
return
i,j=0,0
while(i<len(A) and j<len(B)):
diff=A[i]-B[j]
if diff == target:
print A[i],B[j]
return
# Look for a greater value in list A
elif diff <target:
i+=1
# Look for a greater value in list B
else:
j+=1
A=[4,1,2,1,1,2]
B=[3,6,3,3]
findSwapValues(A,B) | true |
9feeb6d379f053bf516b8321f434bb79d26a0ed6 | mohitsaroha03/The-Py-Algorithms | /src/5.2Graphs/path-of-more-than-k-length-from-a-source.py | 2,423 | 4.375 | 4 | # Link: https://www.geeksforgeeks.org/find-if-there-is-a-path-of-more-than-k-length-from-a-source/
# IsDone: 0
# Program to find if there is a simple path with
# weight more than k
# This class represents a dipathted graph using
# adjacency list representation
class Graph:
# Allocates memory for adjacency list
def __init__(self, V):
self.V = V
self.adj = [[] for i in range(V)]
# Returns true if graph has path more than k length
def pathMoreThanK(self,src, k):
# Create a path array with nothing included
# in path
path = [False]*self.V
# Add source vertex to path
path[src] = 1
return self.pathMoreThanKUtil(src, k, path)
# Prints shortest paths from src to all other vertices
def pathMoreThanKUtil(self,src, k, path):
# If k is 0 or negative, return true
if (k <= 0):
return True
# Get all adjacent vertices of source vertex src and
# recursively explore all paths from src.
i = 0
while i != len(self.adj[src]):
# Get adjacent vertex and weight of edge
v = self.adj[src][i][0]
w = self.adj[src][i][1]
i += 1
# If vertex v is already there in path, then
# there is a cycle (we ignore this edge)
if (path[v] == True):
continue
# If weight of is more than k, return true
if (w >= k):
return True
# Else add this vertex to path
path[v] = True
# If this adjacent can provide a path longer
# than k, return true.
if (self.pathMoreThanKUtil(v, k-w, path)):
return True
# Backtrack
path[v] = False
# If no adjacent could produce longer path, return
# false
return False
# Utility function to an edge (u, v) of weight w
def addEdge(self,u, v, w):
self.adj[u].append([v, w])
self.adj[v].append([u, w])
# Driver program to test methods of graph class
if __name__ == '__main__':
# create the graph given in above fugure
V = 9
g = Graph(V)
# making above shown graph
g.addEdge(0, 1, 4)
g.addEdge(0, 7, 8)
g.addEdge(1, 2, 8)
g.addEdge(1, 7, 11)
g.addEdge(2, 3, 7)
g.addEdge(2, 8, 2)
g.addEdge(2, 5, 4)
g.addEdge(3, 4, 9)
g.addEdge(3, 5, 14)
g.addEdge(4, 5, 10)
g.addEdge(5, 6, 2)
g.addEdge(6, 7, 1)
g.addEdge(6, 8, 6)
g.addEdge(7, 8, 7)
src = 0
k = 62
if g.pathMoreThanK(src, k):
print("Yes")
else:
print("No")
k = 60
if g.pathMoreThanK(src, k):
print("Yes")
else:
print("No") | true |
3eb71a832fee864137d166f1dd11486ffddb2c66 | mohitsaroha03/The-Py-Algorithms | /src/5.2Graphs/UnweightedShortestPathWithBFS.py | 725 | 4.21875 | 4 | # Link: https://www.codespeedy.com/python-program-to-find-shortest-path-in-an-unweighted-graph/
# IsDone: 0
def bfs(graph, S, D):
queue = [(S, [S])]
while queue:
(vertex, path) = queue.pop(0)
for next in graph[vertex] - set(path):
if next == D:
yield path + [next]
else:
queue.append((next, path + [next]))
def shortest(graph, S, D):
try:
return next(bfs(graph, S, D))
except StopIteration:
return None
graph = {'1': set(['2', '3']),
'2': set(['1', '5']),
'3': set(['1', '4']),
'4': set(['3','5']),
'5': set(['2', '4'])}
print(shortest(graph, '1', '5'))
list(bfs(graph, '1', '5')) | true |
907113bfeb27293c239b434f21d29f189f9a1d38 | mohitsaroha03/The-Py-Algorithms | /src/02Recursionandbacktracking/Josephus problem.py | 767 | 4.25 | 4 | # Link: https://www.geeksforgeeks.org/josephus-problem-set-1-a-on-solution/
# https://www.geeksforgeeks.org/josephus-problem-iterative-solution/
# https://www.geeksforgeeks.org/josephus-problem-set-2-simple-solution-k-2/
# solution: https://www.youtube.com/watch?v=uCsD3ZGzMgE
# make n as 2^a + l so survivor will be 2l + 1
# IsDone: 1
# Python code for Josephus Problem
def josephus(n, k):
if (n == 1):
return 1
else:
# The position returned by
# josephus(n - 1, k) is adjusted
# because the recursive call
# josephus(n - 1, k) considers
# the original position
# k%n + 1 as position 1
return (josephus(n - 1, k) + k-1) % n + 1
# Driver Program to test above function
n = 6
k = 2
print("The chosen place is ", josephus(n, k)) | false |
fbc5f704faae1755fbc764868fdce40548478b1d | mohitsaroha03/The-Py-Algorithms | /src/zDynamicprogramming/find-water-in-a-glass.py | 1,656 | 4.4375 | 4 | # Link: https://www.geeksforgeeks.org/find-water-in-a-glass/
# Program to find the amount
# of water in j-th glass of
# i-th row
# Returns the amount of water
# in jth glass of ith row
def findWater(i, j, X):
# A row number i has maximum
# i columns. So input column
# number must be less than i
if (j > i):
print("Incorrect Input");
return;
# There will be i*(i+1)/2
# glasses till ith row
# (including ith row)
# and Initialize all glasses
# as empty
glass = [0]*int(i *(i + 1) / 2);
# Put all water
# in first glass
index = 0;
glass[index] = X;
# Now let the water flow to
# the downward glasses till
# the row number is less
# than or/ equal to i (given
# row) correction : X can be
# zero for side glasses as
# they have lower rate to fill
for row in range(1,i):
# Fill glasses in a given
# row. Number of columns
# in a row is equal to row number
for col in range(1,row+1):
# Get the water
# from current glass
X = glass[index];
# Keep the amount less
# than or equal to
# capacity in current glass
glass[index] = 1.0 if (X >= 1.0) else X;
# Get the remaining amount
X = (X - 1) if (X >= 1.0) else 0.0;
# Distribute the remaining
# amount to the down two glasses
glass[index + row] += (X / 2);
glass[index + row + 1] += (X / 2);
index+=1;
# The index of jth glass
# in ith row will
# be i*(i-1)/2 + j - 1
return glass[int(i * (i - 1) /2 + j - 1)];
# Driver Code
if __name__ == "__main__":
i = 2;
j = 2;
X = 2.0;
# Total amount of water
res=repr(findWater(i, j, X));
print("Amount of water in jth glass of ith row is:",res.ljust(8,'0')); | true |
806c17e8065c8e0565c0d98bbda2a659cbfb1ce2 | mohitsaroha03/The-Py-Algorithms | /src/3.1Array/sort-array-wave-form.py | 660 | 4.5625 | 5 | # Link: https://www.geeksforgeeks.org/sort-array-wave-form-2/
# Python function to sort the array arr[0..n-1] in wave form,
# i.e., arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= arr[5]
def sortInWave(arr, n):
# Traverse all even elements
for i in range(0, n, 2):
# If current even element is smaller than previous
if (i> 0 and arr[i] < arr[i-1]):
arr[i],arr[i-1] = arr[i-1],arr[i]
# If current even element is smaller than next
if (i < n-1 and arr[i] < arr[i+1]):
arr[i],arr[i+1] = arr[i+1],arr[i]
# Driver program
arr = [10, 90, 49, 2, 1, 5, 23]
sortInWave(arr, len(arr))
for i in range(0,len(arr)):
print arr[i], | false |
b98fa8cd45e568c6b75868432d9fcd27c5c648ae | mohitsaroha03/The-Py-Algorithms | /src/02Recursionandbacktracking/permutations-of-a-given-string.py | 735 | 4.28125 | 4 | # Link: https://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
# IsDone: 1
# Python program to print all permutations with
# duplicates allowed
def toString(List):
return ''.join(List)
# Function to print permutations of string
# This function takes three parameters:
# 1. String
# 2. Starting index of the string
# 3. Ending index of the string.
def permute(a, start, end):
if start==end:
print toString(a)
else:
for i in xrange(start,end+1):
a[start], a[i] = a[i], a[start]
permute(a, start+1, end)
a[start], a[i] = a[i], a[start] # backtrack
# Driver program to test the above function
string = "ABC"
n = len(string)
a = list(string)
permute(a, 0, n-1)
| true |
57d1f7d07a1da34dac935ef8c4d63ac7f20f8c2d | mohitsaroha03/The-Py-Algorithms | /src/3.1Array/subarray-form-mountain-not.py | 1,519 | 4.5625 | 5 | # Link: https://www.geeksforgeeks.org/find-whether-subarray-form-mountain-not/
# Python 3 program to check whether a subarray is in
# mountain form or not
# Utility method to construct left and right array
def preprocess(arr, N, left, right):
# initialize first left index as that index only
left[0] = 0
lastIncr = 0
for i in range(1,N):
# if current value is greater than previous,
# update last increasing
if (arr[i] > arr[i - 1]):
lastIncr = i
left[i] = lastIncr
# initialize last right index as that index only
right[N - 1] = N - 1
firstDecr = N - 1
i = N - 2
while(i >= 0):
# if current value is greater than next,
# update first decreasing
if (arr[i] > arr[i + 1]):
firstDecr = i
right[i] = firstDecr
i -= 1
# method returns true if arr[L..R] is in mountain form
def isSubarrayMountainForm(arr, left, right, L, R):
# return true only if right at starting range is
# greater than left at ending range
return (right[L] >= left[R])
# Driver code
if __name__ == '__main__':
arr = [2, 3, 2, 4, 4, 6, 3, 2]
N = len(arr)
left = [0 for i in range(N)]
right = [0 for i in range(N)]
preprocess(arr, N, left, right)
L = 0
R = 2
if (isSubarrayMountainForm(arr, left, right, L, R)):
print("Subarray is in mountain form")
else:
print("Subarray is not in mountain form")
L = 1
R = 3
if (isSubarrayMountainForm(arr, left, right, L, R)):
print("Subarray is in mountain form")
else:
print("Subarray is not in mountain form")
| true |
edfc8906931222ca08025deafff0519fac8d0bd7 | mohitsaroha03/The-Py-Algorithms | /src/3.1Array/largest rectangle of 1’s with swapping.py | 1,779 | 4.3125 | 4 | # Link: https://www.geeksforgeeks.org/find-the-largest-rectangle-of-1s-with-swapping-of-columns-allowed/
# Python 3 program to find the largest
# rectangle of 1's with swapping
# of columns allowed.
# TODO: pending
R = 3
C = 5
# Returns area of the largest
# rectangle of 1's
def maxArea(mat):
# An auxiliary array to store count
# of consecutive 1's in every column.
hist = [[0 for i in range(C + 1)]
for i in range(R + 1)]
# Step 1: Fill the auxiliary array hist[][]
for i in range(0, C, 1):
# First row in hist[][] is copy of
# first row in mat[][]
hist[0][i] = mat[0][i]
# Fill remaining rows of hist[][]
for j in range(1, R, 1):
if ((mat[j][i] == 0)):
hist[j][i] = 0
else:
hist[j][i] = hist[j - 1][i] + 1
# Step 2: Sort rows of hist[][] in
# non-increasing order
for i in range(0, R, 1):
count = [0 for i in range(R + 1)]
# counting occurrence
for j in range(0, C, 1):
count[hist[i][j]] += 1
# Traverse the count array from
# right side
col_no = 0
j = R
while(j >= 0):
if (count[j] > 0):
for k in range(0, count[j], 1):
hist[i][col_no] = j
col_no += 1
j -= 1
# Step 3: Traverse the sorted hist[][]
# to find maximum area
max_area = 0
for i in range(0, R, 1):
for j in range(0, C, 1):
# Since values are in decreasing order,
# The area ending with cell (i, j) can
# be obtained by multiplying column number
# with value of hist[i][j]
curr_area = (j + 1) * hist[i][j]
if (curr_area > max_area):
max_area = curr_area
return max_area
# Driver Code
if __name__ == '__main__':
mat = [[0, 1, 0, 1, 0],
[0, 1, 0, 1, 1],
[1, 1, 0, 1, 0]]
print("Area of the largest rectangle is",
maxArea(mat)) | true |
92ad4efcb9cfdb1ab7d261dfb83912b4d1439c88 | mohitsaroha03/The-Py-Algorithms | /src/5.2Graphs/find-whether-path-two-cells-matrix.py | 2,356 | 4.28125 | 4 | # Link: https://www.geeksforgeeks.org/find-whether-path-two-cells-matrix/
# IsDone: 0
# Node of a Singly Linked List
# Python3 program to find path between two
# cell in matrix
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
# add edge to graph
def addEdge(self, u, v):
self.graph[u].append(v)
# BFS function to find path from source to sink
def BFS(self, s, d):
# Base case
if s == d:
return True
# Mark all the vertices as not visited
visited = [False]*(len(self.graph) + 1)
# Create a queue for BFS
queue = []
queue.append(s)
# Mark the current node as visited and
# enqueue it
visited[s] = True
while(queue):
# Dequeue a vertex from queue
s = queue.pop(0)
# Get all adjacent vertices of the
# dequeued vertex s. If a adjacent has
# not been visited, then mark it visited
# and enqueue it
for i in self.graph[s]:
# If this adjacent node is the destination
# node, then return true
if i == d:
return True
# Else, continue to do BFS
if visited[i] == False:
queue.append(i)
visited[i] = True
# If BFS is complete without visiting d
return False
def isSafe(i, j, matrix):
if i >= 0 and i <= len(matrix) and j >= 0 and j <= len(matrix[0]):
return True
else:
return False
# Returns true if there is a path from a source (a
# cell with value 1) to a destination (a cell with
# value 2)
def findPath(M):
s, d = None, None # source and destination
N = len(M)
g = Graph()
# create graph with n * n node
# each cell consider as node
k = 1 # Number of current vertex
for i in range(N):
for j in range(N):
if (M[i][j] != 0):
# connect all 4 adjacent cell to
# current cell
if (isSafe(i, j + 1, M)):
g.addEdge(k, k + 1)
if (isSafe(i, j - 1, M)):
g.addEdge(k, k - 1)
if (isSafe(i + 1, j, M)):
g.addEdge(k, k + N)
if (isSafe(i - 1, j, M)):
g.addEdge(k, k - N)
if (M[i][j] == 1):
s = k
# destination index
if (M[i][j] == 2):
d = k
k += 1
# find path Using BFS
return g.BFS(s, d)
# Driver code
if __name__=='__main__':
M =[[0, 3, 0, 1], [3, 0, 3, 3], [2, 3, 3, 3], [0, 3, 3, 3]]
if findPath(M):
print("Yes")
else:
print("No") | true |
97c0eb8980cb8209f70cdf04417ee8f6872dbd94 | mohitsaroha03/The-Py-Algorithms | /src/5.1Trees/IsBST2.py | 1,323 | 4.375 | 4 | # Link: https://www.geeksforgeeks.org/a-program-to-check-if-a-binary-tree-is-bst-or-not/
# IsDone: 1
class Node:
# constructor to create new node
def __init__(self, val):
self.data = val
self.left = None
self.right = None
# global variable prev - to keep track
# of previous node during Inorder
# traversal
prev = None
# function to check if given binary
# tree is BST
def isbst(root):
# prev is a global variable
global prev
prev = None
return isbst_rec(root)
# Helper function to test if binary
# tree is BST
# Traverse the tree in inorder fashion
# and keep track of previous node
# return true if tree is Binary
# search tree otherwise false
def isbst_rec(root):
# prev is a global variable
global prev
# if tree is empty return true
if root is None:
return True
if isbst_rec(root.left) is False:
return False
# if previous node'data is found
# greater than the current node's
# data return fals
if prev is not None and prev.data > root.data:
return False
# store the current node in prev
prev = root
return isbst_rec(root.right)
# driver code to test above function
root = Node(4)
root.left = Node(2)
root.right = Node(5)
root.left.left = Node(1)
root.left.right = Node(3)
if isbst(root):
print("is BST")
else:
print("not a BST") | true |
7059826d66377beac0d37ebc89f730f9df827f47 | mohitsaroha03/The-Py-Algorithms | /src/5.1Trees/PathsFinder print all paths.py | 902 | 4.46875 | 4 | # Link: https://www.geeksforgeeks.org/given-a-binary-tree-print-all-root-to-leaf-paths/
# IsDone: 0
# Python3 program to print all of its
# root-to-leaf paths for a tree
class Node:
# A binary tree node has data,
# pointer to left child and a
# pointer to right child
def __init__(self, data):
self.data = data
self.right = None
self.left = None
def printRoute(stack, root):
if root == None:
return
# append this node to the path array
stack.append(root.data)
if(root.left == None and root.right == None):
# print out all of its
# root - to - leaf
print(' '.join([str(i) for i in stack]))
# otherwise try both subtrees
printRoute(stack, root.left)
printRoute(stack, root.right)
stack.pop()
# Driver Code
root = Node(1);
root.left = Node(2);
root.right = Node(3);
root.left.left = Node(4);
root.left.right = Node(5);
printRoute([], root) | true |
bd4a48f712fbbf309d81955ca6fa88551b42f955 | dglauber1/radix_visualizer | /radix_visualizer.py | 1,778 | 4.34375 | 4 | def print_buckets(buckets, ordered_place):
"""print_buckets: array, int ->
Purpose: prints the contents of a 2D array representing the buckets of a radix sort algorithm
Consumes: buckets - an array of int arrays, where the xth int array contains all integers with the digit x at ordered_place
ordered_place - a power of 10 representing the current place that the integers have been sorted on
Produces: nothing
"""
index_string = '| '
for i in range(len(buckets)):
sub_idx_str = ''
bucket_size = len(buckets[i])
if (bucket_size > 0):
sub_idx_str += ' ' * (2 * bucket_size - 1)
else:
sub_idx_str += ' '
middle_index = len(sub_idx_str) / 2
sub_idx_str = sub_idx_str[:middle_index] + str(i) + sub_idx_str[middle_index + 1:]
index_string += sub_idx_str + ' | '
to_print = index_string + 'bucket index'
to_print = '~' * len(index_string) + '\n' + to_print
place = 1
while True:
do_break = True
next_line = '| '
for bucket in buckets:
if len(bucket) < 1:
next_line += ' ' * 2
else:
for number in bucket:
digit = ''
if number >= place:
do_break = False
digit = str(number % (place * 10) / place)
else:
digit = ' '
next_line += digit + ' '
next_line += '| '
if do_break:
break
if ordered_place == place:
next_line += '<- ' + str(place) + '\'s place has been sorted'
to_print = next_line + '\n' + to_print
place *= 10
print to_print + '\n' | true |
b7a876f1d244f9d30b7dc61810f42769265225c3 | itadmin01/GoalSeek_Python | /ExampleScript.py | 1,315 | 4.25 | 4 | ## ExampleScript running GoalSeek (Excel)
# prepared by Hakan İbrahim Tol, PhD
## Required Python Library: NumPy
from WhatIfAnalysis import GoalSeek
## EXAMPLE 1
# Finding the x value, its square results in goal = 10
# (i) Define the formula that needs to reach the (goal) result
def fun(x):
return x**2
# (ii) Define the goal (result)
goal=10
# (iii) Define a starting point
x0=3
## Here is the result
Result_Example1=GoalSeek(fun,goal,x0)
print('Result of Example 1 is = ', Result_Example1)
## EXAMPLE 2
# See Reference for the Excel tutorial: https://www.ablebits.com/office-addins-blog/2018/09/05/use-goal-seek-excel-what-if-analysis/
# Problem: If you sell 100 items at $5 each, minus the 10% commission, you will make $450.
# The question is: How many items do you have to sell to make $1,000?
# (i) Define the formula that needs to reach the (goal) result
def Revenue(x):
# x : quantity of the items (to be solved)
item_price=5 # [$]
comission=0.1 # 10% comission
return item_price*x*(1-comission)
# (ii) Define the goal (result)
goal=1000 # [$]
# (iii) Define a starting point
x0=100
## Here is the result
Result_Example2=GoalSeek(Revenue,goal,x0)
print('Result of Example 2 is = ', Result_Example2)
| true |
275bf060ad16e6af8f13aa8e8b90f2596cc7f6fd | xiashuo/tedu_execises | /month01/day4/exercise5.py | 509 | 4.21875 | 4 | '''
(选做)一个小球从100m高度落下,每次弹回原高度一半.
计算:
-- 总共弹起多少次?(最小弹起高度0.01m)
-- 全过程总共移动多少米?
提示:
数据/操作
'''
distance, height, count = 100, 100, 0
while height > 0.01:
height /= 2
count += 1
distance += height * 2 # 累加起落距离
# print(f"第{count}次弹起来的高度是{height}米,总共移动{distance}米")
print("总共弹起{count}次")
print("总共走了{distance}米")
| false |
bb5a0e5d76b420620364b1d0af30e437e63483c4 | xiashuo/tedu_execises | /month01/day13/homework1.py | 1,305 | 4.1875 | 4 | '''
内置可重写函数练习1
(1). 创建父子类,添加实例变量
创建父类:人(姓名,年龄)
创建子类:学生(成绩)
(2). 创建父子对象,直接打印.
格式: 我是xx,今年xx.
我是xx,今年xx,成绩是xx.
(3). 通过eval + __repr__拷贝对象,体会修改拷贝前的对象名称,不影响拷贝后的对象.
'''
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"我是{self.name},今年{self.age}."
def __repr__(self) -> str:
return f"Person('{self.name}',{self.age})"
class Student(Person):
def __init__(self, name, age, grade):
super().__init__(name, age)
self.grade = grade
def __str__(self) -> str:
# return f"我是{self.name},今年{self.age},成绩是{self.grade}."
return super().__str__() + f",{self.grade}"
def __repr__(self) -> str:
return f"Student('{self.name}',{self.age},{self.grade})"
person1 = Person("大明", 35)
print(person1)
student1 = Student("小明", 10, 90)
print(student1)
person2 = eval(person1.__repr__())
person1.age = 37
print(person2.age)
student2 = eval(student1.__repr__())
student1.grade = 100
print(student2.grade)
| false |
8ea7550e998006d5c906b4d6fccd3c308349304a | ajaymovva/mission-rnd-python-course | /PythonCourse/finaltest_problem3.py | 2,483 | 4.40625 | 4 | __author__ = 'Kalyan'
max_marks = 25
problem_notes = '''
For this problem you have to implement a staircase jumble as described below.
1. You have n stairs numbered 1 to n. You are given some text to jumble.
2. You repeatedly climb down and up the stairs and on each step k you add/append starting k chars from
the text you have (and remove them from the text).
3. You repeat this process till you finish the whole text.
4. Finally you climb up from step 1 and collect all chars to get the jumbled text.
E.g. if the text is "Ashokan" and n = 2. You have the following text on the steps. First you drop
"As" on step 2, then "h" on step 1, then you get to the ground and you
climb back again droping "o" on step 1 and "ka" on step2 and finally "n" on step2
(since you have run out of chars and you dont have 2 chars).
So sequence of steps is 2, 1 then 1, 2 then 2, 1 and so on...
(step2)As;ka;n
----
(step 1)|h;o
----
Final jumbled text is hoAskan (all text on step1 followed by all text on step2, the ; is shown above only to visually
distinguish the segments of text dropped on the stair at different times)
Notes:
1. Raise ValueError if n <= 0
2. Raise TypeError if text is not a str
3. Note that spaces, punctuation or any other chars are all treated like regular chars and
they will be jumbled in same way.
'''
def jumble(text, n):
if(type(text)!=str):
raise TypeError
elif(n<=0):
raise ValueError
else:
list1=[""]*n
j=0
flag=0
while(True):
for i in range(n,0,-1):
if(j+i<=len(text)):
x=text[j:j+i]
else:
x=text[j:len(text)]
list1[i - 1] = list1[i - 1] + x
flag=1
break
list1[i-1]=list1[i-1]+x
j=j+i
if(flag==1):
break
for i in range(1,n+1):
if(j+i<=len(text)):
x=text[j:j+i]
else:
x=text[j:len(text)]
list1[i - 1] = list1[i - 1] + x
flag=1
break
list1[i-1]=list1[i-1]+x
j=j+i
if (flag == 1):
break
return "".join(list1)
pass
def test_jumble():
assert "epdeakram" == jumble("ramdeepak", 3)
x=jumble("ajaykumarisagoodboy", 5)
print(x) | true |
436919d0eba0ddf4ce4328804cb4017394b0ab27 | YusraKhalid/String-Manipulation | /String minipulation.py | 2,287 | 4.25 | 4 | import YKStringProcessor
def main():
string = input("Enter replace string: ")
finding = input("What do you want to find: ")
replace = input("What do you want to replace: ")
replaceWith = input("what do you want to replace it with: ")
flag = True
while flag == True:
try:
index01 = int(input("Where do you want to start from:"))
index02 = int(input("Where do you want to end:"))
except:
flag = True
else:
flag = False
end = input("Check if string ends with till the given end location:")
start = input("Check if string starts with till the given start location:")
print("Length of stirng is:",YKStringProcessor.length(string))
print("The location of",finding," is",YKStringProcessor.find(string,finding))
print("Replaced all:",YKStringProcessor.replace(string,replace,replaceWith))
print("Uppercased:",YKStringProcessor.upperCase(string))
print("Lowercase:",YKStringProcessor.lowerCase(string))
print("Switchcase:",YKStringProcessor.switchCase(string))
print("Is the string alpha:",YKStringProcessor.isAlpha(string))
print("The location of",finding,"from right is:",YKStringProcessor.rfind(string,finding))
print("The reversed string is:", YKStringProcessor.reverse(string))
print("Replaced in the specific range:", YKStringProcessor.replaceStartEnd(string,replace,replaceWith,index01,index02))
print("Found",finding," in a specific range:", YKStringProcessor.findStartEnd(string,finding,index01,index02))
print("Capitalized first letters:",YKStringProcessor.capitalize(string))
print("Does the string ends with",end,"in the specific range:",YKStringProcessor.endwith(string,finding,index01))
print("Does string contains all digits:",YKStringProcessor.isdigit(string))
print("Is sting a decimal",YKStringProcessor.isdecimal(string))
print("Reversed individual words in a string:",YKStringProcessor.indivisualreverse(string))
print("Does the string starts with",start,"in the specific range:",YKStringProcessor.startwith(string,finding,index01))
print("Is all the string in lowercase:",YKStringProcessor.islower(string))
print("Is all the string in uppercase:",YKStringProcessor.isupper(string))
main()
| true |
94e2eb23f3127602c81aeb3d6b11d5cd40795846 | michalwojewoda/python | /Exercises/01_Character Input.py | 1,023 | 4.125 | 4 | # Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.
name = input("Please, state your name: ")
age = input("Please, state your age: ")
age = int(age)
year = str((2020 - age)+100)
print(name + " you will turn 100 years in: " + year)
# clear code and make it "time proof"
name = input("Please, state your name: ")
age = int(input("Please, state your age: "))
import time
year, month, day, hour, min = map(int, time.strftime("%Y %m %d %H %M").split())
year = str(year + (100 - age))
print(name + " , you will turn 100 in year" + year)
# fuck around with the code
name = input("\n Sir, Sir, \n \t Please, tell me who you are: \n")
age = int(input("\n Och, nice to meet you \n \tTel me your Age, and i will tell you a secret! \n "))
import time
year, min = map(int, time.strftime("%Y"))
year = str(year + (100 - age))
print(name + " the big secret of your life is that you will end 100 in year " + year )
| true |
91389b6966a6dc12a08400e02f79cd49afd05db7 | michalwojewoda/python | /Exercises/W3Resource/6.py | 341 | 4.34375 | 4 | # Write a Python program which accepts a sequence of comma-separated numbers from user and generate a list and a tuple with those numbers.
values = input("Input some comma separated numbers: ")
list = values.split(",")
tuple = tuple(list)
print("This is the list: ", list)
print("This is the tuple: ", tuple)
#finished
#but is it?
#yes it is | true |
fb9378ae6c2620d2b72fb7483fb654c46ef13c00 | mohitkhatri611/python-Revision-and-cp | /python programs and projects/python all topics/Generators and iterators.py | 1,223 | 4.46875 | 4 |
def generator_functions():
for i in range(5):
yield i * 20
#generator is a function normal function expect that it contains yield expression.
#yield is a keyword in Python that is used to return from a function without destroying the states of its local
# variable and when the function is called, the execution starts from the last yield statement.
# Any function that contains a yield keyword is termed as generator. Hence, yield is what makes a generator.
""" on large datasets generators are very usefull because generators are memory effiecible.
# means generator function only store the previous result to generate the next sum. Instead of allocation of
# memeory for all the result at the same time
# In layman definition generators occupy less memory and very usefull for memory management."""
# 2 ways to access value of above function:
x= generator_functions()
#print(x)
#1 way
for item in x:
print(item)
#2nd way:
y= generator_functions()
for i in range(5):
print(next(y), end=' ')
#iteratable are string, tuple, list, dict, but they are not iterators
a=[2,4,5,6,7]
#print(next(a))# will give error
b=iter(a)# converting to iterator
next(b)
| true |
26d1082fce2c13c5e33c42da020c5e9adfc3d2e0 | mohitkhatri611/python-Revision-and-cp | /python programs and projects/Programs/enum and compression.py | 388 | 4.375 | 4 | """finding Index of Non-Zero elements in Python list using enum and list comprehension"""
def prog():
test_list = [6, 7, 0, 1, 0, 2, 0, 12]
print("original list: ",test_list)
#index of non- zero elements in python list
#using list comprehension and enumeration.
res = [idx for idx,val in enumerate(test_list) if val!=0]
print("Indexes are: ", res)
prog()
| true |
241e4410b89a58f5fdabbcda2a3207554043ae49 | mohitkhatri611/python-Revision-and-cp | /python programs and projects/Python Data Structures Programs/linked list programs/Linked List Set 1 Introduction.py | 1,539 | 4.375 | 4 | #https://www.geeksforgeeks.org/linked-list-set-1-introduction/
class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def push(self,data):
newNode=Node(data)
newNode.next=self.head
self.head=newNode
def insertAfter(self,prevNode,data):
newNode=Node(data)
if prevNode is None:
print('prev node should be in lList')
return
newNode.next=prevNode.next
prevNode.next=newNode
def append(self,data):
newNode=Node(data)
if self.head is None:
self.head=newNode
return
last=self.head
while last.next:
last=last.next
last.next=newNode
def printList(self):
temp=self.head
while temp:
print(temp.data,end=' ')
temp=temp.next
if __name__=='__main__':
# Start with the empty list
llist = LinkedList()
# Insert 6. So linked list becomes 6->None
llist.append(6)
# Insert 7 at the beginning. So linked list becomes 7->6->None
llist.push(7);
# Insert 1 at the beginning. So linked list becomes 1->7->6->None
llist.push(1);
# Insert 4 at the end. So linked list becomes 1->7->6->4->None
llist.append(4)
# Insert 8, after 7. So linked list becomes 1 -> 7-> 8-> 6-> 4-> None
llist.insertAfter(llist.head.next, 8)
print("Created linked list is:")
print(llist.printList()) | true |
605cc2177cd64ce2b3aca0a11072824567114e44 | mohitkhatri611/python-Revision-and-cp | /python programs and projects/Python Data Structures Programs/tree based programs/level order traversl.py | 2,349 | 4.21875 | 4 | """2ways first second is taking O(n^2) and firstone is using queue is taking o(n)"""
class Node:
def __init__(self,data):
self.data= data
self.left=None
self.right=None
"""this will take O(n)"""
class level1:
def printLevelOrder(self,root):
if root is None:
return
queue=[]
queue.append(root)
print("printing using only O(n) algo queue:")
while(len(queue)>0):
print(queue)
print(queue[0].data, end=' ')
node=queue.pop(0)
if node.left is not None:
queue.append(node.left)
if node.right is not None:
queue.append(node.right)
"""second: --the below code is taking O(n^2) time if tree is sked and space is o(n) for workst skew other wise log(n)"""
class level:
def printLevelOrder(self,root):
h=self.height2(root)
for i in range(1,h+1):
self.printCurrentLevel(root,i)
def printCurrentLevel(self,root , level):
if root is None:
return
if level == 1:
print(root.data,end=" ")
elif level > 1 :
self.printCurrentLevel(root.left , level-1)
self.printCurrentLevel(root.right , level-1)
#this height will be counting root as 0
def height(self,node1):
if node1 is None:
return 0
elif node1.left is None and node1.right is None:
return 0 #return 1 if this height is counting to 0 as root
else:
return 1 + (max(self.height(node1.left),self.height(node1.right)))
#this height is takign root as 1 count like level
def height2(self,node):
if node is None:
return 0
else:
# Compute the height of each subtree
lheight = self.height2(node.left)
rheight = self.height2(node.right)
# Use the larger one
if lheight > rheight:
return lheight + 1
else:
return rheight + 1
if __name__=="__main__":
root = Node(1)
root.left = Node(2)
root.right = Node(5)
root.left.left = Node(4)
root.left.right = Node(3)
lev1 = level1()
lev1.printLevelOrder(root)
# lev=level()
# print(lev.height2(root))
# lev.printLevelOrder(root)
| true |
4aafc75e31aa1adb6dd76e02abb9bdb80e5b3767 | siddhusalvi/basic-python | /8_histogram.py | 638 | 4.21875 | 4 | """
8. Write a Python program to create a histogram from a given list of integers.
"""
def print_histogram(numbers):
flag = True
count = 0
for x in numbers:
if flag:
maximum = x
flag = False
elif maximum < x:
maximum = x
count += 1
output = ""
limit = maximum
for x in range(0, maximum):
for y in range(0, count):
if numbers[y] >= limit:
output += "* "
else:
output += " "
output += "\n"
limit -= 1
print(output)
data = [5, 1, 3, 6, 8, 7]
print_histogram(data)
| true |
cf61818df83ddadbdf01553fe328329ecf722f08 | siddhusalvi/basic-python | /7_value_in_group.py | 598 | 4.21875 | 4 | """
7. Write a Python program to check whether a specified value is contained in a group of values.
Test Data :
3 -> [1, 5, 8, 3] : True
-1 -> [1, 5, 8, 3] : False
"""
def is_in_group(numbers, elem):
for i in numbers:
if elem == i:
return True
return False
data = []
size = int(input("Enter number of elements : "))
for i in range(0, size):
ele = input("enter a ele :")
data.append(ele)
ele = int(input("Enter number to check : "))
if is_in_group(data, ele):
print("element is present in the group.")
else:
print("element is absent in the group.")
| true |
ab2f60ac081dedde2e75b064a17706ff9dca692b | ravi4all/PythonWE_AugMorning | /Backup/IfElse/01-IfElseSyntax.py | 235 | 4.3125 | 4 | # Compund Assignment -> =
userMsg = input("Enter your message : ")
# Comparison Operator -> ==, >, <, >=, <=
# Logical Operators -> AND, OR, NOT
if userMsg == "hello":
print("Hello")
else:
print("I don't understand")
| true |
19b95cd3027752774bd922eeb9269354ef505836 | AdamC66/python_fundamentals2 | /ex4.py | 445 | 4.15625 | 4 | #Define a function that accepts a string as an argument
# and returns False if the word is less than 8 characters long
# (or True otherwise).
def len_check(string):
if len(string)>=8:
return(True)
else:
return(False)
print(len_check("apple"))
print(len_check("orange"))
print(len_check("adamjcote"))
print(len_check("mapleleafs"))
print(len_check("hello"))
print(len_check("hello world"))
print(len_check("battery")) | true |
d24283dc03f5f2846246d86822ef39709e569b84 | Pushkar-chintaluri/projecteuler | /largestprimefactor.py | 1,098 | 4.15625 | 4 | import math
import pdb
def is_prime(num):
""" Helper function that checks if a number is prime or not"""
for n in range(2,int(math.sqrt(num))+1):
if num%n == 0:
return False
return True
def largest_prime_factor(num):
"""A Dynamic Programming Solution -- Close to O(N) solution"""
# pdb.set_trace()
primesDict = {1:True,2:True,3:True,4:False,5:True}
n = 2
factor = 0
while num>1:
if not primesDict.has_key(n): # if number's prime status is not already known
primesDict[n]=is_prime(n) # calculate prime status
if primesDict[n]: # Look-up prime status in dictionary
if num%n == 0:
factor = n
num = num/n
n = 2
else:
n += 1
else:
n += 1
return factor
def main():
if largest_prime_factor(42)==7 and largest_prime_factor(13195)==29 and largest_prime_factor(600851475143)==6857:
print("Tests Passed")
else:
print("Oops, something broke")
if __name__ == "__main__":
main()
| true |
172287e9194a106a1416d545ad51f0b0390d983d | woshiyigelaizibeifangdelang/day16 | /01-map.py | 799 | 4.40625 | 4 |
"""
map():python的内置函数,直接使用类似print()
会根据提供函数对指定的序列做映射
描述:
创建一个迭代器,使用每一个迭代器,当最短的迭代被耗尽时终止
格式:
map(function,iterables)
function:函数,有两个参数
iterables:一个或者多个序列
python2:返回的是一个列表
python3:迭代器
"""
# a = (1,2,3,4,5)
# b = [1,2,3,4,5]
# c = "laowang"
#
# la = map(str,a)
# # print(list(la))
# lb = map(str,b)
# # print(list(lb))
# lc = map(str,c)
# print(list(lc))
#将单个字符转换成对应的字面量整数
# def chr2int(chr):
# return {"0":0,"1":1,"2":2,"3":3,"4":4}[chr]
# d = ["1","2","3"]
# ld = map(chr2int,d)
# print(list(ld))
numbers = ['1','2','3','4','5']
print(list(map(int, numbers)))
| false |
193169fd4dd3139740884f5592efaae07a796b02 | Nish8192/Python | /Python/Python_Fundamentals/Odd_Even.py | 226 | 4.15625 | 4 | def odd_even(x,y):
for i in range(x,y+1):
if(i%2 == 1):
print 'Number is',i,'. This is an odd number.'
else:
print 'Number is',i,'. This is an even number.'
odd_even(1, 2000)
| false |
de7e0d2d5645e16b449a34a225264100080512f0 | phamhailongg/C4T9 | /Homework3/Part 3/x6.py | 282 | 4.28125 | 4 | # Ask user to enter a number n, then print n x n numbers, following multiplication table’s pattern
x = int(input("Number? "))
def print_multiples(n):
for i in range(1, x + 1) :
print(n * i, end="\t")
print()
for i in range(1, x + 1) :
print_multiples(i)
| false |
b8db869b7805d48ff3100a2119f4c07e32636954 | phamhailongg/C4T9 | /minihack2/Part 2/l11.py | 272 | 4.125 | 4 | # make a list
n = input("Enter a list of numbers, separated by ‘, ‘ : ")
n = n.split(',')
print(n)
ln1 = []
for i in n :
i = int(i)
ln1.append(i)
print("All even numbers from entered list: ")
for a in ln1 :
if a % 2 == 0 :
print(*ln1, sep=", ") | false |
f30598c56ab09af3541976a7f7be687a0b93717a | approximata/edx_mit_6.00.2x | /unit3/noReplacementSimulation.py | 1,030 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 6 15:30:33 2016
@author: matekovacsbodor
"""
def noReplacementSimulation(numTrials):
'''
Runs numTrials trials of a Monte Carlo simulation
of drawing 3 balls out of a bucket containing
3 red and 3 green balls. Balls are not replaced once
drawn. Returns the a decimal - the fraction of times 3
balls of the same color were drawn.
'''
# Your code here
balls = ['red', 'red', 'red', 'green', 'green', 'green']
allEqualCount = 0.0
for i in range(numTrials):
ballsSet = balls[:]
ballsPicks = []
for i in range(3):
choice = ballsSet[random.randrange(len(ballsSet))]
ballsPicks.append(choice)
ballsSet.remove(choice)
if ballsPicks[0] == ballsPicks[1] and ballsPicks[0] == ballsPicks[2]:
allEqualCount += 1
return allEqualCount / numTrials
print("All equals for {0} trials: {1}".format(1000, noReplacementSimulation(1000))) | true |
e6dbe4e93200f72bfa93b3a576edf651d1c12f3a | SanjayGorur/UTD-Python | /Assignment6.py | 1,988 | 4.1875 | 4 | class CircQ:
def __init__(self, size):
self.size = size
self.Qu = []
def front(self):
if(self.isEmpty()):
return -1
return self.Qu[0]
def rear(self):
if(self.isEmpty()):
return -1
return self.Qu[-1]
def enQueue(self, obj):
if(self.isFull()):
return False
self.Qu.insert(0, obj)
return True
def deQueue(self):
if(self.isEmpty()):
return False
print()
print(self.Qu.pop(0), "was removed")
return True
def isEmpty(self):
return len(self.Qu) == 0
def isFull(self):
return len(self.Qu) == self.size
k = int(input("Please set the size of your queue: "))
if(k == -1):
print("You are done!")
else:
Q = CircQ(k)
while True:
print()
check = input("Enter a command--front, rear, add, remove, end: ")
if(check == "front"):
print("Current List: ", Q.Qu)
if(Q.front() == -1):
print()
print("Sorry, but there are no elements to peek.")
else:
print()
print("Front element: ", Q.front())
elif(check == "rear"):
print("Current List: ", Q.Qu)
if(Q.rear() == -1):
print()
print("Sorry, but there are no elements to peek.")
else:
print()
print("Last element: ", Q.rear())
elif(check == "add"):
print("Current List: ", Q.Qu)
value = int(input("Enter a number to add to the queue: "))
if(Q.enQueue(value) == False):
print()
print("Sorry, but you can't add any more elements.")
else:
print()
print("Updated Queue:\t", Q.Qu)
elif(check == "remove"):
print("Current List: ", Q.Qu)
if(Q.deQueue() == False):
print()
print("Sorry, but there are no elements to remove.")
else:
print()
print("Updated Queue:\t", Q.Qu)
elif(check == "end"):
print()
print("You are done!")
break
else:
print("Sorry, the command you entered is invalid.")
| false |
2af621899d369f05a783776c094451045ad779ef | ahmedvuqarsoy/Cryptography-with-Python | /Decryption Caesar Cipher with Bruteforce.py | 1,255 | 4.25 | 4 | #Cracking Caesar Cipher using Bruteforce by Hajiahmad Ahmadzada
import time
def bruteforce(encrypted_message):
encrypted_message.upper()
#There is 26 letter and we check each combination
#in normal Caesar Cipher
for key in range(1,27):
decrypted_message = ""
#We decrypt message between keys 1 and 26
for i in range(len(encrypted_message)):
if(not(encrypted_message[i].isalnum())):
decrypted_message += encrypted_message[i]
else:
value = ord(encrypted_message[i]) - key
if(value < 65):
value += 26
decrypted_message += chr(value)
print("The used key = ",key)
print("The possible decrypted message: ", decrypted_message)
time.sleep(2)
#We ask to user is it possible decryption or not.
print("------------------------")
ans = input("Continue? Y/N: ")
print("------------------------")
if(ans == "Y" or ans == "y"):
continue
else:
break
encrypted_message = input("""
----------------------------------
Please enter your encrypted string
----------------------------------
=> """)
bruteforce(encrypted_message)
| true |
f3206910885a7865f46247fc5998eb1a9dc8313b | IAmJustSomeRandomGuy/Hello-World | /project6-for loops.py | 1,734 | 4.125 | 4 | from typing import List
speed = True
for a in "Minecraft":
print(a)
names = ["Karen", "Josh", "Marry"]
for name in names:
print(name)
for index in range(10):
print(index)
*hi, bye = range(12, 16)
for hello in hi:
print(hello)
print()
print(bye)
for name in range(len(names)):
print(names[name])
for text in range(3):
if text == 0:
print("first text")
else:
print("not first text")
print(3 ** 5)
if not speed:
base_num = float(input("enter num:"))
pow_num = float(input("enter power:"))
def raise_to_power():
return base_num ** pow_num
if not speed:
print(raise_to_power())
def raise_power(num1, num2):
result = 1
for b in range(num2):
result = result * num1
return result
print(raise_power(9.5, 8))
print("2:47:14")
formatting = f"hi {names[0]} how are you"
print(formatting)
num_grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10]
]
print(num_grid[2][1])
for row in num_grid:
for column in row:
print(column)
def translate(phrase):
translation = ""
for letter in phrase:
if letter.lower() in "aeiouy":
if letter.isupper():
translation = translation + "F"
else:
translation = translation + "f"
else:
translation = translation + letter
return translation
if not speed:
print(translate(input("Input a phrase: ")))
try:
numa = int(input("Enter a number: "))
numb = int(input("Enter a divider: "))
numc = numa / numb
print(numc)
except ValueError:
print("Bad input")
except ZeroDivisionError as error:
print(error)
| true |
1b9f6b73458c09a9a5445c5a035b0e5cba233a93 | asmitamahamuni/python_programs | /string_reverse.py | 382 | 4.375 | 4 | # Reverse the given string
# 1. Reversing a string - Recursive
def reverse(input):
print(input)
if len(input) <= 1:
return input
return reverse(input[1:]) + input[0]
s = 'reverse'
print(reverse(s))
# 2. Reversing a string - Iterative
def reverse(input):
return ''.join([input[i] for i in range(len(input)-1, -1, -1)])
s = 'reverse'
print(reverse(s))
| true |
5ab1d4b0d1ec2231ab596d61b2bc033b43947eb3 | jwcha/exercism-python | /leap/leap.py | 600 | 4.4375 | 4 | #!/usr/bin/env python3
# function to compute if a given year is a leap year or not.
# A leap year is defined as:
# A year which is divisible by four,
# except if divisible by 100,
# unless divisible by 400.
def is_leap_year(year):
# a one-liner solution
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
# my first attempt:
# if year % 4 == 0:
# if year % 100 == 0:
# if year % 400 == 0:
# return True
# return False
# else:
# return True
# return True
# else:
# return False
| true |
0ee005d39c0631df8f065f53bc4a064e8c0ce2df | kapm/curso-python | /proyecto3/ahorcado.py | 1,427 | 4.1875 | 4 | print("Bienvenido al ahorcado")
print("comencemos")
print("Presiona cualquier tecla para continuar")
input()
palabra_secreta="python"
oportunidades=10
letras_correctas=[]
restantes=[]
for letra in palabra_secreta:
if letra not in restantes:
restantes.append(letra)
def mostrar_casillas(correctas):
for letra in palabra_secreta:
if letra in correctas:
print(letra,end="")
else:
print(" _ ", end ="")
print("\n")
while oportunidades>0 and len(restantes)>0:
mostrar_casillas(letras_correctas)
adivinanza=input("Adivina una letra: ")
if adivinanza in palabra_secreta:
letras_correctas.append(adivinanza)
restantes.remove(adivinanza)
else:
oportunidades-=1
print("Te quedan ",oportunidades)
if len(restantes)==0:
print("Ganaste!")
else:
print("Perdiste")
'''palabra="cuadro"
letra=""
palabra_adivinada=[]
#pedir a usuario que adivine
def preguntar_letra(letra):
while palabra!=palabra_adivinada:
letra=input("Adivina una letra: ")
if letra in palabra:
print("adivinaste una letra!")
letra_adivinada(letra)
else:
print("vuelve a intentar:")
return letra
def letra_adivinada(letra):
i=0
while letra in palabra[i]:
palabra_adivinada.append(letra)
print("Comenzar ahorcado")
print("_"*len(palabra))
preguntar_letra(letra)''' | false |
423fd5804aabce808b46d64cfe83366c641627cf | BraeWebb/adventofcode2017 | /day1/day1.py | 1,169 | 4.15625 | 4 | import sys
def sum_matching(line, index_func=lambda i: i + 1):
"""
Computes the sum of matching pairs in a circular list.
A matching pair is when a number equals the number found at index_func(i)
in the list, where i is the numbers index and index_func is the provided
function. By default this is the next number, i.e. i + 1.
Parameters:
line (str): A string of numbers.
index_func (func): The function used to find a numbers match.
Returns:
(int): The sum of matching pairs.
"""
max = len(line)
sum = 0
for i, num in enumerate(line):
if num == line[index_func(i) % max]:
sum += int(num)
return sum
def run(stdin):
"""
Takes problem input and yields solutions.
Parameters:
stdin (str): The input to the problem as a string.
Yields:
(*): The solutions to the problem.
"""
line = stdin.splitlines()[0]
max = len(line)
yield sum_matching(line)
yield sum_matching(line, index_func=lambda i: i + (max // 2))
if __name__ == "__main__":
results = run(sys.stdin.read())
for result in results:
print(result)
| true |
98f300d7811ec19ff4e815ef2da3dc41736bbf59 | knittingarch/Zelle-Practice | /Exercises/5-4.py | 253 | 4.125 | 4 | '''
A program that makes acronyms out of user-provided phrases.
by Sarah Dawson
'''
def main():
acronym = ""
phrase = raw_input("Please enter your phrase: ")
phrase = phrase.split(" ")
for s in phrase:
acronym += s[0].upper()
print acronym
main() | true |
130fcf0da3968c9892918c896209443a7a77fdf4 | knittingarch/Zelle-Practice | /Exercises/5-2.py | 275 | 4.125 | 4 | '''
A program to assign letters to numerical grades.
by Sarah Dawson
'''
def main():
letter_grade = ['F', 'F', 'D', 'C', 'B', 'A']
num_grade = eval(raw_input("Please enter your numerical grade (0-5): "))
print "You earned a ", letter_grade[num_grade], "on that quiz."
main() | false |
a9398bd73852a4b8ffdc1a9208e855053f4aadef | evaristrust/Courses-Learning | /SecondProgram/input and output/write_texts.py | 476 | 4.25 | 4 | # we are going to open a simple txt file
cities = ["Kigali", "Kampla", "Dar es Salaam", "Nairobi", "Buja"]
with open("cities.txt", 'w') as cities_file:
for city in cities:
print(city, file=cities_file)
# what if i want to append this by a times 2 table
with open("cities.txt", "a") as tables:
for i in range(0, 13):
for j in range(0, 13):
print("{} times {} is {}".format(i, j, i * j), file=tables)
print("--" * 10, file=tables) | false |
28069ad17663f9fc7949345f51c1866c9948eed6 | evaristrust/Courses-Learning | /CreateDB/TestDB/contacts.py | 998 | 4.28125 | 4 | import sqlite3
db = sqlite3.connect('contacts.sqlite')
db.execute("CREATE TABLE IF NOT EXISTS contacts(NAME TEXT, PHONE INT, EMAIL TEXT)")
db.execute("INSERT INTO contacts(NAME, PHONE, EMAIL) VALUES('Big Man', 087894, 'big@gmail.com')")
db.execute("INSERT INTO contacts VALUES('Tiny Man', 085343, 'tiny@gmail.com')")
db.execute("INSERT INTO contacts VALUES('Shy Man', 0234234, 'shy@gmail.com')")
db.execute("INSERT INTO contacts VALUES('Bad Man', 2502321, 'bado@gmail.com')")
#Querying my database by executing queries using cursor
cursor = db.cursor()
cursor.execute("SELECT DISTINCT * FROM contacts")
# print(cursor.fetchall()) # returns a list of rows.. allowing moving back and forth through rows.
# print(cursor.fetchone()) # This is quite useful... returns list in a style
# for row in cursor:
# print(row)
for name, phone, email in cursor:
print(name)
print(phone)
print(email)
print("-" * 20)
cursor.close()
db.commit() # This will save the data well and can be reached in contacts2
db.close() | true |
11b2638a0a7ed50f2ca30eccb989113a1eea3ae4 | evaristrust/Courses-Learning | /myexercises/exercise1.py | 925 | 4.21875 | 4 | # We are here going to work on the addition and multiplication
# Generate two digit integers and do their multiplication
# If their product is greater 1000, generate their sum , else generate their product
import random
num1 = random.randrange(10,100)
num2 = random.randrange(10,100)
product = num1 * num2
sum = num1 + num2
if product >=1000:
print("The sum of ", num1, "and ", num2, "is ", sum)
else:
print("The product of ", num1, "and ", num2, "is ", product)
# going to do the same exercises
# Find two random numbers from 1 to 20, add them and if their sum is greater than 12, do product
numa = random.randrange(1, 20)
numb = random.randrange(1, 20)
product = numa * numb
sum = numa + numb
if sum >= 12:
print("The sum ", numa, "and", numb, "is greater or equal to 12; thus the product is: ", product)
else:
print("The sum is less than 12, and it is: ", sum, ": addition of ", numa, "and", numb) | true |
6e3be7a0cd52a9218b1a29d0885794091e899dc2 | evaristrust/Courses-Learning | /SecondProgram/pytbasics/CHALLENGES/Edabit/largest_numbers.py | 863 | 4.40625 | 4 | #print the largest numbers in a list... n numbers
lst = [20, 42, 21, 34, 23, 70]
lst.sort()
print(lst[-3:]) # print three largest numbers
# or
my_list = [20, 42, 21, 34, 23, 70, 24]
lst = sorted(my_list)
print(lst[-3:])
def largest_numbers(n, lst):
lst = [20, 42, 21, 34, 23, 70, 24,45]
my_list = sorted(lst)
return my_list[len(lst)-n:] # this also works better
print(largest_numbers(5, my_list))
def find_largest(x):
lst = [45, 20, 21, 89, 45, 65, 100]
sorted_list = sorted(lst)
return sorted_list[len(lst)-x:]
print("The top scores in your class are {0}".format(find_largest(3)))
# use this method:
# create a variable outside the function
# works better than the above
my_list = [34, 23, 21, 64, 23, 63, 75, 45] # this looks ugly
def my_largest(x):
lst = sorted(my_list)
return lst[len(lst)-x:]
print(my_largest(3))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.