blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
2c6e2755e7a21558288a4fc545e5bddea0396deb | SandipanGhosh/Data-Structures-and-Algorithms | /bubble_sort.py | 552 | 4.125 | 4 | def bubble_sort(ar_list):
# Outer range will be n for first pass, (n-1) for second pass etc.
for outer_indx in range(len(ar_list)-1, 0, -1):
# Compare within the set range
for inner_indx in range(outer_indx):
if ar_list[inner_indx] > ar_list[inner_indx+1]:
temp = ar_list[inner_indx]
ar_list[inner_indx] = ar_list[inner_indx+1]
ar_list[inner_indx+1] = temp
return ar_list
# Test cases
ar_list = [8,5,2,1,6,9,3,4]
print("Unsorted list: " + str(ar_list).strip('[]'))
print("Sorted list: " + str(bubble_sort(ar_list)).strip('[]'))
| true |
cfe0ef46e5776a4f9e1b0148ce21d2d9b16b252f | henrylin2008/local_project | /Implementation_Queue.py | 1,071 | 4.375 | 4 | # Queue Methods and Attributes
# Before we begin implementing our own queue, let's review the attribute and methods it will have:
# Queue() creates a new queue that is empty. It needs no parameters and returns an empty queue.
# enqueue(item) adds a new item to the rear of the queue. It needs the item and returns nothing.
# dequeue() removes the front item from the queue. It needs no parameters and returns the item. The queue is modified.
# isEmpty() tests to see whether the queue is empty. It needs no parameters and returns a boolean value.
# size() returns the number of items in the queue. It needs no parameters and returns an integer.
class Queue:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def enqueue(self, item):
self.items.insert(0,item)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
In [2]:
q = Queue()
In [3]:
q.size()
Out[3]:
0
In [4]:
q.isEmpty()
Out[4]:
True
In [5]:
q.enqueue(1)
In [6]:
q.dequeue()
Out[6]:
1
| true |
ba79dcfbf5c37f22c58304823149834cb55ed3a3 | dorigum/Python | /sec02/05_data_type.py | 2,711 | 4.1875 | 4 | # 데이터 타입
# 정수 : int
# 실수 : float
# 문자열 : str
# 불리언 : bool
# 변수의 데이터 타입
# - 파이썬에서는 변수는 지정된 자료형이 없음
# - 저장한 값에 따라 변수의 자료형이 정해짐
# - 한 변수에 정수값을 저장하면 int 형이 되고
# - 문자열 값을 저장하면 str 형이 됨
a = 100
print(type(a))
a = "hello"
print(type(a))
# 형 변환 함수
# int(문자열) : 문자열을 정수로 변환
# float(문자열) : 문자열을 실수로 변환
# str(정수 또는 실수) : 정수 또는 실수를 문자열로 변환
# input() 함수 : 콘솔에서 입력 가능 (입력된 값은 문자열)
num = input("숫자 입력 : ")
print(num)
print(type(num))
# 입력된 값을 숫자 연산
# 입력된 값은 문자열이므로 숫자 연산 불가 -> 숫자로 형 변환 필요
print(int(num) + 100)
print(type(num))
# 이름, 나이 입력 받아서 출력
# 이름 : 홍길동, 나이 : 23
name = input("이름 입력 : ")
age = input("나이 입력 : ")
print("이름 : " + name + ", 나이 : " + age)
# eval() : 숫자로 변환 함수 (숫자 입력 및 수식 입력 가능)
x = eval(input("숫자 입력 1 : "))
y = eval(input("숫자 입력 2 : "))
sum = x + y
print("합 : ", sum)
# 연습문제
# 예금액과 이자율 입력 받아서
# 예금액, 이자율, 예금이자, 잔액 출력
# 실행 예
# 예금액 입력 : 10000
# 이자율 입력(%) : 2.5
# --------------------------
# 예금액 : 10000원
# 이자율 : 2.5%
# 예금이자 : 250원 (계산해서 출력)
# 잔액 : 10250원 (계산해서 출력)
deposit = int(input("예금액 입력 : "))
intRate = float(input("이자율 입력(%) : "))
interest = int(deposit * intRate / 100)
balance = deposit + interest
print("----------------------------")
print("예금액 : %d 원" % deposit)
print("이자율 : %.1f %%" % intRate)
print("예금이자 : %d 원" % interest)
print("잔액 : %d 원" % balance)
# 숫자에서 천 단위 구분(,) 기호 출력 : format() 함수 사용
# 숫자에 , 붙임 : 더 이상 숫자가 아니고 문자가 됨 (%s)
# format() 함수와 포맷 코드 같이 사용
print("예금액 : %s 원" % format(deposit, ','))
print("이자율 : %.1f %%" % intRate)
print("예금이자 : %s 원" % format(interest, ','))
print("잔액 : %s 원" % format(balance, ','))
# 포맷 코드 사용하지 않고 format() 함수 사용 가능
print("예금액 : ", format(deposit, ','), " 원")
print("이자율 : %.1f %%" % intRate)
print("예금이자 : ", format(interest, ','), " 원")
print("잔액 : 원", format(balance, ','), " 원")
| false |
3d7246b11e71d8f07f3c90c0b3b28df88ed1cf93 | krhicks221/Trio | /menu.py | 677 | 4.1875 | 4 | menu = """
1. Reverse a string
2. Reverse a sentence
3. Find the minimum value in a list
4. Find the maximum value in a list
5. Calculate the remainder of a given numerator and denominator
6. Return distinct values from a list including duplicates
8. Exit menu
"""
while(True):
print(menu)
choice = input()
if choice == '1':
from kaytlyn1 import *
questionone()
elif choice == '3':
from code import *
q3()
elif choice == '8':
break
elif choice == '4':
from code import *
q4()
elif choice == '2':
from kaytlyn2 import *
numbertwo()
elif choice == '6':
from kaytlyn3 import *
numbersix()
elif choice == '5':
from q5 import *
question5()
| true |
7ae1df6c94c3e3d88a771265d66e3daa52a96637 | ataabi/pythonteste | /Desafios/ex036.py | 887 | 4.125 | 4 | # Escreva um programa para aprovar o empréstimo bancário para a compra de uma casa.
# O Programa vai perguntar o valor da casa, o salário do comprador e em
# quantos anos ele vai pagar.
#calcule o valor da prestação mensal, sabendo que ela não pode exceder 30% do salário
# ou então o empréstimo sera negado.
print('Consulta de emprestimo bancário.')
vacasa = float(input('Qual o Valor da Casa ? R$'))
salario = float(input('Qual o Salário do comprador ? R$'))
anos = int(input('Em quantos anos vai ser pago ? : '))
men = vacasa/(anos*12)
if men > (salario*0.30):
print(f'Desculpe, mas seu salario é de R${salario} e a mensalidade vai fica em {men:.2f}\n'
f'entao nao poderemos aprovar seu empréstimo.')
elif men < (salario*0.30):
print(f'Parabéns. Seu empréstimo foi aprovado.\n'
f'você ira pagar {anos*12:.0f} prestações de R${men:.2f}.')
| false |
a8d923c3664e5b81b7f9cd2b66cd648e9d25e23a | ataabi/pythonteste | /Desafios/ex102.py | 861 | 4.40625 | 4 | # Crie um programa que que faça uma função fatorial() que receba dois parâmetros: o primeiro que indique
# o número a calcular e o outro chamado show, que será um valor lógico(opcional) indicando se será mostrado
# ou não na tela o processo de cálculo de fatorial.
def fatorial(x, show=False):
"""
-> Calcula o Fatorial de um número.
:param x: O número a ser calculado.
:param show: (opcional) mostrar ou não a conta.
:return: O valor do fatorial de um número n.
"""
f = 1
if show == True:
for c in range(x, 0, -1):
f *= c
print(f'{c} x ',end='')
print('= ',end='')
return f
if show == False:
for c in range(x, 0, -1):
f *= c
return f
print(fatorial(5))
print('-='*20)
print(fatorial(5,show=True))
print('-='*20)
help(fatorial)
| false |
03cfac8179d65005d9426c7d9262be977d1dbf7f | digizeph/code | /reference/Python/lang/number_choice.py | 416 | 4.15625 | 4 | import random
secret_number = random.randint(1, 20)
print("Computer is making a number between 1 and 20")
for t in range(1, 7):
print("choose a number.")
choice = int(input())
if choice < secret_number:
print("should be larget")
elif choice > secret_number:
print("should be smaller")
else:
break
if choice == secret_number:
print("Right Job")
else:
print("No") | true |
ffc4d88d75a0a16f60a7f69742b1f8b8ce6ca4fb | glen-s-abraham/data-structures-and-algorithms-python | /linkedList.py | 2,691 | 4.34375 | 4 | """
Each node is composed of data and a reference to the next node
Can be used to implement several other comon data types:stacks,queues
Indexing:O(n)
Insert At begining:O(1)
Insert at end:O(n)
Delete at begining:O(1)
Delete at end:O(n)
Waste space:O(n)
Use linked list if you want to insert/remove elements at begining
,size changes frequently,no random access
Advantages:Dynamic datastructures,memory allocation in runtime,
store items with diff sizes,easier to grow organically.
Disadvantages:waste memory because of references,
nodes need to be read in order,difficulty in reverse traversing
"""
class Node:
"""Data Storage structure for each Node"""
def __init__(self, data):
self.data = data
self.next = None
def remove(self, data, previousNode):
"""Removes an element from the list"""
if self.data == data:
previousNode.next = self.next
del self.data
del self.next
else:
if self.next is not None:
self.next.remove(data, self)
class LinkedList:
def __init__(self):
self.head = None
self.length = 0
def inserAtStart(self, data):
"""Insert an element at the begining of the List"""
node = Node(data)
if self.head is None:
self.head = node
else:
node.next = self.head
self.head = node
self.length += 1
def insertAtEnd(self, data):
"""Insert an element at the end of the list"""
node = Node(data)
if self.head is None:
self.inserAtStart(data)
return
temp = self.head
while temp.next is not None:
temp = temp.next
temp.next = node
self.length += 1
def removeData(self, data):
"""Removes an element from the list"""
if self.head is not None:
if self.head.data == data:
self.head = self.head.next
else:
self.head.remove(data, self.head)
self.length -= 1
def traverseList(self):
"""Traverse the list"""
temp = self.head
while temp is not None:
print('{} '.format(temp.data))
temp = temp.next
def length(self):
"""Return the size of the list"""
return self.length
if __name__ == '__main__':
linkedList = LinkedList()
linkedList.insertAtEnd(1)
linkedList.inserAtStart(2)
linkedList.insertAtEnd(3)
linkedList.insertAtEnd(4)
linkedList.traverseList()
print()
linkedList.removeData(3)
linkedList.traverseList()
print()
linkedList.removeData(2)
linkedList.traverseList()
| true |
c22939da0cab46dee3d3da7c56453396531ad776 | silent-developer/ml_practice | /udemy/linreg/one.py | 1,086 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 9 19:52:04 2017
@author: Tan
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
x = 10 * np.random.rand(100)
y = 3 * x + np.random.randn(100)
plt.scatter(x,y)
from sklearn.linear_model import LinearRegression
model = LinearRegression(fit_intercept="true")
X = x.reshape(-1,1) #convert into a matrix with 1 coloumn. Python figures out the rows
model.fit(X,y) #fit the model i.e apply the learning algorithm
model.intercept_ #gives the intercept(theta1) after learning is complete
model.coef_ #gives the slope(theta2) after learning is complete
x_fit = np.linspace(-1,11) # creates a array of evenly spaced numbers
x_fit = x_fit.reshape(-1,1) # creates a matrix from above array
y_fit = model.predict(x_fit) # predict the value of y matrix using the intercept and coef values found earlier
plt.scatter(x,y) #scatter plot for x and y
plt.plot(x_fit,y_fit) #create a line plot using x_fit and y_fit i.e put a point on the graph for each corresponding x_fit and y_fit values | true |
3742e2a6a8714ef0156faacfb262674a9bb92021 | rita-xiaom/project-name | /Test/0925/004-tuple.py | 475 | 4.15625 | 4 | #元组的数据一旦定义,不能再修改
course=('chinese','math','english','computer')
print(course)
print(course[-1])
print(course[1:3])
#查元组的元素的个数
print(len(course))
#定义只有一个元素的元组,则需要再元素后面加逗号,用来消除数学歧义
t=(1,)
#返回元组中最大/小的值
score=(12,46,894,13,457)
# print(max(score))
# print(min(score))
maxscore=max(score)
print(maxscore)
minscore=min(score)
print(minscore)
| false |
61b665b20e386b40e53b86e47aafb285b267fa85 | miloknowles/coding-practice | /hashing/hashtable.py | 1,373 | 4.21875 | 4 | """ Implement a hash table using lists in python. """
class HashTable(object):
def __init__(self, size):
self.size = size
self.table = [None] * self.size
def hash(self, key):
return hash(key) % self.size
def __setitem__(self, key, val):
""" Uses open addressing to resolve collisions. """
idx = self.hash(key)
if self.table[idx] == None:
self.table[idx] = [(key, val)]
else:
for i in range(len(self.table[idx])):
if self.table[idx][i][0] == key:
self.table[idx][i] = (key, val) # Update existing key
return
# Otherwise, add new keyval pair at this location.
self.table[idx].append((key, val))
def __getitem__(self, key):
idx = self.hash(key)
if self.table[idx] == None:
return None
else:
if type(self.table[idx]) == list:
for pair in self.table[idx]:
if pair[0] == key:
return pair[1]
return None
else:
return self.table[idx][1]
def __contains__(self, key):
if self.__getitem__(key) == None:
return False
else:
return True
if __name__ == '__main__':
ht = HashTable(256)
ht['milo'] = 69
ht['milo'] = 32 # should overwrite previous key
ht['algorithms'] = 348734987
print(ht['milo'])
print(ht['algorithms'])
print(ht['unknown'])
ht['none'] = None
ht['string'] = 'some string'
print(ht['none'])
print(ht['string'])
print('milo' in ht)
print('asd;lkfjsdfl' in ht) | true |
94ffd250faaf4357cca3c5409185bf204051a9eb | Jreema/Kloudone_Assignments | /Python/python2/armstrongNumber.py | 300 | 4.15625 | 4 | #to check if a number is armstrong number or not
x=input("Enter a number: ")
x= x.lstrip('0')
order = len(x)
number = list(x)
out = [int(num)**order for num in number]
total =sum(out)
if total== int(x):
print(x," is an armstrong number")
else:
print(x," is not an armstrong number") | true |
d37732755b7ae9dca2a86bf2930f842f3041cfbf | pawarspeaks/Hacktoberfest-2021 | /Python/reverse_digit.py | 208 | 4.21875 | 4 | //simply program to reverse the digits of any number
a=int(input("enter the number:"))
b=0
c=0
while a!=0:
b=int(b*10)
c=int(a%10)
b=b+c
a=int(a/10)
print(b)
| true |
3c197fa76bd299afdc477d500259e3f5dc7846f0 | pawarspeaks/Hacktoberfest-2021 | /Python/palindrom.py | 352 | 4.5 | 4 | print('CODE TO CHECK WHETHER THE WORD IS PALINDROM OR NOT')
print("--------------------------------->>>>>>>>><<<<<<<<<<<<<<<<<<<<----------------------------------------------")
words=input('Enter a word to check if it\'s palindrom:')
new_word=words[::-1]
if new_word==words:
print('It\'s palindrome')
else:
print('it\'s not palindrome') | true |
fda6466a067f7fce6f15b3a7ecfd17713d76833e | Dillon1john/Turtle-Race | /main.py | 2,065 | 4.3125 | 4 | from turtle import Turtle, Screen
import turtle as t
import random
# Etch Sketch project
# w = forwards
# S = backwards
# A = counter-clockwise(left)
# D = Cloclkwise(right)
# C = clear drawing
is_race_on = False
screen = Screen()
# Resizes screen
screen.setup(width=500, height=400)
user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter a color: ")
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
y_positions = [-70, -40, -10, 20, 50, 80]
all_turtles = []
# Creates multiple turtles through for loop
for turtle_index in range(0,6):
new_turtle = Turtle(shape="turtle")
new_turtle.color(colors[turtle_index])
new_turtle.penup()
new_turtle.goto(x=-230, y=y_positions[turtle_index])
all_turtles.append(new_turtle)
if user_bet:
is_race_on = True
while is_race_on:
for turtles in all_turtles:
if turtles.xcor() > 230:
is_race_on = False
winning_color = turtles.pencolor()
if winning_color == user_bet:
print(f"You've won! The {winning_color} turtle is the winner!")
else:
print(f"You've lost! The {winning_color} turtle is the winner!")
random_distance = random.randint(0,10)
turtles.forward(random_distance)
screen.exitonclick()
#
# def move_forwards():
# tim.forward(10)
#
#
# def move_backwards():
# tim.backward(10)
#
#
# def turn_right():
# # Both do the same thing
# # tim.right(10)
# new_heading = tim.heading() - 10
# tim.setheading(new_heading)
#
#
# def turn_left():
# # Both do the same thing
# # tim.left(10)
# new_heading = tim.heading() + 10
# tim.setheading(new_heading)
#
#
# def clear_screen():
# tim.clear()
# tim.penup()
# tim.home()
# tim.pendown()
#
# screen.listen()
# screen.onkey(key="w", fun=move_forwards)
# screen.onkey(key="s", fun=move_backwards)
# screen.onkey(key="d", fun=turn_right)
# screen.onkey(key="a", fun=turn_left)
# screen.onkey(key="c", fun=clear_screen)
#
#
# tim.home()
| true |
a05ff225aae552b1be22d36a96c61d707b84ebda | LawerenceLee/coding_dojo_projects | /python_stack/fun_with_functions.py | 673 | 4.375 | 4 | def odd_even():
even_or_odd = ""
for x in range(1, 2001):
if x % 2 == 0:
even_or_odd = "even"
else:
even_or_odd = "odd"
print("Number is {}. This is an {} number.".format(x, even_or_odd))
def multiply(lst, multiplier):
for num, val in enumerate(lst):
lst[num] = val * multiplier
return lst
def layered_multiples(arr):
full_lst = []
for val in arr:
lst_of_lst = []
for _ in range(val):
lst_of_lst.append(1)
full_lst.append(lst_of_lst)
return full_lst
odd_even()
print(multiply([2, 4, 10, 16], 5))
print(layered_multiples(multiply([2, 4, 5], 3)))
| false |
8efcc43403d9bf544beb87226a5d0614ed7c3f4e | nathan-lau/ProjectEuler | /problem_3.py | 553 | 4.1875 | 4 | print('Problem 3:');
#Prime Factors
number = int(input('What is the number you want to find its prime factors ? '))
count = 0;
largest_prime = 1;
x = 1;
for x in range(1, number):
if number % x == 0: #iterate to find the factors of the input
for i in range(1, x):
if x % i == 0:
count = count + 1;
if count == 1:
#print('Yes!',x)
if x > largest_prime:
largest_prime = x;
count = 0;
print('Largest Prime Factor:', largest_prime)
| true |
c29d78b2f373f1ad2e182f0ee1eb2f9b5c9b7f9c | Shirley0210/MachineLearning | /MachineLearning/LinearRegresssion.py | 1,721 | 4.15625 | 4 | import numpy as np
import math
#This program is not optimal just understanding of linear regresssion.
Xtrain = [1,2,3,4] #Stores the training inputs
Ytrain = [3,5,7,9] #Stores the training labels
#Hyperparameters
learningRate = .01
numEpochs =1000
#In this case, our hypothesis is in the form of a model representing univariate
#linear regression. y = theta0 + x*theta1
def hypothesis(theta0,theta1,x):
return (theta0 + theta1*x)
#Our loss function is the classic mean squared error form
def costFunction(theta0, theta1):
loss = 0
for i, j in zip(Xtrain,Ytrain):
temp = math.pow((hypothesis(theta0,theta1,i) - j),2)
loss += temp
return loss
#Weight updates are done by taking the derivative of the loss function
#with respect to each of the theta values.
def weightUpdate(withRespectTo, theta0, theta1):
if (withRespectTo == "theta0"):
theta0 = theta0 - learningRate*(derivative(withRespectTo, theta0, theta1))
return theta0
else: #has to be wrt to theta1
theta1 = theta1 - learningRate*(derivative(withRespectTo, theta0, theta1))
return theta1
#Evaluating a numerical deerivative
def derivative(withRespectTo, theta0, theta1):
h = 1./1000.
if (withRespectTo == "theta0"):
rise = costFunction(theta0 + h, theta1) - costFunction(theta0,theta1)
else: #has to be wrt to theta1
rise = costFunction(theta0 , theta1 + h) - costFunction(theta0,theta1)
run = h
slope = rise/run
return slope
#Random initialization of the theta values
theta0 = np.random.uniform(0,1)
theta1 = np.random.uniform(0,1)
#Test value
Xtest = 5
for i in range(0,numEpochs):
theta0 = weightUpdate("theta0", theta0, theta1)
theta1 = weightUpdate("theta1", theta0, theta1)
print (hypothesis(theta0,theta1,Xtest))
| true |
e32e69fd84394bc8ec1ebcea10e0991f4c1805ac | ajh1143/ClassicQuickSort | /QuickSorter.py | 762 | 4.1875 | 4 | def quicksort(arr):
#Initialize Lists
pivoter = []
highVal = []
lowVal = []
#Check size of list, if 1 or less, no need to sort, just return
if len(arr) <= 1:
return arr
#Else, array contains items that must be sorted
else:
#Set pivot = first index
pivot = arr[0]
#For each element in arr, compare and append to higher/lower list or pivoter
for i in arr:
if i < pivot:
lowVal.append(i)
elif i > pivot:
highVal.append(i)
else:
pivoter.append(i)
low = quicksort(lowVal)
high = quicksort(highVal)
quickSorter = (low+pivoter+high)
return quickSorter
x=quicksort([1,3,5,2])
print(x)
| true |
e2a789ca4d1e3d163d022ae6851c9122ca22e933 | nmbrodnax/wim-workshop | /hello.py | 863 | 4.15625 | 4 | # Introduction to Web Scraping with Python
# NaLette Brodnax nbrodnax@indiana.edu
# September 30, 2016
print("Hello, world.")
mystring = 'happy'
print(mystring[0])
print(mystring[2:4])
mylist = ['Leia', 'Rey', 'Maz']
print(mylist[-1])
mydict = {'name': 'Kylo', 'side': 'dark'}
print(mydict['name'])
name = 'Grace Hopper'
if len(name) < 20:
print('Yes')
else:
print('No')
i = 0
for letter in name:
if letter in ['a', 'e', 'i', 'o', 'u']:
i = i + 1
print(name + ' has ' + str(i) + ' vowels.')
i = 0
vowel_count = 0
while i < len(name):
if name[i] in ['a', 'e', 'i', 'o', 'u']:
vowel_count = vowel_count + 1
i = i + 1
print(name + ' has ' + str(vowel_count) + ' vowels.')
my_string = 'aBcDe'
print(my_string)
print(my_string.lower())
def say_hello(name_string):
print('Hello, ' + str(name_string) + '!')
return None
say_hello('NaLette')
| false |
c6f7f66242fc84541c43e3f210a8aee42a7897ea | carlosalbertomachadopires/hw-0 | /personal.py | 234 | 4.15625 | 4 | name = input("Enter your Name")
age = int(input("Enter your age!"))
print(name)
print(type(name))
print(age)
print(type(age))
print(name + " is " + str(age) + " years old")
print(f"{name} is {age} years old")
"Carlos Pires is 53 years old" | false |
ab80b4e087159b923df0761b706363cff08d9e72 | ivkumar2004/Python | /sample/tablemultiplication.py | 576 | 4.125 | 4 |
def mathstable():
"""Function to generate table from sequence 1 to 12, Number get from user"""
tableInt = int(input("Enter the number to generate its multiples: "))
for sequence in range(1,13):
print ("%s x %s = %s"%(tableInt,sequence,tableInt*sequence))
return
if __name__ == "__main__":
exitOperation = False
while exitOperation != True:
ynString = str(input("Do you want to continue generating table (y/n): ")).strip().lower()
if ynString == "y":
mathstable()
elif ynString == "n":
exitOperation = True
else:
print ("Illegal string %s"%ynString)
| true |
0a5c471a71119bac9ab9ef17888b0fb613e79c2b | SteffanySympson/BLUE-MOD-1 | /Exercícios/Exercício de For - 4.py | 427 | 4.21875 | 4 | # 04 - Desenvolva um código em que o usuário vai entrar vários números e no final vai apresentar a
# soma deles (o usuário vai dizer quantos números serão informados antes de começar)
print ("Programa de somas")
print ()
soma = 0
quantidade = int (input ("Quantos números vamos somar?"))
for i in range(quantidade):
soma = soma + int (input ("Digite a entrada numérica: "))
print( "O valor da soma é:", soma) | false |
c51b1df0ce7270dc2a320438ba6a5b0ab3ca5ca5 | SteffanySympson/BLUE-MOD-1 | /Exercícios/Exercício de While - 3.py | 1,444 | 4.25 | 4 | # Crie um programa que leia a idade e o sexo de várias pessoas. A cada pessoa
# cadastrada, o programa deverá perguntar se o usuário quer ou não continuar. No
# final, mostre:
# A) Quantas pessoas tem mais de 18 anos.
# B) Quantos homens foram cadastrados.
# C) Quantas mulheres tem menos de 20 anos.
# contador para maior de 18 anos
# contador para homens
# contador para mulheres com menos de 20
# um input com sedo e idade
# um while infinito enquanto a resposta para a entrada for S
genero_M = 0
genero_F_20 = 0
idade_18 = 0
cadastramento = 0
print ("PROGRAMA DE CADASTRAMENTO")
print ()
cadastro = input("Deseja iniciar um cadastramento (Resp. S / N):\n").upper()
print ()
while cadastro == "S":
genero = input("Informe o gênero (F / M):\n").upper()
while genero != "M" and genero != "F":
genero = input("Entrada não permitida, insira uma entrada válida (M/F).")
genero = genero.upper()
idade = int (input("Informe a idade: "))
cadastramento += 1
cadastro = input("Deseja iniciar outro cadastramento (Resp. S / N):\n").upper()
if genero == "M":
genero_M += 1
if idade > 18:
idade_18 += 1
if genero == "F" and idade < 20:
genero_F_20 += 1
print(f"Existem {genero_M} homens cadastrados.\n")
print(f"Existem {idade_18} maiores de 18 anos cadastrado.\n")
print(f"Existem {genero_F_20} mulheres menores de 20 anos cadastradas. \n")
print(f"Existem {cadastramento} pessoas cadastradas.") | false |
5b3bfc6f9c54e28891a5da187839310de03b3aa7 | SteffanySympson/BLUE-MOD-1 | /Exercícios/Exercício de For - Extra - Tabuada.py | 325 | 4.15625 | 4 | # Crie um programa que pergunte ao usuário um número inteiro e faça a
# tabuada desse número.
from time import sleep
print("*_"*10)
print(" TABUADA")
print("*_"*10)
print()
tabuada = int(input("Informe o valor para a tabuada: "))
for num in range(11):
print (f'{tabuada} x {num} = {tabuada*num}')
sleep(1) | false |
7debdc1b988769380b99662e44ad84ffaf4fbb79 | Adarsh-shakya/python_lab | /element_in_tuple_or_not.py | 277 | 4.28125 | 4 | #check whether an element exists within a tuple.
n=int(input("Enter any number: "))
t=(3,4,7,6,0,10,5,11,97,34)
for i in t:
if n==i:
print('Entered element is exist in the tuple')
break
else:
print('Entered element is not exist in the tuple')
| true |
5d258683c55a1b5d632843aac840e4d45fe010ec | Andrey-Strelets/Python_hw | /hm02/dz2_level_2.py | 526 | 4.4375 | 4 | # Второй уровень ("if-elif-else"):
# Придумать свои собственные примеры на альтернативные варианты if
# и активное использование булевой алгебры.
#example 1
# a = 10
# b = True if a < 100 else False
# print (b)
#example 2
# number = True
# f = ("четное", "нечетное")[number]
# print("Число", f)
#example 3
f = None
b = f or "Данные отсутствуют"
print(b) | false |
4885fe525c8e5378ebefd219dce0bc14add8b85f | kpranshu/python-demos | /07-Oops/oops-2.py | 796 | 4.15625 | 4 | #OOPS - Object Oriented Programming
#Defining a class
class Mobile:
model=''
name=''
brand=''
price=0.0
ram=0
storage=0
def Input(self):
self.model=input("Enter Model Number : ")
self.name=input("Enter Name : ")
self.brand=input("Enter Brand : ")
self.price=float(input("Enter Price : "))
self.ram=int(input("Enter RAM : "))
self.storage=int(input("Enter Storage : "))
def Output(self):
print("Model : " + self.model)
print("Name : " + self.name)
print("Brand : " + self.brand)
print("Price : " + str(self.price))
print("RAM : " + str(self.ram))
print("Storage : " + str(self.storage))
#Creating a class object
a=Mobile()
a.Input()
a.Output()
| false |
8789d03d8451f2e9ddae2852a71bd69ff17630ab | Rachel-Hill/100daysofcode-with-python-course | /days/13-15-text-games/RockPaperScissors/RockPaperScissors.py | 1,982 | 4.1875 | 4 | from player import Player
from roll import Roll
import random
def main():
print_header()
rolls = build_the_three_rolls()
name = get_players_name()
player1 = Player(name)
player2 = Player("computer")
game_loop(player1, player2, rolls)
def get_players_name():
player_name = input("What is your name? ")
return player_name
def print_header():
print('---------------------------------')
print(' ROCK PAPER SCISSORS')
print('---------------------------------')
print()
def build_the_three_rolls():
rock = Roll('rock')
paper = Roll('paper')
scissors = Roll('scissors')
rolls = [rock, paper, scissors]
return rolls
def get_player_roll():
valid_choice = False
while not valid_choice:
choice = input("Choose Rock, Paper, or Scissors: ").lower()
if choice == 'rock':
return Roll('rock')
elif choice == 'paper':
return Roll('paper')
elif choice == 'scissors':
return Roll('scissors')
def game_loop(player1, player2, rolls):
count = 1
while player1.score < 3 and player2.score < 3:
p2_roll = random.choice(rolls)
p1_roll = get_player_roll()
win = p1_roll.can_defeat(p2_roll)
if win:
player1.score += 1
print("{} {} {}. {} wins!".format(p1_roll.name, p1_roll.action, p2_roll.name, player1.name))
elif p2_roll.name == p1_roll.name:
print("it's a tie. Try again")
else:
player2.score += 1
print("{} {} {}. Computer wins.".format(p2_roll.name, p2_roll.action, p1_roll.name))
print("{}: {} {}: {}".format(player1.name, player1.score, player2.name, player2.score))
if player1.score == 3:
print("Congrats, {}. You are the champion!".format(player1.name))
else:
print(" ")
print("Sorry. Computer wins the match.")
# Compute who won
if __name__ == '__main__':
main() | true |
951add88e87cc658810060aed8a8732e33df5840 | as-gupta/my-code-library | /OnlineCodingSessions/student.equals(dishaDey)/Day1/basic_arithmetic2.py | 248 | 4.1875 | 4 | '''
n % 10 -> extract last digit
n // 10 -> remove last digit
n / 10 -> divides the number by 10
'''
n = int(input("enter an integer: "))
print("n / 10 = ", n / 10)
print("last digit = ", n % 10)
print("on removing last digit we get = ", n // 10) | false |
b9d166087724a1d667267af232ee205f1d8c291f | as-gupta/my-code-library | /OnlineCodingSessions/student.equals(dishaDey)/Day3/for_loops_in_python.py | 958 | 4.34375 | 4 | # for loops in python
# Basic structure of a for loop in python
'''
Typical for loop in Python
for i in range(a, b, c):
""" BODY """
'''
# a -> intial value of i
# b -> max value of i is b - 1, such that the
# loop has a condition like (i < b)
# c -> incrementation value of i
'''
Equivalent for loop in C / C++ / Java / etc..
for (i = a; i < b; i += c) {
// BODY
}
'''
''' EXAMPLE '''
# for i in range(1, 6, 1):
# print(i)
# Some types of for loops
#1.
'''
for i in range(b):
""" BODY """
In such a case, a = 0 and c = 1.
It is equivalent to:
for i in range(0, b, 1):
""" BODY """
'''
#2.
'''
for i in range(a, b):
""" BODY """
In such a case, c = 1.
It is equivalent to:
for i in range(a, b, 1):
""" BODY """
'''
#3. The typical for loop in Python as mentioned above.
#4. For - Each loop
'''
for i in a:
print(i)
# Where a is a list
'''
'''
EXAMPLE:
a = [1, "Disha", 3, "CBSE", 5]
for i in a:
print(i)
''' | false |
b259a5d59f37e6c5dd17c5088dea475a2dce1704 | 93akshaykumar/GeneralPractice | /PYTHON/factorial_recursive.py | 309 | 4.28125 | 4 | def factorial(factValue):
if factValue<=1: return 1
else: return factValue * factorial(factValue-1)
try:
factValue=int(input("Please Enter The Number To Find Factorial=="))
except:
print("ERROR - Please Enter The Interger value")
else:
print("The Factorial of ",factValue," is== ",factorial(factValue))
| true |
35c856534fb4a91868572bf2c17caa167c7e0633 | Waka-Entertain/Let-code-everyday | /Python/valid-sudoku.py | 1,892 | 4.125 | 4 | """
Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
Each row must contain the digits 1-9 without repetition.
Each column must contain the digits 1-9 without repetition.
Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.
Example 1:
Input:
[
["5","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]
Output: true
"""
class Solution:
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
for i in range(9):
if not self.isValid([board[i][j] for j in range(9)]) \
or not self.isValid([board[j][i] for j in range(9)]):
return False
for i in range(3):
for j in range(3):
if not self.isValid([board[m][n] for m in range(3 * i, 3 * i + 3) for n in range(3 * j, 3 * j + 3)]):
print(2)
return False
return True
def isValid(self, ls):
ls = list(filter(lambda x: x != '.', ls))
return len(set(ls)) == len(ls)
board = [
["5","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]
print(Solution().isValidSudoku(board))
| true |
a7dc638df6ac53494899c2efbbf822bfdecc1591 | bdieu178/codewars-solns | /codewars-solns/python/FindTheOddInt.py | 400 | 4.125 | 4 |
"""
Given an array, find the int that appears an odd number of times.
There will always be only one integer that appears an odd number of times.
"""
#by Bryan Dieudonne
def find_it(seq):
odd_set = set(range(1,len(seq),2))
#even_set = set(range(0,len(seq),2))
for num2 in seq:
if seq.count(num2) in odd_set:
return num2
if seq.count(num2) == 1:
return num2
| true |
66195bb93f5514fbe43bb8345f44519590b97d67 | rosspeckomplekt/interpersonal | /interpersonal/classes/interaction.py | 1,859 | 4.40625 | 4 | """
An Interaction describes the interaction between
two Persons
"""
class Interaction:
"""
An Interaction describes the interaction between
two Persons
"""
def __init__(self, person_a, person_b):
"""
Initialize an Interaction object for two Persons
So we can compute the various Interaction functions
:param person_a: A Person
:param person_b: Another Person
"""
self.person_a = person_a
self.person_b = person_b
def find_dominator(self):
"""
Find which Person in the Interaction has the higher dominance
"""
a_dominance = self.person_a.get_personality().dominance
b_dominance = self.person_b.get_personality().dominance
print("The dominator is: ")
if a_dominance > b_dominance:
print(self.person_a.name)
return self.person_a
else:
print(self.person_b.name)
return self.person_b
def is_alliance(self):
"""
Find the magnitude with which the two Persons
are likely to be allies
"""
a_friendliness = self.person_a.get_personality().friendliness
b_friendliness = self.person_b.get_personality().friendliness
if a_friendliness * b_friendliness >= 0:
print(self.person_a.name + " and " + self.person_b.name + " are friends")
return True
else:
print(self.person_a.name + " and " + self.person_b.name + " are enemies")
return False
def get_alliance(self):
"""
Find the magnitude with which the two Persons are predicted to be
allied or enemies
"""
a = self.person_a.get_personality().friendliness
b = self.person_b.get_personality().dominance
return (a * b) * (abs(a) + abs(b)) / 20
| true |
26144ff76984d44a0de08f820e4c8d480da471f9 | Blckkovu/Python-Crash-Course-By-Eric-Matthes | /Python_work/Chapter 4 Working with List/List_Comprehension_Exerice.py | 778 | 4.3125 | 4 | #Exercise 4.3 count to 20 to print the numbers 1 to 20 inclusive
for numbers in range(1,21):
print(numbers)
#exercise 4.4 make a list of numbers from one to one million
Digits=[]
for value in range(1, 100):
digit= value
Digits.append(digit)
print(Digits)
#exercise 4.5 Make a list of odd_numbers
odd_numbers=list(range(1,20,2))
print(odd_numbers)
#exercise 4.7 make a list of multiples of 3 from 3 to 30 and use a for loop to print he numbers on the alist
Multiples=[]
for value in range(3,30,3):
Multiple=value
Multiples.append(Multiple)
print(Multiples)
#Exercise 4.8 cubes
Cubes=[]
for value in range(1,11):
cube=value**3
Cubes.append(cube)
print(Cubes)
#exercise 4.9 cube comprehension
Cubes=[value**3 for value in range(1,11)]
print(Cubes)
| true |
46ae0cbd94ef9cfe3d7db2672a7b3fdb7387c420 | zstall/PythonProjects | /Automate the Boring Stuff/Chapter 5/Game Inventory Dictionary.py | 952 | 4.15625 | 4 | '''
Inventory Dictionary
Chapter 5 Pg. 120
Practice printing all the key and values of a dictionary:
This is a 'video game' inventory, and there is a method that
will print out all keys and values.
'''
import pprint
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
def displayInventory(inventory):
print('********************************************')
print('Inventory:')
item_total = 0
for k, v in inventory.items():
print(str(v) + ' ' + k)
item_total += 1
print('Total Inventory: ' + str(item_total))
print('********************************************')
print()
def addToInventory(inventory, addedItems):
for i in addedItems:
inventory.setdefault(i, 0)
inventory[i] = inventory[i] + 1
displayInventory(stuff)
addToInventory(stuff, dragonLoot)
displayInventory(stuff)
| true |
4fee50ea1d7c933618e1d719bcce1c899e501b35 | Ardolia/PythonGB | /Lesson_3/3_1.py | 652 | 4.34375 | 4 | # 1. Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление.
# Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль.
def func_1(a, b):
if b == 0:
return 'На ноль делить нельзя!'
else:
return a / b
number1 = float(input('Введите певое число: '))
number2= float(input('Введите второе число: '))
print(f' {number1} : {number2} = {func_1(number1, number2)}') | false |
1845d484d65c3d093709a18661e3831f02dfe43a | jmbarrie/nth-puzzle-py | /puzzle.py | 2,688 | 4.1875 | 4 | class Puzzle:
def __init__(self):
puzzle = None
def get_puzzle(self):
"""
Returns the current puzzle.
"""
return self.puzzle
def set_puzzle(self, puzzle_index1, puzzle_index2, new_puzzle_value):
"""
Sets the value of the puzzle
Args:
puzzle_index1 (int): First index of the puzzle tuple
puzzle_index2 (int): Second index of the puzzle tuple
new_puzzle_value (int): Value to update
"""
self.puzzle[puzzle_index1][puzzle_index2] = new_puzzle_value
def print_puzzle(self):
"""
Outputs the current puzzle.
"""
for row in self.puzzle:
print(*row, sep=' ')
def create_default_puzzle(self):
"""
Selection 1: Generates a default puzzle for the user.
"""
self.puzzle = [[1, 2, 3],
[4, 0, 6],
[7, 5, 8]
]
def create_custom_puzzle(self):
"""
Selection 2: Allows user to define a custom puzzle.
"""
custom_puzzle = []
print('Enter your puzzle, use a zero to represent the blank, and exit to'
+ 'complete your custom puzzle')
while True:
user_selection = \
input('Enter the row, use space or tabs between numbers\t')
if user_selection == 'exit':
break
else:
row_list = user_selection.split(" ")
row_list = [int(i) for i in row_list]
custom_puzzle.append(row_list)
continue
self.puzzle = custom_puzzle
print()
self.print_puzzle()
print()
def get_index_value(self, puzzle_index1, puzzle_index2):
"""
Returns the contents at tuple index.
Args:
puzzle_index1 (int): First index of the puzzle tuple
puzzle_index2 (int): Second index of the puzzle tuple
"""
return self.puzzle[puzzle_index1][puzzle_index2]
def get_blank_space_index(self):
"""
Finds and returns the index of the blank space.
"""
blank_space_indices = []
for index, list in enumerate(self.puzzle):
if 0 in list:
blank_space_indices.extend((index, list.index(0)))
return blank_space_indices
def get_puzzle_array_size(self):
"""
Returns the size of the puzzle indices, and the length of each list.
"""
list_size = len(self.get_puzzle()[0])
puzzle_size = len(self.get_puzzle())
return [puzzle_size, list_size] | true |
14adc1395c2aeee017807dea90e51c51843db6fe | adanque/Validating-Accuracy-and-Loss-for-Deep-Learning | /run_NGram_Tokenization.py | 618 | 4.25 | 4 | """
Author: Alan Danque
Date: 20210128
Class: DSC 650
Exercise: 10.1.b
Purpose: Implement an `ngram` function that splits tokens into N-grams.
"""
import string
import nltk
def ngram(paragraph, n):
# Split the sentence by spaces
words = paragraph.split()
# Remove punctuation
table = str.maketrans('', '', string.punctuation)
stripped = [w.translate(table) for w in words]
bi_grams = nltk.ngrams(stripped, n)
return bi_grams
paragraph = "This is my sentence, to parse. Get all punctuation out# of here!"
bi_grams = ngram(paragraph, 3)
for gram in bi_grams:
print(gram)
| true |
c87a2c0e8852951280f80560a908687fe6520443 | physmath17/primes | /Sieve_of_Eratosthenes.py | 663 | 4.125 | 4 | import math
val = input("Enter the number to be verified:")
n = int(val)
def SieveOfEratosthenes(m):
# create a boolean array upto m+1 with all entries true, if a number l is not prime prime[l] will be false
prime = [True for i in range(m+1)]
p = 2
while(p*p <= m):
# if prime[p] is not changed it is a prime
if(prime[p] == True):
# update all multiples of p
for i in range(p*p, m+1, p):
prime[i] = False
p += 1
# printing primes
#for i in range(2, n):
if(prime[m] == True):
print("prime")
else:
print("not a prime")
SieveOfEratosthenes(n) | true |
3223a44a65e1e23339b818f7f408debd9aa44061 | elbryant/More-reading-and-writing | /ex15/ex15.py | 692 | 4.5 | 4 | #imports arguments
from sys import argv
#arguments used are script name and file name
script, filename = argv
#variable text is set to open the filename put in the arguments
txt = open(filename)
#it prints out the file name based on what was input
print "Here's your file %r:" % filename
#the system then reads the file
print txt.read()
#close opened file
txt.close()
#asks the user to type the file again
print "Type the filename again:"
#collects the raw input of what the user typed, adds a greater than before the prompt
file_again = raw_input("> ")
#opens the file again
txt_again = open(file_again)
#prints the file text
print txt_again.read()
#close open file
txt_again.close() | true |
e8b30084fcfb745adbb2f189a51a665dc1c7a59b | claytonscot/python_class | /InClass/DictionaryLoop.py | 356 | 4.3125 | 4 | __author__ = 'Home'
#create list
NUM_STUDENTS = 3
the_students = {}
for i in range(NUM_STUDENTS):
student_x = input('Enter Student X Number')
student_name = input('Enter Student Name')
the_students[student_x] = student_name
print(the_students)
#loop through items in existing dictionary
for student_x in the_students:
print(student_x)
| false |
046cf1a29e0eb4086d6c1259ee38eabd21fb69eb | pjrule/math87-final | /person/lostperson.py | 1,209 | 4.25 | 4 | import abc
class LostPerson(abc.ABC):
"""
A Lost Person is exactly what you would imagine - someone who is lost.
In our simulation, a lost person moves once per time step. At each time
step, he may move one or more units in any direction,
starting from his current location. Where exactly he moves is defined
by the subclass implementing this interface.
"""
@abc.abstractmethod
def init(self, start):
"""
Move the person to his starting location
:param start: the starting location on the map (a tuple)
:return:
"""
raise NotImplementedError('Should be implemented by subclasses')
@abc.abstractmethod
def move(self):
"""
Give the person an opportunity to move to a new space
on the map.
:return:
"""
raise NotImplementedError('Should be implemented by subclasses')
@abc.abstractmethod
def get_history(self):
"""
Gets a list of locations at which this person was located, ordered
by time visited.
:return: ordered list of visited locations
"""
raise NotImplementedError('Should be implemented by subclasses')
| true |
c2d933e95360096ca4dd9e5b5ae43d88bf12d98a | pjrule/math87-final | /person/searcher.py | 1,464 | 4.4375 | 4 | import abc
class Searcher(abc.ABC):
"""
A searcher is someone who is looking for the lost person.
Just like the lost persons, each searcher may move once in a given turn,
and his movement is given by the underlying implementation. Searchers
will likely rely upon some model of how the lost person
is moving in order to make decisions.
"""
@abc.abstractmethod
def init(self, start):
"""
Move the person to his starting location
:param start: the starting location on the map (a tuple)
:return:
"""
raise NotImplementedError('Should be implemented by subclasses')
@abc.abstractmethod
def move(self):
"""
Give the person an opportunity to move to a new space
on the map.
:return:
"""
raise NotImplementedError('Should be implemented by subclasses')
@abc.abstractmethod
def check_for_lost_persons(self):
"""
Look for lost persons for current location.
:return: True if lost person located, false otherwise
"""
raise NotImplementedError('Should be implemented by subclasses')
@abc.abstractmethod
def get_history(self):
"""
Gets a list of locations at which this person was located, ordered
by time visited.
:return: ordered list of visited locations
"""
raise NotImplementedError('Should be implemented by subclasses')
| true |
b3f657ec60d4ca40ba577d47db7e858b25c1363c | sumeet0420/100-days-python | /day18/01_basic_shapes.py | 723 | 4.3125 | 4 | # This is a sample Python script.
from turtle import Turtle, Screen
turtle = Turtle()
turtle.shape("turtle")
turtle.color("red")
##Draw a square
for _ in range(4):
turtle.forward(50)
turtle.right(90)
##Triangle
for _ in range(3):
turtle.forward(50)
turtle.right(90)
turtle.right(30)
turtle.up()
turtle.forward(100)
##Dashed Line
for _ in range(10):
turtle.forward(10)
turtle.pendown()
turtle.forward(10)
turtle.penup()
turtle.pendown()
turtle.color("Blue")
def draw_shape(num_side):
angle = 360/num_side
for _ in range(num_side):
turtle.forward(100)
turtle.right(angle)
for side in range(3,11):
draw_shape(side)
screen = Screen()
screen.exitonclick() | true |
71bba7d1d25862d29ac3d8acdc98d43179e80f6a | Hemangi3598/chap-10_p1 | /p1.py | 248 | 4.21875 | 4 | # wapp to accept as input integers
# print if the number is even or odd
print("welcome")
num = int(input(" enter an integer "))
if num % 2 == 0:
msg = "even"
else:
msg = "odd"
print(msg)
print("bye")
# without any exception handling | true |
37797497365526c9b40269ab128289bfb356770f | cnzh2020/30daysofpython-practice | /day_5/day5.py | 2,385 | 4.3125 | 4 |
# Exercises: Level 1
#Declare an empty list
# Declare a list with more than 5 items
#Find the length of your list
#Get the first item, the middle item and the last item of the list
#Declare a list called mixed_data_types, put your(name, age, height, marital status, address)
#Declare a list variable named it_companies and assign initial values Facebook, Google, Microsoft, Apple, IBM, Oracle and Amazon.
#Print the list using print()
#Print the number of companies in the list
#Print the first, middle and last company
#Print the list after modifying one of the companies
#Add an IT company to it_companies
#Insert an IT company in the middle of the companies list
#Change one of the it_companies names to uppercase (IBM excluded!)
#Join the it_companies with a string '#; '
#Check if a certain company exists in the it_companies list.
#Sort the list using sort() method
#Reverse the list in descending order using reverse() method
#Slice out the first 3 companies from the list
#Slice out the last 3 companies from the list
#Slice out the middle IT company or companies from the list
#Remove the first IT company from the list
# Remove the middle IT company or companies from the list
# Remove the last IT company from the list
# Remove all IT companies from the list
# Destroy the IT companies list
# Join the following lists:
'''
front_end = ['HTML', 'CSS', 'JS', 'React', 'Redux']
back_end = ['Node','Express', 'MongoDB']
'''
# After joining the lists in question 26. Copy the joined list and assign it to a variable full_stack. Then insert Python and SQL after Redux.
#Exercises: Level 2
#T he following is a list of 10 students ages:
# ages = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24]
'''
Sort the list and find the min and max age
Add the min age and the max age again to the list
Find the median age (one middle item or two middle items divided by two)
Find the average age (sum of all items divided by their number )
Find the range of the ages (max minus min)
Compare the value of (min - average) and (max - average), use abs() method
'''
#Find the middle country(ies) in the countries list
#Divide the countries list into two equal lists if it is even if not one more country for the first half.
#['China', 'Russia', 'USA', 'Finland', 'Sweden', 'Norway', 'Denmark']. Unpack the first three countries and the rest as scandic countries.
| true |
af7017d3db749e8ca6031eeb1480a728491d3ddf | YagelSalazar/python-actosoft | /tiposdedatos.py | 1,026 | 4.15625 | 4 | #nombre = 'Yagel'
#print('Hola mundo, ' + nombre)
#Operadores aritmeticos y tipos de datos
# = - * / // %
#suma = 5 + 4
#resta = 5 - 4
#multi = 5 * 4
#div = 4 / 2
#divExact = 5 // 2
#print('La suma es igual a ', suma)
#numero = input('ingresa un numero')
#print('el numero ingresado es ', numero)
num1 = float(input('ingresa el primer numero: '))
num2 = float(input('ingresa el segundo numero: '))
totalSuma = num1 + num2
totalMulti = num1 * num2
totalRes = num1 - num2
totalDiv = num1 / num2
totalDivExact = num1 // num2
totalResid = num1 % num2
print('el resultado de la suma es igual a ', '{:0.2f}'.format(totalSuma))
print('el resultado de la multiplicacion es igual a ', '{:0.3f}'.format(totalMulti))
print('el resultado de la resta es igual a ', '{:0.2f}'.format(totalRes))
print('el resultado de la division es igual a ', '{:0.3f}'.format(totalDiv))
print('el resultado de la division exacta es igual a ', '{:0.2f}'.format(totalDivExact))
print('el residuo de la division es igual a ', '{:0.3f}'.format(totalResid))
| false |
b6d7f2bb0a350603094975a35f6187caf2e94db4 | er-aditi/Learning-Python | /List Working Programs/List_Multiple_Threes.py | 237 | 4.3125 | 4 | print("It is table of 3:")
for value in range(1, 11):
data = value * 3
print("3 * " + str(value) + " = " + str(data))
num = int(input("Enter number: "))
for value in range(1, 11):
print(num, "*", value, "=", num * value)
| true |
fef166a1b1209874d026f2cf22647976ca55b75d | ggasmithh/ambient_intelligence_labs | /python-lab2/ex2.py | 606 | 4.125 | 4 |
#populate the dictionaries
task1 = {"todo": "call John for AmI project organization", "urgent": True}
task2 = {"todo": "buy a new mouse", "urgent": True}
task3 = {"todo": "find a present for Angelina's birthday", "urgent": False}
task4 = {"todo": "organize mega party (last week of April)", "urgent": False}
task5 = {"todo": "book summer holidays", "urgent": False}
task6 = {"todo": "whatsapp Mary for a coffee", "urgent": False}
#make a list of dictionaries
tasks = [task1, task2, task3, task4, task5, task6]
#return only urgent tasks
for task in tasks:
if task["urgent"]:
print(task)
| true |
5c65de57c07996977a54cc3df29d7a338e6ca0c2 | ratherfrances/trialphaseone001 | /02.py | 235 | 4.1875 | 4 |
#count the numbers of numbers in a list
def count(values):
counter = 0
for i in values:
if i == 2:
counter += 1
return counter
some_list = [7,7,2,4,2,2,2,2]
how_many = count(some_list)
print(how_many) | true |
749ebb33356adb897f3c945b626e5bf602d0b9dc | bradger68/Coding-Dojos | /Encryption-Dojo.py | 1,113 | 4.125 | 4 | """Problem Description
Given an alphabet decryption key like the one below, create a program that can crack any message using the decryption key."""
alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
abcs = "abcdefghijklmnopqrstuvwxyz"
decryption_key = ["!", ")", "$", "(", "£", "*", "%", "&", ">", "<", "@", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o"]
encrypted_abcs = "!)$(£*&><@abcdefghijklmno"
my_message = "bridget"
# answer = input("encrypt or decrypt?")
def encrypt(message):
encrypted_message = ""
for letter in message:
message_index = abcs.find(letter)
letter = decryption_key[message_index]
encrypted_message += letter
return encrypted_message
print(encrypt(my_message))
def decrypt(message):
decrypted_message = ""
for letter in message:
message_index = encrypted_abcs.find(letter)
letter = alphabet[message_index+1]
decrypted_message += letter
return decrypted_message
print(decrypt(my_message))
| true |
3e59f97243264672cda6cbfe64eebcdda132cec4 | ahmad-elkhawaldeh/ICS3U-Unit4-01-python | /loop.py | 608 | 4.25 | 4 | #!/usr/bin/env python3
# Created by: Ahmad El-khawaldeh
# Created on: Dec 2020
# This program uses a while loop
def main():
# input
positive_integer = print(" Enter how many times to repeat ")
positive_string = input("Enter Here plz : ")
loop_counter = 0
# process & output
try:
positive_integer = int(positive_string)
while loop_counter < positive_integer:
print("{0} time through loop.".format(loop_counter))
loop_counter = loop_counter + 1
except Exception:
print("This was an invalid number ")
if __name__ == "__main__":
main()
| true |
72d0eace3bbf2f6ac6b010bd02a886a893a3e1f7 | danielstaikov/Complex_Conditional_Statements | /Point on Rectangle Border.py | 300 | 4.1875 | 4 | x1 = float(input())
y1 = float(input())
x2 = float(input())
y2 = float(input())
x = float(input())
y = float(input())
isXborder = (x==x1 or x==x2) and y>=y1 and y<=y2
isYborder = (y==y1 or y==y2) and x>=x1 and x<=x2
if isXborder or isYborder:
print("Border")
else:
print("Inside / Outside")
| false |
43d1e9724a6cd7e687d7fff3dabbca353bff647e | anulkar/python-challenge | /PyParagraph/main.py | 1,037 | 4.34375 | 4 | # ===================================================================
# PYTHON HOMEWORK - PyParagraph
# GT DATA SCIENCE BOOTCAMP
# PROGRAMMED BY: ATUL NULKAR
# Date: JANUARY 2020
# ===================================================================
# This is the Main Python script to run for the PyParagraph analysis.
# ===================================================================
# Import the pyparagraph module
# Module contains functions to:
# 1) Assess paragraphs within a text file
# 2) Generate simple metrics
import pyparagraph
# Loop 3 times to assess the three text files we have already prepared
for file_num in range(3):
# Sets the txt file that you want the script to read
input_txt_file = "paragraph_" + str(file_num + 1) + ".txt"
# Call function to analyze the passage in the text file and save the metrics to a list
pypara_metrics = pyparagraph.analyze_passages(input_txt_file)
# Call function to print the list of metrics to terminal
pyparagraph.print_metrics(pypara_metrics, input_txt_file) | true |
7d01963b43e212f2111ce01f79af38e0da96968a | davidvalles007/ContestCoding-Solutions | /magic7.py | 481 | 4.15625 | 4 | ## Author : David Valles
## Date : 03/03/2014
## Solution : 0
n=[0,1]
def generate_fibonacci(num1,num2):
if str(num1+num2)[0] == "7":
n.append((num1+num2))
print "The third digit of the smallest Fibonacci number which has a first digit of 7 is ", str(n[-1])[2]
#75025
else:
n.append((num1+num2))
generate_fibonacci(n[-1],n[-2])
generate_fibonacci(n[-1],n[-2])
raw_input()
| true |
441e754bc2e9fa20ef150206e3df981e4d09219e | JohnMDCarroll/LearningPython | /Exercise_Eleven_Check_Primality.py | 708 | 4.28125 | 4 | '''
Ask the user for a number and determine whether the number is prime or not.
(For those who have forgotten, a prime number is a number that has no divisors.).
You can (and should!) use your answer to Exercise 4 to help you.
Take this opportunity to practice using functions, described below.
'''
num = int(input('Insert a number: '))
if num > 1:
# check for factors
for i in range(2, num):
if (num % i) == 0:
print(num, "is not a prime number")
print(i, "times", num // i, "is", num)
break
else:
print(num, "is a prime number")
# if input number is less than
# or equal to 1, it is not prime
else:
print(num, "is not a prime number")
| true |
846e0d89c165f9bf6633ad4e8c6c2b4fa7f4f2d9 | ToddZenger/PHYS19a | /challenge/challenge-00-00.py | 1,425 | 4.28125 | 4 | """
Author: Todd Zenger, Brandeis University
The purpose of this code is to print out
zeros of a quadratic function
"""
# Side note, I realize that you can make a function for this, but I'm
# keeping this very basic for now
a = 1
b = 2.1
c = -3
x1 = (-b + (b**2 - 4*a*c)**(1/2))/(2*a)
x2 = (-b - (b**2 - 4*a*c)**(1/2))/(2*a)
print("Solution 1: ", x1)
print("Solution 2: ", x2)
# We also can reduce the length of the output using round()
print("Trimming down the data...")
print("Solution 1: ", round(x1, 2))
print("Solution 2: ", round(x2, 2))
# The value 2 tells us how many decimal places we want to cut down to
# Now let's look at a complex solution
# I'm just copying and pasting the same code as above and modifying c value
print("Now we have complex solutions:")
a = 1
b = 2.1
c = 3
x1 = (-b + (b**2 - 4*a*c)**(1/2))/(2*a)
x2 = (-b - (b**2 - 4*a*c)**(1/2))/(2*a)
print("Solution 1: ", x1)
print("Solution 2: ", x2)
"""
In the computer science/engineering world, the complex number
symbol of sqrt(-1) is symbolized by j instead of i
"""
print("Trimming down the data...")
# If you uncomment the two lines below you will get an error
#print("Solution 1: ", round(x1, 2))
#print("Solution 2: ", round(x2, 2))
# We need to print it out piece by piece to trim it down in our case
print("Solution 1: ", round(x1.real, 2), "+", round(x1.imag, 2), "j")
print("Solution 2: ", round(x2.real, 2), "+", round(x2.imag, 2), "j") | true |
55bdad5976aab8dfb3ab6a6938f385ed53617760 | OldKalash7/CiphersProject | /src/ReverseCipher.py | 509 | 4.1875 | 4 | # This cipher takes a string and encrypts it turning it around
import pyperclip
def main():
message = ''
print('ENTER A STRING TO ENCRYPT: ')
message = str(input())
print('THIS IS YOUR MESSAGE ENCRYPTED, COPIED TO CLIPBOARD')
print(reversecipher(message))
def reversecipher(message):
encrypted = ''
i = len(message) - 1
while i >= 0:
encrypted += message[i]
i -= 1
pyperclip.copy(encrypted)
return encrypted
if __name__ == '__main__':
main()
| true |
48f3b61100bfc346b9e64df2c6cd52487b49619a | zzylydx/source | /函数编程/函数-基本介绍.py | 519 | 4.15625 | 4 | #!/usr/bin/env python3
# coding utf-8
'''
def sayshi():
print("Hello, I' m nobody!")
sayshi()
'''
#定义:函数是指将一组语句的集合通过一个名字(函数名)封装起来,要执行这个函数,只需调用函数名即可
#特性:
# 减减少重复代码
# 使程序变得可扩展
# 使程序变得易维护
#下面这段代码
# a,b = 5,8
# c = a**b
# print(c)
#改成函数写
a,b = 5,8
def calc(x,y):
res = x ** y
return res
# print(calc(8,9))
# c = calc(a,b)
# print(c)
| false |
c7d92faa3acae56dacaec2575cba2ca7d8238c0b | Jparedes20/python_work | /squares.py | 884 | 4.46875 | 4 | #print the squares of a list of numbers
#define the list
_squares=[]
_values=list(range(1,21))
print("\nWe print a list of 20 numbers: \n"+str(_values))
#next loop will create the square of each number and will be appended to the list
for value in _values:
_squares.append(value**2)
print("\nWe print the squares of each number in the list: \n"+str(_squares))
#simple statistics with numbers
print("\nThe lower number in the list os squares is: "+str(min(_squares)))
print("\nThe Bigger number in the list os squares is: "+str(max(_squares)))
print("\nThe sum of all the square numbers is: "+str(sum(_squares)))
#Creating comprehensions
#It is possible to create comprehensions, which combines the foor loop and the creation of new elements
#in a single line
_cubes=[value**3 for value in _values]
print("\nWe print the cubes of each number in the list: \n"+str(_cubes))
| true |
f23b6cb9054b8780c307ba568fb8ebd2e9b53829 | denistet100/PythonBasics2 | /Tetyushin_Denis_dz_2/PZ1.py | 438 | 4.28125 | 4 | #1. Выяснить тип результата следующих выражений:
#15 * 3
#15 / 3
#15 // 2
#15 ** 2
multiplication = 15 * 3
division = 15 / 3
integer_division = 15 // 2
degree = 15 ** 2
print (type (multiplication),'multiplication = ', multiplication)
print (type (division),'division = ', division)
print (type (integer_division),'integer_division = ', integer_division)
print (type (degree),'degree = ', degree)
| false |
831184ffb8435f4b5112614b9af5858d7a2288d9 | WillLuong97/Linked-List | /copyListRandomPointer.py | 2,916 | 4.125 | 4 | #python3 implementation of leetcode 138. Copy List with Random Pointer
#Problem statement:
'''
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
The Linked List is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:
val: an integer representing Node.val
random_index: the index of the node (range from 0 to n-1) where random pointer points to, or null if it does not point to any node.
Example 1:
Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]
Example 2:
Input: head = [[1,1],[2,1]]
Output: [[1,1],[2,1]]
Example 3:
Input: head = [[3,null],[3,0],[3,null]]
Output: [[3,null],[3,0],[3,null]]
Example 4:
Input: head = []
Output: []
Explanation: Given linked list is empty (null pointer), so return null.
Constraints:
-10000 <= Node.val <= 10000
Node.random is null or pointing to a node in the linked list.
The number of nodes will not exceed 1000.
'''
#list node structure
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
class SpecialLinkedList:
def __init__(self, head):
self.head = None
#function add element into the linked list:
def insertIntoLinkedList(self, data):
#if the linked list is empty:
if not self.head:
new_node = Node(data)
#set the new data to the head values
self.head = new_node
return
#if the list is not empty:
new_node = Node(data)
new_node.next = self.head
self.head.random = new_node.next.next
#after the insertion, the new node will become the head of the linked list
self.head = new_node
#function to make a deep copy of the current linked list with random pointer
def copyRandomList(head: 'Node') -> 'Node':
#base case:
if not head:
return None
#visited dictionary to check if the current element has been repeated or not
visited = {}
return recursivelyCopy(head, visited)
#helper method to recursively copy all element in the linked list
def recursivelyCopy(head, visited):
#check if the head node has been visited or not
if head in visited:
return visited[head]
#if not, then make a copy of the linked list andd assign it into the dictionary
copiedNode = Node(head.val)
visited[copiedNode] = head
#the copied node would have next and random attribute from the class created:
#recursively call for the next and random element of the node
copiedNode.next = recursivelyCopy(head.next, visited)
copiedNode.randome = recursivelyCopy(head.random, visited)
return copiedNode
| true |
2e95b1adacf391d32c67da7bb97f2560aa1bbf9e | tatumalenko/algorithm-time | /2018-02-07/daily_temperatures.py | 1,017 | 4.34375 | 4 | # 739. Daily Temperatures
# Given a list of daily temperatures, produce a list that, for each day in
# the input, tells you how many days you would have to wait until a warmer
# temperature. If there is no future day for which this is possible, put 0 instead.
# For example, given the list temperatures = [73, 74, 75, 71, 69, 72, 76, 73],
# your output should be[1, 1, 4, 2, 1, 1, 0, 0].
# Note: The length of temperatures will be in the range[1, 30000]. Each
# temperature will be an integer in the range[30, 100].
def daily_temperatures(nums):
def predicate(index, value):
counter = 1
for i in range(index, len(nums) - 1):
if nums[i + 1] > nums[i]:
return counter
elif i == len(nums - 1):
return 0
else:
counter += 1
return predicate(3, 71)
# return map(predicate, enumerate(nums))
def main():
print(daily_temperatures([73, 74, 75, 71, 69, 72, 76, 73]))
if __name__ == '__main__':
main()
| true |
4b576abe2176f88f35662fef91e37586c796aa5f | ahidalgoma/cursopython | /ExpresionesRegulares3.py | 569 | 4.125 | 4 | import re
lista_nombre=["Ana", "Pedro", "María", "Rosa", "Sandra", "Celia"]
print("Elementos que contengan en alguna parte alguna de las siguientes letras O,P,Q,R,S,T")
for elemento in lista_nombre:
if re.findall('[o-t]', elemento):
print(elemento)
print("Elementos que inicien con las letras O,P,Q,R,S,T")
for elemento in lista_nombre:
if re.findall('^[O-T]', elemento):
print(elemento)
print("Elementos que terminen con las letras o,p,q,r,s,t")
for elemento in lista_nombre:
if re.findall('[o-t]$', elemento):
print(elemento)
| false |
6669c091b6fab9fd499a04902bec2c2ba67d6b5d | Larionov0/Group2-lessons | /Homeworks/FunctionalProgramming/numbers.py | 500 | 4.21875 | 4 | '''
Пользователь вводит числа через пробел. Программа выводит список из тех чисел пользователя,
которые не делятся на 3. Циклы запрещены.
'''
# odd_numbers = list(filter(lambda number: number % 2 == 0, numbers))
numbers = input('enter numbers:')
numbers_lst = numbers.split(' ')
numbers_lst = list(map(int, numbers_lst))
print(list(filter(lambda number: number % 3 != 0, numbers_lst)))
| false |
8fb4275fc1a702630316e4aeb764243a8f078eeb | shcherbinaap/new_rep_for_hw | /Lesson_2/task 1.py | 1,255 | 4.34375 | 4 | #1. Создать список и заполнить его элементами различных типов данных.
# Реализовать скрипт проверки типа данных каждого элемента.
# Использовать функцию type() для проверки типа.
# Элементы списка можно не запрашивать у пользователя, а указать явно, в программе.
my_list = ["Строка", (1, 2), 1, 10.5]
# Вариант 1. Через while
print("Вариант №1")
i = 0
while i < len(my_list):
print(f"Тип {i + 1} элемента списка {type(my_list[i])}")
i += 1
# Вариант 2. Через for, когда нужна информация об индексе
print("Вариант №2")
my_list_type = []
for i in range(len(my_list)):
print(f"Тип {i + 1} элемента списка {type(my_list[i])}")
my_list_type.append(type(my_list[i]))
print(my_list_type)
# Вариант 3. Через for, когда информация об индексе не нужна
print("Вариант №3")
for item in my_list:
print(f"Тип элемента списка '{item}' - {type(item)}")
| false |
d02cf719b79e33c508fb926e9b7e38b364db4fcd | jacyyang04/Learn-Python-the-Hard-Way | /ex7.py | 643 | 4.34375 | 4 | #more printing from Learn Python the Hard Way
#sets variable equal to days of the week
days = "Mon Tue Wed Thur Fri Sat Sun"
#sets variable to the months with a new line for each month
months = "\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug\nSept\nOct\nNov\nDec"
print("Here are the days: ", days)
print("Here are the months: ", months)
#prints the paragraph
paragraph = """
There's something going on here.
With the three double quotes.
I think it will print this all out?
As there has been two quotes and one
more that. Which means that the
terminal will print a break and
then this paragraph. Although,
it's not tabbed.
"""
print(paragraph)
| true |
700a82e58a7707ca2cb0dc14bafb18e4a727e4bf | jacyyang04/Learn-Python-the-Hard-Way | /ex11.py | 975 | 4.21875 | 4 | #modules is the same as libraries
#importing modules to this script
#argv holds the argument I pass to python
from sys import argv
#unpacks argv and assigns variables
script, first, second, third, fourth = argv
#can set variables up as raw_input() but would need to make sure
#in terminal, run it as:
#python3 ex11.py first second third fourth
first = input("What is your favorite color? ", )
second = input("What is your favorite ice cream? ", )
third = input("What is your favorite drink? ", )
fourth = input("Who is your hero? ", )
#I can also run raw_input at the end.
print("The script is called:", script)
input("First variable is: ")
input("Second variable is: ")
input("Third variable is: ")
input("Fourth variable is: ")
#Output:
#in terminal, type [python3 ex11.py ___ ___ ___ ___]
#I would pick out the given arguments
#python ex11.py hello Jacy Yang
#The script is called: ex11.py
#First variable is: hello
#Second variable is: Jacy
#Third variable is: Yang
| true |
79aef0118f5e68c75a8bd183fc03255326a62093 | emuro7/learn-python | /zen-eo.py | 1,016 | 4.1875 | 4 | import this
print("\n")#Skip a line
#Python basic data types
print("Python basic data types\n")
#Boolean
bool_t = True
bool_f = False
#Number
#Float
flt = 0.5
#Interger
num = 35
string = "Hello world"
#Some data types are either mutable or immutable
#Mutable means that the datatype can me modified or changed
#Mutable data type examples
#Lists
l = [True, False, 35,0.5, "Dog"]
print(l)
print(type(l))
#dictionaries
dic = {"Kelly":"Scooter", "Robert": "Mr. Giggles", "John":"Robert" }
print(dic)
print(type(dic))
#Immutable means that the datatype can not be modified or changed
#Immutable data type exampes
#Booleans
bool_t = True
print(bool_t)
print(type(bool_t))
bool_f = False
print(bool_f)
print(type(bool_f))
#Intergers
num = 35
print(num)
print(type(num))
#Floats
flt = 0.5
print(flt)
print(type(flt))
#Tuples
tup = (0,11,22)
print(tup)
print(type(tup))
#String
word = "Cat"
print(word)
print(type(word))
#Check data type
type(bool_t)
| true |
1230004df711b9365b3a1f522ec71d49e7a41f1f | NikitaMatyas/Learning-Python | /Generators.py | 891 | 4.125 | 4 | # Генераторы - объекты, предназначенные для создания последовательностей
a = sum(range(1, 101))
print(a)
# Функция генератора (возвращает значение с помощью yield, а не return)
def my_range(first=0, last=10, step=1):
number = first
while number < last:
yield number
number += step
# Важно понимать, что обычная функция возвращает просто значение и не помнит о предыдущих вызовах
# Генератор же отслеживает где он находится во время предыдущего вызова и возвращает следующее значение
print(type(my_range))
ranger = my_range(1, 5)
print(type(ranger))
for x in ranger:
print(x)
| false |
46654e2236d2a7ec249e16df19e638cb8181a2f1 | sathvik-dhanya/python-programming-masterclass | /Section9_Dictionaries_Sets/dictionary1.py | 2,491 | 4.1875 | 4 | #!/usr/bin/env python3
"""
Modify the program so that the exits is a dictionary rather than a list,
with the keys being the numbers of the locations and the values being
dictionaries holding the exits (as they do at present). No change should
be needed to the actual code.
Once that is working, create another dictionary that contains words that
players may use. These words will be the keys, and their values will be
a single letter that the program can use to determine which way to go.
locations = {0: "At Home",
1: "On the Road",
2: "On the Hill",
3: "In the Building",
4: "In the Valley",
5: "In the Forest"
}
exits = [{"Q": 0},
{"W": 2, "E": 3, "N": 5, "S": 4, "Q": 0},
{"N": 5, "Q": 0},
{"W": 1, "Q": 0},
{"N": 1, "W": 2, "Q": 0},
{"W": 2, "S": 1, "Q": 0}
]
loc = 1
while True:
availableExits = ", ".join(exits[loc].keys())
print(locations[loc])
if loc == 0:
break
direction = input("Available exits are " + availableExits + " ").upper()
print()
if direction in exits[loc]:
loc = exits[loc][direction]
else:
print("You cannot go that way")
"""
locations = {0: "At Home",
1: "On the Road",
2: "On the Hill",
3: "In the Building",
4: "In the Valley",
5: "In the Forest"
}
exits = {0: {"Q": 0},
1: {"W": 2, "E": 3, "N": 5, "S": 4, "Q": 0},
2: {"N": 5, "Q": 0},
3: {"W": 1, "Q": 0},
4: {"N": 1, "W": 2, "Q": 0},
5: {"W": 2, "S": 1, "Q": 0}
}
vocab = {"QUIT": "Q",
"NORTH": "N",
"SOUTH": "S",
"EAST": "E",
"WEST": "W"
}
loc = 1
while True:
availableExits = ", ".join(exits[loc].keys())
print(locations[loc])
if loc == 0:
break
direction = input("Available exits are " + availableExits + " ").upper()
print()
# Parse user input to use vocabulary dictionary if needed
if len(direction) > 1: # if more than one letter
# for i in vocab:
# if i in direction:
# direction = vocab[i]
words = direction.split()
for i in words:
if i in vocab:
direction = vocab[i]
break
if direction in exits[loc]:
loc = exits[loc][direction]
else:
print("You cannot go that way")
| true |
2cddc7e70d96a836e0ef587d77da9ffa0716482f | sathvik-dhanya/python-programming-masterclass | /Section13_DBs/contacts.py | 829 | 4.4375 | 4 | #!/usr/bin/env python3
"""
Example for SQL in python
"""
import sqlite3
db = sqlite3.connect("contacts.sqlite")
db.execute("CREATE TABLE IF NOT EXISTS contacts (name TEXT, phone INTEGER, email TEXT)")
db.execute("INSERT INTO contacts(name, phone, email) VALUES('Tim', 6545678, 'tim@email.com')")
db.execute("INSERT INTO contacts VALUES('Brian', 1234, 'brian@myemail.com')")
cursor = db.cursor()
cursor.execute("SELECT * FROM contacts")
# print each row
# for row in cursor:
# print(row)
# unpack and print
# for name, phone, email in cursor:
# print(name)
# print(phone)
# print(email)
# print("-" * 20)
# print all rows in a list
# print(cursor.fetchall())
# print each row in an iterable manner
# print(cursor.fetchone())
# print(cursor.fetchone())
# print(cursor.fetchone())
cursor.close()
db.commit()
db.close()
| true |
33dfbfa574f4b5980cf31b6e40956267499ac684 | reshmastadas/Machine_Learning | /Common_Functions/EDA/null_values.py | 971 | 4.1875 | 4 | import pandas as pd
def find_null_percent(df):
'''
Purpose:
Function to find % of null values in each column of a dataframe.
Input:
df: Dataframe.
Returns:
null_df: a dataframe with % of null values.
Imports:
import pandas as pd
Author: Reshma Tadas
'''
null_df = pd.DataFrame(df.isnull().sum()).reset_index()
null_df[0] = null_df[0]/len(df)
null_df[0] = null_df[0].apply(lambda x: str(round(x,4)*100)+' %')
return null_df
def get_num_cat_cols(df,limit=10):
'''
Purpose:
Function to get numerical and categorical columns of a dataframe.
Input:
df: Dataframe.
limit: max number of unique values allowed in categorical column.
Returns:
num_cols: numerical columns
cat_cols: categorical columns
Imports:
import pandas as pd
Author: Reshma Tadas
'''
unique_df = pd.DataFrame(df.nunique()).reset_index()
cat_cols = list(unique_df[unique_df[0]<=limit]['index'])
num_cols = list(unique_df[unique_df[0]>limit]['index'])
return (num_cols,cat_cols) | true |
3c2d80b827853bf05c41635cfa2bb252a77f2a40 | ashleefeng/qbb2017-answers | /day2-morning/03-types.py | 613 | 4.15625 | 4 | #!/usr/bin/env python
print "Basic types..."
a_string = "This is a string"
an_integer = 7
int_to_str = str(an_integer)
a_real = 5.689
string_to_real = float("5.668")
truthy = True
falsy = False
for value in a_string, an_integer, a_real, truthy, falsy:
print value, type(value)
print "Lists and tuples"
a_list = [1, 2, 3, 4, 5]
a_tuple = (1, "foo", 3.2)
# print a_list, type(a_list)
# print a_tuple, type(a_tuple)
#
a_list[3] = 777
print a_list
#
# # a_tuple[2] = "hi"
# print a_tuple[2]
# copy content into another list
another_list = list(a_list)
another_list[3] = 888
print another_list
print a_list
| true |
5a03cf6a51cb82092c5893c798e39fa215be2e9b | Ultenhofen/Sorting-Algorithms | /mergeSort.py | 1,335 | 4.15625 | 4 | from datetime import datetime
from timeit import default_timer as timer
def mergeSort(list):
if len(list) > 1:
m = len(list)//2 # Determine the midpoint of the list
Left = list[:m] # Then split the list into two halves
Rght = list[m:] # and then call mergeSort on the halves
mergeSort(Left)
mergeSort(Rght)
i,j,k=0,0,0
while len(Left) > i and len(Rght) > j: # To sort, add the split lists back together
if Left[i] > Rght[j]: # lower values first
list[k] = Rght[j] # Keep track of three separate iterators:
j+=1 # i for Left, j for Rght, and k for list
else:
list[k] = Left[i]
i+=1
k+=1
while i < len(Left): # At one point, the first loop will end and
list[k] = Left[i] # that could happen before one of the arrays are empty
i+=1 # Empty the remaining values into the list
k+=1
while j < len(Rght):
list[k] = Rght[j]
j+=1
k+=1
| true |
fe0c65e6c220fe64851190821b18615cc7309b74 | niksfred/SoftUni_Fundamentals | /Functions_exercise/palindrome_integers.py | 321 | 4.21875 | 4 | def palindrome(numbers_string):
numbers_list = numbers_string.split(", ")
for number in numbers_list:
reversed_number ="".join(reversed(number))
if number == reversed_number:
print("True")
else:
print("False")
numbers_string = input()
palindrome(numbers_string)
| true |
33703fa66bc1111940b91e017dc249640ece8eee | MirouHsr/one-million-arab-coders | /project/test.py | 2,263 | 4.4375 | 4 | # lesson 5: variables & strings
#we can use variable to define something like an int number or string or array
#syntax: var_name = expression ..
age = 23
days_of_year = 365.25
hours_of_sleep = 7
age_in_days = age * days_of_year
sleep_hours_in_life = age_in_days * hours_of_sleep
awake_hours_in_life = (age_in_days * 24) - sleep_hours_in_life
print age_in_days
print sleep_hours_in_life / 24
print awake_hours_in_life / 24
# name of variable can't be separated by spaces like (age in day)..
# a string is a type of variable ==> it means a series of Character ..
last_name = 'Hasrane ' # between '...'
# OR
first_name = "Amir " # between "..."
# both are right
print "Hello " + first_name + last_name + '!' * 3
# as you see we can add to strings by the plus operator (+).. and we call that "String concatenation" ....
# We can even multiply a string by a integer number for avoiding repeatation....
# This code shows the difference between the string "4" and the number 4.
# Remove the four comment characters (#) on the lines below to see what happens.
print 4
print "4"
print 4 + 4
print "4" + "4"
# Write Python code that prints out Udacity (with a capital U),
# given the definition of s below.
s = 'audacityda'
# answer is :
print 'U' + s[2:]
# This segment is just a chance for you to play around with
# finding strings within strings. Read through the code and
# press Test Run to see what it does. Is there anything
# interesting or unexpected?
print "Example 1: using find to print the second occurrence of a sub-string"
print "test".find("t")
print "test".find("t", 1)
print "Example 2: using a variable to store first location"
first_location = "test".find("t") # here we store the first location of "t"
print "test".find("t", first_location+1) # then we use that location to find the second occurrence.
print "Example 3: using find to get rid of exclamation marks!!"
example = "Wow! Python is great! Don't you think?"
first = example.find('!')
second = example.find('!', first + 1)
new_string = example[:first] + example[first+1:second] + example[second+1:]
print new_string # oops, I should probably replace the !s with periods
new_string = example[:first] +'.'+ example[first+1:second] +'.'+ example[second+1:]
print new_string | true |
36806298597b23a57a45afcf94b1771f36ae4560 | debaonline4u/Python_Programming | /arrays_in_python/method_array_1.py | 820 | 4.28125 | 4 | # Python program to understand various methods of array class.
from array import *
arr = array('i', [10, 20, 30, 40, 50, 60, 70]) # Creating an array.
print('Original Array: ', arr)
# append 30 to the array
arr.append(30)
arr.append(60)
print('After appending 30 and 60: ', arr)
# insert 999 at position number 1 in arr
arr.insert(1, 999)
print('After inserting 999 in 1st position: ', arr)
# remove an element from arr
arr.remove(20)
print('After remove 20: ', arr)
# remove last element using pop()
n = arr.pop()
print('Array after using pop()', arr)
print('Popped element: ', n)
# finding position of element using index() method
n = arr.index(30)
print('First occurance of 30: ', n)
# convert the array into a list using tolist() method
lst = arr.tolist()
print('List: ', lst)
print('Array: ', arr)
| true |
6affe16c2e1a39601d1e086763094dd3cf020142 | debaonline4u/Python_Programming | /arrays_in_python/linear_search.py | 811 | 4.1875 | 4 | # Python program to implement Linear Search.
from array import *
arr = array('i', []) # Creating an empty array.
print('How many elements you want to enter: ', end='')
n = int(input())
for i in range(n):
print('Enter elements: ', end='')
arr.append(int(input()))
print('Original Array: ', arr)
s = int(input('Enter element to search: \n'))
# Now implement Linear search.
#
# flag = False
# for i in range(n):
# if s == arr[i]:
# print('{} found at position: {}'.format(s, i+1))
# flag = True
#
# if flag is False:
# print('{} not found in the array. '.format(s))
# implementing position of the number using index()
try:
pos = arr.index(s)
print('{} found at position: {}'.format(s, pos + 1))
except ValueError:
print('{} not found in the array. '.format(s)) | true |
56141ddfbbd276d0d440eb5d555e1a350d28063a | debaonline4u/Python_Programming | /string_functions_in_python/string_Template_with_list.py | 537 | 4.25 | 4 | # program to demonstrate string template for printing values in list.
from string import Template
# make a list of student_name and mark for students.
students=[('Ram',40),('Joshi',75),('Karan',55)]
#creating the basic structure to print the student name and their marks.
t=Template("Hi $name, you have got $mark marks. Good Luck. ")
for each_student in students:
print(t.substitute(name=each_student[0], mark=each_student[1]))
# here with the substitute function, we are giving values to $name and $mark from the list.
| true |
29a45bee78b2ca23292e554f3d96a206dfce9e1d | debaonline4u/Python_Programming | /string_functions_in_python/string_function_center_ljust_rjust.py | 453 | 4.375 | 4 | # Python code to demonstrate working of
# center(), ljust() and rjust()
str = "geeksforgeeks"
# Printing the string after centering with '-'
print ("The string after centering with '-' is : ",end="")
print ( str.center(20,'-'))
# Printing the string after ljust()
print ("The string after ljust is : ",end="")
print ( str.ljust(20,'-'))
# Printing the string after rjust()
print ("The string after rjust is : ",end="")
print ( str.rjust(20,'-')) | true |
607890591a6745e04229ad49080a34af90918738 | zhangda7/leetcode | /solution/_74_search_a_2D_matrix.py | 1,229 | 4.125 | 4 | # -*- coding:utf-8 -*-
'''
Created on 2015/7/30
@author: dazhang
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3, return true.
'''
class Solution:
# @param {integer[][]} matrix
# @param {integer} target
# @return {boolean}
def searchMatrix(self, matrix, target):
if matrix == None or len(matrix) == 0:
return False
rowIndex = 0
for i in range(0, len(matrix)):
row = matrix[i]
if len(row) == 0:
continue
if row[0] <= target and row[len(row) - 1] >= target:
rowIndex = i
break
for num in matrix[rowIndex]:
if num == target:
return True
return False
if __name__ == '__main__':
s = Solution()
print(s.searchMatrix([[1,3,5,7],[10,11,16,20], [23,30,34,50]], 23))
#print(s.searchMatrix([[1],[3]],3))
pass | true |
5c4f11e238a0dd47fddeff007707a00b389ac392 | pythonwithalex/Fall2014 | /week2/mutability.py | 836 | 4.46875 | 4 | # Programming With Python Week 2
# Mutability vs Immutability
# If a data type is mutable, parts of it can be changed and it is still the same 'object'.
# If a data type is immutable, then you can't change any part. You can only create an object by the same name and give it different values.
# Lists are mutable
#################
l = [0,1,2,3,4]
l.append(5)
print l
# prints [0,1,2,3,4,5]
# l is still the same object after I added 5 to it.
# Strings are immutable
#####################
s = 'bob'
s[0] = 'R'
# You can't do that!
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# TypeError: 'str' object does not support item assignment
id(s)
# prints '140470567078568'
s = 'robert'
id(s)
# prints '140470567089616'
# CONCLUSION: s refers to a new object when you assign it the value 'robert'
| true |
0dae5b397f93b263bfecc3682edf263ac1a009a0 | go-bears/coding-challenges | /sum_3_to_0.py | 2,181 | 4.40625 | 4 | """
Write a function to determine if any 3 integers in an array sum to 0.
If so, return True if, else False
>>> is_sum_three_to_zero([1,-1,3,5,2,-2])
True
>>> is_sum_three_to_zero([1,1,1,1,1])
False
>>> is_sum_three_to_zero([1,-1])
False
>>> is_sum_three_to_zero([1,-1, 0])
True
"""
def is_sum_three_to_zero(lst):
"""
Write a function to determine if any 3 integers in an array sum to 0.
>>> is_sum_three_to_zero2([1,-1,3,5,2,-2])
True
>>> is_sum_three_to_zero2([1,1,1,1,1])
False
"""
# validity check
if len(lst) < 3:
return False
if sum(lst) == 0:
return True
# sort integer list from low-high to prevent duplicates during iterations
lst = sorted(lst)
# set ranges for iteration lists for other sum_three values
j_lst = lst[1::]
k_lst = lst[2::]
# initialize list of integers that store 3 values that sum to three
sum_three = [None, None, None]
# nested for-loops
for i in lst:
sum_three[0] = i
for j in j_lst:
sum_three[1] = j
for k in k_lst:
sum_three[2] = k
if sum(sum_three) == 0:
return True
if sum(sum_three) != 0:
return False
def is_sum_three_to_zero2(lst):
"""
Write a function to determine if any 3 integers in an array sum to 0.
Method 2: sort list in to postitive and negative & check for
"""
positive = []
negative = []
for i in lst:
if i > 0:
positive.append(i)
if i < 0:
negative.append(i)
if abs(sum(negative)) in positive:
return True
else:
return False
def main():
import doctest
import timeit
print is_sum_three_to_zero([1,-1,3,5,2,-2])
print timeit.timeit(lambda: is_sum_three_to_zero([1,-1,3,5,2,-2]), number=100)
print is_sum_three_to_zero2([1,-1,3,5,2,-2])
print timeit.timeit(lambda: is_sum_three_to_zero2([1,-1,3,5,2,-2]), number=100)
if doctest.testmod().failed == 0:
print "\n*** All tests passed!\n"
if __name__ == '__main__':
main() | true |
fef6245c108e3c742c3154e6549edca88b72d599 | devopshndz/curso-python-web | /Python sin Fronteras/Python/2- Tipos de datos/3- Tuplas.py | 1,441 | 4.5625 | 5 | # Las tuplas son muy parecidas a las listas, pero, estas, una vez que las creas NO PUEDES MODIFICARLAS.
# Necesariamente se debe generar una copia de estas en el caso de querer cambiarlas
# Sintaxis:
tupla = ('Hola', 'Mundo', 'somos', 'tupla') # las tuplas son como las listas, pero en vez de
# utilizar [] utilizamos ()
print(tupla)
# Podemos observar que al imprimir la tupla, nos muestra sus valores dentro de ()
# a difierencia de las listas que nos los muestran dentro de []
# Las tuplas a diferencia de las listas tienen bastante menos metodos.
# metodo count: contará cuantas veces está un argumento en la tupla.
print(tupla.count('Hola'))
# Metodo index: sirve para saber en que posición se encuentra un elemento dentro de una tupla
print(tupla.index('Hola'))
# Modificar contenido de una tupla: Python no permite hacer modificaciones a una tupla, pero,
# se puede realizar modificaciones y convertimos una tupla en una lista.
listaDeTupla = list(tupla)
# lo que se hace es lo siguiente:
# 1. se crea una variable y se le asigna la funcion list() la cual va a convertir valores a lista
# 2. dentro de list() se coloca nuestra tupla: list(tupla)
# 3. se imprime la nueva lista para comprobar que ya no es una tupla sino una lista:
print(listaDeTupla)
# Ya podemos trabajar con la nueva lista creada a partir de la tupla.
listaDeTupla.append('Junior tu papa')
print(listaDeTupla) | false |
b6d430d16a1f17a379149b2ec88d337c2c298ef7 | devopshndz/curso-python-web | /Python sin Fronteras/Python/2- Tipos de datos/1- String y numeros.py | 643 | 4.15625 | 4 | # un string es una palabra o una frase, está dentro de '' o ""
# los numero en python son varios, tenemos los enteros int, los flotantes float/double
# y los complejos
palabra = 'Hola mundo' # string
oracion = "Hola mundo comilla doble" # string
entero = 25 # numeros enteros son numeros sin decimales
flotante = 25.5 # float, con decimales, para declarar un flotante no hace falta escribir
# la palabra reservada float, pero se se utiliza en ciertos casos en
# donde hayan muchos datos.
complejo = 1j # complejo, siempre se agrega una j despues del número.
print(palabra, oracion, entero, flotante, complejo) | false |
a1ad614d6e4a92c1457b89125d1f74d9bfbb14e8 | a1ip/checkio-17 | /feed-pigeons.py | 931 | 4.125 | 4 |
def checkio(food):
minute = 0
fed_pigeons = 0
pigeons = 0
while True:
minute += 1
old_pigeons = pigeons
pigeons += minute
if food < pigeons:
# to feed sombody from newly arrived pegions
# if remains_food < 0, means that only 3 distinct pigeons fed
# remains_food hold amount of newly arrived pegions which we able to feed
remains_food = food - old_pigeons
if remains_food > 0:
fed_pigeons += remains_food
break
else:
food -= pigeons
fed_pigeons += minute
return fed_pigeons
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert checkio(1) == 1, "1st example"
assert checkio(2) == 1, "2nd example"
assert checkio(5) == 3, "3rd example"
assert checkio(10) == 6, "4th example" | true |
caa1f296c7a4868110314debe4ac821ea99a20a6 | gcgc100/mypythonlib | /gClifford/setTools.py | 616 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def merge_set_from_pairs(pairs):
"""Merge to a serious of set from a list of pairs
e.g. [1,2] [2,3] [5,6] [9,8] [1,3] -> [1,2,3] [5,6] [8,9]
:pairs: a list of pairs, every pair has two value
"""
setResult = []
for p in pairs:
assert len(p) == 2
setExists = False
for s in setResult:
if p[0] in s or p[1] in s:
s.add(p[0])
s.add(p[1])
setExists = True
break
if not setExists:
setResult.append(set(p))
return setResult
| true |
604febde80e37c3d2b2f8e700973b850522a24bb | KellyJason/Python-Tkinter-example. | /Tkinter_Walkthrough_3.py | 1,394 | 4.28125 | 4 | import os
import tkinter as tk
#begining of the window
root= tk.Tk()
#this creates an area for the labes and button to go in
canvas1 = tk.Canvas(root, width = 350, height = 400, bg = 'lightsteelblue2', relief = 'raised')
canvas1.pack()
# this is the label
label1 = tk.Label(root, text='Hello Kelly Girls,''\n''Ready to be Awesome?''\n''Click the button!', bg = 'lightsteelblue2',font=('helvetica', 20))
#This adds the label to the canvas
canvas1.create_window(175, 80, window=label1)
#now to try and configure the button to go somewhere
def button ():
#begining of the window
window= tk.Tk()
#this creates an area for the labes and button to go in
canvas2 = tk.Canvas(window, width = 350, height = 250, bg = 'lightsteelblue2', relief = 'raised')
canvas2.pack()
# this is the label
label2 = tk.Label(window, text='Hello Kelly Girls,''\n''You are Awesome!!', bg = 'lightsteelblue2',font=('helvetica', 20))
#This adds the label to the canvas
canvas2.create_window(175, 80, window=label2)
#end of window
window.mainloop()
# here is the button
but1 = tk.Button(text=' The Awesome Button ', command = button, bg='green', fg='white', font=('helvetica', 12, 'bold' ))
but1.pack()
#this adds the button to the canvas
canvas1.create_window(175, 180, window=but1)
#end of window
root.mainloop()
| true |
012d9c61edc947b5903c70e1871587391ebede71 | diallog/GCPpy | /01_listExercise.py | 1,074 | 4.15625 | 4 | #!/usr/bin/env python3
# obtain name and age data for multiple people until entering 'stop'
# then report who is the oldest person
# use lists for this exercise
import os
os.system('clear')
# initialize variables
nameList = []
ageList = []
newName = None
newAge = 0
maxAge = 0
maxIndex = 0
# get input
newName = input ("What is the person's name? (enter 'stop' to quit collecting names.) ")
newName = newName.lower()
while newName != 'stop':
nameList.append(newName)
newAge = input ("How old is {newName}? ".format(newName = newName.capitalize()))
newAge = int(newAge)
ageList.append(newAge)
print ("Thank you. Name and age recorded for {newName}.".format(newName = newName.capitalize()))
print ("\n")
newName = input ("What is the person's name? (enter 'stop' to quit collecting names.) ")
newName = newName.lower()
# process data
maxAge = max(ageList)
maxIndex = ageList.index(maxAge)
# report results
print ("\n")
print ("{oldest} is the oldest person with an age of {age}."
.format(oldest = nameList[maxIndex].capitalize(), age = ageList[maxIndex]))
| true |
12c512b16f6ff3f3b68a3766d513617b758518a1 | diallog/GCPpy | /listExercise.py | 438 | 4.15625 | 4 | #!/usr/bin/env python3
# input name and age for multiple people until entering 'stop'
# then report who is the oldest person
# use lists for this exercise
# initialize variables
newName = None
listIndex = 0
maxAge = 0
names = []
ages = []
# get input
newName = input ("What is the person's name?")
try:
if type(newName) == str:
newName.lower()
except:
print ("Expected to get a name. This doesn't look like a name.")
| true |
04b758aea347fa68ae3d73565b85f2a400e76057 | shirish-babbur/Python | /ex6.py | 779 | 4.5625 | 5 | #Different ways to format or concatination of strings.
types_of_people = 10
x = f"There are {types_of_people} types of people."
#F'string example for storing in varibles
binary = "binary"
do_not = "don't"
y = f"Those who know {binary} and those who {do_not}."
#1 #2
print(x)
print(y)
#print statement using 'F' Strings
print(f"I said: {x}")#3
print(f"I also said: {y}")#4
#Format function demo code
hilarious = False
joke_evaluation = "Isn't that joke so funny?! {} "
#print statement using format function
print(joke_evaluation.format(hilarious))
#String varibles
w = "This is the left side of..."
e = "a string with right side"
#print statement concatinating both strings. Operator overloading '+'
print(w+e)
| true |
e77eafb6540aa0eb93f82ef966c063db852d67b5 | rahlk/algorithms-in-py | /mergesort.py | 2,557 | 4.21875 | 4 | import numpy as np
from pdb import set_trace
def _merge(one, two):
"""
Merge two arrays
Parameters
----------
one : <numpy.ndarray>
A sorted array
two : <numpy.ndarray>
A sorted array
Returns
-------
<numpy.ndarray>
Merged array
Notes
-----
1. The intuition here is that the two arrays are sorted. So the smallest
element in each of the arrays is always on the top.
2. So, we can compare the two topmost elements and save the least until
both the arrays are exhausted.
"""
aux = []
while one and two:
if one[0] < two[0]:
next_ = one.pop(0)
else:
next_ = two.pop(0)
aux.append(next_)
aux.extend(one)
aux.extend(two)
return aux
def mergesort(raw_array):
"""
Perform merge sort.
Parameters
----------
raw_array : <numpy.ndarray>
An array of unsorted numbers
Returns
-------
<numpy.ndarray>
Sorted array
Notes
-----
1. Divide the array in two approximately equal halves (left and right)
2. Recurse on the left array
3. Recurse on the right array
4. Merge the two arrays
"""
if len(raw_array) == 1:
return raw_array
numel = len(raw_array)
left = raw_array[:int(numel/2)]
right = raw_array[int(numel/2):]
"It's possible that there is only one element, these must be lists"
if not isinstance(left, list):
left = list(left)
if not isinstance(right, list):
right = list(right)
return merge(sort(left), sort(right))
def mergesort_dynamic(raw_array):
"""
Perform merge sort with dynamic programming
Parameters
----------
raw_array : <numpy.ndarray>
An array of unsorted numbers
Returns
-------
<numpy.ndarray>
Sorted array
Notes
-----
1. Divide the array in two approximately equal halves (left and right)
2. Recurse on the left array
3. Recurse on the right array
4. Merge the two arrays
"""
while len(raw_array) > 1:
numel = len(raw_array)
for idx in range(int(numel/2)):
one = raw_array.pop(idx)
two = raw_array.pop(idx)
"It's possible that there is only one element, these must be lists"
if not isinstance(one, list):
one = [one]
if not isinstance(two, list):
two = [two]
raw_array.insert(idx, _merge(one, two))
return raw_array[0]
| true |
b6f99862030a2f99685e1570afaa1f020a38f11a | mrutyunjay23/Python | /topics/Closure.py | 638 | 4.4375 | 4 | '''
Closure
'''
def outerFunction(num1):
def innerFunction(num2):
return num2 ** num1
return innerFunction
x2 = outerFunction(2) #num1 will be 2
print(x2(10)) #num2 will be 10 and num1 = 2
print(x2(20)) #num2 will be 20 and num1 = 2
'''
the value num1 is 2 is carreid in both the statement
Hence Closue is used to attach value with function
here the outerfunction holds value num1=2 for every call of innerfunction
'''
x3 = outerFunction(3) #now this will atach value 3 with the innerfunction
print(x3(10)) #num2 will be 10 and num1 = 3
print(x3(20)) #num2 will be 20 and num1 = 3
print(outerFunction(3)(20))
| true |
e396579c2eefea08087468aca0a9019cd0f0769b | LeBron-Jian/BasicAlgorithmPractice | /LeetCode_practice/LinkedList/02_03DeleteMiddleNodeLcci.py | 1,696 | 4.125 | 4 | # _*_coding:utf-8_*_
'''
面试题02.03 删除中间节点
题目:
实现一种算法,删除单向链表中间某个节点(即不是第一个或最后一个节点)
假定你只能访问该节点
示例:
输入:单向链表a->b->c->d->e->f中的节点c
结果:不返回任何数据,但该链表变为a->b->d->e->f
'''
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def deleteNode1(self, node):
"""
这个题的核心实现就是把node的下一位的值覆盖给node,然后跳过node的下一位
因为我们无法访问到head节点,所以除了直接从node开始往下找,其他都是不现实的
即:
(注意:首先把当前值变为d,即把c变为d,存在两个 d
a->b->c->d->e->f 变为 a->b->d->d->e->f
然后把第一个d的next设为e,跳过第二个d(我们需要跳过第二个d)
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.val
node.next = node.next.next
def deleteNode11(self, node, n):
'''
对上面代码的改进,防止报错,如给了当前节点的值 current.val
不过思路都是一样,用当前节点取代下一个节点,跳过下一个节点
:param node:
:return:
'''
while True:
if node.val == n:
node.val = node.next.val
node.next = node.next.next
break
else:
node = node.next
| false |
bd6fd3e6ffe25c4cc471919edf5a31f3a282ad48 | joshuafreemn/py | /x10.py | 204 | 4.15625 | 4 | number = input("Pick a number: ")
number = int(number)
if number % 10 == 0:
print("The number " + str(number) + " is divisiable by 10")
else:
print("The number " + str(number) + " not divisible by 10") | false |
dea1247f080064554b3638c8c2bda4759e3d5a1c | catherine7st/SoftUni-Python_Fundamentals | /Functions/(function-ex)palindrome_integers.py | 241 | 4.21875 | 4 | def palindrome(string):
for each_str in string:
if each_str == each_str[::-1]:
print('True')
else:
print('False')
return string
current_string = input().split(", ")
palindrome(current_string) | false |
45887c00e398049a52c41a583970207ed0a3a065 | Frankiee/leetcode | /array/73_set_matrix_zeroes.py | 2,674 | 4.1875 | 4 | # https://leetcode.com/problems/set-matrix-zeroes/
# 73. Set Matrix Zeroes
# History:
# Facebook
# 1.
# Mar 8, 2020
# 2.
# Apr 22, 2020
# Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
#
# Example 1:
#
# Input:
# [
# [1,1,1],
# [1,0,1],
# [1,1,1]
# ]
# Output:
# [
# [1,0,1],
# [0,0,0],
# [1,0,1]
# ]
# Example 2:
#
# Input:
# [
# [0,1,2,0],
# [3,4,5,2],
# [1,3,1,5]
# ]
# Output:
# [
# [0,0,0,0],
# [0,4,5,0],
# [0,3,1,0]
# ]
# Follow up:
#
# A straight forward solution using O(mn) space is probably a bad idea.
# A simple improvement uses O(m + n) space, but still not the best solution.
# Could you devise a constant space solution?
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
"""
col0 = 1
for r in range(len(matrix)):
for c in range(len(matrix[0])):
if matrix[r][c] == 0:
matrix[r][0] = 0
if c == 0:
col0 = 0
else:
matrix[0][c] = 0
for r in range(len(matrix) - 1, -1, -1):
for c in range(len(matrix[0]) - 1, -1, -1):
if matrix[r][0] == 0 or (matrix[0][c] == 0 if c != 0 else col0 == 0):
matrix[r][c] = 0
class SolutionTwoVariable(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
"""
if not matrix or not matrix[0]:
return matrix
first_row_zero = False
first_column_zero = False
for r in range(len(matrix)):
if matrix[r][0] == 0:
first_column_zero = True
break
for c in range(len(matrix[0])):
if matrix[0][c] == 0:
first_row_zero = True
break
for r in range(1, len(matrix)):
for c in range(1, len(matrix[0])):
if matrix[r][c] == 0:
matrix[r][0] = matrix[0][c] = 0
for r in range(len(matrix) - 1, -1, -1):
for c in range(len(matrix[0]) - 1, -1, -1):
if r == 0:
if first_row_zero:
matrix[r][c] = 0
if c == 0:
if first_column_zero:
matrix[r][c] = 0
if r != 0 and c != 0 and matrix[r][0] == 0 or matrix[0][c] == 0:
matrix[r][c] = 0
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.