blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
0e66cef7b14800d47a750139d943d8c439338232 | fengkaiwhu/A_Byte_of_Python3 | /example/addr_book.py | 1,812 | 4.1875 | 4 | #!/usr/bin/env python
# coding=utf-8
# Filename: addr_book.py
class addr_book:
'''Represent an addr_book'''
book = {}
def __init__(self, book):
addr_book.book = book
def get_book(self):
return addr_book.book
def add_person(self):
name = input('Please input name-->')
address = input('Please input address-->')
phone = input('Please input phone-->')
from person import person
person = person(name, address, phone)
if person.name in addr_book.book.keys():
print('The person already exists')
else:
addr_book.book[person.name] = person
del person
def del_person(self):
name = input('Please input name-->')
if name not in addr_book.book.keys():
print('The person is not exists')
else:
addr_book.book.pop(name)
def modify_person(self):
name = input('Please input name-->')
if name not in addr_book.book.keys():
print('The person is not exists')
else:
person = addr_book.book[name]
print('Original infomation Name: {0}, address: {1}, phone: {2}'.format(name, person.address, person.phone))
person.name = input('Please input new name-->')
person.address = input('Please input new address-->')
person.phone = input('Please input new phone-->')
def show_person(self):
if len(addr_book.book.keys()) == 0:
print('Address book is empty.')
else:
for name, person in addr_book.book.items():
print('Name: {0}, address: {1}, phone:{2}'.format(person.name, person.address, person.phone))
if __name__ == '__main__':
addr_book = addr_book()
addr_book.add_person()
| true |
85ca3ab76550a0092f926eb777a834246c85c557 | RyanWaltersDev/NSPython_chapter3 | /travel_dest.py | 729 | 4.71875 | 5 | #Ryan Walters Nov 21 2020 -- Practicing the different sorting methods with travel destinations
#Initial list
travel_dest = ['tokyo', 'venice', 'amsterdam', 'osaka', 'wales', 'dublin']
#Printing as a raw Python list and then in order
print(travel_dest)
print(sorted(travel_dest))
#Printing in reverse alphabetical order without a permanent change to the list
print(travel_dest)
print(sorted(travel_dest, reverse=True))
#Using reverse method to change the order and then back again
print(travel_dest)
travel_dest.reverse()
print(travel_dest)
travel_dest.reverse()
print(travel_dest)
#Alphabetical sorting and reverse permanent
travel_dest.sort()
print(travel_dest)
travel_dest.sort(reverse=True)
print(travel_dest)
#END OF PROGRAM
| true |
4ca4e141304cac59a47ae96c22a9d54ea6bd4ef2 | danielmlima1971/CursoemVideo-Python-Exercicios | /Mundo 1/Ex022.py | 645 | 4.3125 | 4 | # EXERCICIO 022
# Exercício Python 22: Crie um programa que leia o nome
# completo de uma pessoa e mostre:
# – O nome com todas as letras maiúsculas e minúsculas.
# – Quantas letras ao todo (sem considerar espaços).
# – Quantas letras tem o primeiro nome.
nome = str(input('Digite seu nome completo: '))
print('Seu nome com todas as letras maiúsculas é {}'.format(nome.upper()))
print('Seu nome com todas as letras minúsculas é {}'.format(nome.lower()))
print('Seu nome tem {} caracteres'.format(len(nome.replace(" ", ""))))
dividido = nome.split()
print('Seu primeiro nome tem {} letras'.format(len(dividido[0])))
| false |
e4a79d6a56885eed560cf5a5f2c7ab6c614cb164 | danielmlima1971/CursoemVideo-Python-Exercicios | /Mundo2/Ex036-EmprestimoBancario.py | 1,167 | 4.34375 | 4 | # Exercício Python 36: 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.
print('\033[7;30;41m=\033[m' * 21)
print('\033[7;30;41m EMPRESTIMO BANCÁRIO \033[m')
print('\033[7;30;41m=\033[m' * 21)
casa = float(input('Qual o valor da casa? '))
prazo = int(input('Qual o prazo de pagamento? (em anos) '))
sal = float(input('Qual sua renda média mensal? '))
prazo = prazo * 12
parcela = casa / prazo
print('Valor da casa: R$ {:.2f}'.format(casa))
print('Valor da Parcela: R$ {:.2f}'.format(parcela))
if parcela > (sal * 0.30):
print('Você NÃO será aprovado pois seu salário (R$ {:.2f}) é baixo '
'\npara a parcela de R$ {:.2f}'.format(sal, parcela))
else:
print('Você será aprovado pois pode pagar uma '
'\nparcela de R$ {:.2f} com o salário de R$ {:.2f}'.format(parcela,
sal))
| false |
9207040ba05bb7cceb6eff73afcae3d3e2d2232a | daisyzl/program-exercise-python | /Sort/4insertsort.py | 1,706 | 4.375 | 4 | #-*-coding:utf-8-*-
'''
插入排序
基本思想:插入排序是一种简单直观的排序算法。它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,
找到相应位置并插入。插入排序在实现上,在从后向前扫描过程中,需要反复把已排序元素逐步向后挪位,为最新元素提供插入空间。
插入排序的时间复杂度问题
最优时间复杂度:O(n) (升序排列,序列已经处于升序状态)
最坏时间复杂度:O(n2)
稳定性:稳定
https://www.runoob.com/python3/python-insertion-sort.html
思想:
把n个待排序的元素看成一个有序表和一个无序表,开始时有序表中只包含一个元素,无序表中包含n-1个元素,
排序过程中每次从无序表中取出第一个元素,把它的排序码依次与有序元素的排序码进行比较,
将它插入到有序表中的适当位置,使之成为新的有序表
插入排序和希尔排序一起记忆
'''
if __name__ == '__main__':
def insert_sort(data):
for i in range(1, len(data)):
# 前一个数已经排序
key = data[i]
j = i-1
# key前面一个数的下标
# j >= 0 保证给key找插入位置不越界
# key < data[j] 待插入的位置没有找到
while(j >= 0 and key < data[j]):
data[j+1] = data[j]
# 将前一个数往后移一位
j -= 1
# 退出循环,找到位置 key >data[j],放到后面
data[j+1] = key
return data
li = [99, 22, 64, 55, 11, 35, 89, 1, 2]
print(insert_sort(li))
| false |
3b848a03a86b5e409bd266d06e55998791035a9d | daisyzl/program-exercise-python | /BinaryTree/zuidashendu.py | 1,373 | 4.1875 | 4 | # -*- coding:utf-8 -*-
'''
function:二叉树的最大深度
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
题目:https://leetcode-cn.com/explore/learn/card/data-structure-binary-tree/3/solve-problems-recursively/12/
答案:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/solution/tu-jie-104-er-cha-shu-de-zui-da-shen-du-di-gui-pyt/
'''
class TreeNode(object):
""" Definition of a binary tree node."""
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
else:
left_height = self.maxDepth(root.left)
right_height = self.maxDepth(root.right)
return max(left_height, right_height) + 1
if __name__ == '__main__':
n1 = TreeNode(1)
n2 = TreeNode(2)
n3 = TreeNode(3)
n4 = TreeNode(4)
n5 = TreeNode(5)
n1.left = n2
n1.right = n3
n2.left = n4
n2.right = n5
print(Solution().maxDepth(n1))
| false |
d0d118fe3a88f33f1c18d12c565e9e83620fe9f8 | spettigrew/cs2-codesignal-practice-tests | /truck_tour.py | 2,736 | 4.5 | 4 | """
Suppose there is a circle. There are N petrol pumps on that circle. Petrol pumps are numbered 0 to (N - 1) (both inclusive). You have two pieces of information corresponding to each of the petrol pump: (1) the amount of petrol that particular petrol pump will give, and (2) the distance from that petrol pump to the next petrol pump.
Initially, you have a tank of infinite capacity carrying no petrol. You can start the tour at any of the petrol pumps. Calculate the first point from where the truck will be able to complete the circle. Consider that the truck will stop at each of the petrol pumps. The truck will move one kilometer for each litre of the petrol.
Input Format
The first line will contain the value of N.
The next N lines will contain a pair of integers each, i.e. the amount of petrol that petrol pump will give and the distance between that petrol pump and the next petrol pump.
Constraints:
1 <= N <= 10^5
1 <= amount of petrol, distance <= 10^9
Output Format
An integer which will be the smallest index of the petrol pump from which we can start the tour.
Sample Input
3
1 5
10 3
3 4
Sample Output
1
Explanation
We can start the tour from the second petrol pump.
"""
#!/bin/python3
import os
import sys
#
# Complete the truckTour function below.
#
def truckTour(petrolpumps):
#
# Write your code here.
#
# answer the question, can we make it around the circle starting at a given index
# first thing we do when we get to a pump:
# take all the petrol available
# second -> try to go to the next pump:
# if our current is > distance, then we can make it there
# travel to the next one:
# increment our index, subtract the distance from current
# if we make it back to our starting point, then we can answer true
start = 0
current = 0
petrol = 0
while start <= len(petrolpumps):
petrol += petrolpumps[current][0]
petrol -= petrolpumps[current][1]
if petrol < 0:
# we didn't make it to the next one
start = current + 1
current = start
petrol = 0
continue
current = (current + 1) % len(petrolpumps)
# OR
# current += 1
# if current >= len(petrolpumps):
# current = 0
if current == start:
return start
return None
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
petrolpumps = []
for _ in range(n):
petrolpumps.append(list(map(int, input().rstrip().split())))
result = truckTour(petrolpumps)
fptr.write(str(result) + '\n')
fptr.close()
| true |
53ba03e8e1cbb013f566be89f6b0df2722a7319d | spettigrew/cs2-codesignal-practice-tests | /roman-to-integer.py | 2,820 | 4.25 | 4 | """
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer.
Example 1:
Input: s = "III"
Output: 3
Example 2:
Input: s = "IV"
Output: 4
Example 3:
Input: s = "IX"
Output: 9
Example 4:
Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 5:
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
Constraints:
1 <= s.length <= 15
s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
It is guaranteed that s is a valid roman numeral in the range [1, 3999].
"""
# if you need the index, do a range loop. If you need the value, do a for/in loop. If you need both, do an enumerate (returns index, and value)
class Solution:
def romanToInt(self, roman):
numerals = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
'IV': 4,
'IX': 9,
'XL': 40,
'XC': 90,
'CD': 400,
'CM': 900
}
# init i as our starting index
i = 0
# init num to hold the resulting addition of the found roman numerals
num = 0
# iterate the string
while i < len(roman):
# if there are 2 chars to check and they are both in numerals
if i + 1 < len(roman) and roman[i:i + 2] in numerals:
# add the integer version of the found 2 character roman numeral to
# the num var
num += numerals[roman[i:i + 2]]
# increment counter by 2 since we found a 2 character roman numeral
i += 2
else:
# add the integer version of the found roman numeral to the num var
num += numerals[roman[i]]
# increment counter by 1 since we found a single character roman
# numeral
i += 1
return num
| true |
d9bc3016a040ecb9b68e404cf4a9244ed6ee81a6 | spettigrew/cs2-codesignal-practice-tests | /anagrams.py | 2,712 | 4.46875 | 4 | """
A student is taking a cryptography class and has found anagrams to be very useful. Two strings are anagrams of each other if the first string's letters can be rearranged to form the second string. In other words, both strings must contain the same exact letters in the same exact frequency. For example, bacdc and dcbac are anagrams, but bacdc and dcbad are not.
The student decides on an encryption scheme that involves two large strings. The encryption is dependent on the minimum number of character deletions required to make the two strings anagrams. Determine this number.
Given two strings, a and b, that may or may not be of the same length, determine the minimum number of character deletions required to make a and a anagrams. Any characters can be deleted from either of the strings.
Example
a = 'cde'
b = 'dcf'
Delete e from a and f from b so that the remaining strings are cd and dc which are anagrams. This takes 2 character deletions.
Function Description
Complete the makeAnagram function in the editor below.
makeAnagram has the following parameter(s):
string a: a string
string b: another string
Returns
int: the minimum total characters that must be deleted
Input Format
The first line contains a single string, a.
The second line contains a single string, b.
Constraints
1 <= |a|, |b| < = 10^4
The strings a and b consist of lowercase English alphabetic letters, ascii[a-z].
Sample Input
cde
abc
Sample Output
4
Explanation
Delete the following characters from the strings make them anagrams:
Remove d and e from cde to get c.
Remove a and b from abc to get c.
It takes 4 deletions to make both strings anagrams.
"""
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the makeAnagram function below.
def makeAnagram(a, b):
letters = {}
for letter in letters(a):
if letter not in letter:
createLetter()
incrementLetter()
for letter in letters(b):
if letter in letters:
if letter > 0:
matchLetter()
else:
incrementLetter()
else:
createLetter()
incrementLetter()
result = 0
for letter in letter:
result += letters[letter]
def createLetter():
letters: {
letter: 0
}
def incrementLetter():
letters: {
letter: + 1
}
def matchLetter():
letters: {
letter: - 1
}
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
a = input()
b = input()
res = makeAnagram(a, b)
fptr.write(str(res) + '\n')
fptr.close()
| true |
307c0d178659494d3639d78df5f4b1bd1dfc9607 | thomasmcclellan/pythonfundamentals | /02.01_strings.py | 525 | 4.21875 | 4 | # Strings hold text info and hold "" or ''
# Can have []
'hello'
"hello"
"I'm a dog"
my_string = 'abcdefg'
print(my_string)
print(my_string[0])
print(my_string[3:])
print(my_string[:3]) #Goes up to, BUT NOT INCLUDING the number
print(my_string[2:5])
print(my_string[::])
print(my_string[::2]) #The number is the step size (goes up by two)
# Strings are IMMUTIBLE
x = my_string.upper()
print(x)
y = my_string.lower()
print(y)
z = my_string.capitalize()
print(z)
two_words = 'Hello world'
t = two_words.split()
print(t) | true |
d7c16c08b73fa5b2a45356431d35416a2e30155e | alaasal95/problem-solving | /Convert_second _to_hour_min_second.py | 323 | 4.15625 | 4 |
'''
----->Ex:// read an integer value(T) representing time in seconds
and converts it to equivalent hours(hr),minutes(mn)and second(sec)
'''
p1=int
p2=int
p3=int
second=4000
p1=second%60
p2=second/60
print('p2_',p2)
p3=p2%60
print('p2',p2)
p2=p2/60
print(p2 ,":",p3,":",p1)
| true |
06e6aa8918528136b1b4a56e463dcfb369580261 | emmanuelthegeek/Python-Exercises | /Widgets&gizmos.py | 1,130 | 4.25 | 4 | #An online retailer sells two products. widgets and gizmos. Each widget weighs 75 grams, while each gizmo weighs 112 grams.
#Write a program that displays the total weight of an order, in kilograms, given two variables containing the number of widgets
#and gizmos.
#Solution
# 1 widget = 75g
# 1 gizmos = 112g
# 1000g = 1kg
CustomerName = input('Kindly provide your name ')
try:
Widget_quantity_ordered = float(input('How many quantities of widgets do you need? '))
Gizmos_quantity_ordered = float(input('How many quantities of gizmos do you want? '))
Total_Widget_weight_in_grams = Widget_quantity_ordered * 75
Total_Gizmos_weight_in_grams = Gizmos_quantity_ordered * 112
Total_weight_of_an_order_in_grams = Total_Widget_weight_in_grams + Total_Gizmos_weight_in_grams
Total_weight_of_an_order_in_kilograms = Total_weight_of_an_order_in_grams / 1000
print(f"Dear {CustomerName}, you have just ordered {Total_weight_of_an_order_in_kilograms}kg of widgets and gizmos")
except:
print('Quantities should be in whole numbers')
finally:
print(f"Thank you {CustomerName} for doing business with us") | true |
6cc0e043bd8778e825fa2fd6748518a6e641a5f9 | MihaiDinca1000/Game | /Exercitii/Test_inheritance.py | 2,254 | 4.59375 | 5 | '''
In this Python Object-Oriented Tutorial, we will be learning about inheritance and how to create subclasses.
Inheritance allows us to inherit attributes and methods from a parent class.
This is useful because we can create subclasses and get all of the functionality of our parents class,
and have the ability to overwrite or add completely new functionality without affecting the parents class in any ways.
'''
class Angajat:
marire = 1.04
nr_angajati = 0
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@gmail.com'
Angajat.nr_angajati += 1
def nume_Angajat(self):
return '{} {}'.format(self.first, self.last)
def aplica_marire(self):
self.pay = int(self.pay * self.marire)
class Dezvoltator(Angajat):
marire = 1.1
def __init__(self, first, last, pay, statut):
super().__init__(first, last, pay)
# Angajat.__init__(self, first, last, pay) e acelasi lucru ca linia de mai sus
self.statut = statut
class Manager(Angajat):
def __init__(self, first, last, pay, statut, angajati = None):
super().__init__(first, last, pay)
if angajati is None:
self.nr_angajati = []
else:
self.angajati = angajati
def add_ang(self, ang):
if ang not in self.angajati:
self.angajati.append(ang)
def remove_ang(self, ang):
if ang in self.angajati:
self.angajati.remove(ang)
def print_ang(self):
for ang in self.angajati:
print('-->',ang.nume_Angajat())
an1 = Angajat('Sebastian', 'Bach', 67500)
dev1 = Dezvoltator('Gigi', 'Becali', 180000, 'cioban cu bani')
dev2 = Dezvoltator('viorica', 'Dancila', 26000, 'premier analfabet')
# print(help(an1)) iti arata totul despre acest angajat +mostenirea
manager1 = Manager('Liviu', 'Dracnea', 400000, 'furacios cu in parlament', [dev2, dev1])
manager1.remove_ang(dev1)
manager1.print_ang()
# print(manger1.angajati)
# print(dev1.email)
# print(dev2.statut)
# print(dev1.pay)
# dev1.aplica_marire()
# print(dev1.pay)
| true |
43bdd743c29efec4b9756ce9d6ecd8f5bcf61b99 | porregu/unit3 | /unitproject.py | 1,336 | 4.21875 | 4 | def arearectangle(a,b):
"""
solve the area of the rectangle
:param a: heigth
:param b: with
:return: return the fucntion to do it more times
"""
return a*b
def withh():# dpuble (h) because dosent let me put one # with called by the user
"""
make the user tell the with
:return: the function so we know the number and we can make the calculation
"""
a=float(input("what is the with"))
return a
def lenght():# lenght called by the user
"""
user called the lenght
:return: return the function to make the calculations
"""
b=float(input("what is the lenght"))
return b
def height():# height called by the user
"""
user called height
:return: return the function to make the claculations
"""
c=float(input("what ois the height"))
return c
def instructions():
print("this is gonna calculate the surace area of a rectangle with the length, with and height choosed by the user")
def calculations():#surface area calculations
a =withh()
b=lenght()
c=height()
top=arearectangle(a,b)
bottom=arearectangle(b,a)
front=arearectangle(c,b)
back=arearectangle(b,c)
left=arearectangle(c,a)
right=arearectangle(a,c)
total=top+bottom+right+left+front+back
instructions()
print(total)
calculations()
| true |
b6d777bda60b89b9880543ecdd6f132a111b039e | tanay2098/homework4 | /task2.py | 1,023 | 4.15625 | 4 | import random # importing package random
nums = [] # initializing an empty list called nums
for i in range(0,2): # Loop for 2 elements
nums.append(random.randint(0,10)) # generating 2 numbers between 0 to 10 and appending them in the list
t1 = tuple(nums) # converting list into a tuple named t1
correct_answer = (int)(t1[0] * t1[1] )# converting product of first and second element of tuple into integer and storing it
print("How much is",t1[0],"times",t1[1],"? ") # Displaying the question
temp = 0 # a variable to store sentinel value
while(temp<1):
user_answer = int(input("->"))# prompting user to enter the answer
if user_answer==correct_answer: # Comparing the user's answer with correct answer
print("done") # If answer is right then display done
temp= temp +1 # incrementing the value in variable by 1, so as to exit the loop
else:
print(t1[0],"times",t1[1],"is not,",user_answer,"please try again: ")# if answer is wrong then prompt user to enter the correct answer | true |
f76f683497bbf7caff26732105b355888d3160e1 | damiannolan/python-fundamentals | /current-time.py | 224 | 4.1875 | 4 | # Problem 2 - Current Time
import time;
import datetime;
# Print the the date and time using 'time'
print("Current time is : ", time.asctime(time.localtime(time.time())))
print("Today's date is: ", datetime.date.today())
| true |
82bd6970962a9f11921c2dc8892969dacad895c8 | srholde2/Project-4 | /queue.py | 1,103 | 4.28125 | 4 | class Queue:
# queue class constructor
def __init__(self):
self.queue = ["car", "car", "car", "car", "car"]
def enqueue(self):
item = input("Please enter the item you wish to add to the queue: ")
self.queue.append(item)
def dequeue(self):
item = self.queue.pop(0)
print("You have just removed item from queue: ", item)
def size(self):
for x in range (len(self.queue)):
print(self.queue[x])
queue = Queue()
newitem = Queue()
while True:
print("")
print("Python Implementation of a Queue")
print("********************************")
print("1. Create a new object")
print("2. Add a new item to the queue")
print("3. Remove item from the queue")
print("********************************")
menu_choice = int(input("Please enter your menu choice: "))
print("")
print("")
if menu_choice == 1:
newitem.enqueue()
elif menu_choice == 2:
queue.enqueue()
elif menu_choice == 3:
queue.dequeue()
| true |
1050e66e270df03c2c88cb35e5d4bf364de138b7 | hiranmayee1123/Hacktoberfest-2021 | /windowslidingproblem.py | 1,013 | 4.21875 | 4 | #This technique shows how a nested for loop in some problems can be converted to a single for loop to reduce the time complexity.
#Let’s start with a problem for illustration where we can apply this technique –
#Given an array of integers of size ‘n’.
#Our aim is to calculate the maximum sum of ‘k’
#consecutive elements in the array.
#Input : arr[] = {100, 200, 300, 400}
k = 2
Output : 700
Input : arr[] = {1, 4, 2, 10, 23, 3, 1, 0, 20}
k = 4
Output : 39
We get maximum sum by adding subarray {4, 2, 10, 23}
of size 4.
Input : arr[] = {2, 3}
k = 3
Output : Invalid
There is no subarray of size 3 as size of whole
array is 2.
import sys
INT_MIN = -sys.maxsize - 1
def maxSum(arr, n, k):
max_sum = INT_MIN
for i in range(n - k + 1):
current_sum = 0
for j in range(k):
current_sum = current_sum + arr[i + j]
max_sum = max(current_sum, max_sum)
return max_sum
arr = [1, 4, 2, 10, 2,
3, 1, 0, 20]
k = 4
n = len(arr)
print(maxSum(arr, n, k))
| true |
183a7f2a4ed17abee62bb4e1bb2879469dbe126f | rickpaige/dc-cohort-week-one | /day3/lists-strings.py | 435 | 4.1875 | 4 | # List
['john', 'jane','sue']
greeting = "Hello"
print(greeting[0]) # Prints H
print(greeting[0::2]) # Prints Hlo
# Converting
print(greeting.lower())
print(greeting.upper())
# print(input("What is your name? ").lower())
# Split and Join
hello = "Hello, my name is Josh".split(" ") # prints ['Hello', 'my', 'name', 'is', 'Josh']
hello.pop() # removes last index Josh
hello.append("Ricky")
hello = " ".join(hello)
print(hello)
| false |
3a7e5870dc242615ee553d0f00295ace995c470a | green-fox-academy/klentix | /Topic 5 Data Structure/List Introduction 1.py | 810 | 4.5625 | 5 | namelist = ['William']
namelist.extend(['Jony', 'Amanda']) # add on multiple items in the list
print("No. of name", len(namelist)) # print total number of items
print("Name list: ", namelist) # print out each element
print("the 3rd name is:", namelist[2])
#iterate through a list and print out individual name
for i in namelist:
print(i)
#iterate through a list and print out individual name with index number
for num,name in enumerate (namelist,start = 1):
print("{}. {}".format(num,name))
#remove 2nd name
namelist.pop(1)
print("after remove 2nd name: ", namelist)
#iterate through a list in reverse order
namelist.reverse()
for k in namelist:
print("name in reversed order: ", k)
#remove all element
namelist.clear()
print ("namelist after remove all: ", namelist)
print("\nend")
| true |
ce86046945bc3f35b226e37d29f8be3d4f36b893 | PramitaPandit/Rock-Paper-Scissor | /main.py | 2,492 | 4.4375 | 4 | #Rock-Paper-Scissor game
#
import random
#step1: Stating game instructions
print('Rules of Rock-Paper-Scissor are as follows:\n Rock v/s Paper -> Paper wins \n Rock v/s Scissor -> Rock wins \n Scissor v/s Paper -> Scissor wins ')
# Step2: Taking user input
user = input('Enter your name: ')
while True:
player_choice = input('Enter a choice: \n a. Rock \n b. Paper \n c. Scissor \n ').lower()
# Step3: Checking for invalid input
if player_choice == 'a' or player_choice == 'b' or player_choice == 'c':
print('Good luck ' + user)
else:
while player_choice != 'a' or player_choice != 'b' or player_choice != 'c':
player_choice = input('Invalid choice. Please enter your choice again: ').lower()
break;
# Step4: Initializing value of choice_name variable corresponding to the choice value
if player_choice == 'a':
player_choice_name = 'Rock'
elif player_choice == 'b':
player_choice_name = 'Paper'
else:
player_choice_name = 'Scissor'
#step5: Creating a list of possible choices for computer
possible_choice = ['Rock', 'Paper', 'Scissor']
#step6: Computer chooses randomly from the available choices
Computer_choice = possible_choice[random.randint(0,2)]
print('Computer chooses ' + Computer_choice)
##step7: Game conditions
if player_choice_name == Computer_choice:
print(f"Both players selected {Computer_choice}. It's a tie!")
elif player_choice_name == 'Rock':
if Computer_choice == 'Scissor':
print('Rock smashes Scissor. You win!')
else:
print('Paper covers Rock. You lose!')
elif player_choice_name == 'Paper':
if Computer_choice == 'Rock':
print('Paper covers Rock. You win!')
else:
print('Scissor cuts Paper. You lose!')
elif player_choice_name == 'Scissor':
if Computer_choice == 'Paper':
print('Scissor cuts Paper. You win!')
else:
print('Rock smashes Scissor. You lose!')
#step8: Asking user wish to continue
Option = input('Do you want to play again? \n 1. Yes \n 2. No \n')
while Option < '1' or Option > '2':
Option = input('Invalid choice. Please enter your choice again: ')
if Option == '1':
print('Get ready for the next round!')
else:
break
#step9: Thanking the player after coming out the while loop
print('Thanks for playing ' + user)
| true |
3dfecdcc2e10e2a8726896802dbed82b8ceef96c | FX-Wood/python-intro | /name_length.py | 291 | 4.375 | 4 | # Exercise 3:
# Write a script that asks for a name and prints out, "Your name is X characters in length."
# Replace X with the length of the name without the spaces!!!
name = input('Please enter your name: \n > ')
print(f"Your name is {len(name.replace(' ', ''))} characters in length") | true |
04a659e77718a85fad089298850585a77cdb9d00 | FX-Wood/python-intro | /collections/print_names.py | 246 | 4.40625 | 4 | # Exercise 1
# Create a list named students containing some student names (strings).
# Print out the second student's name.
# Print out the last student's name.
students = ["Fred", "Alice", "Bob", "Susie"]
print(students[1])
print(students[-1]) | true |
c7dbc874de58b7713d58d422a399f09efebbe726 | deepakkadarivel/python-programming | /7_file_processing/7_2_search_in_file.py | 946 | 4.28125 | 4 | """
“Write a program to prompt for a file name, and then read through the file and look for lines of the form:
X-DSPAM-Confidence:0.8475”
Pseudo code
1. Read file name from user
2. open file
3. Handle No file exception
4. Iterate through files for text and increment count
5. print total count
"""
import sys
file_name = input('Enter file name: ')
try:
file_hand = open(file_name)
except OSError:
print('File cannot be opened:', file_name)
sys.exit(0)
search_value = 'X-DSPAM-Confidence:'
count = 0
line_count = 0
for line in file_hand:
if not line.startswith(search_value): continue
value_pos = line.find(':')
value = line[value_pos + 1:].strip()
count += float(value)
line_count += 1
try:
average = count/line_count
except ZeroDivisionError:
print('Zero lines found with for', search_value)
sys.exit(0)
print('Average spam confidence:', count/line_count)
| true |
f2d750dadce5e8cf3359b18e806ba763842042e9 | deepakkadarivel/python-programming | /6_1_reverse_string.py | 567 | 4.40625 | 4 | """
Write a while loop that starts at the last character in the string
and works it’s way through first character in the string, printing
each letter in a separate line except backwards.
TODO 1: Accept a string from io
TODO 2: Find the length of the string
TODO 3: decrement len and print character in len with new line
TODO 4: stop iteration and once len is less than 0
"""
value_string = input('Enter a string: ')
value_length = len(value_string)
while value_length > 0:
value_length -= 1
print(value_string[value_length])
| true |
8915bb5963f3b0accb33e02d68fba4a8c3bf7628 | deepakkadarivel/python-programming | /6_2_letter_count.py | 757 | 4.375 | 4 | """
Find the count of a letter in a word. Encapsulate the code in a function named count,
and generalize it so that it accepts the string and letter as an argument.
TODO 1: Accept input for a word and letter to search for.
TODO 2: Define a count function that accepts word and letter as parameter to count the number of occurrences in word.
- Define a variable that will increment for each occurrence of letter
- print the total count
"""
def count(word, letter):
letter_count = 0
for character in word:
if character == letter:
letter_count = letter_count + 1
print(letter_count)
word_input = input('Enter Word: ')
letter_input = input('Enter Letter: ')
count(word_input, letter_input)
| true |
f788b258b7e4820673ca63bfb4293d34aef1ad8f | LuisaoStuff/Entrega-1 | /Ejercicio 5.py | 701 | 4.15625 | 4 | # Escriba un programa que pregunte cuántos números se van a introducir, pida esos
# números, y muestre un mensaje cada vez que un número no sea mayor que el primero.
limite=int(input("\n ¿Cuántos números va a introducir? "))
# Validación
while limite<=0:
limite=int(input("\n ¡Eso es imposible!\n ¿Cuántos números va a introducir? "))
numero=int(input(" Introduzca un número: "))
print("\n")
for cont in range(0,limite): # Bucle "for" para introducir números hasta llegar al limite establecido
print(" Escriba un número mayor que ",numero,end=": ")
otro=int(input())
if otro<numero:
print("\n ¡",otro," no es mayor que ",numero,"!\n")
print("\n\n Fin del programa\n") | false |
6a154af4ddbf024665295fdfab72fe4d6f828de8 | Jrbrown09/Brown-Assignment5 | /.vscode/exercise6.py | 2,138 | 4.4375 | 4 | from helpers import *
'''
Exercise 6
Calories from Fat and Carbohydrates
This program calculates the calories from fat and carbohydrates that the user consumed.
The calorie amounts are calculated using the input from the user in carbohydrates and fat.
'''
'''
Define the 'main' function
'''
def main():
fat_grams_entered = get_fat_grams()
carb_grams_entered = get_carb_grams()
fat_calories = calculate_fat_calories(fat_grams_entered)
carb_calories = calculate_carb_calories(carb_grams_entered)
display_calories_output(fat_calories, carb_calories)
'''
Defines the function for the user input of the number of grams of fat entered
return fat_grams, the number of grams of fat entered by the user
'''
def get_fat_grams():
fat_grams = getFloat("Please enter the number of grams of fat you consume: ")
return fat_grams
'''
Defines the function for the user input of the number of grams of carbohydrates entered
return carb_grams, the number of grams of carbohydrates entered by the user
'''
def get_carb_grams():
carb_grams = getFloat("Please enter the number of grams of carbs you consume: ")
return carb_grams
'''
Defines the function for calculating the number of calories of fat that the user has consumed
@param fat_grams
return fat_calories, calories from fat calculated
'''
def calculate_fat_calories(fat_grams):
fat_calories = fat_grams * 9
return format(fat_calories, ",.1f")
'''
Defines the function for calculating the number of calories of carbohydrates that the user has consumed
@param carb_grams
return carb_calories, calories from carbohydrates calculated
'''
def calculate_carb_calories(carb_grams):
carb_calories = carb_grams * 4
return format(carb_calories, ",.1f")
'''
Defines the function for displaying the output of the calories from carbohydrates and fat calculated
from the user
@param fat_calories
@param carb_calories
'''
def display_calories_output(fat_calories, carb_calories):
print("You have consumed ", str(fat_calories), " calories from fat.")
print("You have consumed ", str(carb_calories), " calories from carbohydrates.")
main() | true |
32b144e97cd8f10500b1848ebd8af4599ae66d12 | markvassell/Python | /test/multiplication_table.py | 1,248 | 4.21875 | 4 | import math
print("This is test multiplication table: Still in progress")
file_name = "Multiples.txt"
try:
#opens a file to write to
mult_file = open(file_name, "w")
while (True):
try:
inp_range = int(input("Please enter how many multiplication tables you would like to generate: "))
if(inp_range <= 0):
print("Please only enter numeric values that are greater than zero: ")
continue
break
except ValueError:
print("Plase only enter a numeric value")
continue
for i in range(1,inp_range+1):
for j in range(1,inp_range+1):
mult_file.write(str(i*j) + "\n")
mult_file.write("\n")
mult_file.close()
print("The tables were successfully written to the file!")
except:
print("An error occured while trying to write the random numbers to", file_name)
#used to find the range
#http://pythoncentral.io/pythons-range-function-explained/
#learned about for loops in python
#http://www.tutorialspoint.com/python/python_for_loop.htm
#errors and exceptions
#https://docs.python.org/2/tutorial/errors.html
#how to write to a file in python.
#http://learnpythonthehardway.org/book/ex16.html
| true |
c52dac3f89683c8ade4f3bc4f81b4a9ff350cc1d | surendhar-code/python_practice | /program1.py | 306 | 4.3125 | 4 | #python program to interchange first and last elements in a list.
def firstlast(list1,n):
beg=list1[0]
end=list1[n]
print("The first and last element of the list {0} is {1} and {2}\n".format(list1,beg,end))
list1=list(range(0,5))
print(list1)
n=(len(list1))-1
firstlast(list1,n)
| true |
60b5cb899cef0911bd7d7a775cfbb7ea557aa01f | Robdowski/code-challenges | /running_sum_1d.py | 739 | 4.125 | 4 | """
This problem asks to keep a running total of the sum of a 1 dimensional array, and add that sum to each item in the array as we traverse.
To do this, we can simply declare a variable, running sum, and add it to each item in the array as we traverse. We need to add the sum to the item in the array, while storing the original value of the item in a temporary
variable to add to the running sum.
Example output [1, 2, 3, 4] --> [1, 3, 6, 10]
Runtime Complexity: O(n)
Space Complexity: O(1)
"""
class Solution:
def runningSum(self, nums):
running_sum = 0
for i in range(len(nums)):
temp = nums[i]
nums[i] += running_sum
running_sum += temp
return nums | true |
2d516c584352f0d835fc8f9f7dc076fd032e8af3 | N0l1Na/Algorithms_Python | /PIL006/PIL006.py | 1,306 | 4.25 | 4 | """
PIL - The exercise is taken from the Pilshchikov's Pascal problem book
Task 8.7 page 40
Regular types: vectors
Using the Gender and Height arrays, determine:
a) The name of the tallest man
b) The average height of women
Creator Mikhail Mun
"""
import random
array = []
total_height_women = 0
amount_women = 0
max_height = None
names = ("Valeria", "Gena", "Eugene", "Nikola", "Maria", "Nina", "Sasha", "Tanya", "Fedor", "Shura")
genders = ("woman", "man", "man", "man", "woman", "woman", "woman", "woman", "man", "woman")
for i in range(0, 10):
# gender determination
output_gender = print(names[i] + " " + str(genders[i]))
# height determination
generate_random_height = random.randrange(140, 201)
output_age = print(names[i] + " (" + str(generate_random_height) + "sm)")
# max the height of the man
if genders[i] == "man":
# add element in the list
array.append(str(generate_random_height))
# find max element of the list
max_height = max(array)
# average function
elif genders[i] == "woman":
amount_women = amount_women + 1
total_height_women = total_height_women + generate_random_height
print("Max the height of the man " + str(max_height))
print("Average women= " + str(total_height_women / amount_women)) | true |
3e4ce1aa7ffd6fc8365800767121069c313ff9b7 | SashaJohnson123/introduction_to_python | /loops_exercises.py | 1,566 | 4.25 | 4 | # #Question 1
# add via append
# my_list = [1, 4, 2, 1]
# # while loop +
# while len(my_list) < 5:
# my_var = input("give me a number? ")
# my_list.append(my_var)
# print(my_var)
# print(my_list)
# print(my_list)
#Question 2
#print each item in the list + amount:
# pets = [
# ["Roary", "roary@moth.catchers"],
# ["Remus", "remus@kapers.dog"],
# ["Prince Thomas of Whitepaw", "hrh.thomas@royalty.wp"],
# ["Biscuit", "biscuit@whippes.park"],
# ["Rory", "rory@whippies.park"],
# ]
# print(pets)
# # #display for loop to access each item
# for pet in pets:
# print(f"{pets[0]}:")
# for pet in pets[0:]:
# print(f" {pet}")
#Question 3
#Ask user for three names
# name = input("What are three names?")
# while len(name) > 1:
# if name == "Izzy":
# print("You are awesome!")
# else:
# print(f"Hi {name}")
# name = input("What is your name? ")
# while True:
# name = input("What is your name? ")
# name.append(["Archie", "Boston"])
# print(name_collection)
#Question 4
# groceries = [
# ["Baby Spinach", 2.78],
# ["Hot Chocolate", 3.70],
# ["Crackers", 2.10],
# ["Bacon", 9.00],
# ["Carrots", 0.56],
# ["Oranges", 3.08]
# ]
# print(groceries)
# total = 0
# for item in groceries:
# quantity = input(f"What quantity of {item[0]} would you like? ")
# item[1] = item[1] * int(quantity)
# total += item[1]
# total = f"${total:.2f}"
# print("====Izzy's Food Emporium====")
# for item in groceries:
# print(f"{item[0]:<20} ${item[1]:.2f}")
# print("============================")
# print(f"{total:>27}")
| false |
ec6e1871e6a55516a520a49b11dcd267d7dbb28a | nguyenthanhthao1908/classpython_basic_online | /rewrite_code_resource_w/dictionary/bai9.py | 235 | 4.3125 | 4 | """Write a Python program to iterate over dictionaries using for loops."""
D = {"Name": "Thao", "Age": 20, 19: 8}
# for i in D.items():
# print(i)
# solution 2:
for key, value in D.items():
print(key, "is:", D[key])
| true |
aa2b00e3bcd8cc17d08ef67e68ab65aaa64c0435 | nguyenthanhthao1908/classpython_basic_online | /rewrite_code_resource_w/dictionary/bai15.py | 226 | 4.15625 | 4 | """Write a Python program to get the maximum and minimum value in a dictionary. """
D = {3: 30, 2: 20, 19: 8}
print("Maximum:", max(D.keys(), key=(lambda k: D[k])))
print("Minimum:", min(D.keys(), key=(lambda k: D[k]))) | true |
6c952a8e00c4a823828985e353e4ff04c5c747c8 | Bigg-Iron/152_001 | /C_activities/C10.py | 2,963 | 4.1875 | 4 | """ 10.1.2: Modify a list.
Modify short_names by deleting the first element and changing the last element to Joe.
Sample output with input: 'Gertrude Sam Ann Joseph'
['Sam', 'Ann', 'Joe']
"""
# user_input = input()
# short_names = user_input.split()
# ''' Your solution goes here '''
# del short_names[0]
# del short_names[-1]
# short_names.append('Joe')
# print(short_names)
""" 10.2.1: Reverse sort of list.
Sort short_names in reverse alphabetic order.
Sample output with input: 'Jan Sam Ann Joe Tod'
['Tod', 'Sam', 'Joe', 'Jan', 'Ann'] """
# user_input = input()
# short_names = user_input.split()
# ''' Your solution goes here '''
# short_names.sort()
# short_names.reverse()
# print(short_names)
""" 10.3.1: Get user guesses.
Write a loop to populate the list user_guesses with a number of guesses. The variable num_guesses is the number of guesses the user will have, which is read first as an integer. Read integers one at a time using int(input()).
Sample output with input: '3 9 5 2'
user_guesses: [9, 5, 2] """
# num_guesses = int(input())
# user_guesses = []
# ''' Your solution goes here '''
# for index in range(num_guesses):
# user_guesses.append(int(input()))
# print('user_guesses:', user_guesses)
"""10.3.2: Sum extra credit.
Assign sum_extra with the total extra credit received given list test_grades. Full credit is 100, so anything over 100 is extra credit. For the given program, sum_extra is 8 because 1 + 0 + 7 + 0 is 8.
Sample output for the given program with input: '101 83 107 90'
Sum extra: 8"""
# user_input = input()
# test_grades = list(map(int, user_input.split())) # contains test scores
# sum_extra = -999 # Initialize 0 before your loop
# ''' Your solution goes here '''
# sum_extra = 0
# for grade in test_grades:
# if (grade > 100):
# sum_extra += grade - 100
# print('Sum extra:', sum_extra)
"""10.3.3: Hourly temperature reporting.
Write a loop to print all elements in hourly_temperature. Separate elements with a -> surrounded by spaces.
Sample output for the given program with input: '90 92 94 95'
90 -> 92 -> 94 -> 95
Note: 95 is followed by a space, then a newline. """
# user_input = input()
# hourly_temperature = user_input.split()
# ''' Your solution goes here '''
# for temp in hourly_temperature:
# if temp == hourly_temperature[-1]:
# print(temp, '')
# else:
# print(temp, end=' -> ')
"""10.5.1: Print multiplication table.
Print the two-dimensional list mult_table by row and column. Hint: Use nested loops.
Sample output with input: '1 2 3,2 4 6,3 6 9':
1 | 2 | 3
2 | 4 | 6
3 | 6 | 9 """
user_input= input()
lines = user_input.split(',')
# This line uses a construct called a list comprehension, introduced elsewhere,
# to convert the input string into a two-dimensional list.
# Ex: 1 2, 2 4 is converted to [ [1, 2], [2, 4] ]
mult_table = [[int(num) for num in line.split()] for line in lines]
''' Your solution goes here '''
print(mult_table)
| true |
f683cbbba69ce43dbcf7aa072a7b5890b123aadb | kennylugo/Tweet_Generator_Data_Structures_-_Probability | /1.3_anagram_generator.py | 1,343 | 4.15625 | 4 | import sys, random
# THIS ANAGRAM GENERATOR IS NOT WORKING YET
# method signature
def generate_anagram():
# the list method will break a word apart and add each letter to a list data structure
list_of_letters_from_word_input = list(sys.argv[1])
# we store the count of the elements in the list above
length_of_word_list = len(list_of_letters_from_word_input)
possible_indexes = length_of_word_list - 1
new_anagram = []
for letter in range(-1, length_of_word_list):
random_integer = random.randint(0, possible_indexes)
list_of_letters_from_word_input[letter], list_of_letters_from_word_input[random_integer] = list_of_letters_from_word_input[random_integer],list_of_letters_from_word_input[letter]
new_anagram.append(list_of_letters_from_word_input[random_integer])
# new_anagram.append(list_of_letters_from_word_input[random_integer])
concatenate_indexes = "".join(list_of_letters_from_word_input)
newer_anagram = "".join(new_anagram)
print concatenate_indexes, newer_anagram
# create method
# convert the letters in the input variable into a list
# loop over the list
# create a random integer from 0 to #oflettersInword
# assign that randomInt to an index in the list holding the letters for the word_file
# return the new word
generate_anagram()
| true |
0af53ed79a3d2df089f628732cd0f0989ef4e26c | abdullahclarusway/Python_Assignments | /Assignment_9.py | 214 | 4.28125 | 4 | name = input("Please enter your name:").title()
my_name = "Abdullah"
if name == my_name:
print("Hello, {}! The password is: W@12".format(my_name))
else:
print("Hello, {}! See you later.".format(name)) | true |
146c15c96e35d304f7b67806a38f51f629dbee01 | firchatn/python-101-introduction | /week1/for-demos.py | 251 | 4.25 | 4 | """
For use cases
"""
print("For 1:")
for i in range(2, 5, 2):
print(i)
print("For 2:")
for i in range(5, 2, -1):
print(i)
print("For 3:")
l = [1, 5, 9]
for i in l:
print(i)
print("For 4:")
s = "hello"
for i in s:
print(i, end='')
| false |
5474cc84193f02c47d2a4c23e53ebe6f412e303d | lareniar/Curso2018-2019DAW | /2do Trimestre/Diciembre/factorialFunciones.py | 679 | 4.34375 | 4 | # En esta funcion generamos un calculo factorial de un número
def factorial(n1):
fact = 1
i = 1
while(i <= n1):
fact = fact * i
i = i + 1
return fact
# En esta funcion calculamos la multiplicación del resultado de diferentes factoriales
def triple_factorial(n1,n2,n3):
resultado = factorial(n1) * factorial(n2) * factorial(n3)
return resultado
# fact1 la peticion de la funcion en triple_factorial,donde su resultado es el que se calcula mediante factorial
fact1 = (int(input("Inserta un numero")))
fact2 = (int(input("Inserta un numero")))
fact3 = (int(input("Inserta un numero")))
print(triple_factorial(fact1, fact2, fact3))
| false |
5f1df607c99984af8b32cabeb6d38bb9b85d91e3 | srinisha2628/new_practice | /cuberoot.py | 358 | 4.125 | 4 | x= int(input("enter a number\n"))
ans=0
while ans**3 < abs(x):
ans+=1
if(ans**3!= abs(x)):
print("it is not a perfect cube")
else:
if(x<0):
ans = -ans
print("cube root of "+ str(x)+" is "+ str(ans))
cube=int(input("enter a number"))
for guess in range(cube+1):
if(guess**2==cube):
print("cube root of",cube ,"is",guess)
| true |
076f59fedeb631a4284093eab8358526ea1390a5 | mewilczynski/python-classwork | /program41.py | 865 | 4.375 | 4 | #Marta Wilczynski
#February 2nd, 2016 ©
#Chapter 4 assignment program41.py
#Start program
#Import math since we will be using PI
#Set up a range of numbers, using the for loop.
#Calculate area of a circle with "radius", where the equation
# will be area = (PI * (radius ** 2))
#Calculate circumfrence with "radius",
# where the equation will be circumfrence = (2 * PI * radius)
#Format and display the radii, areas, and circumfrences.
#End program
#import math
import math
#Start the loop,
for radius in range(10, 51, 10):
area = (math.pi * (radius ** 2)) #Calculate the area
circumfrence = (2 * math.pi * radius) #calculate the circumfrence
print(format(radius, '5,.3f'), '\t', format(area, '9,.3f'), '\t', format(circumfrence, '7,.3f')) #Format the numbers into a column, aligning the decimal points and going to 3 decimal points
| true |
b496deacdbb5b1098a24631825f11221a2cbfcb6 | mewilczynski/python-classwork | /order32.py | 1,681 | 4.21875 | 4 | #Marta Wilczynski
#February 2nd, 2016 ©
#order32.py
#Start program.
#Get the number of t-shirts being purchased from the user,
#assign to variable "amountOfShirts".
#Calculate amountOfShirts * 12.99, assign to variable "priceOfShirts".
#Assign number 8.99 to variable "shipping".
#Determine discounts by looking at amount of shirts being bought.
#If amountOfShirts >= 12, calculate (priceOfShirts) - (priceOfShirts * 0.3)
#If amountOfShirts >= 6 and <=11,
#calculate (priceOfShirts) - (priceOfShirts * 0.2) + shipping
#If amountOfShirts >= 3 and <=5,
#calculate (priceOfShirts) - (priceOfShirts * 0.1) + shipping
#If amountOfShirts == 1 or == 2, calculate (priceOfShirts) + shipping
#Assign calculated price of shirts to variable "finalPrice".
#Display the amount needed to pay.
#Ask user for amount of t-shirts
amountOfShirts = int(input("How many shirts are you buying? "))
#Assign base price of shirts to variable "priceOfShirts"
priceOfShirts = float(amountOfShirts * 12.99)
#Assign shipping price to variable "shipping"
shipping = float(8.99)
#Determine whether or not the user qualifies for discounts
if amountOfShirts >= 12:
finalPrice = ((priceOfShirts) - (priceOfShirts * 0.3))
else:
if amountOfShirts >= 6 and amountOfShirts <= 11:
finalPrice = ((priceOfShirts) - (priceOfShirts * 0.2) + shipping)
else:
if amountOfShirts >= 3 and amountOfShirts <= 5:
finalPrice = ((priceOfShirts) - (priceOfShirts * 0.1) + shipping)
else:
finalPrice = ((priceOfShirts) + shipping)
#Display the final price of the shirts.
print ("Your total comes to $", format(finalPrice, ',.2f'), sep='')
| true |
61a787ee69c3e67a8fbaab6c6d057aeab66245e6 | Manish-bitpirate/Hacktoberfest | /python files/story_maker_by_cyoa.py | 2,019 | 4.125 | 4 | name=input("What's your name?")
print("Treasure Hunter, a custom story by " + name )
print("You are a brave explorer that was recognized by the world and found an ancient Mayan temple!")
opt1=input("Do you walk in? y/n?")
opt2=""
opt3=""
opt4=""
if opt1=="y":
print("You walk in, your footsteps echoing in the dark. You turn on a flashlight and came across two paths.")
opt2=input("You look down the first path and see jewels glinting in the darkness. You look down the left and hear a low hissing sound like snakes. Which path did you take? r/l? ")
if opt2=="r":
print("You walk down the path and found a treasure box stuffed with gems! You stuff a few handfuls of diamond, ruby, and sapphire into your backpack, and come across another crossroad.")
opt3=input("At the second intersection, you peer into the darkness and don't see anything. The choice is your's to make. r/l? ")
if opt3=="l":
print("You found the treasure room! You walked in and found ancient treasures!")
opt4=input("The door closes on you! You're trapped! Do you give up hope or keep looking? give up/ keep looking? ")
if opt4=="keep looking":
print("You kept looking, and found a piston mechanism that led you up to a stairway out. You escaped with a ton of jewels, and a story to be told for generations to come!")
if opt1=="n":
print("You return and report your findings. You are stripped of your rights as an adventurer and are looked down upon as a coward.")
if opt2=="l":
print("You walk down the descending staircase and look up. A venomous spider thought to be long extinct bit you and as your vision faded, you were alone.")
if opt3=="r":
print("You find the Emperor's tomb. You decided to take the coffin up for the museums. But as you did, the lid was pushed off, and the ankhet the emperor was wearing cursed you to be forever stuffed into a bottle.")
if opt4=="give up":
print("The world forgot you and your name fades, as your bones turn to dust...")
| true |
6786774819903db96e9008597ea4d8060fc6f217 | sunnysong1204/61a-sp14-website | /slides/lect21.py | 2,276 | 4.125 | 4 | class Tree:
"""A Tree consists of a label and a sequence of 0 or more
Trees, called its children."""
def __init__(self, label, *children):
"""A Tree with given label and children. For convenience,
if children[k] is not a Tree, it is converted into a leaf
whose operator is children[k]."""
self.__label = label;
self.__children = \
[ c if type(c) is Tree else Tree(c) for c in children]
@property
def is_leaf(self):
return self.arity == 0
@property
def label(self):
return self.__label
@property
def arity(self):
return len(self.__children)
def __getitem__(self, k):
return self.__children[k]
def __iter__(self):
return iter(self.__children)
def __repr__(self):
if self.is_leaf:
return "Tree({0})".format(self.label)
else:
return "Tree({0}, {1})" \
.format(self.label, str(self.__children)[1:-1])
from functools import reduce
from operator import add
def leaf_count(T):
"""Number of leaf nodes in the Tree T."""
if T.is_leaf:
return 1
else:
# s = 0
# for child in T:
# s += leaf_count(child)
# return s
return reduce(add, map(leaf_count, T))
def tree_contains(T, x):
"""True iff x is a label in T."""
if T.label == x:
return True
for c in T:
if tree_contains(c, x):
return True
return False
def tree_contains2(T, x):
"""True iff x is a label in T."""
return T.label == x or any(map(lambda tree: tree_contains(tree, x), T))
def tree_to_list_preorder(T):
return [T.label] + reduce(add, map(tree_to_list_preorder, T), [])
def tree_find(T, x):
"""True iff x is a label in set T, represented as a search tree.
That is, T
(a) Represents an empty tree if its label is None, or
(b) has two children, both search trees, and all labels in
T[0] are less than T.label, and all labels in T[1] are
greater than T.label."""
if T.label is None:
return False
else:
return x == T.label \
or (x < T.label and tree_find(T[0], x)) \
or (x > T.label and tree_find(T[1], x))
| false |
bf74914843bb8ad4e81ba45d203d4f45aeaf80da | kate711/day1 | /code/元组.py | 555 | 4.25 | 4 | # 创建元组
my_tuple = ('x', 'y', 'z')
print('{}'.format(my_tuple))
print('{}'.format(len(my_tuple)))
print('{}'.format(my_tuple[1]))
longer_tuple = my_tuple + my_tuple
print('{}'.format(longer_tuple))
# 元组解包
one, two, three = my_tuple
print('{0} {1} {2}'.format(one, two, three))
var1 = 'red'
var2 = 'robin'
print('{} {}'.format(var1, var2))
var1, var2 = var2, var1
print('{} {}'.format(var1, var2))
# 元组转成列表
my_list = [1, 2, 3, 4]
my_tuple = ('x', 'y', 'z')
print('{}'.format(tuple(my_list)))
print('{}'.format(list(my_tuple)))
| false |
111b3cb6d2a16e162794847257edd366dbb1afa3 | ProfessorJas/Python_100_days | /day_031/class_attributes_ex.py | 1,269 | 4.4375 | 4 | class Person(object):
# Define class attribute and assign the value
nation = 'China'
city = 'Shanghai'
def __init__(self, name, age):
# define object attribute
self.name = name
self.age = age
p1 = Person('Joe Wang', 34)
p2 = Person('Javier Amgio', 25)
print('Visit the class attribute nation: %s, city: %s' % (Person.nation, Person.city))
print('Visit the class attribute through p1 object nation: %s, city: %s' % (p1.nation, p1.city))
print('Visit the class attribute through p2 object nation: %s, city: %s' % (p2.nation, p2.city))
print('Visit the object attribute through p1 object name: %s, age: %s' % (p1.name, p1.age))
print('Visit the object attribute thorugh p2 object name: %s, age: %s' % (p2.name, p2.age))
print('-' * 34)
# Add city attribute for class object p1 and p2
print('After add city attribute for p1 and p2')
p1.city = 'Blacksburg'
p2.city = 'Peru'
print('Visit the class attribute through class, nation: %s, city: %s' % (Person.nation, Person.city))
print('Visit the class attribute through p1 object, nation: %s, city: %s' % (p1.nation, p1.city))
print('Visit the class attribute through p2 object, nation: %s, city: %s' % (p2.nation, p2.city))
print('You cannot visit the object attribute through class') | false |
2027aa5e1dc4f9de83c2d23b0a4a47eb44783f96 | ProfessorJas/Python_100_days | /day_027/str_method.py | 2,311 | 4.34375 | 4 | str = 'abcabcabc'
print(str.count('ab')) # count 'ab' in the str
print(str.count('ab', 2)) # count 'ab' in the str from index 2
print(str.endswith('bc')) # endwith check with the string end with some string
# true
print(str.endswith('b')) # false
print(str.startswith('ab')) # check whether string starts with some string
# True
print(str.startswith('b')) # False
print(str.find('ab')) # 0
print(str.find('ab', 2)) # find start from the second character, 3
print(str.find('ba')) # -1
str = 'My name is {0}, and I am {1} years old.'.format('Amigo', 12)
print(str)
# My name is Amigo, and I am 12 years old.
str = 'My name is {1}, and I am {0} years old.'.format('Amigo', 12)
print(str)
# My name is 12, and I am Amigo years old.
str = "The %s's price id is %4.2f" % ('Amigio', 2.5)
print(str)
str = '%s %s %s' % (123, 1.23, 'jaja amigo')
print(str)
# 123 1.23 jaja amigo
str = '%r %r %r' % (123, 1.23, 'jaja amigo')
print(str)
# 123 1.23 'jaja amigo'
str = '123 %c %c' % ('a', 65)
print(str)
# 123 a A
str = '123 {0} {1}'.format('a', '65')
print(str)
# 123 a 65
str = '%d%d' % (123, 1.56)
print(str)
# 1231
str= '%d %d' % (123, 1.56)
print(str)
# 123 1
str = '%6d' % 123 # specify the width, filling in space by default
print(str)
# 123
str = '%6d' % 123456789
print(str)
# 123456789
str = '%-6d' % 123
print(str)
# '123 '
str = '%06d' % 123
print(str)
# 000123
x = 12.3456789
print('%e %f %g' % (x, x, x))
# 1.234568e+01 12.345679 12.3457
x = 1.234e10
print('%E %F %G' % (x, x, x))
# 1.234000E+10 12340000000.000000 1.234E+10
str = '\n\r abc \n\r'.strip() # strip method would remove all the space, tab, and new line character
print(str)
# abc
str = 'www.xhu.edu.cn'.strip('wcn') # delete the specified characters
print(str)
# .xhu.edu.
str = 'ab12' * 4
print(str)
print(str.replace('ab', 'amigo')) # replace the specific characters with other characters
print(str.replace('ab', 'amigo', 2))
str = "this is string example....wow!!!"
print (str.replace("is", "was", 3))
str = 'ab cd ef'
print(str.split())
# ['ab', 'cd', 'ef']
str = 'ab,cd,ef'
print(str.split(','))
# ['ab', 'cd', 'ef']
str = 'ab,cd,ed'
print(str.split(',', 1))
# ['ab', 'cd,ed']
| false |
9e7c846198b684c569f43e0305bedee64c624eff | ProfessorJas/Python_100_days | /day_027/list_meethod.py | 2,661 | 4.21875 | 4 | print([]) # create an empty list object
# []
print(list()) # create an empty list object
# []
print([1, 2, 4]) # list with the same type
print([1, 2, 3, ('a', 'bc', 'defg'), [12, 34, 'amigo']]) # list with different type
print(list('abcd')) # listify an iterative object # ['a', 'b', 'c', 'd']
print(list((1, 22, 333))) # [1, 22, 333] listify a tuple
# get the length
print(len([])) # 0
print(len([1, 2, ('a', 'abc'), [12, 34]])) # 4
# merge a list
print([1, 2] + ['abc', 20]) # [1, 2, 'abc', 20]
# repetition
print([1, 2] * 3)
# [1, 2, 1, 2, 1, 2]
print('----------\n')
# iteration
x = [1, 2, ('a', 'b'), ['ab', 'cd', 'efg']]
for amigo in x:
print(amigo)
print(2 in [1, 2, 3]) # True
print('a' in [1, 2, 3]) # False
x = [1, 2, ['a', 'b']]
print(x[0]) # 1
print(x[2]) # ['a', 'b']
print(x[-1]) # ['a', 'b']
x[2] = 200 # modify the second list object
print(x)
print(x + list(range(10))) # [1, 2, 200, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(x[2: 5]) # [200]
x = x + list(range(10))
print(x[2:5]) # [200, 0, 1]
print(x[2:]) # [200, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(x[:5]) # [1, 2, 200, 0, 1]
print(x[2:7:2]) # [200, 1, 3]
print(x[7:2:-2]) # [4, 2, 0]
x[2: 5] = 'abc'
print(x) # [1, 2, 'a', 'b', 'c', 2, 3, 4, 5, 6, 7, 8, 9]
# Matrix
x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(x)
print(x[0])
print(x[0][0])
# visit, sort, and reverse the list
# append adds an element at the end of the list
x = [1, 2]
x.append('amigo')
print(x) # [1, 2, 'amigo']
# extend adds several object at the end of the list
x = [1, 2]
x.extend(['a', 'b'])
print(x) # [1, 2, 'a', 'b']
x.append('ab')
print(x) # [1, 2, 'a', 'b', 'ab']
x = [1, 2, 3]
x.insert(1, 'abc') # insert the element at the specific position
print(x) # [1, 'abc', 2, 3]
x = [9, 8, 7, 7]
x.remove(7) # remove will delete the specific object, if it has duplicate, remove the first
print(x)
x = [1, 2, 3, 4]
print(x.pop()) # 4
print(x) # [1, 2, 3]
print(x.pop(1)) # 2 # pop delete the item at index 1
print(x) # [1, 3]
x = [10, 2, 30, 5]
x.sort()
print(x) # [2, 5, 10, 30]
x = ['bbc', 'abc', 'abc', 'BBC', 'Abc']
x.sort()
print(x) # ['Abc', 'BBC', 'abc', 'abc', 'bbc']
x = [1, 2, 3]
x.reverse()
print(x) # [3, 2, 1]
| false |
8fde712d6f525b47c1989497f3dbd086c61c7041 | SAMLEVENSON/ACET | /Factorialwi.py | 233 | 4.125 | 4 | def main():
print("To find the Factorial of a Number")
a= int(input("Enter the Number:"))
if(a>=20)
fact =1
for i in range(1,a + 1):
fact = fact*i
print(fac)
if __name__ == '__main__':
main()
| true |
63c49cd9cc64bfbaa471cfe06e10071ca8f82ca0 | adelyalbuquerque/projetos_adely | /numeros.py | 337 | 4.125 | 4 | def maior_numero():
primeiro_numero = float(raw_input("Digite o primeiro numero: "))
segundo_numero = float(raw_input("Digite o segundo numero: "))
if primeiro_numero > segundo_numero:
print "Maior numero: {}".format(primeiro_numero)
else:
print "Maior numero: {}".format(segundo_numero)
maior_numero() | false |
9eb5f962bc60fa4c74d117fab1c7234562f1266d | anantkaushik/Data-Structures-and-Algorithms | /Data-Structures/Graphs/bfs.py | 1,458 | 4.125 | 4 | """
Graph traversal means visiting every vertex and edge exactly once in a well-defined order.
While using certain graph algorithms, you must ensure that each vertex of the graph is visited exactly once.
The order in which the vertices are visited are important and may depend upon the algorithm or question that
you are solving.
During a traversal, it is important that you track which vertices have been visited.
The most common way of tracking vertices is to mark them.
Breadth First Search (BFS)
There are many ways to traverse graphs. BFS is the most commonly used approach.
BFS is a traversing algorithm where you should start traversing from a selected node (source or starting node)
and traverse the graph layerwise thus exploring the neighbour nodes (nodes which are directly connected to source node).
You must then move towards the next-level neighbour nodes.
As the name BFS suggests, you are required to traverse the graph breadthwise as follows:
- First move horizontally and visit all the nodes of the current layer
- Move to the next layer
"""
def bfs(graph, root):
visited, queue = set(), [root]
visited.add(root)
while queue:
vertex = queue.pop(0)
print(vertex)
for neighbour in graph[vertex]:
if neighbour not in visited:
visited.add(neighbour)
queue.append(neighbour)
graph = {0: [2], 1: [0,2], 2: [3], 3: [1,2]}
bfs(graph, 2) # return 2 3 1 0 | true |
2964932bc4395158beb2ee0eba705ee180eaac84 | dbzahariev/Python-and-Django | /Python-Basic/exam_preparation_1/part_1/task_4.py | 539 | 4.1875 | 4 | best_player_name = ''
best_player_goal = -1
while True:
text = input()
if text == 'END':
break
player_name = text
player_goals = int(input())
if player_goals > best_player_goal:
best_player_name = player_name
best_player_goal = player_goals
if player_goals >= 10:
break
print(f"{best_player_name} is the best player!")
if best_player_goal >= 3:
print(f'He has scored {best_player_goal} goals and made a hat-trick !!!')
else:
print(f'He has scored {best_player_goal} goals.')
| true |
6eadedf8522df051f41b244895ef32a747c2a06e | Vinicius-Moraes20/personal-projects | /programming/python/aula12/ex01.py | 323 | 4.21875 | 4 | nome = str(input("Digite seu nome: ")).strip().capitalize()
if (nome == 'Vinicius'):
print("Que nome bonito!")
elif (nome == 'Pedro' or nome == 'Maria' or nome == 'Paulo'):
print("Seu nome é bem popular no Brasil!")
elif (nome in 'Ana Claudia Jessica Juliana'):
print("Belo nome feminino!")
print("Tenha um bom dia {}".format(nome)) | false |
be68e36dca52277ac44319e15da56c61f319f267 | Vinicius-Moraes20/personal-projects | /programming/python/ex044.py | 740 | 4.125 | 4 | valCompras = float(input("Digite o valor total das compras: R$"))
print ("""---- Formas de pagamento ----
[1] à vista dinheiro/cheque
[2] à vista cartão
[3] 2x no cartão
[4] 3x ou mais no cartão""")
op = int(input("> "))
if op == 1:
valPagar = valCompras - (valCompras * 0.10)
elif op == 2:
valPagar = valCompras - (valCompras * 0.05)
elif op == 3:
valPagar = valCompras
print("Você pagara 2 parcelas de R${:.2f}".format(valCompras / 2))
elif op == 4:
valPagar = valCompras + (valCompras * 0.20)
parcelas = int(input("Quantidade de parcelas: "))
print("Você pagara {} parcelas de R${}".format(parcelas, valPagar / parcelas))
print("Sua compra de R${:.2f}, custará R${:.2f}".format(valCompras, valPagar)) | false |
7260c5bc6c62ec8395e56dc66f10c3858e1ae155 | cocodrips/python2-collection | /snakeCamel.py | 776 | 4.15625 | 4 | """
snake_case => camelCase
camelCase => snake_case
"""
def is_snake_case(word):
if "_" in word :
return True
return False
def translate(word):
new_word = ""
if is_snake_case(word):
is_next_upper = False
for c in word:
if c == "_":
is_next_upper = True
else:
if is_next_upper:
is_next_upper = False
new_word += c.upper()
else:
new_word += c
else:
for c in word:
if c.upper() == c:
new_word += "_"
new_word += c.lower()
return new_word
if __name__ == '__main__':
while True:
word = raw_input().strip()
print translate(word)
| false |
0adc5800f99519b907a6939fee2c38ebc950da38 | chaosWsF/Python-Practice | /leetcode/0326_power_of_three.py | 710 | 4.34375 | 4 | """
Given an integer, write a function to determine if it is a power of three.
Example 1:
Input: 27
Output: true
Example 2:
Input: 0
Output: false
Example 3:
Input: 9
Output: true
Example 4:
Input: 45
Output: false
Follow up:
Could you do it without using any loop / recursion?
"""
from math import log10
class Solution:
def isPowerOfThree1(self, n):
"""The solution cannot pass if we use log or log2 due to precision errors."""
return (n > 0) and ((log10(n) / log10(3)) % 1 == 0)
def isPowerOfThree2(self, n):
"""The integer has the limit 32bits, 3**19 < 2**31 - 1 < 3**20"""
return (n > 0) and (1162261467 % n == 0)
| true |
ba66e9707f75734abd0a2bfb61c9c74655f4ed62 | chaosWsF/Python-Practice | /leetcode/0035_search_insert_position.py | 1,291 | 4.15625 | 4 | """
Given a sorted array and a target value, return the index if
the target is found. If not, return the index where it would
be if it were inserted in order.
You may assume no duplicates in the array.
Example 1:
Input: [1,3,5,6], 5
Output: 2
Example 2:
Input: [1,3,5,6], 2
Output: 1
Example 3:
Input: [1,3,5,6], 7
Output: 4
Example 4:
Input: [1,3,5,6], 0
Output: 0
"""
class Solution:
def searchInsert(self, nums, target):
"""binary search"""
a = 0
b = len(nums) - 1
while a <= b:
c = (a + b) // 2
m = nums[c]
if m < target:
a = c + 1
elif m == target:
return c
else:
b = c - 1
return a
def searchInsert2(self, nums, target):
"""python's sorted()/list.sort()"""
return sorted(nums + [target]).index(target)
def searchInsert3(self, nums, target):
"""linear search"""
if nums[0] >= target:
return 0
for i in range(len(nums) - 1):
if nums[i] < target <= nums[i + 1]:
return i + 1
if nums[-1] == target:
return len(nums) - 1
else:
return len(nums)
| true |
6c9a0b00945ee3ea85cc7430ec2b40e660d05d4e | chaosWsF/Python-Practice | /leetcode/0532_k-diff_pairs_in_an_array.py | 1,281 | 4.1875 | 4 | """
Given an array of integers and an integer k, you need to find the number of unique k-diff
pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j
are both numbers in the array and their absolute difference is k.
Example 1:
Input: [3, 1, 4, 1, 5], k = 2
Output: 2
Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5). Although we have
two 1s in the input, we should only return the number of unique pairs.
Example 2:
Input:[1, 2, 3, 4, 5], k = 1
Output: 4
Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).
Example 3:
Input: [1, 3, 1, 5, 4], k = 0
Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).
Note:
The pairs (i, j) and (j, i) count as the same pair.
The length of the array won't exceed 10,000.
All the integers in the given input belong to the range: [-1e7, 1e7].
"""
from collections import Counter
class Solution:
def findPairs(self, nums, k):
if k < 0:
return 0
elif k == 0:
return len([x for x in Counter(nums).values() if x > 1])
else:
nums = set(nums)
return len([i for i in nums if i + k in nums])
| true |
99b3a845267202d53a1f0e9e346b8bcb0a21a577 | chaosWsF/Python-Practice | /leetcode/0020_valid_parentheses.py | 1,707 | 4.1875 | 4 | """
Given a string containing just the characters
'(', ')', '{', '}', '[' and ']', determine if the input
string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true
"""
class Solution:
def isValid(self, s):
"""use stack"""
if not s:
return True
if len(s) % 2 == 1:
return False
pars = {')': '(', ']': '[', '}': '{'}
stack = []
for ss in s:
if ss in pars:
if len(stack) == 0:
return False
if pars[ss] == stack[-1]:
stack.pop()
else:
return False
else:
stack.append(ss)
return len(stack) == 0
def isValid2(self, s):
"""use replace"""
if not s:
return True
if len(s) % 2 == 1:
return False
pars = {'(': ')', '[': ']', '{': '}'}
while s:
flag = 0
for par in pars.items():
par = ''.join(par)
if par in s:
s = s.replace(par, '')
else:
flag += 1
if flag == 3:
return False
else:
return True
| true |
ee5da787fc7206823a2f764e883ca3d3ecbf5caf | chaosWsF/Python-Practice | /leetcode/0344_reverse_string.py | 1,092 | 4.25 | 4 | """
Write a function that reverses a string. The input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii characters.
Example 1:
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
"""
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
for i in range(len(s) // 2):
s[i], s[len(s)-1-i] = s[len(s)-1-i], s[i]
def reverseString1(self, s): # 204ms
s[:] = s[::-1]
def reverseString2(self, s): # 196ms
s.reverse()
def reverseString3(self, s): # 196ms
head = 0
tail = len(s) - 1
while head < tail:
tmp = s[head]
s[head] = s[tail]
s[tail] = tmp
head += 1
tail -= 1
| true |
c70a497fa0a9db39e3f4546fd96775912458e71d | chaosWsF/Python-Practice | /leetcode/0027_remove_element.py | 1,988 | 4.25 | 4 | """
Given an array nums and a value val, remove all instances of
that value in-place and return the new length.
Do not allocate extra space for another array, you must do this
by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn't matter what
you leave beyond the new length.
Example 1:
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two
elements of nums being 2.
It doesn't matter what you leave beyond the returned length.
Example 2:
Given nums = [0,1,2,2,3,0,4,2], val = 2,
Your function should return length = 5, with the first five
elements of nums containing 0, 1, 3, 0, and 4.
Note that the order of those five elements can be arbitrary.
It doesn't matter what values are set beyond the returned
length.
Clarification:
Confused why the returned value is an integer but your answer
is an array?
Note that the input array is passed in by reference, which means
modification to the input array will be known to the caller
as well.
Internally you can think of this:
// nums is passed in by reference.
(i.e., without making a copy)
int len = removeElement(nums, val);
// any modification to nums in your function would be known
by the caller.
// using the length returned by your function, it prints
the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}
"""
class Solution:
def removeElement(self, nums, val):
"""direct solution"""
i = 0
while i < len(nums):
if nums[i] == val:
del nums[i]
else:
i += 1
return len(nums)
def removeElement2(self, nums, val):
"""use filter"""
tmp = list(filter(lambda x: x != val, nums))
nums[:len(tmp)] = tmp
del nums[len(tmp):]
# nums[len(tmp):] = []
return len(nums)
| true |
bcd5d58a4b1789a205e03f69fe2458b9b4a5b5a2 | chaosWsF/Python-Practice | /leetcode/0088_merge_sorted_array.py | 2,069 | 4.21875 | 4 | """
Given two sorted integer arrays nums1 and nums2, merge nums2 into
nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m
and n respectively.
You may assume that nums1 has enough space (size that is
greater or equal to m + n) to hold additional elements from
nums2.
Example:
Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
"""
class Solution:
"""
Do not return anything, modify nums1 in-place instead.
"""
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
# back assigning
while m > 0 and n > 0:
if nums1[m-1] > nums2[n-1]:
nums1[m+n-1] = nums1[m-1]
m -= 1
else:
nums1[m+n-1] = nums2[n-1]
n -= 1
if m == 0:
nums1[:n] = nums2[:n]
# if n == 0:
# return
# if m == 0:
# nums1[:n] = nums2
# i, j = 0, 0
# while i < m and j < n:
# if nums1[i] > nums2[j]:
# nums1[i+1:] = nums1[i:-1]
# nums1[i] = nums2[j]
# j += 1
# m += 1
# i += 1
# if i == m:
nums1[m:] = nums2[j:]
def merge1(self, nums1, m, nums2, n):
"""Two Pointers"""
i = 0
j = 0
while j < n:
while i < m and nums1[i] <= nums2[j]:
i += 1
if i == m:
nums1[m:] = nums2[j:]
break
nums1[i+1:] = nums1[i:-1]
nums1[i] = nums2[j]
i += 1
m += 1
j += 1
def merge2(self, nums1, m, nums2, n):
"""Builtin Method"""
if not nums2:
return nums1
nums1[m:] = nums2
nums1.sort()
| true |
dd0ca36d22e09a8278608bbd0c02f554bc9cab26 | chaosWsF/Python-Practice | /leetcode/1002_find_common_characters.py | 1,281 | 4.15625 | 4 | """
Given an array A of strings made only from lowercase letters, return a list of all characters that show up
in all strings within the list (including duplicates). For example, if a character occurs 3 times in all
strings but not 4 times, you need to include that character three times in the final answer. You may return
the answer in any order.
Example 1:
Input: ["bella","label","roller"]
Output: ["e","l","l"]
Example 2:
Input: ["cool","lock","cook"]
Output: ["c","o"]
Note:
1. 1 <= A.length <= 100
2. 1 <= A[i].length <= 100
3. A[i][j] is a lowercase letter
"""
from collections import Counter
from functools import reduce
class Solution:
def commonChars1(self, A):
def helper(cnt1, cnt2):
if len(cnt1) > len(cnt2):
cnt1, cnt2 = cnt2, cnt1
res = {}
for key in cnt1:
if key in cnt2:
res[key] = min(cnt1[key], cnt2[key])
return res
return [key for key, val in reduce(helper, map(Counter, A)).items() for _ in range(val)]
def commonChars2(self, A):
res = Counter(A[0])
for i in range(1, len(A)):
res &= Counter(A[i])
return list(res.elements())
| true |
674ef5c016216bb2e64195ccb36ccb056773a720 | chaosWsF/Python-Practice | /leetcode/0434_number_of_segments_in_a_string.py | 546 | 4.15625 | 4 | """
Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.
Please note that the string does not contain any non-printable characters.
Example:
Input: "Hello, my name is John"
Output: 5
"""
class Solution:
def countSegments1(self, s):
return len(s.split())
def countSegments2(self, s):
res = 0
for i in range(len(s)):
if (i == 0 or s[i - 1] == ' ') and s[i] != ' ':
res += 1
return res
| true |
400142c7d92f56ad7af22a82663441976791369d | JQuinSmith/learning-python | /ex15.py | 813 | 4.34375 | 4 | # imports the module
from sys import argv
# the script, and the text file are used as modules
script, filename = argv
# Assuming "open" opens the file being passed into it for use in the rest of the script.
txt = open(filename)
# # Serves up the filename based on what is entered into the terminal.
# print ("Here's your file %r:" % filename)
# # Prints the variable "txt". ".read()", I assume, is a Python native function that reads the content of the file being opened by txt.
# print (txt.read())
# just a string being printed
print ("Type the filename again:")
# input prompt with "> " as the...prompt indicator?
file_again = raw_input("> ")
# variable that holds the basic function "open"
txt_again = open(file_again)
# reads the file being input during the raw_input prompt.
print (txt_again.read()) | true |
71678e32831ef0554e88ee5e916b749ba0a8ced9 | Program-Explorers/Random_Password_Generator | /random_password.py | 1,963 | 4.21875 | 4 | # import statements
#Random Password Generator
import random
import string
def greeting():
print("This programs makes your password more secure based on a word you provide!"
+ "\nIt increases the strenth of your password by adding random letters and digits before or after the word\n")
class password_generator():
def __init__(self, word, length=8):
self.word = word
self.length = length
def random_char(self):
characters = string.ascii_letters + string.digits
pass_list = []
len_to_add = self.length - len(self.word)
while len_to_add != 0:
len_to_add -= 1
random_chars = random.choice(characters)
pass_list.append(random_chars)
return pass_list
def letters_to_add(self, to_add):
list_word = list(self.word)
length_of_to_add = len(to_add)
while length_of_to_add != 0:
popped = to_add.pop()
rand_choice = random.randint(0, 1)
if rand_choice == 0:
list_word.insert(0, popped)
elif rand_choice == 1:
list_word.append(popped)
length_of_to_add -= 1
return list_word
def main():
print('\n' * 10)
greeting()
word = input("Enter in a word for your random password: ")
length_word = int(input("How many random characters do you want in your password: "))
while len(word) > length_word:
print('Sorry your word is longer than the passwords length')
word = input("Enter in a word for your random password: ")
length_word = int(input("How many random characters do you want in your password: "))
users_password = password_generator(word, length_word)
add_to_word = users_password.random_char()
the_password = users_password.letters_to_add(add_to_word)
print(f"\n\nYour new password is \n{''.join(the_password)}")
if __name__ == "__main__":
main()
| true |
1cb20485ce03458d71b766dc450d2b9f624f8e21 | Benjamin-Menashe/Project_Euler | /problem1.py | 470 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 3 10:09:34 2021
@author: Benjamin
"""
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
import numpy as np
fives = np.array(range(0,1000,5))
threes = np.array(range(0,1000,3))
fifteens = np.array(range(0,1000,15))
Answer = sum(fives) + sum(threes) - sum(fifteens)
print(Answer) | true |
8d208cee28c4dc5fa45b42d4a7e57e2508840a3d | Yasaman1997/My_Python_Training | /Test/lists/__init__.py | 1,599 | 4.375 | 4 | zoo_animals = ["pangolin", "cassowary", "sloth", "dog"];
# One animal is missing!
if len(zoo_animals) > 3:
print "The first animal at the zoo is the " + zoo_animals[0]
print "The second animal at the zoo is the " + zoo_animals[1]
print "The third animal at the zoo is the " + zoo_animals[2]
print "The fourth animal at the zoo is the " + zoo_animals[3]
animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]
duck_index = animals.index("duck") # Use index() to find "duck"
# Your code here!
animals.insert(duck_index, "cobra")
print animals # Observe what prints after the insert operation
start_list = [5, 3, 1, 2, 4]
square_list = []
# Your code here!
for x in start_list:
square_list.append(x**2)
square_list.sort()
print square_list
my_list = [1, 9, 3, 8, 5, 7]
for number in my_list:
# Your code here
for number in my_list:
print 2 * number
# Assigning a dictionary with three key-value pairs to residents:
residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}
print residents['Puffin'] # Prints Puffin's room number
print residents['Sloth']
print residents['Puffin'] # Prints Puffin's room number
print residents['Burmese Python']
menu = {} # Empty dictionary
menu['Chicken Alfredo'] = 14.50 # Adding new key-value pair
print menu['Chicken Alfredo']
# Your code here: Add some dish-price pairs to menu!
menu['pizza'] = 2.50
menu['soup'] = 1.50
menu['Salad'] = 5.50
print "There are " + str(len(menu)) + " items on the menu."
print menu | true |
b3b79f7f01bee57c0eca157d2034692141628364 | pedrohenriquebraga/Curso-Python | /Mundo 3/Aulas/Aula_17_Listas_1.py | 645 | 4.34375 | 4 | # PARA ADICIONAR ELEMENTOS A LISTAS USAMOS: lista.append(elemeto ser adicionado)
# PARA ADICIONAR ELEMENTOS EM LUGARES ESPECÍFICOS DA LISTA USAMOS:
# lista.insert(posição a ser adicionada, o que vai ser adicionado)
# PARA EXCLUIR ELEMENTOS: del lista[elemento]
# Também pode - se usar o lista.pop(elemento)
# OUTRA MANEIRA É USAR O lista.remove(valor a ser eliminado)
# PARA ORGANIZAR UMA LISTA USAMOS lista.sort()
# PARA ORGANIZAR EM ORDEM INVERSA USAMOS lista.sort(reverse=True)
num = []
num.append(5)
num.append(9)
num.append(3)
for c, v in enumerate(num):
print(f"Na posição {c} encontrei o valor {v}!")
print("Acabou a lista!") | false |
c57cd7f705639865c0832d6ea4a0017e87e4562f | pedrohenriquebraga/Curso-Python | /Mundo 3/Exercícios/ex_079.py | 639 | 4.125 | 4 | # Verificação de valores em listas
valores = list()
while True:
print("~" * 45)
num = int(input("Digite um valor: "))
if num not in valores:
valores.append(num)
print("VALOR ADICIONADO COM SUCESSO...")
else:
print("VALOR DUPLICADO!! NÃO VOU ADICIONAR...")
continuar = str(input("Quer adicionar outro? [S/N] ")).strip().upper()[0]
if continuar not in "SsNn":
while continuar not in "SsNn":
continuar = str(input("Digite uma opção válida: "))
if continuar == "N":
valores.sort()
break
print("~" * 45)
print(f"Você digitou os valores {valores}") | false |
810e9b7a1d47e4c5e19b452bb3ecda92a5cd79d1 | zerojpyle/learningPy | /ex19_practice.py | 590 | 4.15625 | 4 | # define a function to do some math
# I'm trying to find 10 ways to run a function
def my_calc(number1, number2):
print(f"First, {number1} + {number2} = {number1 + number2}!")
print(f"Second, {number1} x {number2} = {number1 * number2}!")
print(f"And that's it! Come back later and maybe you'll get more.\n")
# 1
my_calc(3,5)
# 2
print('Hit enter to run "my_calc"')
input(">")
my_calc(4,5)
# 3
num1 = input('Pick a number: ')
num2 = input('Pick another number: ')
my_calc(int(num1), int(num2))
# 4
print("Pick two numbers")
my_calc(int(input("1st: ")), int(input("2nd: ")))
| true |
ea825b27fe780710ee9520c77bc7bdd9b69b6515 | zerojpyle/learningPy | /ex6.py | 887 | 4.4375 | 4 | # define variable with a number
types_of_people = 10
# define a variable as a literal string
x = f"There are {types_of_people} types of people."
# define a couple strings as variables
binary = "binary"
do_not = "don't"
# define a variable as a literal string
y = f"Those who know {binary} and those who {do_not}."
# print x & y literal strings
print(x)
print(y)
# print more literal strings directly, with embedded literal strings x & y
print(f"I said: {x}")
print(f"I also said: '{y}'")
# define a variable with a boolean
hilarious = False
# define a variable with a string
joke_evaluation = "Isn't that joke so funny?! {}"
# print the variable, adding the boolean that's formatted to be a string
print(joke_evaluation.format(hilarious))
# define more strings
w = "This is the left side of..."
e = "a string with a right side."
# combine and then print two strings
print(w + e)
| true |
263486d8994eed386e885f539f2d9e6733973b11 | praak/think_python | /chapter6/6_6.py | 884 | 4.15625 | 4 | # Palindrome
def first(word):
return word[0]
def last(word):
return word[-1]
def middle(word):
return word[1:-1]
# Part 1:
# a = 'aaa'
# print a
# print 'first: ' , first(a)
# print 'middle: ' , middle(a)
# print 'last: ' , last(a)
# Part 2:
def is_palindrome(stringArg):
if (first(stringArg) == last(stringArg)):
# tests to check where in the code you are.
# print 'here'
# print middle(stringArg)
if len(middle(stringArg)) > 1:
# print 'inside middle check'
value = is_palindrome(middle(stringArg))
# print 'out of middle check'
return True
else:
return False
# Change string a to anything to check if it is a Palindrome
# Pythons string comparison is ASCII, so it is case sensitive.
a = 'racecar'
isit = is_palindrome(a)
print 'Is',a, 'a Palindrome? [True/False]: ' , isit
| false |
a0f73784a1ad1a2971e71c9844e3d48c9eeed9a1 | cyber-holmes/Centimeter_to_meter-and-inches_python | /height_cm.py | 418 | 4.4375 | 4 | #Goal:Convert given Height from Centimeter to Meter and Inches.
#Step1:Take the input.
height = input("Enter the Height in Centimeter: ")
#Step2:Calculate the value of Meter from Centimeter.
meter = height/100.0
#Step3:Calculate the value of Inch from Centimeter.
inch = height/2.54
#Step4:Print the Height in Meter.
print "Height in Meter: ",meter,"m"
#Step5:Height in Inch.
print "Height in Inch: ",inch,"in"
| true |
3870ff88d2ccf9e93b614019b111298bcf131898 | durstido/Data-Structures-Practice | /mergesort.py | 907 | 4.125 | 4 | def mergesort(arr):
if (len(arr)>1):
mid = len(arr) // 2
left = arr[:mid]
right = arr[mid:]
mergesort(left)
mergesort(right)
#indexes for each array
left_i = 0
right_i = 0
arr_i = 0
while right_i<len(right) and left_i<len(left): #while there is still elements in both lists
if (right[right_i] < left[left_i]): #if curr elem in right < element in left, add right elem
arr[arr_i] = right[right_i]
right_i += 1
arr_i += 1
else: #else, add left elem
arr[arr_i] = left[left_i]
left_i += 1
arr_i += 1
#in case there are leftover elements in right array
while right_i < len(right):
arr[arr_i] = right[right_i]
right_i += 1
arr_i += 1
#in case there are leftover elements in left array
while left_i < len(left):
arr[arr_i] = left[left_i]
left_i += 1
arr_i += 1
return arr
arr = [54,26,93,17,77,31,44,55,20]
print(mergesort(arr))
| false |
a592a2234e5b6947afc1999a5e3b93dc30d13efd | Termich/All | /Ch1/Workshop_1.py | 1,891 | 4.15625 | 4 | #Загадать случайное число
#Ввожу что то, что я изучу через несколько уроков:
import random
start = 1
end = 100
#Указали точку начала и конца откуда можно производить случайный вывод числ. при чем задали их что они переменные.
print('Давайте сыграем в игру: ты загадаешь число, а я попробую его угадать.')
print('Для попощи мне, используй знаки "<" ">" Или "=" если я угадал ')
#Далее формула:
while True:
number = random.randint(start, end) #Где номер это функция Random выполняющия свою функцию от чила откоректированного пользователем в формули ниже.
print(number)
key = input('Введите символ') #Где ключ это символ которым пользователь поиогает компьютеру) или корректирует переменную start или end с помощью формул ниже
if key == '=':
print('Победа, меня не так то просто обхетрить') #Условие победы с последующим выходом из цикла
break
elif key == '<': #Корректируем переменную Start для Random
start = number + 1
print('Неправильно, Маловато')
elif key == '>': #Корректируем переменную end для Random
end = number - 1
print('Многовато, попробую еще')
| false |
7377dab7bacfc1c807b49f473775fea650c305b3 | starmap0312/python | /libraries/enumerate_zip.py | 849 | 4.78125 | 5 | print("1) enumerate():")
# 1) enumerate(iterable):
# return enumerate object that can be used to iterate both the indices and values of passed-in iterable
for index, value in enumerate(["one", "two", "three"]):
print(index, value)
# 2) zip(iterable1, iterable2):
# return an iterator of tuples, where the i-th tuple contains the i-th element from each of the passed-in iterables
# use zip() to iterate multiple lists simultaneously
print("2) zip(), iterating multiple lists simultaneously")
alist = ["a1", "a2", "a3"]
blist = ["b1", "b2", "b3"]
clist = ["c1", "c2", "c3"]
print(zip(alist, blist, clist))
for a, b, c in zip(alist, blist, clist):
print(a, b, c)
print("use zip() with argument unpacking")
multilists = [["a1", "a2", "a3"], ["b1", "b2", "b3"], ["c1", "c2", "c3"]]
for a, b, c in zip(*multilists):
print(a, b, c)
| true |
9dc6900c0eb28775c0e4e8f9fbb353f0a57f6af9 | xploreraj/HelloPython | /algos/programs/ZeckendorfsTheorem.py | 479 | 4.28125 | 4 | '''
Print non-consecutive fibonacci numbers summing up to a given number
'''
# return nearest fibonacci num lesser or equal to argument
def nearest_fibo_num(num):
a, b = 0, 1
while True:
if a + b > num:
break
temp = b
b = a + b
a = temp
return b
if __name__ == '__main__':
num = int(input('Enter number and hit enter: '))
while num>0:
f = nearest_fibo_num(num)
print(f, end=' ')
num -= f
| true |
2dcff43bb6f73d3b5141178c3374911344e3c4aa | ronaldaguerrero/practice | /python2/python/fundamentals/lambdas.py | 1,291 | 4.6875 | 5 | # # Example 1
# # create a new list, with a lambda as an element
# my_list = ['test_string', 99, lambda x : x ** 2]
# # access the value in the list
# # print(my_list[2]) # will print a lambda object stored in memory
# # invoke the lambda function, passing in 5 as the argument
# print(my_list[2](5))
# # Example 2
# # define a function that takes one input that is a function
# def invoker(callback):
# # invoke the input pass the argument 2
# print(callback(2))
# invoker(lambda x: 2 * x)
# invoker(lambda y: 5 + y)
# # Example 3
# add10 = lambda x: x + 10 # store lambda expression in a variable
# print(add10(2)) # returns 12
# print(add10(98)) # returns 108
# # Example 4?
# def incrementor(num):
# start = num
# return lambda x: num + x
# incrementor(5)
# Example 5
# create a list
# my_arr = [1,2,3,4,5]
# define a function that squares values
# def square(num):
# return num ** 2
# # invoke map function
# print(list(map(square, my_arr)))
# Example 6
my_arr = [1,2,3,4,5]
print(list(map(lambda x: x ** 2, my_arr))) # invoke map, pass in a lambda as the first argument
# why are lambdas useful? When we only need a function once, we don't need to define a function and unnecessarily consume memory and complicate our code, just to produce the same result: | true |
d2331f4d0ae550d79cc36677b8d55a4c92153840 | zahraaliaghazadeh/python | /functions_intro/banner.py | 2,242 | 4.15625 | 4 | # def banner_text(text=" ", screen_width=80):
def banner_text(text: str = " ", screen_width: int = 80) -> None:
""" Print a string centred, with ** either side.
:param text: The string to print.
An asterisk (*) will result in a row of asterisks.
The default will print a blank line, with a ** border at
the left and right edges.
:param screen_width: The overall width to print within
(including the 4 spaces for the ** either side).
:raises ValueError: if the supplied string is too long to fit.
"""
# when combining argument annotation and default value use space around =
# either use annotation on all or don't use it at all
# screen_width = 80
# screen_width = 50
if len(text) > screen_width - 4:
# To raise an exception in Python
raise ValueError("String {0} is larger than specified width {1}"
.format(text, screen_width))
# print("EEK!!")
# print("THE TEXT IS TOO LONG TO FIT IN THE SPECIFIED WIDTH")
if text == "*":
print("*" * screen_width)
else:
centered_text = text.center(screen_width -4)
output_string = "**{0}**".format(centered_text)
print(output_string)
# you have to put , 66 after the "" in these if you want to have
# a value for the 2 arguments, but when you put a default value
# inside the function definition, you dont have to pass in that value
# in the execution
banner_text("*")
banner_text("Always look on the bright side of life...")
banner_text("If life seems jolly rotten,")
banner_text("There s something you ve forgotten!")
banner_text("And that s to laugh and smile and dance and sing")
# if nothing is passed here you need to pass a default value for text
banner_text()
banner_text(screen_width=60)
banner_text("When you are feeling in the dumps")
banner_text("Don't be silly chumps,")
banner_text("Just purse your lips and whistle - that s the thing")
banner_text("And...always look on the bright side of life...")
banner_text("*")
# result = banner_text("Nothing is returned")
# print(result)
#
# numbers = [4, 4, 7, 5, 8, 3, 9, 6, 1]
# print(numbers.sort())
# Tele Type
# Punch Card
# ANSI sequence
# ANSI escape code
| true |
5fdfa562e309a1adf91d366bfe03937faa133888 | zahraaliaghazadeh/python | /NU-CS5001/lab02/adder.py | 463 | 4.1875 | 4 | # num1 = float(input("Enter a first value: "))
# num2 = float(input("Enter a second value: "))
# sum = num1 + num2
# print("The sum of {} + {} is {}".format(num1, num2, sum))
# ==================================
# same code with function dedinition
def main():
num1 = float(input("Enter a first value: "))
num2 = float(input("Enter a second value: "))
sum = num1 + num2
print("The sum of {} + {} is {}".format(num1, num2, sum))
main()
| true |
181c9171852431ee36304736b097816f6cf423a3 | jenjnif/cassidoo | /parentheses/parentheses.py | 2,217 | 4.28125 | 4 | '''
13 April 2020
This week’s question:
Given a number n, write a function to generate all combinations
of well-formed parentheses.
Example:
generateParens(3)
[“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
'''
# def generate_parentheses(n):
# parentheses_list = []
# if n == 1:
# parentheses_list.append("()")
# elif n > 1:
# parentheses_list.append(("(" * n + ")" * n))
# recursion_list = generate_parentheses(n-1)
# parentheses_list.append(recursion_list[0] + "()")
# return parentheses_list
def generate_parentheses(n):
parentheses_list = ["()"]
if n == 1:
return parentheses_list
elif n > 1:
parentheses_list[0] = "(" + parentheses_list[0] + ")"
parentheses_list.append("()" * n)
return parentheses_list
def test_type_generate_parentheses():
assert type(generate_parentheses(3)) == list
def test_generate_parentheses():
assert generate_parentheses(1) == ["()",
]
assert generate_parentheses(2) == ["(())",
"()()",
]
assert generate_parentheses(3) == ["((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
assert generate_parentheses(4) == ['(()())()',
'((()))()',
'((())())',
'(())()()',
'()(())()',
'(()(()))',
'(((())))',
'(()()())',
'()((()))',
'()(()())',
'(())(())',
'()()(())',
'()()()()',
'((()()))'
]
| false |
ac9d5c265190401c2e11d2b144cbf16961da09a2 | snalahi/Python-Basics | /week3_assignment.py | 2,114 | 4.4375 | 4 | # rainfall_mi is a string that contains the average number of inches of rainfall in Michigan for every month (in inches)
# with every month separated by a comma. Write code to compute the number of months that have more than 3 inches of
# rainfall. Store the result in the variable num_rainy_months. In other words, count the number of items with values > 3.0.
rainfall_mi = "1.65, 1.46, 2.05, 3.03, 3.35, 3.46, 2.83, 3.23, 3.5, 2.52, 2.8, 1.85"
rain_list = rainfall_mi.split(", ")
num_rainy_months = 0
for i in rain_list:
if float(i) > 3.0:
num_rainy_months += 1
# The variable sentence stores a string. Write code to determine how many words in sentence start and end with the same letter,
# including one-letter words. Store the result in the variable same_letter_count.
sentence = "students flock to the arb for a variety of outdoor activities such as jogging and picnicking"
same_letter_count = 0
sent_list = sentence.split()
for i in sent_list:
if i[0] == i[-1]:
same_letter_count += 1
# Write code to count the number of strings in list items that have the character w in it. Assign that number to the variable
# acc_num.
items = ["whirring", "wow!", "calendar", "wry", "glass", "", "llama","tumultuous","owing"]
acc_num = 0
for i in items:
if "w" in i:
acc_num += 1
# Write code that counts the number of words in sentence that contain either an “a” or an “e”. Store the result in the variable
# num_a_or_e.
sentence = "python is a high level general purpose programming language that can be applied to many different classes of problems."
sent_list = sentence.split()
num_a_or_e = 0
for i in sent_list:
if "a" in i or "e" in i:
num_a_or_e += 1
# Write code that will count the number of vowels in the sentence s and assign the result to the variable num_vowels. For this problem,
# vowels are only a, e, i, o, and u.
s = "singing in the rain and playing in the rain are two entirely different situations but both can be fun"
vowels = ['a','e','i','o','u']
num_vowels = 0
for i in s:
if i in vowels:
num_vowels += 1
| true |
06dbe5531992d6c6df8feb30c6b97b17b113b824 | Daksh-ai/swapcase-of-string | /string swapcase.py | 216 | 4.21875 | 4 | def swapcase(string):
return s.swapcase()
s=input("Enter The String")
sub=swapcase(s)
print(sub)
#example-->input=Daksh output-->dAKSH
#in genrally we say that its used to change the case of string and vice-versa | true |
4a5c254c5d241a0c09862ca7995b1652932cd858 | arvagas/Sorting | /src/recursive_sorting/recursive_sorting.py | 1,557 | 4.125 | 4 | # TO-DO: complete the helpe function below to merge 2 sorted arrays
def merge( arrA, arrB ):
elements = len( arrA ) + len( arrB )
merged_arr = [0] * elements
# TO-DO
count = 0
while count < elements:
if len(arrA) == 0:
merged_arr[count] = arrB[0]
arrB.pop(0)
elif len(arrB) == 0:
merged_arr[count] = arrA[0]
arrA.pop(0)
elif arrA[0] >= arrB[0]:
merged_arr[count] = arrB[0]
arrB.pop(0)
elif arrA[0] <= arrB[0]:
merged_arr[count] = arrA[0]
arrA.pop(0)
count += 1
return merged_arr
# TO-DO: implement the Merge Sort function below USING RECURSION
def merge_sort( arr ):
# TO-DO
# keep on splitting the array until the length is one
if len(arr) < 2:
return arr
else:
# (1) split up the array in half and have it be recursive
# first half of the given array
arr_one = merge_sort(arr[:len(arr)//2])
# second half of the given array
arr_two = merge_sort(arr[len(arr)//2:])
# (2) run the helper function to merge
return merge(arr_one, arr_two)
return arr
# STRETCH: implement an in-place merge sort algorithm
def merge_in_place(arr, start, mid, end):
# TO-DO
return arr
def merge_sort_in_place(arr, l, r):
# TO-DO
return arr
# STRETCH: implement the Timsort function below
# hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt
def timsort( arr ):
return arr
| true |
654e27532d4de8711c90cdb88e30006c8702751a | srimanikantaarjun/Object_Oriented_Programming_Fundamentals | /08 Constructor in Inheritance.py | 868 | 4.34375 | 4 | class A:
def __init__(self):
print("in A init")
def feature1(self):
print("Feature 1 is working")
def feature2(self):
print("Feature 2 is working")
class B:
def __init__(self):
super().__init__()
print("in B init")
def feature3(self):
print("Feature 3 is working")
def feature4(self):
print("Feature 4 is working")
# a1 = A()
# b1 = B()
# If we create object of sub class it will first try to find init of Sub class, if it is not found then it will call
# init of Super class
# If we use super(). then it will call init of Super class then call init of Sub class
class C(A, B):
def __init__(self):
super().__init__()
print("in C init")
c1 = C()
# METHOD RESOLUTION ORDER
# To represent Super class we use super(). method
| true |
2d787005363b28c07c13fe69bc091055ee638769 | draetus/python_10apps_course | /app3/birthday_countdown.py | 1,156 | 4.1875 | 4 | import datetime
def print_header():
print('-------------------------------------')
print(' BIRTHDAY APP')
print('-------------------------------------')
print()
def get_birthday_from_user():
print('Tell us when you were born: ')
year = int(input('Year [YYYY]: '))
month = int(input('Month [MM]: '))
day = int(input('Day [DD]: '))
birthday = datetime.datetime(year,month,day)
return birthday
def compute_days_between_dates(original_date,now):
date1 = now
date2 = datetime.date(now.year,original_date.month,original_date.day)
dt = date1 - date2
days = int(dt.total_seconds() / 60 / 60 / 24)
return days
def print_birthday_information(number_of_days):
if number_of_days < 0:
print('Your birthday is in {} days!'.format(-number_of_days))
elif number_of_days > 0:
print('Your bithday was {} days ago...'.format(number_of_days))
else:
print('YOUR BITHDAY IS TODAY!!!!')
print_header()
bday = get_birthday_from_user()
now = datetime.date.today()
number_of_days = compute_days_between_dates(bday, now)
print_birthday_information(number_of_days)
| false |
6154996b2d90ec547184c54837d887f043baf163 | CodeWithShamim/python-t-code | /Main/Method overriding.py | 886 | 4.15625 | 4 |
#Method not overriding...........
class google:
def __init__(self):
print("Result 1 : Hello, programmer!!.")
class amazon(google):
#add amazon all method..
pass
val = amazon()
#------------------------------------------------------------------
#Method overriding...........
class google:
def __init__(self):
print("Hello, programmer!!.")
class amazon(google):
#add amazon all method..
def __init__(self):
print("Result 2 : Hello, Python programmer!!.")
val = amazon()
#-------------------------------------------------------------------------
class google:
def __init__(self):
print("Result 3 : Hello, programmer!!.")
class amazon(google):
#add amazon all method..
def __init__(self):
super().__init__()
print("Result 3 : Hello, Python programmer!!.")
val = amazon() | false |
bfd3194a3f57b9e1daf459572d0c3a3c9fd0b24c | LarissaMidori/curso_em_video | /exercicio062.py | 594 | 4.15625 | 4 | ''' Melhore o DESAFIO 61, perguntando para o usuário se ele quer mostrar mais alguns termos. O programa encerrará quando ele disser que quer mostrar 0 termos. '''
print(f'==== Super analisador de P.A. ====')
termo = int(input('Primeiro termo: '))
razao = int(input('Razão: '))
mais = 10
total = 0
cont = 1
while mais != 0:
total += mais
while cont <= total:
print(f'{termo} => ', end = '')
termo += razao
cont += 1
print(f'Pausa')
mais = int(input(f'Quantos termos você quer mostrar a mais? '))
print(f'Progressão finalizada com {total} termos.')
| false |
e18f604f43805660026cff8a0ce10d14b0b99ea4 | LarissaMidori/curso_em_video | /exercicio036.py | 703 | 4.1875 | 4 | ''' 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('Valor da casa: R$ '))
salario = float(input('Salário do comprador: R$ '))
anos = int(input('Quantos anos de financiamento? '))
prestacao = casa / (anos * 12)
minimo = salario - (salario * 30 / 100)
print(f'Para pagar uma casa de {casa:.2f} em {anos} anos, a prestação será de R$ {prestacao:.2f} por mês.')
if prestacao <= minimo:
print(f'EMPRÉSTIMO CONCEDIDO!!')
else:
print(f'EMPRÉSTIMO NEGADO!!')
| false |
8c6fc494dc35319b1b15e1df3de92677d366f2fe | LarissaMidori/curso_em_video | /exercicio014.py | 218 | 4.28125 | 4 | # Escreva um programa que leia uma temperatura digitada em °C e converta para °F
temp = float(input('Digite a temperatura em °C: '))
print(f'A temperatura de {temp:.1f}°C, equivale à {(temp * 1.8 + 32):.1f}°F.') | false |
9853a2266d1acbf23b8bba45db882b0b444fa030 | hari2pega/Python-Day-wise-Practice-Sheets | /Hari_July 27th_Practice Sheet - Numbers and Introduction to List.py | 1,862 | 4.53125 | 5 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
#Commenting the Line
#What ever has been written after the Hash symbol, It will be considered as Comment
#Numbers
#Integers
2+3
# In[2]:
#Numbers
3-2
# In[3]:
#Float - It will be give the decimal value - Declaring in Decimal is called Float
0.1+0.2
# In[8]:
# Assigning Numbers
X=2
Y=8
Z=4
X+Y+Z
# In[9]:
#Advance approach of aasignment
X,Y,Z = 9,4,6
X+Y+Z
# In[10]:
#Constants in Python: A constant in a Python is like a variable whose value says the same approach --
# -- through out the life of the program
# In python we will be declaring the constant variables in Capital Letters or Capital case
MAX_CONNECTION = 100
# In[13]:
#*** Introduction to List - Data type
# 1. List is an Mutable data type -- All modifications done on this
# 2. String is a Immutable data type
# 3. Alist is a collection of items in a particular order.
# 4. How to define a List - [] - Separated by Commas (,)
# Eg: Bicycles = ['Hero','Redline', 'Atlas', 'Trek', 'Ranger']
Bicycles = ['Hero','Redline','Atlas','Trek','Ranger']
print(Bicycles)
# In[19]:
# How to print a Individual element from a list?
# Ans: With the help of indexing
# **** From where Index will start -- Point 0 -- But not 1 ****
# Want to print first element from the List?
Bicycles = ['Hero','Redline','Atlas','Trek','Ranger']
print (Bicycles[0])
# In[20]:
Bicycles = ['Hero','Redline','Atlas','Trek','Ranger']
print (Bicycles[3])
# In[21]:
Bicycles = ['Hero','Redline','Atlas','trek','Ranger']
print (Bicycles[3].title())
# In[22]:
Bicycles = ['Hero','Redline','Atlas','Trek','ranger']
print (Bicycles[4].upper())
# In[23]:
Bicycles = ['Hero','Redline','Atlas','Trek','Ranger']
print (Bicycles[4].lower())
# In[24]:
Bicycles = ['Hero','Redline','Atlas','Trek','Ranger']
print (Bicycles[2])
# In[ ]:
| true |
74402dc7fb9d97f14ecaebf30b201a5b96a7e7e3 | dogeplusplus/DailyProgrammer | /222balancingwords.py | 1,304 | 4.3125 | 4 | def balance_word(word):
'''the position and letter itself to calculate the weight around the balance point. A word can be balanced if the weight on either side of the balance point is equal. Not all words can be balanced, but those that can are interesting for this challenge.
The formula to calculate the weight of the word is to look at the letter position in the English alphabet (so A=1, B=2, C=3 ... Z=26) as the letter weight, then multiply that by the distance from the balance point, so the first letter away is multiplied by 1, the second away by 2, etc.
As an example: STEAD balances at T: 1 * S(19) = 1 * E(5) + 2 * A(1) + 3 * D(4))'''
letter_list = list(word)
letter_weights = list(map(lambda x: ord(x) - 64, letter_list)) # calculate the alphabetical position of the letter based on lowercase ordinal
for i, letter in enumerate(letter_list):
position_weights = list(map(lambda x: x - i, range(len(letter_list))))
total_weights = [x*y for (x,y) in zip(letter_weights,position_weights)]
if sum(total_weights) == 0:
return ('%s %s %s - %d') % (''.join(letter_list[:i]), word[i] ,''.join(word[i+1:]), abs(sum(total_weights[:i])))
return word, 'does not balance.'
print(balance_word('STEAD'))
print(balance_word('CONSUBSTANTIATION'))
print(balance_word('UNINTELLIGIBILITY')) | true |
9b7ebf29fc78cf160361291530a3339ee5e0122a | maq-622674/python | /c语言中文网/py/7.函数和lambda表达式/7.1py函数/main.py | 1,135 | 4.3125 | 4 | '''
Python函数(函数定义、函数调用)用法详解
'''
n=0
for c in "http://c.biancheng.net/python/":
n = n + 1
print(n)
#自定义 len() 函数
def my_len(str):
length = 0
for c in str:
length = length + 1
return length
#调用自定义的 my_len() 函数
length = my_len("http://c.biancheng.net/python/")
print(length)
#再次调用 my_len() 函数
length = my_len("http://c.biancheng.net/shell/")
print(length)
'''
Python函数的定义
'''
#定义个空函数,没有实际意义
def pass_dis():
pass
#定义一个比较字符串大小的函数
# def str_max(str1,str2):
# str = str1 if str1 > str2 else str2
# return str
#更简洁
def str_max(str1,str2):
return str1 if str1 > str2 else str2
'''
py函数的调用
'''
pass_dis()
strmax = str_max("http://c.biancheng.net/python","http://c.biancheng.net/shell");
print(strmax)
'''
为函数提供说明文档
'''
#定义一个比较字符串大小的函数
def str_max(str1,str2):
'''
比较 2 个字符串的大小
'''
str = str1 if str1 > str2 else str2
return str
help(str_max)
#print(str_max.__doc__) | false |
30c7107dc51933bf4c72c5a9cdd5e87c73ac6d01 | maq-622674/python | /csdn_py/7.py网络爬虫基础(上)/1.py中的正则表达式.py | 1,106 | 4.15625 | 4 | # 一些表达式进行提取,正则表达式就是其中一种进行数据筛选的表达式。
# 正则表达式(Regular Expression)是一种文本模式,包括普通字符(例如,a 到 z 之间的字母)和特殊字符(称为"元字符")。
# 正则表达式通常被用来匹配、检索、替换和分割那些符合某个模式(规则)的文本。
# Python 自1.5版本起增加了re模块,它提供Perl风格的正则表达式模式。
# re 模块使 Python 语言拥有全部的正则表达式功能,使用前需要使用 import re 导入此模块
# compile 函数根据一个模式字符串和可选的标志参数生成一个正则表达式对象。该对象拥有一系列方法用于正则表达式匹配和替换。
import re
str = 'This year is 2018'
pat = re.compile("[0-9]{4}")
print(pat.findall(str))
#结果:['2018']
#re 模块也提供了与这些方法功能完全一致的函数,这些函数使用一个模式字符串做为它们的第一个参数。
import re
str = 'This year is 2018'
res = re.findall("[0-9]{4}",str)
print(res)
#结果:['2018'] | false |
117a672a7dc9c01ed5581a3983b3d7e57d53ecf9 | maq-622674/python | /c语言中文网/py/5.py字符串常用方法/5.11py字符串大小写转换/main.py | 521 | 4.21875 | 4 | '''
Python字符串大小写转换(3种)函数及用法
'''
#1.py title()方法
#两个单词之间无论用什么分开他都会把首字母变为大写
#比如apple——orange apple?orange apple_orange apple*orange
str="c_biancheng.net"
print(str.title())
#2.py lower()方法
#全部变小写
str="I LIKE C"
print(str.lower())
#3.py upper()方法
str="i like c"
print(str.upper())
#需要注意的是,以上 3 个方法都仅限于将转换后的新字符串返回,而不会修改原字符串。
print(str) | false |
e90b652e9b9d921a5d3ca94e1b299ce07e07812f | sfmajors373/PythonPractice | /OddTest.py | 364 | 4.1875 | 4 | #Input
largestoddnumbersofar = 0
counter = 0
#Test/Counter
while counter < 10:
x = int(input("Enter a number: "))
if x%2 == 1:
if x > largestoddnumbersofar:
largestoddnumbersofar = x
counter = counter + 1
print(counter)
#Output
if counter == 10:
print ("The largest odd number is " + str(largestoddnumbersofar))
| true |
02673b7a8aaac520aec772ab345391aae54ab1d8 | Vlad-Mihet/MergeSortPython | /MergeSortAlgorithm.py | 2,189 | 4.3125 | 4 | import random
# Generating a random Array to be sorted
# If needed, the random elements assignment could be removed, so a chosen array could be sorted
ArrayToBeSorted = [random.randint(-100, 100) for item in range(15)]
def MergeSort (array, left_index, right_index):
if left_index >= right_index:
return
middle = (left_index + right_index) // 2
MergeSort(array, left_index, middle)
MergeSort(array, middle + 1, right_index)
Merge(array, left_index, right_index, middle)
def Merge(array, left_index, right_index, middle):
# Make copies of each half of the initial array
left_array = array[left_index:middle + 1]
right_array = array[middle + 1:right_index + 1]
# Track the position we're in in both halves of the array (left and right arrays)
left_array_index = 0
right_array_index = 0
sorting_index = left_index
#Go through the elements of each array until we've run out of elements in any of them
while left_array_index < len(left_array) and right_array_index < len(right_array):
# The smallest element between the left and right arrays will be placed in the original array
if left_array[left_array_index] <= right_array[right_array_index]:
array[sorting_index] = left_array[left_array_index]
left_array_index += 1
else:
array[sorting_index] = right_array[right_array_index]
right_array_index += 1
# After we've sorted an element, we increment the position so we can add the other elements
sorting_index += 1
# After we've run our of elements in the arrays, we check for any elements that might have been left out
while left_array_index < len(left_array):
array[sorting_index] = left_array[left_array_index]
left_array_index += 1
sorting_index += 1
while right_array_index < len(right_array):
array[sorting_index] = right_array[right_array_index]
right_array_index += 1
sorting_index += 1
print(ArrayToBeSorted)
MergeSort(ArrayToBeSorted, 0, len(ArrayToBeSorted) - 1)
print(ArrayToBeSorted) | true |
b20c48f78e7e9ead7849a262a327b419abf97ee8 | aloksharma999/GreaterNumber | /GreaterNumber.py | 240 | 4.125 | 4 | a = int(input('Enter the first number: '))
b = int(input('Enter the second number:'))
if a > b:
print(a,'is the bigger number')
elif a <b:
print(b,'is the bigger number')
elif a ==b:
print(str(a) + 'is equal to ' +str(b)) | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.