blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
2fe3fc390fae95939e69d1d267fce295028c0392 | dgallegos01/Python-Course | /Modules/module.py | 793 | 4.5 | 4 | # a module is basically a file with python code
# we use them to organize our code into multiple files
# we will take this piece of code and turn it into a module
# we will make a separate file called 'converters.py' and put some code into it. every file is a module
# then we will do this:
import converters # we are calling the name of the file to import and reference its code. (do not include '.py')
from converters import kg_to_lbs # here we are just calling a specific function from that module. you can use this if you don't want to reference every function from that file
kg_to_lbs(100) # this does not need 'converters.' because the sepecific function was directly imported
print(converters.kg_to_lbs(70)) # we are calling the function, passing the value '70' and printing the output | true |
059a9560e85ffca2d871c4b543cc1563f50ee175 | dgallegos01/Python-Course | /Lists/List Methods/exercise.py | 267 | 4.15625 | 4 | # Write a program to remove the duplicates in a list
numbers = [2,2,4,6,3,4,6,1]
uniques = []
for number in numbers:
if number not in uniques:
uniques.append(number) # this will add one of every number from the original list to the new list
print(uniques) | true |
8cdc58e052f95ceb5278da01927608baadfac4e9 | dgallegos01/Python-Course | /Nested Loops/NestedLoops.py | 383 | 4.5 | 4 | # Nested loops are loops inside a loop
# example with coordinates
for x in range(4): # x starts with 0
for y in range(3): # y will print each value in range first before it goes back the the first loop
print(f'({x}, {y})') # for every x value, ther is a set of y values
""" output:
(0, 0)
(0, 1)
(0, 2)
(1, 0)
(1, 1)
(1, 2)
(2, 0)
(2, 1)
(2, 2)
(3, 0)
(3, 1)
(3, 2)
""" | true |
01d458dbe17a70af01eb93a02f15652fa6885af7 | gigennari/mc102 | /MC 102 (Exemplos de aula)/fibonacci.py | 397 | 4.15625 | 4 | #Sequência de Fibonacci
#a some de dois elementos define o próximo
def fib(n): #cria uma função para calcular a sequência de fibonacci até n
a, b = 0, 1 #atribuição múltipla
while a < n: #laço de repetição
print(a, end=' ')
a, b = b, a+b #redefinindo a e b, ou seja, A vira o último B e B vira a soma dos últimos a e b
print()
| false |
8a609648624167ed657cc06475ea91abf5c2854f | gigennari/mc102 | /MC 102 (Exemplos de aula)/listadecompras.py | 638 | 4.1875 | 4 | """ Escreva um programa que leia uma sequência de valores de itens de compra
e mostre o valor da soma de todos os itens.
O usuário deverá escrever o valor de cada item, um por linha.
Quando não houver mais itens o usário irá indicar esse fato escrevendo um número negativo """
""" entrada: 3.50, 5.00, 16.36, -1 saída:24.86"""
lista_compras = []
valor = float(input('Insira o valore do primeiro item: '))
while valor >= 0:
lista_compras.append(valor)
valor = float(input('Insira o valor do próximo item: '))
soma = 0.0
for valor in lista_compras:
soma += valor
print(f'O valor total de sua compra é {soma}')
| false |
faac7cc84283e1306a816a53a971eef15316f25d | gigennari/mc102 | /MC 102 (Exemplos de aula)/range.py | 266 | 4.1875 | 4 | for i in range(5,11):
for j in range(10-i):
print(" ", end="")
for j in range(2*i):
print("*", end="")
for j in range(10-i): #o código faz a mesma coisa sem essa linha?
print(" ", end="")
print()
"""""" | false |
73f39969c88997e29d58812ace1d3f9be750f869 | Nidia1903/zoologico | /zoo.py | 1,099 | 4.15625 | 4 | class Animal:
def __init__(self, nombre, tipo):
self.nombre= name
self.tipo= tipo
print ("Nuevo animal creado ")
def set_nombre(self,nombre):
self.nombre = nombre
print("El nuevo animal es " + self.nombre)
def get_nombre(self):
print("El animal actual es " + self.nombre)
def set_tipo(self,tipo):
self.tipo = tipo
print("El animal es de tipo: " + self.tipo)
def get_tipo(self):
print("El actual tipo de animal es: " + self.tipo)
lista1 =["Reptil","Tortuga"]
for x in lista1:
print(x)
lista1.append("Animal")
print(lista1)
lista1.append(["Pug","Dog"])
print(lista1)
lista1.extend(["Beta","Fish"])
print(lista1)
lista2 =[1,2,3]
print(id(lista2))
print(id(lista2))
print(id(lista2))
def mostrar_id(objeto):
print(id(objeto))
mostrar_id(lista2)
objeto = object()
mostrar_id(object)
def main():
Animal = Animal("Tigre","felino")
Animal.set_nombre("tigre")
Animal.get_nombre()
| false |
0a11c70fd889ebaf6be07a110b5581939adbd3c3 | Carmenliukang/leetcode | /算法分析和归类/树/递增顺序查找树.py | 2,045 | 4.21875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
给你一个树,请你 按中序遍历 重新排列树,使树中最左边的结点现在是树的根,并且每个结点没有左子结点,只有一个右子结点。
示例 :
输入:[5,3,6,2,4,null,8,1,null,null,null,7,9]
5
/ \
3 6
/ \ \
2 4 8
/ / \
1 7 9
输出:[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]
1
\
2
\
3
\
4
\
5
\
6
\
7
\
8
\
9
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/increasing-order-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def increasingBST(self, root):
# 这里使用的是 yield 方式同步,能够节省内存,这里真的太赞了 TODO 学习
def inorder(node):
if node:
yield from inorder(node.left)
yield node.val
yield from inorder(node.right)
# 进行相关的遍历方式同步
ans = cur = TreeNode(None)
for v in inorder(root):
cur.right = TreeNode(v)
cur = cur.right
return ans.right
def increasingBSTMethod(self, root):
# 这里是递归的方式同步
def inorder(node):
if node:
# 先遍历其左子树,然后将node 的 左子树节点 置位 null,防止成为环
inorder(node.left)
node.left = None
self.cur.right = node
self.cur = node
inorder(node.right)
ans = self.cur = TreeNode(None)
inorder(root)
return ans.right
| false |
4e355aa38d37c8af194cf8fc58921b89faf59e0a | Carmenliukang/leetcode | /算法分析和归类/树/二叉搜索树中的搜索.py | 1,407 | 4.1875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
给定二叉搜索树(BST)的根节点和一个值。 你需要在BST中找到节点值等于给定值的节点。 返回以该节点为根的子树。 如果节点不存在,则返回 NULL。
例如,
给定二叉搜索树:
4
/ \
2 7
/ \
1 3
和值: 2
你应该返回如下子树:
2
/ \
1 3
在上述示例中,如果要找的值是 5,但因为没有节点值为 5,我们应该返回 NULL。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/search-in-a-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def searchBST(self, root: TreeNode, val: int) -> TreeNode:
# 1. 确定边界条件
# 2. 确定每一个节点的条件
# 3. 确定参数配置
if not root:
return None
# 这里的每一个节点的循环条件
if val == root.val:
return root
# 这里进行了剪纸
if root.val > val:
res = self.searchBST(root.left, val)
else:
res = self.searchBST(root.right, val)
return res
| false |
2f21a090d0067a1d934d7ecbaaddc7d34fd17be4 | Carmenliukang/leetcode | /算法分析和归类/树/合并二叉树.py | 1,729 | 4.1875 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。
你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 NULL 的节点将直接作为新二叉树的节点。
示例 1:
输入:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
输出:
合并后的树:
3
/ \
4 5
/ \ \
5 4 7
注意: 合并必须从两个树的根节点开始。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-two-binary-trees
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode:
if not t1: return t2
if not t2: return t1 # 又一次这里写错了,操作返回结果出现了问题,这里需要处理,代码简单的修改一点,就有可能产生意想不到的错误。
val = self.check_val(t1.val) + self.check_val(t2.val)
res = TreeNode(val)
res.left = self.mergeTrees(t1.left, t2.left)
res.right = self.mergeTrees(t1.right, t2.right)
return res
def check_val(self, val):
return val if val else 0
| false |
ceadb16ed3bd33ced0e961850449f7e26d9a32af | Carmenliukang/leetcode | /算法分析和归类/排序/插入排序.py | 615 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def insertion_sort(nums):
"""
插入排序,使用的流程就是同步
:param nums:
:return:
"""
for i in range(1, len(nums)):
# 开始节点
pre = i - 1
cur = nums[i]
# 这里就是一种循环的计算方式去计算
while (pre >= 0 and nums[pre] > cur):
# 从最后向前进行倒序循环
nums[pre + 1] = nums[pre]
pre -= 1
nums[pre + 1] = cur
return nums
if __name__ == '__main__':
nums = [1, 5, 46, 23, 7]
print(insertion_sort(nums))
| false |
f3eafbd386e367d66a40aba4f44330fda6cc0453 | shravankumar0811/Coding_Ninjas | /Introduction to Python/9 Searching & Sorting/Code Bubble Sort.py | 759 | 4.5 | 4 | ##Code Bubble Sort
##Send Feedback
##Given a random integer array. Sort this array using bubble sort.
##Change in the input array itself. You don't need to return or print elements.
##
##
##Input format :
##Line 1 : Integer N, Array Size
##Line 2 : Elements of the array separated by single space
##Output format :
##Elements of array in sorted order. Print them in a single line and space-separated
## Read input as specified in the question.
## Print output as specified in the question.
def bubbleSort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
print(*arr)
n=int(input())
l=list(map(int,input().split()))
bubbleSort(l)
| true |
e99c54d11f4dffc02d03fd28ed96b1d1773b6ed1 | shravankumar0811/Coding_Ninjas | /Introduction to Python/9 Searching & Sorting/Code Merge Sort.py | 709 | 4.34375 | 4 | ##Code Merge Two Sorted Arrays
##Send Feedback
##Given two sorted arrays of Size M and N respectively, merge them into a third array such that the third array is also sorted.
##Input Format :
## Line 1 : Size of first array i.e. M
## Line 2 : M elements of first array separated by space
## Line 3 : Size of second array i.e. N
## Line 2 : N elements of second array separated by space
##Output Format :
##M + N integers i.e. elements of third sorted array in a single line separated by spaces.
## Read input as specified in the question.
## Print output as specified in the question.
n=int(input())
l=list(map(int,input().split()))
m=int(input())
k=list(map(int,input().split()))
a=l+k
a.sort()
print(*a)
| true |
b9bb38ad71a34571620cf6df170f3d4b48c9ed8d | shravankumar0811/Coding_Ninjas | /Introduction to Python/9 Searching & Sorting/Rotate Array.py | 594 | 4.40625 | 4 | ##Rotate array
##Send Feedback
##Given a random integer array of size n, write a function that rotates the given array by d elements (towards left)
##Change in the input array itself. You don't need to return or print elements.
##Input format :
##Line 1 : Integer n (Array Size)
##Line 2 : Array elements (separated by space)
##Line 3 : Integer d
##Output Format :
##Updated array elements in a single line (separated by space)
def Rotate(arr, d):
return arr[d:]+arr[:d]
# Main
n=int(input())
arr=list(int(i) for i in input().strip().split(' '))
d=int(input())
l=Rotate(arr, d)
print(*l)
| true |
8b4bb72520492b9d38d9eb359a7eb5af7a149cc4 | manikandanmass-007/manikandanmass | /Python Programs/program to find GCD of a number.py | 207 | 4.1875 | 4 | #program to find GCD of a number
n1=int(input("enter the number n1:"))
n2=int(input("enter the number n2:"))
rem=n1%n2
while rem!=0:
n1=n2
n2=rem
rem=n1%n2
print ("gcd of given numbers is:",n2) | false |
fcda74e98ffa560dfcd3739f7316c45ce82025bc | manikandanmass-007/manikandanmass | /Python Programs/program to print odd numbers from 1 to 100.py | 215 | 4.3125 | 4 | #program to print odd numbers from 1 to 100
start=int(input("enter the starting value:"))
end=int(input("enter the ending value:"))
for i in range(start, end+1):
if i%2!=0:
print(i, end = " ")
| true |
061aed039890d409f9406faf0f9926101f01b038 | Aryanakh7/Election_Analysis | /Python_Practice.py | 1,862 | 4.34375 | 4 | # counties = ["Arapahoe", "Denver", "Jefferson"]
# if counties[1] == 'Denver':
# print(counties[1])
# if counties[3] != 'Jefferson'
# print(counties[2])
# temperature = int(input("What is the temperature outside? "))
# if temperature > 80:
# print("Turn on the AC.")
# else:
# print("Open the windows.")
# What is the score?
# What is the score ?
# score = int(input("What is your test score? "))
# Determine the grade
# if score >= 90:
# print('Your grade is an A.')
# elif score >= 80:
# print('Your grade is a B.')
# elif score >= 70:
# print('Your grade is a C.')
# elif score >= 60:
# print('Your grade is a D.')
# else:
# print('Your grade is an F.')
# counties = ["Arapahoe", "Denver", "Jefferson"]
# if "El Paso" in counties:
# print("El Paso is in the list of counties. ")
# else:
# print("El Paso is not the list of counties")
# x = 5
# y = 5
# if x == 5 and y == 5:
# print("True")
# else:
# print("False")
# if "Arapahoe" in counties and "El Paso" not in counties:
# print("Only Arapahoe is in the of counties.")
# else:
# print("Arapahoe is in the list of counties and El Paso is not in the list of counties.")
# x = 0
# while x <= 5:
# print(x)
# x= x + 1
# for county in counties:
# print('Jefferson')
# numbers = [0, 1, 2, 3, 4]
# for num in numbers:
# print(num)
# for num in range(5):
# print (num)
# for i in range(len(counties)):
# print(counties[i])
# counties_tuple = ("Arapahoe", "Denver", "Jefferson").
# Arapahoe
# Denver
# Jefferson
# print("Hello World")
# print("Your interest for the year is $" + str(3000))
# my_votes = int(input("How many votes did you get in the election? "))
# total_votes = int(input("What is the total votes in the election? "))
# print(f"I received {my_votes / total_votes * 100} of the total votes.")
| false |
9a3be16f0a9423f68cdc883e0cf257af2e7978e1 | kaio358/Python | /Mundo 1/Tratando Dados e fazendo contas/Desafio#9.py | 566 | 4.21875 | 4 | numero = int(input("Informe o seu numero : "))
print('|----- TABUADA --------|')
print('{} X 1 = {}'.format(numero,numero*1))
print('{} X 2 = {}'.format(numero,numero*2))
print('{} X 3 = {}'.format(numero,numero*3))
print('{} X 4 = {}'.format(numero,numero*4))
print('{} X 5 = {}'.format(numero,numero*5))
print('{} X 6 = {}'.format(numero,numero*6))
print('{} X 7 = {}'.format(numero,numero*7))
print('{} X 8 = {}'.format(numero,numero*8))
print('{} X 9 = {}'.format(numero,numero*9))
print('{} X 10 = {}'.format(numero,numero*10))
print('|----------------------|') | false |
47ec62b7cdb60bcd08fc15c07595911fe8ddaaab | BTunney92/pands-problem-sheet | /Week5/Weekday.py | 460 | 4.3125 | 4 | #Program that outputs whether or not today is a weekday
#Author: Brendan Tunney
# This imports python's datetime module
import datetime
# Weekday function returns days as an integer (0 for Monday up to 6 for Sunday)
dayOfWeek = datetime.datetime.today().weekday()
if dayOfWeek < 5:
print ("Unfortunately, it is a weekday. Get back to work!")
else:
print ("Its the weekend, but still too early for cans!")
# Referenced W3 Schools, Stackoverflow & Pythonic | true |
5dd09561de925974b05b8b207a048aa4d1db2ab2 | Ankit949/LinearRegression | /LinearRegression_multipleFeature.py | 1,483 | 4.125 | 4 | import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error
#loading pre-existing data set set from sklearn
diabetes=datasets.load_diabetes()
#print(diadetes)
#printing key values of dataset i.e features of data
print(diabetes.keys())
# Selecting only one feature for implementing linearRegression i.e y= w0+w1*x
diabetes_X=diabetes.data
# Spliting the data into training and test data using list slicing
diabetes_x_train=diabetes_X[:-30]
diabetes_x_test=diabetes_X[-30:]
diabetes_y_train=diabetes.target[:-30] # target is a class used here to specify that these are the target values
diabetes_y_test=diabetes.target[-30:]
# form a linear model
model=linear_model.LinearRegression()
#fitting the model i.e training the model
model.fit(diabetes_x_train,diabetes_y_train)
#predicting the data i.e testing the data
diabetes_y_predict=model.predict(diabetes_x_test)
# Calculating mean sqruared error . MSE=(target_vaue-Predicted_value)
print("Mean Squared error is ",mean_squared_error(diabetes_y_test,diabetes_y_predict))
#Printing weights of the model. If single feature is selected then there will be only one weight.
print("weights ", model.coef_)
#ploting the graph for pictorial view
#plt.scatter(diabetes_x_test,diabetes_y_test)
#plt.plot(diabetes_x_test,diabetes_y_predict)
#intersecting point
#print("Intercept ",model.intercept_)
#plt.show() | true |
5734b500a6aa67fd753cfb3b9ae2744775e4474a | YuHw81/Python_basic | /vscodePython/2-3.py | 2,456 | 4.15625 | 4 | # 리스트
ex = [1, 2, ['Life', 'is']]
# print(len(ex)) >> result : 3
print(ex[2]) # ex의 세번째 요소 ['Life', 'is']
print(ex[2][0]) # ex의 세번째 요소 ['Life', 'is'] 중 첫번째 요소 'Life'
ex = [1, 2, ['Life', ['too', 'short']]]
'''
ex = [
1,
2,
[
'Life',
[
'too',
'short'
]
]
]
'''
print(ex[2][1][1]) # ex의 세번째 요소 ['Life', ['too', 'short']] 중 두번째 요소 중 ['too', 'short'] 중 두번째 요소 'short'
# 리스트 연산하기
print('================리스트 연산하기')
a = [1, 2, 3]
b = [4, 5, 6]
p = a + b
print(p) # [1, 2, 3, 4, 5, 6]
p = a * 3
print(p) # [1, 2, 3, 1, 2, 3, 1, 2, 3]
# 연산 오류
print('================연산 오류')
# a = 3 + 'hi' # TypeError: unsupported operand type(s) for +: 'int' and 'str'
a = str(3) + 'hi'
print(a)
print(type(int('4')))
print('====================')
a = '1'
print(type(list(a)))
def sum(a, b):
return print(a + b)
sum(2, 3)
# 리스트 수정 삭제 추가
print('================리스트 수정 삭제 추가')
a = [1, 2, 3]
a[2] = 4 # 리스트 세번째 인덱스 수정
print(a)
del a[1] # 리스트 두번째 인덱스 삭제 # del : 객체 삭제(객체:모든 자료형)
print(a)
a = [1, 2, 3]
a.append(4) # 리스트 요소 추가
a.append([5, 6]) # 리스트 요소 추가
print(a) # [1, 2, 3, 4, [5, 6]]
print(a[4]) # [5, 6]
print(a[4][1]) # 6
b = a[4] # [5, 6]
print(b[1]) # 6
# 리스트 정렬
print('================리스트 정렬')
a = [1, 4, 3, 2]
a.sort() # 리스트 정렬
print(a)
a = ['a', 'c', 'b']
a.reverse() # 리스트 뒤집기
print(a)
a = [1, 2, 3]
print(type(a))
# a.index[4] # TypeError: '
a.insert(0, 4) # list 0 위치에 4 입력
print(a)
a = [1, 2, 3, 1, 2, 3]
a.remove(3) # list 중 첫번째 3을 삭제
print(a)
a.remove(3) # 두번 실행하여 3을 삭제
print(a)
a.clear() # 리스트 전체 삭제
print(a)
# 리스트 pop
print('================리스트 pop')
a = [1, 2, 3, 4]
b = a.pop() # 빈값은 리스트의 마지막. str.pop(index)
print(b)
print(a)
a = [1, 2, 3, 4]
b = a.pop(1) # 1 = index
print(b)
print(a)
def x():
y()
print('x')
def y():
z()
print('y')
def z():
print('z')
x()
| false |
72f8fca98b3edd529513e3de1f2b7d96082e2934 | bibek720/Hacktoberfest | /Python/Trie_implementation.py | 1,439 | 4.21875 | 4 | class TrieNode:
# Trie node class
def __init__(self):
self.children = [None]*26
self.isWordEnd = False
class Trie:
# Trie data structure class
def __init__(self):
self.root = self.getNode()
def getNode(self):
return TrieNode()
def insert(self,key):
# If not present, inserts key into trie, if prefix of node
#marks it as leaf
node = self.root
length = len(key)
for level in range(length):
index = ord(key[level])-ord('a')
if not node.children[index]:
node.children[index] = self.getNode()
node = node.children[index]
# mark last node as leaf
node.isWordEnd = True
def search(self, key):
node = self.root
length = len(key)
for level in range(length):
index = ord(key[level])-ord('a')
if not node.children[index]:
return False
node = node.children[index]
return node is not None and node.isWordEnd
def main():
#tree object
t = Trie()
c="y"
while c == "y":
val = input("Enter 1: Insert, 2: Search")
if val == "1":
key = input("Enter Word to insert : ")
t.insert(key)
elif val == "2":
searchKey = input("Enter Word to be searched : ")
if t.search(searchKey):
print("Present")
else:
print("Not Present")
c=input("Do you want to continue(y/n): ")
if __name__ == '__main__':
main()
| true |
758e03c248d6ea6c2ea119fc73ecdc7d2c55b66f | nshekhawat/PythonClass | /Questions-Unit4/Question13-Unit4.py | 303 | 4.25 | 4 | #!/usr/bin/env python
# Author: Narendra
__doc__ = '''
With a given tuple (1,2,3,4,5,6,7,8,9,10),
write a program to print the first half values in one line and the last half values in one line.
'''
tuple1 = (1,2,3,4,5,6,7,8,9,10)
middle = len(tuple1) / 2
print tuple1[:middle]
print tuple1[middle:] | true |
c84871b747bacf4aefd0c3bffb9f6676dd149926 | nshekhawat/PythonClass | /Questions-Unit4/Question2-Unit4.py | 857 | 4.46875 | 4 | #!/usr/bin/env python
# Author: Narendra
__doc__ = '''
Assign a list to a reference a , containing a regular sequence of 5 - 8 elements,
such that if you knew the first 3 elements you would be able to predict the rest. E.G: [3,6,9,12,15,21,24] .
- Using a slice operation assign 2 elements from the middle of your sequence: e.g. 12 and 15 to another list called c.
- Take a backup of your list a in b by assigning: b=a You might need to copy the backup in b back to a if you screw a up.
- Using the del operator twice on indexed elements of list a, remove the 2 elements from the middle of a that you
assigned into the list c. E.G if you had (blindly) used the above values your list might now look like: [3,6,9,18,21,24].
- Using a slice assignment operation, restore the list a to its original sequence by inserting list c into the
middle of list a.
'''
| true |
51661069c279df5e185f9bd8b8dd04392f014362 | nshekhawat/PythonClass | /Questions-Unit4/Question10-Unit4.py | 336 | 4.375 | 4 | #!/usr/bin/env python
# Author: Narendra
__doc__ = '''
Define a function which can print a dictionary where the keys are numbers between 1 and 3 (both included)
and the values are square of keys.
'''
def square(x):
d = {}
for i in range(1, x):
d[i] = i**2
return d
if __name__ == "__main__":
print square(4)
| true |
d4e342ce06fd6dc9b2034124c4d09b46c9cf23b3 | ddg20/CS0008-f2016 | /Ch3-Ex6 Magic Dates.py | 468 | 4.125 | 4 | #name: Dhruv Gohel
#email: ddg20@pitt.edu
#date: 09/08/2016
#class: CS0008-f2016
#instructor: Max Novelli
#
#description: Introduction to programming with Python, Chapter 3, Exercise 6
#
#Notes:
month = int(input("Enter a month: "))
date = int(input("Enter a date: "))
year = int(input("Enter a 2-digit year: "))
magicNumber = month * date
if (magicNumber == year):
print("\nThe date is magic.")
else:
print("\nThe date is not magic.") | true |
bd5d5cfe604da46ad7c908ead2d9d91ee8890b98 | mistyjack/pirple | /python-is-easy/homework4/main.py | 889 | 4.34375 | 4 | """
This file contains code that adds a new item to an
existing list
"""
# Create the global list called myUniqueList
myUniqueList = []
myLeftovers = []
# Create a function that makes it possible to add list items
def addNewItem(item, mainList, otherList):
# Does item exists? no, add to global list and return true
if item not in mainList:
mainList.append(item)
print("Item added to unique list")
return True
# Exists? add to leftover list and return false
else:
otherList.append(item)
print("Item added to leftover list")
return False
# End of function
# Test
addNewItem("hello", myUniqueList, myLeftovers)
addNewItem("hi", myUniqueList, myLeftovers)
addNewItem("hello", myUniqueList, myLeftovers)
addNewItem("hello", myUniqueList, myLeftovers)
addNewItem(15, myUniqueList, myLeftovers)
print(myUniqueList) | true |
b73847c154cb32553516b216a0b48caf0843701c | zeealik/My_Python_Coding | /Chapter 4/VSCode_coding_tricks.py | 412 | 4.125 | 4 | def multipy(*numbers):
total = 1
for number in numbers:
total *= number
return total
print("Start")
print(multipy(1, 2, 3))
print(multipy(1, 2, 3))
# alt + uparrow/downarrow move line up or down
# shift + alt + up to copy
# home key to go at first line
# end key to move at the end of page
# ctrl + / to comment
# write one or two word so you get the full name ,, then
# just press enter
| true |
4b9661179828a7f1f5166d3a68945b6a262d08ea | funandeasyprogramming/python_tutorial_for_beginners | /list_methods/list_methods.py | 2,490 | 4.4375 | 4 | #group 1: append, extend, insert
#group 2: remove, pop, clear
#group 3: count, reverse, sort, index, copy
# help(list)
# append - appends a new elment to the end of the list./
# list_one = [1, 2, 3]
# list_one.append(4)
# print (list_one)
# list_one.append('123')
# print (list_one)
# extend - adds all elements in an iterable(tuple, dict, list, string) to the end of the list.
# list_one = [1, 2, 3]
# list_two = [4, 5, 6]
# tuple_one = (1, 2, 3)
# string_one = 'abc'
# list_one.extend(string_one)
# print (list_one)
# print (list_one + list_two)
# insert - inserts an element into the specified index within the list.
# list_one = ['a', 'b', 'c']
# # list_one.insert(1, 'd')
# # print (list_one)
# list_one.insert(0, 'aa')
# print (list_one)
#group 2: remove, pop, clear
# remove - remove an element from the list.
# list_one = ['a', 'b', 'c']
# removed_item = list_one.remove('b')
# print (removed_item)
# print (list_one)
# pop - by default, removes the last element from the list, but you can also specify the index of the element that you want to remove.
# list_one = ['a', 'b', 'c']
# removed_item = list_one.pop(0)
# print (removed_item)
# print (list_one)
# clear - clears out all the elements in the list.
# list_one = [1, 2, 3, 4, 5, 6]
# list_one.clear()
# print (list_one)
# del list_one[:]
# print (list_one)
#group 3: count, reverse, sort, index, copy
# count - counts the number of element found in the list.
# list_one = ['a', 'b', 'c', 'a']
# count = list_one.count(4)
# print (count)
# reverse - reverses all the elements in the list.
# list_one = [1, 2, 3, 1, 2, 3]
# list_one.reverse()
# print (list_one)
# print (list_one[::-1])
# sort - sorts elements in the list either ascending or descending order.
# list_one = [1, 4, 7, 5, 2, 6, 1, 9, 3]
# list_two = ['e', 'b', 'a', 'g', 'h', 'c']
#
# list_one.sort(reverse = True)
# print (list_one)
# list_two.sort(reverse = True)
# print (list_two)
# index - returns the index of the first occurrence of an element found in the list.
# list_one = ['a', 'b', 'c', 'a', 'b', 'c']
#
# index = list_one.index('a', 3, 6)
# print (index)
# copy - creates a new list with the copied value.
list_one = [1, 2, 3]
list_two = list_one.copy()
print (list_one, list_two)
list_one.append(4)
print (list_one, list_two)
print (id(list_one), id(list_two))
# list_two = list_one
#
# print (list_one, list_two)
# list_one.append(4)
# print (list_one, list_two)
# print (id(list_one), id(list_two))
| true |
f301fff4afa813e05215829b28da2a4363fcf360 | funandeasyprogramming/python_tutorial_for_beginners | /practice_programs/unit_conversion.py | 2,626 | 4.375 | 4 | # 1 Create a function that takes user inputs
# 2 Create a function for unit conversion
# 3 Think and implement the strategies for the actual unit conversion
# bad strategy # 1 - 100% manual implementation - not working and not complete.
# if from_unit == "CM":
# if to_unit == "KM":
# print(number / 100000)
# elif to_unit == "M":
# print(number / 100)
# elif to_unit == "MM":
# print(number * 10)
# elif from_unit == "M":
# if to_unit == "KM":
# print(number / 100000)
# elif to_unit == "CM":
# print(number / 100)
# elif to_unit == "MM":
# print(number * 10)
# elif from_unit == "KM":
# if to_unit == "CM":
# print(number / 100000)
# elif to_unit == "M":
# print(number / 100)
# elif to_unit == "MM":
# print(number * 10)
# elif from_unit == "MM":
# if to_unit == "KM":
# print(number / 100000)
# elif to_unit == "M":
# print(number / 100)
# elif to_unit == "CM":
# print(number * 10)
def get_user_input():
print ("MENU 1) Unit Conversion 2) Quit")
menu = int(input("Choose an option from the MENU: "))
if menu == 1:
number = float(input("Enter a number: "))
from_unit = input("Enter the From Unit: ")
to_unit = input("Enter the To Unit: ")
return {"menu": menu, "number": number,
"from_unit": from_unit, "to_unit": to_unit}
elif menu == 2:
return {"menu": menu}
def convert_unit():
while True:
user_input = get_user_input()
if user_input.get("menu") == 2:
break
number = user_input.get("number")
from_unit = user_input.get("from_unit").upper()
to_unit = user_input.get("to_unit").upper()
# bad strategy # 2 - bit better than #1
# but still involves manual calculations
if from_unit == "KM":
mapper = {"M": 1000, "CM": 100000, "MM": 1000000}
print (number * mapper[to_unit])
elif from_unit == "M":
mapper = {"KM": 0.001, "CM": 100, "MM": 1000}
print(number * mapper[to_unit])
elif from_unit == "CM":
mapper = {"KM": 0.00001, "M": 0.01, "MM": 10}
print(number * mapper[to_unit])
elif from_unit == "MM":
mapper = {"KM": 0.000001, "M": 0.001, "CM": 0.1}
print(number * mapper[to_unit])
standard_unit_mapper = {"M": 1, "KM": 0.001,
"CM": 100, "MM": 1000,
"FT": 3.280839895,
"IN": 39.37007874}
convert_unit()
| true |
912c672705a2a75cc09710f00b41eb830b664ec8 | JamesNowak/Chapter-7-Practice | /7.7.py | 551 | 4.125 | 4 | # TODO 7.7 Processing lists
# total the values in list3 and print the results
list1 = [1, 3, 5, 7, 9]
list2 = [2, 4, 6, 8, 10]
list3 = list1 + list2
print(len(list3))
# get the average of values in list 3 and print the results
total = 0.0
for value in list3:
total += value
average = total / len(list3)
print(average)
# open the file states in read mode, read the contents of the file into the list states_list and print the
# contents of states_list on screen
states = open('states.txt', 'r')
for n in states:
print(n)
| true |
d862eb7b31e9e99c84cf4fe89e87ff41e9507cd8 | SerkanKaanBahsi/python-examples | /python-examples/advanced_topics/e004_decorators/main.py | 1,886 | 4.75 | 5 |
#Basically, a decorator takes in a function, adds some functionality and returns it.
#Here is a decorator example.
#In this example some operations must be done without some numbers
def cantUseNum(func):
def addNum(num1,num2):
if num1 == 1 or num2 == 1:
print("Cant Use Number 1 With Addition")
return
return func(num1,num2)
def divNum(num1,num2):
if num2 == 0:
print("That is not possible")
elif num1 == 2 or num2 ==2:
print("Cant Use Number 2 With Division")
return
return func(num1,num2)
def mulNum(num1,num2):
if num1 == 2 or num2 == 2:
print("Cant use Number 2 With Multiplication")
return
return func(num1,num2)
def subNum(num1,num2):
if num1 == 1 or num2 == 1:
print("Cant Use Number 1 With Subtraction")
return
return func(num1,num2)
if func.__name__ == "add":
return addNum
elif func.__name__ == "div":
return divNum
elif func.__name__ == "mul":
return mulNum
elif func.__name__ == "sub":
return subNum
@cantUseNum
def add(num1,num2):
return num1+num2
@cantUseNum
def div(num1,num2):
return num1/num2
@cantUseNum
def mul(num1,num2):
return num1*num2
@cantUseNum
def sub(num1,num2):
return num1-num2
#We can also chain decorators
def patternFirst(func):
def inner(*args, **kwargs):
print('{' * 12)
func(*args, **kwargs)
print('}' * 12)
return inner
def patternSecond(func):
def inner(*args, **kwargs):
print('<' * 12)
func(*args, **kwargs)
print('>' * 12)
return inner
@patternFirst
@patternSecond
def printCool(message):
print(message)
add(1,1)
y =(mul(5,4))
print(y)
printCool("Air Bender")
| true |
d386f45c170de70377e41321bdf1af848ebb589c | SerkanKaanBahsi/python-examples | /python-examples/file_operations/e004_file_io/main.py | 2,303 | 4.3125 | 4 | # if we open the file in 'with' it closes itself
# we must write the encoding 'cp1252' for windows, 'utf-8' for linux
# r means read only
# w means write(also deletes everything) if file does not exist create a new file
# x Open a file for exclusive creation. If the file already exists, the operation fails. (What is exclusive creation ?)
# a Open for appending at the end of the file without truncating it.
# Creates a new file if it does not exist. (Look this up too)
# t open in text mode (try this)
# b Open in binary mode (can try this to)
# + Open a file for updating (reading and writing)
# We can also use try blocks for opening files
with open("test.txt", 'w', encoding='cp1252') as f:
f.write("hello world \n")
f.write("My name is Serkan ")
f.write("And welcome \n")
f.write("next Line")
# seek goes to the line we write
# tell gives us our position
# f.readline reads the line takes the '\n' to
# f.readlines takes all
# if we are at the end this functions return empty
with open("test.txt", 'r', encoding='cp1252') as f:
print(f.read(4)) # reads only the first 4
print(f.read(4))
print(f.tell())
f.seek(0)
print(f.read()) # read all
f.seek(0)
print(f.readline(), end="")
st = f.readlines() # takes the \n to so watch out in string operations
print(st)
# print(f.read())
f.seek(0)
# We can also use for to read lines
for line in f:
print(line, end="") # if we dont use end="" it gives to empty lines because of print(print has automatic \n)
# We have many functions to use in file operations (check out file streams)
"""close() closes the file
detach() ?
fileno() ? Return an integer number (file descriptor) of the file(probably gives file a number)
flush() ?
isatty() ?
read(n) reads all or n number of characters
readable() return true if file stream is readable
readline(n) readline or n bytes from a line
readlines(n) read all or n lines
seek(offset,from=SEEK_SET) start, current, end
seekable() return true if file stream supports random access
tell() tell the position
truncate(size=None) Resize the file stream to size bytes. If size is not specified, resize to current location. ?
writable() returns true if file stream is writable
write(s)
writelines() writes a list of lines (try this one)
"""
| true |
75d3625d07faa8ad12c07f110a97e49eeccbca7f | SerkanKaanBahsi/python-examples | /python-examples/language_basics/IfElse.py | 276 | 4.1875 | 4 | #If Else Code
a=5
c=int(input("Enter a Number: "))
b=int(input("Enter a Number: "))
if b<=a:
if b<=c:
print("%d is the smallest" %b)
else:
print("%d is the smallest" %c)
elif a > c:
print("C is the smallest")
else:
print("A is the smallest")
| true |
36e645d1edc9a87d3c6508982043602840471406 | ElijahWxu/Python_for_Physics | /problem11.py | 390 | 4.125 | 4 | # Function for nth Fibonacci number
def Fibonacci(n):
if n<= 0:
print("Incorrect input")
# First Fibonacci number is 0
elif n == 1:
return 0
# Second Fibonacci number is 1
elif n == 2:
return 1
else:
return Fibonacci(n-1)+Fibonacci(n-2)
nx=5 ## This is to try the return
print(nx, "order Fibonacci number is",Fibonacci(nx))
| true |
106b0683255caf2df92a8dcbc44363e0874a0f09 | KalebeGouvea/exercicios-python | /lista02/exer5.py | 841 | 4.1875 | 4 | #Faça um Programa que leia três números e mostre o maior e o menor deles.
n1 = float(input('Digite o primeiro número: '))
n2 = float(input('Digite o segundo número: '))
n3 = float(input('Digite o terceiro número: '))
maior = max(n1, n2, n3)
menor = min(n1, n2, n3)
print (f'O maior número é {maior}')
print (f'O menor número é {menor}')
"""Ou também
n1 = float(input('Digite o primeiro número: '))
n2 = float(input('Digite o segundo número: '))
n3 = float(input('Digite o terceiro número: '))
if n1 >= n2 and n1 >= n3:
print (f'O maior número é {n1}')
elif n2 >= n3:
print (f'O maior número é {n2}')
else:
print (f'O maior número é {n3}')
if n1 <= n2 and n1 <= n3:
print (f'O menor número é {n1}')
elif n2 <= n3:
print (f'O menor número é {n2}')
else:
print (f'O menor número é {n3}')
""" | false |
3a28b1eae38af4fcec116e4f894825200f687cc4 | KalebeGouvea/exercicios-python | /exercicios_classes/classPessoa.py | 1,409 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
4. Classe Pessoa: Crie uma classe que modele uma pessoa:
a. Atributos: nome, idade, peso e altura
b.Metodos: Envelhercer, engordar, emagrecer, crescer. Obs: Por padrao, a cada ano que nossa pessoa envelhece,
sendo a idade dela menor que 21 anos, ela deve crescer 0,5 cm.
"""
class Pessoa:
def __init__(self, nome, idade, peso, altura):
self.nome = nome
self.idade = idade
self.peso = peso
self.altura = altura
def envelhecer (self, ano):
if self.idade < 21:
self.crescer(0.5*ano)
self.idade += ano
def engordar (self, quilos):
self.peso += quilos
def emagrecer (self, quilos):
self.peso -= quilos
def crescer (self, metros):
self.altura += metros
ind = Pessoa("Fulano da Silva", 17, 78, 170)
print("O nome da pessoa é: ", ind.nome)
print ("O peso da pessoa é: ", ind.peso)
ind.engordar(10.5)
print ("O peso da pessoa agora é: ", ind.peso)
print ("O peso da pessoa é: ", ind.peso)
ind.emagrecer(5)
print ("O peso da pessoa agora é: ", ind.peso)
print ("A altura da pessoa é: ", ind.altura)
ind.crescer(2)
print ("A altura da pessoa agora é: ", ind.altura)
print ("A idade da pessoa é: ", ind.idade)
print ("A altura da pessoa é: ", ind.altura)
ind.envelhecer(3)
print ("A idade da pessoa agora é: ", ind.idade)
print ("A altura da pessoa agora é: ", ind.altura) | false |
2ccb63fc2b47480ac4484fa64f1c3e47ddd758fa | CarolinaMistika/python-poo3 | /AV1/lista01/10/main.py | 1,255 | 4.3125 | 4 | '''
10. Utilizando listas faça um programa que faça 5 perguntas para uma pessoa sobre um
crime. As perguntas são:
a) "Telefonou para a vítima?"
b) "Esteve no local do crime?"
c) "Mora perto da vítima?"
d) "Devia para a vítima?"
e) "Já trabalhou com a vítima?"
O programa deve no final emitir uma classificação sobre a participação da pessoa no
crime. Se a pessoa responder positivamente a 2 questões ela deve ser classificada
como "Suspeita", entre 3 e 4 como "Cúmplice" e 5 como "Assassino". Caso contrário,
ele será classificado como "Inocente".
'''
print('**************** JOGO DO DETETIVE ********************')
print('reponda 1 para sim e 0 para não ')
count = 0
resposta = int(input('Telefonou para a vítima?: '))
if resposta == 1:
count += 1
resposta = int(input('Esteve no local do crime?: '))
if resposta == 1:
count += 1
resposta = int(input('Mora perto da vítima?: '))
if resposta == 1:
count += 1
resposta = int(input('Devia para a vítima?: '))
if resposta == 1:
count += 1
resposta = int(input('Já trabalhou com a vítima?: '))
if resposta == 1:
count += 1
if count == 2:
print('Suspeito(a)')
if count == 3 or count == 4:
print('Cúmplice')
if count == 5:
print('Assassino')
else:
print('Inocente') | false |
81e48e63782de8b6d8531642d41b9aca6e99ee83 | sonya-sa/coding-challenges | /game.py | 2,402 | 4.25 | 4 | import random
#create a list of possible words for the game
wordlist = ["frazzled", "grogginess", "crypt", "ostracize", "oxygen", \
"rhythmic", "pajama", "jinx", "yacht", "banjo", "awkward", \
"zigzag", "twelfth", "unzip", "mystify", "jukebox"]
return random.choice(wordlist).lower()
# #randomize the list
# random.shuffle(wordlist)
# #select the first word from the list and create a list of that item
# #word = ['p','a','j','a','m','a']
# word = list(wordlist[0])
#print word
word = get_word()
#empty list called display that will show user spaces of selected word
display = []
#empty list contains used letters
used = []
#adds the word to display
#display = ['p','a','j','a','m','a']
display.extend(word)
#adds guessed letter to used list
used.extend(display)
#iterate through display and replace it with '__'
#display = ['__', '__', '__', '__','__','__','__']
for i in range(len(display)):
display[i] = '_'
#'prettify' what the user sees
#removes spaces from display by converting list into string
#__ __ __ __ __ __
print (' '.join(display))
print ()
def main():
#create counter that stops when all letters have been guessed
counter = 0
#limit the number of incorrect guesses allowed
incorrect = 5
#keep asking user until all guesses have been used
while counter < len(word) and incorrect > 0:
guess = input("Please select a letter: ")
guess = guess.lower()
#shows correct guesses taken
print ("Number of correct guesses: {}".format(counter))
#iterates through letter in word
for i in range(len(word)):
#if letter guessed matches letter in word
if word[i] == guess and guess in used:
#display matched letter in its corresponding space
display[i] = guess
#increment counter
counter = counter + 1
#print item uses
used.remove(guess)
#wrong guess
if guess not in display:
incorrect = incorrect - 1
print ("Sorry, that's incorrect. You have", incorrect, "chances remaining.")
#prints string with matched letters
print (' '.join(display))
print ()
if counter == len(word):
print ("Great job! You found the word.")
else:
print ("Game over. You ran out of attempts.")
main()
| true |
174c043ce78e39a5c8d6796df6243ba944543f21 | nithyaraman/pythontraining | /chapter3/src/list_function.py | 1,978 | 4.375 | 4 | """ Use list functions append(), count(), extend(), index(),
insert(), pop(), remove(), reverse() and sort()"""
print"####Program using list function####"
print"1.append()"
list1 = ['1', '2', '3']
print list1
number = int(input("how many elements to appen"))
count = 0
while(count < number):
list1.append(raw_input("enter element:"))
count += 1
print list1
print "list is appended successfull"
print"\n\n2.count()"
object = raw_input("from the about list which you need to count?")
count_obj = list1.count(object)
print"it is present in %d times" % count_obj
print"no. of object counted successfully"
print "\n\n3.extend()"
number = int(input("how many elements to expand"))
counts = 0
while(counts < number):
list1.extend(raw_input("enter element:"))
counts += 1
print list1
print "list is extended successfully"
print "\n\n3.index()"
index_obj = raw_input("which element position want to know in about list")
if index_obj not in list1:
print " it is not presented in above list"
else:
position = list1.index(index_obj)
print "element located on position", position
print "\n\n4.insert()"
insert_obj = raw_input("enter the element you want to insert:")
obj_position = int(input("enter the position you want to insert:"))
list1.insert(obj_position, insert_obj)
print list1
print "element is inserted successfully"
print "\n\n5.pop"
pop_num = int(input("how many element you need to pop"))
num = 0
while(num < pop_num):
list1.pop()
num += 1
print list1
print "successfully %d element poped" % pop_num
print "\n\n6.remove()"
rm_obj = (raw_input("above list which you want to remove"))
if rm_obj not in list1:
print "object is not there"
else:
list1.remove(rm_obj)
print "object successfully removed"
print "list=", list1
print "\n\n7.revers"
list1.reverse()
print list1
print "list reversed successfully"
print "\n\n8.sort"
list1.sort()
print list1
print "list sorted successfully"
| true |
d2a8b064d4e1a4b7655746af4414d9af827c71a8 | Hholz/PythonTest | /HighFunctionTest/HighFunction_16.py | 265 | 4.15625 | 4 | """高阶函数"""
# 把函数作为参数传入,这样的函数称为高阶函数,函数式编程就是指这种高度抽象的编程范式
print(abs(-3))
print(abs)
f2 = abs;
print(f2(-4))
def add(x, y, f):
return f(x) + f(y)
print(add(-4, 5, abs))
| false |
03532fe330711edb4cc7a43dc643aa58d3e68a42 | Hholz/PythonTest | /functionTest/DefinedFunction_08.py | 1,054 | 4.15625 | 4 | """定义函数"""
import math
def my_abs(x):
if not isinstance(x, (int, float)):
raise TypeError('bad operand type')
if x >= 0:
return x
else:
return -x
print(my_abs(-2))
def nop():
pass
age = 1
if age >= 18:
pass
def move(x, y, step, angle=0):
nx = x + step * math.cos(angle)
ny = y - step * math.sin(angle)
return nx, ny
def quadratic(a, b, c):
# if not (isinstance(a,(int,float)) and isinstance(b,(int,float)) and isinstance(c,int,float))):
# raise TypeError('Pleae type right int or float')
if a == 0:
return ('相同,非二元一次方程式')
else:
r = b * b - 4 * a * c
if r < 0:
return ('复数')
else:
x1 = (-b + math.sqrt(r)) / (2 * a)
x2 = (-b - math.sqrt(r)) / (2 * a)
return x1, x2
a = float(input('请输入系数a:'))
b = float(input('请输入系数b:'))
c = float(input('请输入系数c:'))
print('%dx^2+%dx+%d=0的解为%s' % (a, b, c, quadratic(a, b, c)))
| false |
ca28dddd87bd0f2294dceef96587c5bf325c7fb6 | girishsj11/LeetCode_Exercise | /Program2.py | 903 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 16 20:11:59 2020
@author: giri
"""
def finding_longest_substring(string):
sub_strings = dict()
longest = 0
current_length = 0
for index,letter in enumerate(string):
if(letter not in sub_strings):
sub_strings[letter] = index
current_length += 1
if (current_length > longest):
longest = current_length
else:
current_length = index - sub_strings[letter]
sub_strings[letter] = index
return longest
if __name__ == "__main__":
string = str(input("Enter the input string to find its longest substring without repeatating chars : "))
print("longest substring value without repeatating chars is '{}' among the input string is '{}' ".format(finding_longest_substring(string),string))
| true |
1dce72bca492d48e4df09cd73c2999108ed572eb | ethanswcho/SudokuSolver | /helpers/possible_values/get_possible_square_values.py | 477 | 4.25 | 4 | """
Given a cell, return possible values relative to the 3x3 square it is part of
"""
import math
possible_values = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
def get_possible_square_values(cell, input):
# Grab values within same row/col (depending on mode chosen) that are solved (numbers as value)
solved_values = [x["value"] for x in input if x["square"] == cell["square"] and x["value"] != "x"]
return set(possible_values) - set(solved_values)
| true |
99eb400f59e4040b0815ffb2cb5e77697944e654 | hasandgursoy/Python_Zero_To_Hero | /11-Listler/listSlicing.py | 587 | 4.25 | 4 | # LIST SLICING - LİSTE DİLİMLEME
liste = ['a', 'b', 'c', 'd', 'e', 'f']
print(liste[2:5])
print(liste[0:4])
print(liste[0:])
# Liste Kopyalamak list[:] = Bu kopyala demektir.
yeni_liste = liste[:]
yeni_liste
print(yeni_liste)
baska_liste = liste[:]
baska_liste
print(baska_liste)
# Liste 1 ve 2 elemanlarını değiştir.
liste[1:3] = ['hasan', 'mehmet']
print(liste)
# ID YONTEMI
# Python'da tüm nesneler bir 'id' ile tutulur
# ID degeri -> id() fonksiyonu ile bulunur.
# Liste değişkenlerin ıd sini alalım.
print(id(liste))
print(id(yeni_liste))
print(id(baska_liste)) | false |
b3da99623883c587ad400787cadb798b6eb566e6 | Samikshaborkar17/Python | /Lagest number.py | 695 | 4.46875 | 4 | Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> num1 = float(input('Enter the first number: '))
Enter the first number: 6
>>> num2 = float(input('Enter the second number: '))
Enter the second number: 7
>>> num3 = float(input('Enter the third number: '))
Enter the third number: 8
>>> if(num1>num2) and (num1>num3):
print(num1,'is largest of all the three numbers')
elif(num2>num1) and (num2>num3):
print(num2,'is largest of all the three numbers')
else:
print(num3,'is largest of all the three numbers')
8.0 is largest of all the three numbers
>>> | true |
dc423dc1880cd0e13442f6a63f439624c1be6e7e | Samikshaborkar17/Python | /Odd even.py | 384 | 4.21875 | 4 | Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> num = int(input(' Enter the number: '))
Enter the number: 5
>>> if(num%2)== 0:
print(' The number is an even number')
else:
print(' The number is an odd number')
The number is an odd number
>>> | true |
056b56b80dac6273e9a386e40be6ab89cd4c26a1 | amey-joshi/python_training | /happy_num.py | 981 | 4.1875 | 4 | #!/usr/bin/python3
def get_digits(n):
"""Returns the digits in the argument as a list."""
if type(n) != type(1):
raise ValueError(f"{n} is not an integer")
if n < 0:
n = -n
digits = []
while n%10 != n:
digits.append(n%10)
n = n // 10
digits.append(n)
return digits
def is_happy(n):
"""Checks if an integer is a happy number. If the integer is negative, its absolute
value is considered.
ValueError is raised if the argument is not an integer."""
ss = [] # Sum of squares of digits
n = sum([d**2 for d in get_digits(n)])
ss.append(n)
result = True
while n != 1:
n = sum([d**2 for d in get_digits(n)])
if n in ss:
result = False
break
else:
ss.append(n)
return result
for n in range(1, 50):
if is_happy(n):
print(f"{n} is a happy number.")
else:
print(f"{n} is not a happy number.")
| true |
13ce5bcb26acda5c7471a8981ca8dd7060281f87 | kuroneko17/pythonPractice | /ProgramCode/printTable.py | 959 | 4.28125 | 4 | #! python3
# printTable.py
"""
编写一个名为 printTable()的函数,它接受字符串的列表的列表,将它显示在组
织良好的表格中, 每列右对齐。假定所有内层列表都包含同样数目的字符串。例如,
该值可能看起来像这样:
apples Alice dogs
oranges Bob cats
cherries Carol moose
banana David goose
"""
def printTable(tableList):
# tableList[0][0] tableList[1][0]
# tableList[0][1]
lengthList = []
for i in tableList:
length = 0
for j in i:
if len(j) > length:
length = len(j)
lengthList.append(length)
for i in range(0, len(tableList[0])):
for j in range(0, len(tableList)):
print(tableList[j][i].rjust(lengthList[j]), end = ' ')
# print(tableList[j][i], end = ' ')
print()
tableData = [
['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']
]
printTable(tableData)
| false |
9b0c2401525dc2e5eed58a430bba30db516f6bff | kuroneko17/pythonPractice | /ProgramCode/classProgramTest/Restaurant.py | 1,708 | 4.125 | 4 | # Restaurant.py
# 创建Restaurant类
class Restaurant():
# 初始化方法
def __init__(self, restaurantName, cuisineType):
self.name = restaurantName
self.cuisineType = cuisineType
self.numberServed = 0
# 打印餐厅描述
def describeRestaurant(self):
print('There is a restaurant named {}.And it style is {}'.format(self.name, self.cuisineType))
# 打印餐厅正在营业中
def openRestaurant(self):
print('Restaurant {} is opening.'.format(self.name))
# 设置初始用餐人数
def setNumberServed(self, number):
self.numberServed = number
def getNumberServed(self):
return self.numberServed
# 增加用餐人数
def incrementNumberServed(self, number):
if number >= 0:
self.numberServed += number
else:
return 'Number must be positive.'
"""
restaurant = Restaurant('restaurant', 'ChineseFood')
print(restaurant.name)
print(restaurant.cuisineType)
restaurant.describeRestaurant()
restaurant.openRestaurant()
restaurant.setNumberServed(23)
print(restaurant.getNumberServed())
restaurant.incrementNumberServed(12)
print(restaurant.getNumberServed())
"""
class IcecreamStand(Restaurant):
def __init__(self, restaurantName, cuisineType, flavors):
super().__init__(restaurantName, cuisineType)
self.flavors = flavors
def getAllFlavor(self):
allFlavor = []
for flavor in self.flavors:
flavorIcecream = flavor + ' ice-cream'
allFlavor.append(flavorIcecream)
return allFlavor
def showAllIcecream(self):
allFlavorIcecream = self.getAllFlavor()
print('All Ice-cream:')
for icecream in allFlavorIcecream:
print(icecream)
iceCreamStand = IcecreamStand('ice-cream stand', 'ice-cream', ['apple', 'banana', 'mochi'])
iceCreamStand.showAllIcecream() | false |
dace77ac78bd23f5bb476b569b367049f8912586 | mrgoutam/PythonAlgorithm | /venv/DS/BinarySearchTreeDataStructure/01_Basics/01_search_insert.py | 1,559 | 4.1875 | 4 | def search(root, key):
if root is None or root.val == key:
return root
# Key is greater then root's key
if root.val < key:
return search(root.right, key)
# Key is smaller than root's key
return search(root.left, key)
"""
Steps:
1. Start from root
2. Compare the inserting element with root, if less than root then recurse for left,
else recurse for right.
3. If element to search is found anywhere, return true, else return false.
"""
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def insert(root, key):
mNode = Node(key)
if root is None:
root = mNode
else:
if root.val < mNode.val:
if root.right is None:
root.right = mNode
else:
insert(root.right, key)
else:
if root.left is None:
root.left = mNode
else:
insert(root.left, key)
def in_order(root):
if root:
in_order(root.left)
print(root.val, end=' ')
in_order(root.right)
# Driver program to test the above functions
# Let us create the following BST
# 50
# / \
# 30 70
# / \ / \
# 20 40 60 80
r = Node(50)
insert(r, 30)
insert(r, 20)
insert(r, 40)
insert(r, 70)
insert(r, 60)
insert(r, 80)
print('-----------Traversal-----------')
in_order(r)
print('')
print('-------------search 2--------------')
print(search(r, 2))
print('-------------search 70--------------')
print(search(r, 70))
| true |
b5a4f03c010965c116b43ee7f2731902079a25ca | ryanblack/python | /python practice/twostrings.py | 937 | 4.21875 | 4 | def twoStrings(s1, s2):
if [i for i in s1 if i in s2]:
return 'YES'
else: return 'NO'
if __name__ == '__main__':
s1='Con'
s2='Aha'
print(twoStrings(s1, s2))
'''
Given two strings, determine if they share a common substring. A substring may be as small as one character.
For example, the words "a", "and", "art" share the common substring . The words "be" and "cat" do not share a substring.
Function Description
======================
Complete the function twoStrings in the editor below. It should return a string, either YES or NO based on whether the strings share a common substring.
twoStrings has the following parameter(s):
s1, s2: two strings to analyze .
Input Format
============
The first line contains a single integer p, the number of test cases.
The following p pairs of lines are as follows:
The first line contains string s1.
The second line contains string s2. ''' | true |
2441f3e60b7043dff78ca3cc753fc7f430e84c5f | dlondonmedina/intro-to-programming-python-code | /exercises/4-2/2-square/fun.py | 548 | 4.28125 | 4 | # experiment with forward/backward and left/right
from turtle import *
def draw_it(t,pen_dir,dir_num,angle_dir,angle_num):
if pen_dir == "forward":
t.forward(dir_num)
else:
t.backward(dir_num)
if angle_dir == "right":
t.right(angle_num)
else:
t.left(angle_num)
bgcolor('black')
bob = Turtle() # create a turtle named bob
bob.color('red', 'yellow') # define pen and fill colors
bob.begin_fill()
for i in range(4):
draw_it(bob,"forward",100,"left",90)
bob.end_fill()
done() #screen will stay open until you close it
| true |
0da16b2ae7c15f01a8039bca6a21880c0197e823 | Saransh-kalra/Python-Labs | /Python/conversion_2.py | 403 | 4.53125 | 5 | #introduce the program
print("welcome to the farheneit to celcius conversion program")
#ask the use for a farheneit temperature
degree_f=float(input("please enter a farheneit temperature: "))
#convert the user's input to celciuys by dividing it by 1.8 and subtracting 32
degree_c=float((degree_f - 32)/1.8)
#print out the result of the calculation
print(degree_f, "farheneit is ", degree_c, "celcius" )
| true |
6d3fc84fffeb532ce4fe3c53b8602b7cfe0d68cc | qbuch/python_szkolenie | /homework_8/caesars_code/caesars.py | 1,079 | 4.25 | 4 | # Napisz program który wprowadzony przez użytkownika tekst zakodje wg szyfru cezara
#* dodaj funkcjonalność dekodowania zaszyfrowanej wiadomości.
pass_to_encrypt = (input('Enter a string you would like to encrypt: ')) #.lower()
def encrypt_password():
char_list = list(pass_to_encrypt)
change_char_ascii = [ord(i) for i in char_list]
encrypt_ascii = [i + 3 for i in change_char_ascii]
encrypted_letters = [chr(i) for i in encrypt_ascii]
encrypted_pass = ''.join(str(i) for i in encrypted_letters)
return encrypted_pass
pass_to_decrypt = encrypt_password()
def decrypt_password():
char_list = list(pass_to_decrypt)
change_char_ascii = [ord(i) for i in char_list]
decrypt_ascii = [i - 3 for i in change_char_ascii]
decrypted_letters = [chr(i) for i in decrypt_ascii]
decrypted_pass = ''.join(str(i) for i in decrypted_letters)
return decrypted_pass
print(encrypt_password())
print(decrypt_password())
# print(user_input)
# print(change_char_ascii)
# print(encrypt_ascii)
# print(encrypted_letters)
# print(encrypted_pass)
| false |
33c00e61e72e9cc3f73f50ec9f4baf08c51f53cb | xiemeigongzi88/Python_Beginners | /Think Python 2 version/5_chapter Conditionals and recursion .py | 2,647 | 4.15625 | 4 | 5_chapter Conditionals and recursion
page 80
5.1 Floor division and modulus 地板除和求模
>>> minutes=105
>>> minutes/60
1.75
>>> minutes//60
1
>>> hour =minutes//60
>>> remainder=minutes-hour*60
>>> remainder
45
an alternative is to use the modulus operator %
>>> remainder=minutes%60
>>> remainder
45
check whether one number is divisible by another
-- if x%y is 0 then x is divisible by y
page 81
5.2 Boolean expressions
>>> 5==5
True
>>> 5==6
False
>>> 5=6
SyntaxError: can't assign to literal
True and False are special values that belong to the type bool; they are not strings
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
x!=y
x>y
x<y
x>=y
x<=y
page 82
5.3 Logical operators
there are three logical operators:
and or not
the operands of the logical operators should be boolean expressions but python is not very strict
any nonzero number is interpreted as True
>>> 42 and True
True
>>> 0 and True
0
>>> 0 or True
True
>>> not 0
True
>>> 1 and 2
2
>>> 0 and 2
0
## so strange
page 83
5.4 Conditional execution
PAGE 5.5
5.5 alternative execution
if else
5.6 Chained conditionals 链式条件
if x<y:
print('x is less than y')
elif x>y:
print('x is greater than y')
else:
print('x and y are equal')
page 85
5.7 Nested conditionals 嵌套条件
if x==y:
print('x and y are equal')
else:
if x<y:
print('x is less than y')
else:
print('x is greater than y')
if x>0:
if x<10:
print('x is a positive single-digit number')
get same effect with the and operator
if x>0 and x<10:
print('x is a positive single-digit number')
page 87
5.8 Recursion
def countdown(n):
if n<=0:
print('Blastoff!')
else:
print(n)
countdown(n-1)
def print_n(s,n):
if n<=0:
return
print(s)
print_n(s,n-1)
s='python is good!'
n=4
print_n(s,n)
page 90
5.10 infinite recursion
def recurse():
recurse()
recurse()
page 91
5.11 Keyboard input
text=input()
input: Eric
'Eric'
name=input('what ... is your name?\n')
#name=input('what ... is your name?\n')
#text=input()
prompt="What ... is the airspeed velocity of an unladen swallow?\n"
speed=input(prompt)
## input() 得到是字符串 ‘。。。’ 需要转化
OUT:
What ... is the airspeed velocity of an unladen swallow?
42
>>> int(speed)
42
>>> speed
'42'
page 95
5.14 EXC
| true |
d01d0ca983956ecfe01d67016a91b1236a15bee5 | StevenCReal/PythonCode | /input_while.py | 953 | 4.25 | 4 | name = input("Please enter your name: ")
print("Hello, " + name + "!")
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "
name = input(prompt)
print("\nHello, " + name + "!")
age = input("How old are you? ")
if int(age) >= 18: # need 'int()' to convert the input to number
print("You're an adult now! ")
value = 0
while value <= 5:
print(str(value) + " is not big enough!")
value += 1
print(value)
mirror = ""
prompt = "I'll repeat your word."
prompt += "\nIf you don't want to continue, enter 'quit'."
print(prompt)
while mirror != 'quit':
mirror = input()
if mirror != 'quit':
print(mirror)
# 标志
active = True
prompt = "I'll repeat your word."
prompt += "\nIf you don't want to continue, enter 'quit'."
print(prompt)
mirror = ""
while active:
mirror = input()
if mirror == 'quit':
active = False
else:
print(mirror)
| true |
87837c9e62889591e6364256af0a163d5efcd3ff | davidz-repo/recruiting-exercises | /inventory-allocator/src/util.py | 2,349 | 4.34375 | 4 | #
# Utility for generating random test cases (Python 3)
#
# Qixiang Zhang (David)
# qixianz@uci.edu
# https://www.linkedin.com/in/dzhangdev
import random
PRODUCTS = [
'apple ',
'banana ',
'chicken ',
'dragons ',
'eggos ',
'fajita ',
'granola ',
'hummus ',
'icecream',
'jalapeno',
]
TOTAL_NUM_PRODUCTS = len(PRODUCTS)
ORDER_MAX_QUANTITY = 5
MAX_NUM_WAREHOUSES = 10 # TOTAL_NUM_PRODUCTS * ORDER_MAX_QUANTITY
MAX_WAREHOUSE_PRODUCT_COUNT = ORDER_MAX_QUANTITY * 2
WAREHOUSE_PREFIX = 'WareHouse_'
def generate_order(order_quantity=ORDER_MAX_QUANTITY):
""" Generates a list of products with quantity """
order = dict()
num_products = random.randint(0, TOTAL_NUM_PRODUCTS + 1)
for _ in range(num_products):
item = PRODUCTS[random.randint(0, TOTAL_NUM_PRODUCTS - 1)]
quantity = random.randint(1, order_quantity)
order[item] = quantity if item not in order else quantity + order[item]
return order
def generate_warehouses():
""" Generate a list of warehouse with dictionary of inventories """
warehouses = []
num_warehouses = random.randint(0, MAX_NUM_WAREHOUSES)
for i in range(num_warehouses):
name = "{}{}".format(WAREHOUSE_PREFIX, i)
inventory = generate_order(MAX_WAREHOUSE_PRODUCT_COUNT)
warehouses.append({'name':name, 'inventory':inventory})
return warehouses
def show_inputs(order, warehouse_inventories, test_num=None):
""" Print the input parameters in terminal """
print("-----------------------------------------------")
if test_num:
print("Random Test {}:".format(test_num))
print("\tOrder: ")
for k, v in order.items():
print("\t\t\t{}:\t{}".format(k, v))
print("\tWarehouses: ")
for wh in warehouse_inventories:
print("\t\t{}".format(wh['name']))
for k, v in wh['inventory'].items():
print("\t\t\t{}:\t{}".format(k, v))
def show_output(allocation):
""" Print the allocation result in terminal """
if not allocation:
print("\tNo Allocation!")
else:
print("\tAllocation: ")
for warehouse in allocation:
for name, inventory in warehouse.items():
print("\t\t{}".format(name))
for k, v in inventory.items():
print("\t\t\t{}:\t{}".format(k, v))
| true |
b669dfb3211fd8c5f790d81da51ad1a68d1e34bf | PranoopMutha/PythonDeepLearning | /ICP/ICP 1/ICP 1.py | 1,199 | 4.375 | 4 | from math import sqrt
########## Dynamic Input ################
num1String = input('Please enter an integer: ')
num2String = input('Please enter a second integer: ')
########## Part 1 - Reversing a Number##########
rev = num1String[::-1]
print('The original number is :',num1String)
print('The number obtained by reversing the digits is:',rev)
num1 = int(num1String)
num2 = int(num2String)
################## Part 2 - Arithmetic Operations ####################
print('The sum of square root of the two numbers is',sqrt(num1)+sqrt(num2))
print (num1,' plus ',num2,' equals ',num1+num2)
print (num1,' multiplied by ',num2,' equals ',num1*num2)
print (num1,' divided by ',num2,' equals ',num1/num2)
print (num1,' is greater than ',num2,' by ',num1-num2)
################ Part 3 - Identifying Letters, words and digits in a given string ############
saminp = "Python and Deep Learning CS 5590 5542"
words = len(saminp.split())
digits = sum(c.isdigit() for c in saminp)
letters = sum(c.isalpha() for c in saminp)
print('Number of digits in the string are:',digits)
print('Number of letters in the string are:',letters)
print('Number of words in the string are:',words)
print ('Thank you. END') | true |
2e965a7613772764821c8bfd460e4fc043b3f4d1 | dylanPMurphy/Functions_Basic_2 | /functionsBasic2.py | 2,511 | 4.3125 | 4 |
# Countdown - Create a function that accepts a number as an input. Return a new list that counts down by one, from the number (as the 0th element) down to 0 (as the last element).
# Example: countdow(n(5) should return [5,4,3,2,1,0]
def countdown(num):
output = []
for i in range(num,-1,-1):
output.append(i)
return output
print(countdown(234))
# Print and Return - Create a function that will receive a list with two numbers. Print the first value and return the second.
# Example: print_and_return([1,2]) should print 1 and return 2
def print_and_return(list):
print(list[0])
return list[1]
print(print_and_return([2,4]))
# First Plus Length - Create a function that accepts a list and returns the sum of the first value in the list plus the list's length.
# Example: first_plus_length([1,2,3,4,5]) should return 6 (first value: 1 + length: 5)
def first_plus_length(list):
sum = 0
for i in range(0, len(list)):
sum+=list[i]
print(f"first value: {list[0]} + length:{len(list)}")
first_plus_length([3425,35,2,134,5,67,34,2,342,5,35,62,4457,45])
# Values Greater than Second - Write a function that accepts a list and creates a new list containing only the values from the original list that are greater than its 2nd value. Print how many values this is and then return the new list. If the list has less than 2 elements, have the function return False
# Example: values_greater_than_second([5,2,3,2,1,4]) should print 3 and return [5,3,4]
# Example: values_greater_than_second([3]) should return False
def values_greater_than_second(list):
itemsGreaterThanSecond = []
if len(list) < 2:
return False
secondValue = list[1]
for i in range(0,len(list)):
if list[i] > secondValue:
itemsGreaterThanSecond.append(list[i])
print(len(itemsGreaterThanSecond))
return itemsGreaterThanSecond
print(values_greater_than_second([3425,35,2,134,5,67,34,2,342,5,35,62,4457,45]))
# This Length, That Value - Write a function that accepts two integers as parameters: size and value. The function should create and return a list whose length is equal to the given size, and whose values are all the given value.
# Example: length_and_value(4,7) should return [7,7,7,7]
# Example: length_and_value(6,2) should return [2,2,2,2,2,2]
def length_and_value(length, value):
output = []
for i in range(0,length):
output.append(value)
return output
print(length_and_value(4,7)) | true |
41aa5ebdafa1597259d5ef796fee8e711ca67fc1 | fto0sh/100DaysOfCode | /Day14.py | 671 | 4.125 | 4 | Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> thislist=["A","B","C","D","E"]
>>> print(thislist[1:3])
['B', 'C']
>>> thislist = ["apple", "banana", "cherry"]
>>> if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
Yes, 'apple' is in the fruits list
>>> thislist=["python"]*4
>>> print(thislist)
['python', 'python', 'python', 'python']
>>> thislist1=["ahamed","khald","omar"]
>>> thislist2=["sara","fatimah","ftosh"]
>>> thislist3=thislist1+thislist2
>>> print(thislist3)
['ahamed', 'khald', 'omar', 'sara', 'fatimah', 'ftosh']
>>>
| false |
67a31cc7c00ead1cc4d9b3854288fdb1ea7e1ae0 | SpyrosDellas/learn-python-the-hard-way | /src/ex37a.py | 1,404 | 4.40625 | 4 | # Accessing nested list elements
al = [1, 2, 'Spyros', 3]
ab = [al, al]
print "\n", ab
print ab[1][2]
# Modifying a list while looping on its elements
ac = ["alpha", "gamma", "european"]
print "\n", ac
for i in ac[:]: # loops over a slice copy of the list
if len(i) > 5:
ac.insert(0, i)
print ac
# Playing with functions and function names
def fib(upper_limit, dummy1 = None, dummy2 = None):
result = []
a, b = 0, 1
while a + b < upper_limit:
result.append(b)
a, b = b, a + b
return result
print fib(500, dummy2 = "dummy")
fibonacci = fib # Name fibonacci now is linked to fib
print fibonacci(upper_limit = 500)
# Using the raise statement
# raise ValueError("I don't like that!")
print "Let's continue...\n"
# Playing with dictionaries. Remember dictionaries are intrinsically unsorted
dict1 = {"name": "Spyros", "surname": "Dellas", "age": 37}
dict2 = dict(a = 1, b = 2, c = 3, d = 4)
dict3 = {x: x ** 2 for x in range(5)}
print dict1
print dict2
print dict3
print dict1['name']
print dict1.keys()
print sorted(dict1.keys()), "\n"
# Unpacking argument lists and dictionaries for a function call
# EXAMPLE 1 - UNPACKING AN ARGUMENT LIST
list1 = [2, 10, 2]
print range(*list1)
# EXAMPLE 2 - UNPACKING AN ARGUMENT DICTIONARY
def dummy_a(surname, name, age):
print "My name is", name, surname, "and I'm", age, "years old.\n"
dummy_a(**dict1)
| true |
eb3980e363b0befcf4e8ffb8a3099a8f0f728418 | SpyrosDellas/learn-python-the-hard-way | /src/ex37b.py | 2,277 | 4.5625 | 5 | # Lambda expressions
# EXAMPLE 1 - A FUNCTION RETURNING A LAMBDA FUNCTION
def incrementor(step):
return lambda x: x + step
print incrementor(0.1)(1000), "\n"
dum1 = incrementor(0.1); # dum1 is now equv. to lambda x: x + 0.1
print dum1(1000), "\n"
# EXAMPLE 2 - PASSING A LAMBDA EXPRESSION AS A FUNCTION ARGUMENT
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
# Sort above list using .sort(key = ..... ), which extracts a comparison key
# from each element in the list. key must be an one argument function
print pairs
pairs.sort(key = lambda element: element[1])
print pairs
# Using lists as stacks, i.e. adding/removing elements from the end
stack1 = [1, 3, 5]
print "\n", stack1
stack1.append(7)
stack1.append(9)
print stack1
stack1.pop()
stack1.pop()
print stack1
# Using lists as queues
# Althougn we can use .insert and .pop for adding/removing elements at
# the beginning of the list this operation is not memory efficient.
# We should use collections.deque(), creating an efficient "deque" object
# which is a generalization of stacks and queues
from collections import deque
queue1 = deque(["Alpha", "Beta", "Gamma", "Delta"])
print "\n", queue1
queue1.appendleft("Zero")
queue1.append("Epsilon")
print queue1
queue1.popleft()
queue1.pop()
print queue1
# Using filter(function, sequence)
def func1(x):
return x % 5 == 0 or x % 7 == 0
list1 = range(101)
tup1 = tuple(list1)
print "\n", filter(func1, list1)
print "\n", filter(func1, tup1)
# We can also do it in one line of code, using a lambda function
print "\n", filter(lambda x: (x % 5 == 0 or x % 7 == 0), tup1)
# Using map(function, sequence [,sequence]*n)
# EXAMPLE 1 - USING MAP WITH ONE SEQUENCE
def cube(x):
return x ** 3
print "\n", map(cube, range(11))
# We can also do it in one line of code, using a lambda function
print "\n", map(lambda x: x ** 3, range(11))
# EXAMPLE 2 - USING MAP WITH TWO SEQUENCES
def func2(a, b):
return a + 2 * b
print "\n", map(func2, range(11), range(11, 22))
# We can also do it in one line of code, using a lambda function
print "\n", map(lambda a, b: (a + 2 * b), range(11), range(11, 22))
# Using reduce(function, sequence)
def factorial(x):
return reduce(lambda a, b: a * b, range(1, x + 1))
print "\n", factorial(5)
| true |
e80f30a95f36e4258d04b194cc9c5aff3a0c67c0 | Turc0/Random_Number_Game | /random_num.py | 1,284 | 4.25 | 4 | import random
import time
"""
This program is game that generates a random number for the user
to guess. The user will have 5 chances to guess a number between
0 - 100.
"""
def start_game():
print("Welcome to my random number guessing game!")
start = input("When you are ready to play, enter 'Ready': \n")
if start != 'Ready':
print("Please enter 'Ready' ")
start_game()
def play_game():
num_of_guesses = 0
print("Generating random value between 0 and 100...")
time.sleep(5)
random_num = random.randint(0, 100)
print("Let's play! You only have 5 guesses!")
for x in range(5):
guess = int(input("Please enter your guess: "))
if int(guess) == random_num:
print(f"You guessed the right value, {random_num} in {num_of_guesses} turns!\n")
break
elif x == 4:
print("You ran out guesses but you can try again!")
print(f"The correct number was {random_num}\n")
break
else:
if guess < random_num:
print("Guess again but higher!\n")
else:
print("Guess again but lower!\n")
num_of_guesses += 1
start_game()
play_game()
| true |
77ab37099860ad3b8159c32be0271f1fe05e6d66 | andres-halls/IAPB13_suvendatud | /Kodutoo_5/Kodutoo_5_Andres.py | 2,510 | 4.34375 | 4 | def file_get_words(*fileNames):
'''
Takes a variable number of fileNames and returns
a two-dimensional list of words for each file.
@arg *fileNames - variable number of file names.
@returns list of words for each file
'''
words = []
for fileName in fileNames:
file = open(fileName)
words.append(words_in_file(file))
file.close()
return words
#######################################
def words_in_file(file):
'''
Returns list of words in a file.
@arg file - handle to file
@returns list of words
'''
file_contents = file.read()
words = []
word = ""
for char in file_contents:
char = char.lower()
if char.isalpha():
word += char
else:
if word != "":
words.append(word)
word = ""
if word != "":
words.append(word)
return words
#######################################
def print_results(functions, printStrs):
'''
Higher-order function that calls variable number of functions and
prints the results with the corresponding printStr appended from printStrs.
@arg functions - list of functions to call
@arg printStr - list of strings to append to print of each result
@returns no return value
'''
for i, function in enumerate(functions):
result = function()
print(result, printStrs[i])
#######################################
def main():
file1 = "scarlet.txt"
file2 = "hound.txt"
words = file_get_words("scarlet.txt", "hound.txt")
words_unique = [set(words[0]), set(words[1])]
functions = [
lambda: len(words[0]), lambda: len(words[1]),
lambda: len(words_unique[0]), lambda: len(words_unique[1]),
lambda: len(words_unique[0] | words_unique[1]),
lambda: len(words_unique[0] - words_unique[1]),
lambda: len(words_unique[1] - words_unique[0]),
lambda: len(words_unique[0] & words_unique[1])
]
printStrs = [
"words in file " + file1, "words in file " + file2,
"unique words in file " + file1, "unique words in file " + file2,
"total unique words in files " + file1 + " and " + file2,
"unique words in " + file1 + " not present in " + file2,
"unique words in " + file2 + " not present in " + file1,
"unique words that are in both " + file1 + " and " + file2
]
print_results(functions, printStrs)
if __name__ == "__main__":
main() | true |
708741a9f5674425f9d48116cede2d85b9708bf7 | Nivethika7623/sample2 | /b34.py | 935 | 4.1875 | 4 | import re
line = (" A Turing machine is a device that manipulates "
"symbols on a strip of tape according to a table "
"of rules. Despite its simplicity, a Turing machine "
"can be adapted to simulate the logic of any computer "
"algorithm, and is particularly useful in explaining "
"the functions of a CPU inside a computer. The 'Turing'"
" machine was described by Alan Turing in 1936, who "
"called it an""a(utomatic)-machine"". The Turing "
"machine is not intended as a practical computing "
"technology, but rather as a hypothetical device "
"representing a computing machine. Turing machines "
"help computer scientists understandthe limits of "
"mechanical computation.")
print (line)
print ()
count = len(re.findall(r'\.', line))
print ("The number of lines in this paragraph:", count)
| true |
0ee6aef5f61539668c624a69dfa37657486fbddd | tgpethan-alt/pyaaa | /band_name_generator.py | 755 | 4.15625 | 4 | print("Welcome to the Band name generator!")
# Overcomplicated functions to prevent blank names
def request_city():
city = input("Enter your birth city:\n") # Request City
if city == "":
print("City cannot be blank!")
return request_city() # City is blank, loop back and ask again
else:
return city
def request_pet_name():
pet_name = input("Enter the name of one of your pets:\n") # Request pet name
if pet_name == "":
print("Pet name cannot be blank!")
return request_pet_name() # Pet name is blank, loop back and ask again
else:
return pet_name
city = request_city()
pet_name = request_pet_name()
print("Your band name is: {0} {1}".format(city, pet_name)) | true |
1686cfa631ccbeb1b0b5ea4cdc45f3c195d9693b | alexkillgur/python_demo | /HT_1/14.py | 375 | 4.25 | 4 | """
14. Write a script to generate and print a dictionary that contains a number (between 1 and n) in the form (x, x*x).
Sample Dictionary ( n = 5) :
Expected Output : {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
"""
n = 5
dic = {x: x ** 2 for x in range(1, n + 1)}
print ("Сгенерированный словарь из {} значений: {}".format(n, dic))
| true |
743fd5db699c4a7cfd987e9c4384995b946bafb8 | Siwangi/Class | /inheritance.py | 1,404 | 4.5 | 4 | class Parent:
def __init__(self, last_name, eye_color):
print("Parent Constructor Called")
self.last_name = last_name
self.eye_color = eye_color
def show_info(self):
print("Last name: ", self.last_name)
print("Eye Color: ", self.eye_color)
class Child(Parent):
def __init__(self, last_name, eye_color, number_of_toys):
print("Child Constructor Called")
Parent.__init__(self, last_name, eye_color) #inherit the constructor from parent
self.number_of_toys = number_of_toys
def show_info(self):
print("Last name: ", self.last_name)
print("Eye Color: ", self.eye_color)
print("Number of toys:", str(self.number_of_toys))
" #Instance of Parent class "
billy_cyrus = Parent("cyrus", "blue")
" #def one more function in parent class and call it "
billy_cyrus.show_info()
print(billy_cyrus.last_name)
" #Instance of Child class "
miley_cyrus = Child("cyrus", "blue", 5)
"""Method Overriding"""
# Case 1 - If the show_info method/function is in parent & not child : Child class will call parent other functions(its not in child but can inherit from parent) :
# Case 2 - If the show info method/function is in child with added info, it will call child's info method and not the parent :
miley_cyrus.show_info()
print(miley_cyrus.last_name)
print(miley_cyrus.number_of_toys)
| true |
f8aad70424e1e61706c517810783264688b95d2d | rebeccanjagi/bootcamp-7 | /day_2/super_sum.py | 283 | 4.1875 | 4 | def super_sum(A):
'''
Takes a list A, and :
-Halves every even number
-Doubles every odd number
And returns the sum of all.
'''
result = 0
for list_value in A:
if list_value % 2 == 0:
result += list_value / 2
else:
result += list_value * 2
return result
| true |
f6bb3a89c31f307e91da613e30b60be28b8689f4 | rebeccanjagi/bootcamp-7 | /andela_labs/reverse_string.py | 420 | 4.5 | 4 | def reverse_string(string):
'''
A function, reverse_string(string), that returns the reverse of the string provided.
If the reverse of the string is the same as the original string,
as in the case of palindromes, return true instead.
'''
rev_string = ""
if string is not "":
for b in string:
rev_string = b+rev_string
if rev_string == string:
return True
return rev_string
else:
return None
| true |
fcfef06d857479f9b18cb75d8f3634bc21c5dd28 | shaoweigege/hello-world-python3 | /exercicio_py/ex0045_fatorial_modulo.py | 219 | 4.21875 | 4 | '''
Usuário informa um número inteiro e programa retorna o seu fatorial; usando o módulo.
'''
from math import factorial
num = int(input('Digite um número inteiro: '))
f = factorial(num)
print(f'Fatorial: {f}')
| false |
4ec1b15ccf5d0fe8d9464ad90720ac3e76ca69fc | shaoweigege/hello-world-python3 | /exercicio_py/ex0035_tabuada_multi_for.py | 237 | 4.25 | 4 | '''
Usuário digita um número e programa retorna a tabuada de multiplicação desse número, usando o laço for.
'''
num = float(input('Digite um número: '))
i = 1
for i in range(i, 10):
print(f'{num:4} x {i} = {num*i}')
print()
| false |
70c09d7a56274828f03168bec199b7c2f2820aa7 | shaoweigege/hello-world-python3 | /exercicio_py/ex0029_quant_caractere_string.py | 646 | 4.21875 | 4 | '''
Usuário informa um nome completo (nome e sobrenome) e
programa retorna quantos letras o nome completo possui (excluindo os espaços) e
quantas letras o primeiro nome possui.
'''
nome_completo = input('Digite seu nome completo: ')
#count(' ') conta os espaços em branco
#len() retorna o tamanho da string
tamanho_completo = len(nome_completo) - nome_completo.count(' ')
print(f'Seu nome completo possui: {tamanho_completo} letras.')
#find() retorna a posição de um caractere
# nesse caso queremos enccontrar o primeiro espaço
posicao_nome = nome_completo.find(' ')
print(f'Seu primeiro nome possui: {posicao_nome} letras.')
print()
| false |
dd15b449a5e7edd75c9562961d3acdf38f3c1ec8 | shaoweigege/hello-world-python3 | /exercicio_py/ex0021_area_tinta.py | 511 | 4.3125 | 4 | '''
Usuário informa a altura e largura de uma parede que será pintada.
Programa retorna a área e a quantidade de tinta necessária para pintar essa área,
sabendo que o rendimento da tinta é de 2m² por litro.
'''
alt = float(input('Digite a altura(m): '))
larg = float(input('Digite a largura(m): '))
#calculando área
area = alt * larg
print(f'Área: {area}m²')
quant = area / 2
#.2f mostra apenas duas casas de ponto flutuante
print(f'Quantidade de tinta necessária: {quant:.2f} litros.')
print()
| false |
529b58e9e5ca69cbdab4ced4d87364cbb2960dc8 | shaoweigege/hello-world-python3 | /exercicio_py/ex0019_tabuada_multi.py | 437 | 4.4375 | 4 | '''
Usuário digita um número e programa retorna a tabuada de multiplicação desse número.
'''
num = float(input('Digite um número: '))
print(f'{num:4} x 1 = {num*1}')
print(f'{num:4} x 2 = {num*2}')
print(f'{num:4} x 3 = {num*3}')
print(f'{num:4} x 4 = {num*4}')
print(f'{num:4} x 5 = {num*5}')
print(f'{num:4} x 6 = {num*6}')
print(f'{num:4} x 7 = {num*7}')
print(f'{num:4} x 8 = {num*8}')
print(f'{num:4} x 9 = {num*9}')
print()
| false |
1ac4f2fd8707c7065738f2ee4d6768086607aa8a | shaoweigege/hello-world-python3 | /exercicio_py/ex0023_primeiro_ultimo_caractere_string.py | 380 | 4.1875 | 4 | '''
Usuário digita uma palavra ou frase e programa retorna o primeiro e o último caractere da string.
'''
msg = input('Digite uma palavra ou frase: ')
#posição inicial do primeiro caractere
print(f'Primeiro caractere: {msg[0]}')
#posição -1 indica que o caractere será contado detrás pra frente
# assim pegando o último
print(f'Último caractere: {msg[-1]}')
print()
| false |
330ac6b889a9e7347944fd0907228429c9b85b10 | shaoweigege/hello-world-python3 | /exercicio_py/ex0051_break.py | 332 | 4.21875 | 4 | '''
Usuário digita vários números e o programa retorna quantos foram digitados.
A condição de parada é quando for informado o número 999 (desconsiderar este da contagem).
'''
i = 0
while True:
num = float(input('Digite um número: '))
if num == 999:
break
i += 1
print(f'Foram digitados {i} números.')
| false |
08e50163d29d48a6274d471c78709b8a60aef45a | 24Red/APS-Python-Workshop | /workshop_scripts/Part 1/2_variables.py | 1,466 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created for APS Summer REU Python 3 Workshop
@author: victoriacatlett
"""
###############################################################################
# Task) Create and print 3 variables:
# the integer 2019, the float 6.7x10^-11, and the string "Hello there!"
#
# Write your code below
###############################################################################
# Task) Create a list of integers with 4 elements
# and a list of strings with 2 elements.
# Then, print the second value of each list.
#
# Write your code below
###############################################################################
# Task) Make a 2x3 array,
# then print the first element of the second row
#
# Write your code below
###############################################################################
# Task) From the dictionary below, the value for the key 'Count'
# is a list. Print the 2nd element of that list.
my_dictionary = {'Year':2020, 'School':'UTD', 'Count':[1,2,3]}
# Write your code below
###############################################################################
# Task) Determine what type of variable "test_variable" is,
# then print the result
test_variable = "1234.56"
# Write your code below
# Is it what you expected?
############################################################################### | true |
98897404625586c1b8b213ad21ec73a23c145cc3 | declan-wu/data-structure-algorithms | /Graphing/BFS.py | 1,160 | 4.28125 | 4 | # This article is excellent in explaining DFS and BFS: https://jeremykun.com/2013/01/22/depth-and-breadth-first-search/
import Graphing.Graph_ADT
def bfs(graph, start):
visited = []
queue = [start]
while queue:
vertex = queue.pop(0)
if vertex not in visited:
visited.append(vertex)
queue.extend(
set(graph.nodes[vertex].getConnections()) - set(visited))
return visited
def bfs_paths(graph, start, goal):
result = []
queue = [(start, [start])]
while queue:
(vertex, path) = queue.pop(0)
for nxt in set(graph.nodes[vertex].getConnections()) - set(path):
if nxt == goal:
result.append(path + [nxt]) # could use yield path + [nxt]
else:
queue.append((nxt, path + [nxt]))
return result
def shortest_path(graph, start, goal):
try:
return (bfs_paths(graph, start, goal))[0]
except StopIteration:
return None
g = Graph()
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.add_edge(1, 5)
g.add_edge(2, 3)
g.add_edge(3, 3)
g.add_edge(3, 5)
print(shortest_path(g, 0, 5))
| true |
9ca19e63d43c1597d50e2ee1c5e6136d107205d9 | Romulus83/python | /odd_number.py | 731 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 11 20:46:30 2020
@author: user
"""
"""
This Python function accepts a list of numbers and computes the product of all the odd numbers:(odd_number.py)
def productOfOdds(list):
result = 1
for i in list:
if i % 2 == 1:
result *= i
return result
Rewrite the Python code using map, filter, and reduce:
def productOfOdds(list):
return reduce(r_func, filter(f_func, map(m_func, list)))
"""
from functools import reduce
def productOfOdds(listt1):
return reduce(lambda x,y: x*y , list(filter(lambda a: a%2==1, list1)))
list1= map(int, input('Enter the numbers: ').split(","))
print('Product of Odd numbers:',productOfOdds(list1))
| true |
4a8e0b7668660be99e472e1a2635d087065b2f5f | 8BitJustin/practice_python | /05_list_overlap.py | 536 | 4.15625 | 4 | """
Take two lists, say for example these two:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
and write a program that returns a list that contains only the elements that are common between
the lists (without duplicates). Make sure your program works on two lists of different sizes.
"""
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
c = a + b
d = []
for num in c:
if num not in d:
d.append(num)
d.sort()
print(c)
print(d)
| true |
76c2bc017e9ec1c966edb2c2f786860eeca9b530 | JBannwarth/OrbitalMechanics | /chapter1/example_1_7.py | 1,085 | 4.21875 | 4 | """ Orbital Mechanics for Engineering Students Example 1.7
Question:
Show that if there is no atmosphere, the shape of a low-altitude ballistic
trajectory is a parabola. Assume the acceleration g is constant and neglect the
earth curvature
Written by: J.X.J. Bannwarth
"""
from numpy import linspace, tan, sin, cos, pi
import matplotlib.pyplot as plt
# Title
print("Orbital Mechanics for Engineering Students Example 1.7")
# Initial conditions
x0 = 1. # m
y0 = 1. # m
v0 = 5. # m/s
gamma0 = 60.*pi/180. # radian
g = 9.807 # m/s^2
tmax = 2. # s
# Compute using y(t) for checking purposes
t = linspace(0.,tmax,20)
x = x0 + (v0*cos(gamma0))*t
y1 = y0 + (v0*sin(gamma0))*t - 0.5*g*t**2
# Compute using y(x)
y = y0 + (x-x0)*tan(gamma0) - 0.5*g*(x-x0)**2 / (v0*cos(gamma0))**2
# Plot trajectory
fig = plt.figure()
plt.grid()
plt.arrow(x0, y0, v0*cos(gamma0), v0*sin(gamma0), color='r', label="v0", head_width=0.2)
plt.plot(x, y, label="y(x)")
plt.plot(x, y1, '-.', label="y(t)")
plt.xlabel("x (m)")
plt.ylabel("y (m)")
plt.legend()
plt.ylim(top=y0+1.1*v0*sin(gamma0))
plt.show()
| false |
01b35106e560f898d1575f2d661d672d36c1336a | ch374n/python-programming | /general_programming/palindrome.py | 510 | 4.21875 | 4 | # # program to check whether given string is palindrome or not
# def check_palindrome(string):
# if not string:
# return True
# else:
# front = 0
# back = len(string) - 1
# while front <= back:
# while string[front : front + 1] == ' ':
# front += 1
# while string[back : back + 1] == ' ':
# back -= 1
# if string[front : front + 1] != string[back : back + 1]:
# return False
# front += 1
# back -= 1
# return True
# print(check_palindrome('che tan nateh c'))
| false |
9854dabcd0bc28e682272c80632b87dc17ebd65a | kinwzhang/Codings | /leetcode/7. Reverse Integer.py | 957 | 4.21875 | 4 | '''
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
'''
# Accepted Codes:
class Solution:
def reverse(self, x: int) -> int:
if x < 0:
string = list(str(abs(x)))
addNegative = 1
else:
string = list(str(x))
addNegative = 0
result = []
while len(string) > 0:
result.append(string.pop())
result = ''.join(result)
if addNegative == 1:
result = '-' + result
if abs(int(result)) > pow(2, 31):
return 0
return int(result)
# 32 ms, 13.2 MB | true |
db0f6a3635e80f99869dffbd6415bbaa6bf3405b | hamidhmz/python-exercises | /type.py | 897 | 4.125 | 4 | """data types"""
X = '0'
print('\n int')
print(int(X))
print('\n ===type(int(X))===', type(int(X)))
print('\n boolean')
print(bool(X))
print('\n ===type(bool(X))===', type(bool(X)))
print('\n float')
print(float(X))
print('\n ===type(float(x))===', type(float(X)))
print('\n string')
print(str(X))
print('\n ===type(str(x))===', type(str(X)))
# --------------------------- list of falsy values --------------------------- #
# Zero of any numeric type.
# Integer: 0
# Float: 0.0
# Complex: 0j
# Empty lists []
# Empty tuples ()
# Empty dictionaries {}
# Empty sets set()
# Empty strings ""
# Empty ranges range(0)
# None
# False
# -------------------------- for specify type of sth ------------------------- #
print('\n ===type(x)===', type(X))
# ------------------------------- complex type ------------------------------- #
print('\n ===range type===')
print('type(range(3))',type(range(3)))
| false |
caa23b2ead9a5d66e2cce44cca4652dfee1708c0 | jgaman/CodingNomads | /python_fundamentals-master/python_fundamentals-master/06_functions/06_02_stats.py | 321 | 4.1875 | 4 | '''
Write a function stats() that takes in a list of numbers and finds the max, min, average and sum.
Print these values to the console when calling the function.
'''
example_list = [1, 2, 3, 4, 5, 6, 7]
def stats(list):
print("Max value element:", max(list))
# call the function below here
stats(example_list)
| true |
7ecdea49f1ad052d0d06cf27fab9555986820e81 | mrarpit5/python | /array.py | 205 | 4.125 | 4 | arr=["abc","jkl","mno"]
print(arr)
print(arr[0])
for x in arr:
print(x)
arr.append("Honda")
arr.append("xyz")
print(arr)
arr.append("jkl")
print(arr)
arr.pop(1)
print(arr)
arr.remove("abc")
print(arr)
| false |
e8027a0ac53fda955115ef5b3b8b817ff36e72b0 | DENNIS-CODES/Stack-Machine | /Stack1.py | 570 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 12 19:21:16 2021
@author: user
"""
def check_palindrome(string):
length = len(string)
first = 0
last = length -1
status = 1
while(first<last):
if(string[first]==string[last]):
first=first+1
last=last-1
else:
status = 0
break
return int(status)
string = input("Enter the string: ")
print("Method 1")
status= check_palindrome(string)
if(status):
print("It is a palindrome")
else:
print("Sorry! Try again")
| true |
876e783998f46f8b2fca6f035356a32a22de5cb0 | bryanle96/Python | /Python Project.py | 2,793 | 4.1875 | 4 | finalCostFloat = 0
finalWeightFloat = 0
deliveryCostFloat = 0
preDeliveryCostFloat = 0
terminateBoolean = False
ordersInt = 0
finalTrackPriceFloat = 0
def ComputeAvgPrice():
#Based on the information, the average price will be calculated for all orders
avgCost = 0
if ordersInt == 0:
avgCost = 0
else:
avgCost = finalTrackPriceFloat / ordersInt
return avgCost
def CalcDeliveryCost(totalWeight):
#Based on the weight total, the shipping cost will be calculated
shipping = 0
if(totalWeight <= 5):
shipping = 3.5;
elif(totalWeight <= 20):
shipping = 10;
else: shipping = 9.5 + (.1 * totalWeight)
return shipping
def CalcOrderPricing(artichoke, carrots, beets):
#Calculate the price of an order based on # of pounds of artichokes
#carrots, and beets
return (artichoke * 2.67) + (carrots * 1.49) + (beets * .67)
#There will be a continous loop as long as user wishes to input data
while terminateBoolean == False:
artichokeFloat = float(input("Enter Artichoke pounds: "))
carrotsFloat = float(input("Enter Carrot pounds: "))
beetsFloat = float(input("Enter beets pounds: "))
#Discount Rate & Amount
rateFloat = .05
amountFloat = 0
#Compute cost and total number of pounds
finalCostFloat = CalcOrderPricing(artichokeFloat,carrotsFloat,beetsFloat)
finalWeightFloat = artichokeFloat + carrotsFloat + beetsFloat
#Determine if discount needs to be applied
if(finalCostFloat > 100):
amountFloat = rateFloat * finalCostFloat
finalCostFloat = finalCostFloat - amountFloat
preDeliveryCostFloat = finalCostFloat
#Update the information that has been collected
ordersInt += 1
finalTrackPriceFloat = finalTrackPriceFloat + preDeliveryCostFloat
#Here is where the shipping cost will be calculated
shippingFloat = CalcDeliveryCost(finalWeightFloat)
#Include the shipping cost
finalCostFloat = finalCostFloat + shippingFloat
print ("\n" + "Order Price: $", '%.2f' %preDeliveryCostFloat)
print ("Shipping Cost: $", '%.2f' %shippingFloat)
print ("Total Order Cost: $", '%.2f' %finalCostFloat, "\n")
print("Do you want to enter another order?")
userResponse = input("If yes, enter 'Y', otherwise 'N' for no")
#Based on the user response, the boolean will be altered
if(userResponse == "Y"):
terminateBoolean = False
else:
terminateBoolean = True
avgOrdPriceFloat = ComputeAvgPrice()
print ("\n" + "Total Price: $", '%.2f' %finalTrackPriceFloat)
print ("Number of orders: ", ordersInt)
print("Average price per order: $", '%.2f' %avgOrdPriceFloat)
| true |
2ca5379e9b98e80264dc3324efb9b66700887c42 | hsi-cy/codewars | /SOLVED/Search_for_letters.py | 883 | 4.25 | 4 | """
Create a function which accepts one arbitrary string as an argument, and return a string of length 26.
The objective is to set each of the 26 characters of the output string to either '1' or '0' based on the fact
whether the Nth letter of the alphabet is present in the input (independent of its case).
So if an 'a' or an 'A' appears anywhere in the input string (any number of times), set the first character of
the output string to '1', otherwise to '0'. if 'b' or 'B' appears in the string, set the second character to '1',
and so on for the rest of the alphabet.
"""
def change(st):
import string
alphabet = string.ascii_lowercase
ls = []
y = sorted(set(st.lower()))
for letter in alphabet:
if letter in y:
ls.append(1)
else:
ls.append(0)
ans = ""
for i in ls:
ans += str(i)
return ans
| true |
7a4c7d9e1cca1d1b686e8fa281f57d5f86873aa1 | miaviles/Data-Structures-Algorithms-Python | /primitive_types/swap_bits.py | 660 | 4.3125 | 4 | """
Every even position bit is swapped with adjacent bit on right side
, and every odd position bit is swapped with adjacent on left side.
00010111
00101011
The solution assumes that input number is stored using 32 bits.
"""
def swapBits(x):
# Get all even bits of x
even_bits = x & 0xAAAAAAAA
# Get all odd bits of x
odd_bits = x & 0x55555555
# Right shift even bits so they become odd bits
even_bits >>= 1
# Left shift odd bits so they become even bits
odd_bits <<= 1
# Combine even and odd bits
return (even_bits | odd_bits)
# Driver program
# 00010111
x = 23
# Output is 43 (00101011)
print(swapBits(x))
| true |
ffad7b69b4184074becc031c2e1be75fe226c3f0 | miaviles/Data-Structures-Algorithms-Python | /advanced_python/Python_Decorators/decorators_with_parameters.py | 1,412 | 4.46875 | 4 | # Python code to illustrate
# Decorators with parameters in Python
def decorator_func(x, y):
def Inner(func):
def wrapper(*args, **kwargs):
print("I like Geeksforgeeks")
print("Summation of values - {}".format(x + y))
func(*args, **kwargs)
return wrapper
return Inner
# Not using decorator
def my_fun(*args):
for ele in args:
print(ele)
# another way of using dacorators
decorator_func(12, 15)(my_fun)('Geeks', 'for', 'Geeks')
print('-' * 60)
# Python code to illustrate
# Decorators with parameters in Python (Multi-level Decorators)
def decodecorator(dataType, message1, message2):
def decorator(fun):
print(message1)
def wrapper(*args, **kwargs):
print(message2)
if all([type(arg) == dataType for arg in args]):
return fun(*args, **kwargs)
return "Invalid Input"
return wrapper
return decorator
@decodecorator(str, "Decorator for 'stringJoin'", "stringJoin started ...")
def stringJoin(*args):
st = ''
for i in args:
st += i
return st
@decodecorator(int, "Decorator for 'summation'\n", "summation started ...")
def summation(*args):
summ = 0
for arg in args:
summ += arg
return summ
print(stringJoin("I ", "like ", "Geeks", "for", "geeks"))
print()
print(summation(19, 2, 8, 533, 67, 981, 119))
| true |
0c532e65de815bd2225503f712c5189d84717404 | Pranathi-star/Data-Structures-class | /pangram.py | 353 | 4.375 | 4 | #check whether a string is a pangram or not
alphabet = "abcdefghijklmnopqrstuvwxyz"
def pangram_or_not(input_string):
return not set(alphabet) - set(input_string.lower())
input_string = input().strip()
result = pangram_or_not(input_string)
if result:
print("The sentence is a pangram.")
else:
print("The sentence is not a pangram.")
| true |
562f77fea125b457e120e842622f1f1c33e77455 | Kr-Varun/python | /regex1.py | 1,532 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jun 23 23:37:40 2018
@author: unmanaged 5
"""
import re
"""
reg_pattern=r"[A-Z]{5,25}"
pswd=input("Enter a password: ")
result=re.search(reg_pattern,pswd)
if(result):
print("Match_found")
else:
print("Match not found")
"""
"""
reg_pattern= r"(?=.*[A-Za-z])" #indicates that it should have minimum one character, . means minimum 1 char
# ?= means lookahead assertion, in this case it would say lookahead for min 1 char
pswd=input("Enter a password: ")
result=re.search(reg_pattern,pswd)
if(result):
print("Match_found")
else:
print("Match not found")
"""
"""
reg_pattern= r"(?=.*[A-Za-z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{4,8})" #This regex says minimum 1 special char, min 1 capital letter, min 1 numeric and 4-8 digits required.
pswd=input("Enter a password: ")
result=re.search(reg_pattern,pswd)
if(result):
print("Match_found")
else:
print("Match not found")
"""
str="Customer Number : 455345734 , Date: June 22, 2018"
items= re.findall("[0-9]+", str) #findall will extract the matching pattern and will print
print(items)
items= re.findall("[0-9]+.*:.*", str) #this would say start with number, check for anything before and after :
print(items)
str = "yes I said yes I will Yes."
res = re.sub("[yY]es","no", str) #sub will substitute the yes or Yes by no.
print (res)
str="Task to complete elk by 23 July 2018"
res=re.sub("[0-9]{4}","2020",str)
print(res)
| true |
bf44ba0ee8022e103f6918848148a7964dec8761 | woaipuppyball/Jane-learn-python-104 | /ex3.py | 422 | 4.28125 | 4 | print"I will now count my chickens:"
print"hens", 25 + 30/6
print"roosters", 100 - 25*3%4
print"Now I will count the egg:"
print 3+2+1-5+4%2-1/4+6
print "Is it true that 3+2 < 5-7?"
print 3+2<5-7
print"what is 3 + 2?",3+2
print "What is 5-7?", 5-7
print "that's why it is false."
print"how about some more."
print"Is it greater?",5>-2
print"Is it greater or equal? ", 5 >= -2
print "Is it less or equal?", 5 <= -2
| true |
c1c7b8ed8a054940abfc53594184966e14f75c0d | salaberri/python.basics | /functions/functions.py | 1,328 | 4.46875 | 4 | # FUNCTIONS ARE BLOCKS OF CODE THAT RUNS WHEN IT IS CALLED
# IT MAY RECEIVE PARAMETERS (DATA)
# IT MAY RETURN DATA
# TO CREATE A FUNCTION IN PYTHON WE USE THE WORD DEF
def new_function():
print("This is my function")
# CALLING THE FUNCTION
new_function()
# PASSING PARAMETER TO THE FUNCTION
def say_my_name(name):
print("My name is " + name)
# CALLING THE FUNCTION
say_my_name("John")
# USE DEFAULT PARAMETER IN FUNCTIONS
def default_function(parameter="default"):
print("My default value is " + parameter)
# CALLING THE FUNCTION TO PRINT DEFAULT PARAMETER
default_function()
# CALLING THE FUNCTION AND OVERWRITE DEFAULT PARAMETER
default_function("not default")
# FUNCTION THAT RETURNS A VALUE
def sum_values(a, b):
return a + b
# CALLING THE FUNCTION AND PRINTING THE RETURNED VALUE
print(sum_values(1, 1))
# LAMBDA FUNCTION : USE THE LAMBDA KEYWORD
# ALSO CALLED AS ANONYMOUS FUNCTION
# SAME SUM FUNCTION IN LAMBDA
lambdaFunction = lambda a, b: a + b
# CALLING LAMBDA FUNCTION AND PRINTING THE VALUE
print(lambdaFunction(1, 1))
# GENERATING RUN-TIME FUNCTION WITH LAMBDA
def lambda_function(x):
return lambda a: a * x
# RUN-TIME ASSIGN TO A VARIABLE AND PRINTING RETURNED VALUES
fiveTimes = lambda_function(5)
print(fiveTimes(2))
tenTimes = lambda_function(10)
print(tenTimes(2)) | true |
23bd346c32c1f26bedae63f8ca99d2a5e851659e | stroodle96/DSpython | /If Statements HW_ Ping Test.py | 711 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 19 11:49:53 2018
This asks the user for a host name and then tells them if it is pingable or not.
@author: dstro
"""
#%%
def main(): "Asks the user for the hostname and also calls the respond function"
global response
import os
hostname = input('What is the HostName or IP? \n')
response = os.system("ping " + hostname )
respond()
def respond(): "Checks the response of the ping test and displays the results."
if response == 0:
print (hostname, 'is up!')
else:
print (hostname, response, 'is down!')
main()
"""
OUTPUT
What is the HostName or IP? google.com
google.com is up!
""" | true |
aebb7613567b27e21ac50f627b007dbfbd8e82ad | Jafaranafi/NEWTON_AIMSCMR1920 | /Newtonforscalar.py | 766 | 4.15625 | 4 | import numpy as np
#This example is for example 1 of Newton method for one variable
import matplotlib.pyplot as plt
x=np.linspace(-2,2,100)
def newton(x0,f,g,n,tol):
for i in range(n):
x1=x0-f(x0)/g(x0)
if abs(x1-x0)>tol:
x0=x1
print(i,":%10f:%10f:%10f" %(x1,f(x0),abs(x1-x0)))
return x1,i
def f(x):
return np.exp(x)-x**2+3*x-2
def g(x):
return np.exp(x)-2*x+3
x1,i = newton(0,f,g,30,1.e-10)
x0=1
y=(np.exp(x1)-2*x1+3)*(x-x1)
print(x1,i)
plt.xlabel("x")
plt.ylabel("f(x)")
plt.title("$x**2-1$")
plt.plot(x,y,"blue",label="Tangent line")
plt.plot(x,f(x),"green",label="Equation graph")
#plt.plot(x,p,"r.-")
plt.title("Continuation Graph using Newton method")
plt.plot(x1,f(x1),"r.-",label="Solution point")
#plt.plot(u,p,'r.-')
plt.legend()
plt.show()
| false |
1f3cbab4ab472afaab83943a2a32bc2da85c21b4 | catr1ne55/epam_training_python | /lec2/lec/task2.py | 369 | 4.125 | 4 | def str2int(string):
"""Transforms the given string into it's numerical representation and returns it."""
num = 0
for s in string:
cur = ord(s)
l = 0
div = cur
while div > 0:
div = div // 10
l += 1
num = num * 10 ** l + cur
return num
print(str2int('abcd'))
print(str2int('asdcbhffds'))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.