blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
e1149ba3d4f87b3c3969341602823a13b1ac0b93 | Rajno1/PythonBasics | /variables/MultipleValuesToVariable.py | 543 | 4.28125 | 4 | """
Python allows you to assign many values to multiple variables
we can assign one value to multiple variables
if you have a collection of values in a list, Python allows you to extract the values to
variables- this called unpacking
"""
# assigning many values to multiple variables
x,y,z="Raju",2,True
print(x+" is",type(x),"datatype")
print(type(y),y)
print(type(z),z)
# we can assign one value to many variables as well
x=y=z="orange"
print(x,y,z)
# unpacking
fruits = ["Apple","Banana","Mango"]
a,b,c =fruits
print(a)
print(b)
print(c) | true |
2bdd24b3e5fbc8c8e0af0e76ee4b179811a0532f | DipendraDLS/Python_Basic | /08. Dictionary/loops_in_dictionary.py | 1,046 | 4.5625 | 5 | # Iterations on Dicionary
# Example 1:
details = {'name': 'Ram', 'age': 24} # details vanni yeuta dictonary ho. Yesma Key and value huncha "curly bracket" leh vancha yo dictionary ho.
print(details.items())
# For looping through values
for x in details.values():
print(x)
# For LOOPING THROUGH KEYS
for k in details: # k is a variable but k by convention for key
print("key :", k, "&", "value :", details[k])
for key in details.keys():
print("key :", key, "&", "value :", details[key])
# For LOOPING THROUGH KEY-VALUE PAIRS
for key, val in details.items():
print(key, val)
# Example 2:
emails = {
"dhiraj": "dhiraj@email.com",
"hari": "hari@example.com",
"ram": "ram@gmail.com"
}
# For looping through values
for x in emails.values():
print(x)
# For LOOPING THROUGH KEYS
for key in emails.keys():
print("key :", key, "&", "value :", emails[key])
for k in emails:
print(k)
for k in emails:
print("index", k, "is", emails[k])
# For LOOPING THROUGH KEY-VALUE PAIRS
for k, elem in emails.items():
print(k, elem)
| false |
94ec66938d15c309a1358f77ebd76391ca4e8990 | DipendraDLS/Python_Basic | /05. List/list_enumerate().py | 219 | 4.125 | 4 | # Syntax:
# Syntax ==> enumerate(iterable, start_index)
# Example 1:
list = [10, 50, 75, 83, 98, 84, 32]
for x, res in enumerate(list):
print(x, ":", res)
for x, res in enumerate(list, 0):
print(x, ":", res) | false |
9ff4aee52115a0b8582c751ef58607da41b9b404 | DipendraDLS/Python_Basic | /18. Working_with_text_file/reading_and_writing.py | 455 | 4.125 | 4 |
# # Example 1 : reading from one file and writing to another file
with open("file1.txt") as f:
content = f.read()
with open("file2.txt", 'w') as f:
f.write(content)
# # Example 2 : Reading from old file and writing to the new file and finally deleting the old file
import os
oldname = "file1.txt"
newname = "newfile1.txt"
with open(oldname) as f:
content = f.read()
with open(newname, "w") as f:
f.write(content)
os.remove(oldname)
| true |
c6d31b991fdbf9b991517d72bda2055cd39d96c2 | DipendraDLS/Python_Basic | /05. List/accessing_list.py | 307 | 4.3125 | 4 | # Accessing value of list
a = [1, 2, 4, 56, 6]
# Example 1:
# Access using index using a[0], a[1], a[2]
print(a[2])
# Assigning Values ( i.e change the value of list using)
a[0] = 10
print(a)
a_list = [1,2,3]
a_list[1] = 4
print(a)
#list repeatation
list4 = [1, 2]
list5 = list4 * 3
print(list5)
| true |
012797ebeff24d2a2453e2296cfc0d239b8e057c | DipendraDLS/Python_Basic | /13. Lambda_Function/lambda_function_with_map.py | 785 | 4.40625 | 4 | # The map() function in Python takes in a function and a list.
# The function is called with all the items in the list and a new list is returned which contains items returned by that function for each item.
# Example 1 : program to double each item in the list using map() function.
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(map(lambda x: x * 2, my_list)) # map function le map object return garcha so teslai list ma convert garna ko lagi typecasting gareko ho
print(new_list)
# Example 2 : Program to half each item in the list uisng map() function
myList = [10, 25, 17, 9, 30, -5]
myList2 = list(map(lambda n: n/2, myList)) # map function le map object return garcha so teslai list ma convert garna ko lagi typecasting gareko ho
print(myList2)
| true |
a74d594c5cc9d009acad884b4dc313b08acead88 | DipendraDLS/Python_Basic | /05. List/list_creation.py | 770 | 4.375 | 4 | # In python, list size can always be dynamic (i.e list ko size badna or ghatna sakcha).. no need to be worry of creating dynamic size like in C & C++
# lists are mutable (meaning that, values or items in the list can be changed or updated)
# Syntax 1 : for Creating empty list in python
first_list = []
print('Type of first_list is :', type(first_list))
# Example 1 :
# Create a list using []
a = [1, 2, 8, 7, 6]
# Print the list using print() function
print(a)
# Syntax 2 : for creating empty list in python
second_list = list()
print('Type of second_list is :', type(second_list))
# Example 2 :
for i in range(4, 15, 2):
second_list.append(i)
print(second_list)
# We can create a list with items of different types
c = [47, "Hitman", False, 6.9]
print(c)
| true |
2b54cb7e8716146aa9a754c89c636539c7421a61 | wharward/CourseWork | /Python/Tutorial/Python in a day/Ch4-Stings.py | 395 | 4.1875 | 4 | date = "11/12/2013"
#Go through string and split
#where there is a '/'
date_manip = date.split('/')
#Show the outcome
print date_manip
print date_manip[0]
print date_manip[1]
print date_manip[2]
print 'Month: ' + date_manip[0]
print 'Day: ' + date_manip[1]
print 'Year: ' + date_manip[2]
print('Month: ' + date_manip[0] +
'. Day: ' + date_manip[1] +
'. Year: ' + date_manip[2])
| false |
13abef90c48da1dadfb1e1556edb9abfa3309a77 | Datbois1/Dat_bois1 | /Number 3.py | 217 | 4.1875 | 4 | Number=input("Enter Number")
Number=int(Number)
if Number > 10:
print(str(Number)+" is greater than 10")
elif Number < 10:
print(str(Number)+" is less than 10")
else:
print(str(Number)+" is equal to ten")
| true |
d7e5111382f2368564d228026c1d212c882a5284 | Fatihnalbant/deneme_2 | /sozcukListe.py | 649 | 4.1875 | 4 | """
Bir yazı okuyunuz.
Yazı boşluk karakterleriyle ayrılmış sözcüklerden oluşmuş olsun.
Aynı sözcükleri atarak sözcükleri bir listeye yerleştiriniz.
Örneğin girilen yazı şöyle olsun:
bugün hava evet bugün çok hava güzel güzel
Sonuç olarak şöyle bir liste elde edilmeli:
['bugün', 'hava', 'evet', 'çok', 'güzel']
Elde edilen listedeki sözcüklerin yazıdaki sözcük sırasında olması gerekmektedir.
"""
# s = print('Bir yazı giriniz:')
s = 'bugün hava evet bugün çok hava güzel güzel'
result = []
for word in s.split():
if word not in result:
result.append(word)
print(result)
| false |
5bf19e52f679cea80074807211bfcca522b215f0 | Tochi-kazi/Unit4-04 | /function_program.py | 1,113 | 4.125 | 4 | # Created by: Tochukwu Iroakazi
# Created on: Nov 2016
# Created for: ICS3U
# This program displays marks
def marks_number(number):
if level == '4+' :
score = 95
return score
elif level == '4':
score = 90
return score
elif level == '4-' :
score = 80
return score
elif level == '3+' :
score = 78
return score
elif level == '3':
score = 73
return score
elif level == '3-':
score = 70
return score
elif level == '2+':
score = 69
return score
elif level == '2':
score = 65
return score
elif level == '2-':
score = 60
return score
elif level == '1+':
score = 59
return score
elif level == '1':
score = 59
return score
elif level == '1-':
score = 50
return score
elif level == 'R':
score = 30
return score
else:
score = -1
return score
level = str(raw_input('Type in your level :'))
number = marks_number(level)
print(number)
# input is for integers
# raw_input for string
| false |
50eb55ab4c06453ea292a630967fa1cb3369b477 | blacklemons/python_lecture | /Data_Structure/set/set.py | 713 | 4.15625 | 4 | s1 = set([1,2,3])
print(s1)
s2 = set("HELLO")
print(s2)
s3 = set([2,3,4])
print(s3)
# access item
print("H" in s2)
# convert to list
l1 = list(s1)
print(l1)
l2 = list(s2)
print(l2)
# add
## item
s2.add('A')
print(s2)
## set
s2.update(s3)
print(s2)
# remove
## remove
s2.remove('A')
print(s2)
## discard
s2.discard(2)
print(s2)
## pop
x = s2.pop()
print(x)
print(s2)
# convert to set from list
new_s1 = set(l1)
print(new_s1)
# len
print(len(s1))
# Intersection
print(s1&s3)
print(s1.intersection(s3))
# Difference
print(s1-s3)
print(s1.difference(s3))
print(s3-s1)
print(s3.difference(s1))
# union
print(s1|s3)
print(s1.union(s3))
# Symmetric difference
print(s1^s3)
print(s1.symmetric_difference(s3)) | false |
245c748c47b25a75ea18cddb1a79af1e097db93a | blacklemons/python_lecture | /Data_Structure/dictionary/dictionary.py | 1,015 | 4.1875 | 4 | dic = {'name':'pey', 'phone':'0119993323', 'birth': '1118'}
# key , value
# key : can only be strings and numbers (can't list, tuple)
# add item
dic['email'] = 'dic@gmail.com'
print(dic)
dic[3] = '3'
print(dic)
# get value by key
print(dic.get('name'))
print(dic['name'])
## fail to get value by key
print(dic.get('tel')) # return None
# print(dic['tel']) # error
# change value by key
dic['name'] = 'pay'
print(dic)
# del
del dic[3]
print(dic)
# make key/value/item list
a = dic.keys()
b = dic.values()
c = dic.items()
print(a)
print(b)
print(c)
# check key (not value)
print('name' in dic)
print('1118' in dic)
# convert list to dictionary
## a : key , b : value
new_dict = dict(zip(a,b))
print(new_dict)
## a,b : item
new_dict = dict((a,b))
print(new_dict)
# iterate dictionary with 'for' loop
for i in dic.keys():
print(i)
for i in dic.values():
print(i)
for key, value in dic.items():
print(f"key : {key}, value : {value}")
for i in dic:
print(i)
# clear
dic.clear()
print(dic) | false |
3c99e735729ff6283b0aec80b4ae3bd47e41fa5f | SACHSTech/ics2o-livehack1-practice-laaurenmm | /windchill.py | 717 | 4.1875 | 4 | """
Name: windchill.py
Purpose: This program allows the user to input a the degree in celsius and windspeed to calculate the
Author: Mak.L
Created: 08/02/2021
"""
print ("******Windchill******")
print("")
#User will input temperature and wind speed
temp_c = float(input("Enter the temperature in celsius: "))
windspeed = float(input("Enter the wind speed in km/h: "))
#formula for windchill
windchill = 13.12 + (0.6215 * temp_c) - (11.37 * windspeed ** 0.16) + (0.3965 * temp_c * windspeed ** 0.16)
# output windchill
print("With the windchill factor, it feels like " + str(windchill) + "° outside.")
print("With the windchill factor, it feels like " + str(round(windchill,1)) + "° outside.") | true |
ad8927ec17caa8739aeb326c8965aa7641faf4d0 | renatronic/data_structures_and_algorithms | /finders.py | 2,101 | 4.25 | 4 | from node import Node
from linked_list import LinkedList
'''
The grace of the both solutions is that both have O(n) time complexity,
and O(1) space complexity. We always use two variables to represent two
pointers no matter what size the linked list is).
'''
# returns the nth to last element
def nth_last_node(linked_list, n):
current = None
tail_seeker = linked_list.head_node
count = 0
while tail_seeker:
tail_seeker = tail_seeker.get_next_node()
count += 1
if count >= n + 1:
if current is None:
current = linked_list.head_node
else:
current = current.get_next_node()
return current
# returns the middle node of a linked list
def find_middle(linked_list):
fast_pointer = linked_list.head_node
slow_pointer = linked_list.head_node
while fast_pointer:
fast_pointer = fast_pointer.get_next_node()
if fast_pointer:
fast_pointer = fast_pointer.get_next_node()
slow_pointer = slow_pointer.get_next_node()
return slow_pointer
'''
Half Speed
Another equally valid solution is to move the fast pointer once with
each loop iteration but only move the slow pointer every-other
iteration.
'''
def find_middle_alt(linked_list):
count = 0
fast = linked_list.head_node
slow = linked_list.head_node
while fast:
fast = fast.get_next_node()
if count % 2 != 0:
slow = slow.get_next_node()
count += 1
return slow
'''
ERRORS
.nth_last_node RETURNS THE WRONG ELEMENT WHEN I START TO COUNT ON 1
.find_middle() and .find_middle_alt RETURNS ONE MORE THEN THE MIDDLE
'''
# playground
'''
def generate_test_linked_list(length):
linked_list = LinkedList()
for i in range(length, 0, -1):
linked_list.insert_beginning(i)
return linked_list
test_list = generate_test_linked_list(9)
# print(test_list.stringify_list())
# nth_last = nth_last_node(test_list, 10)
# print(nth_last.value)
mid_nod = find_middle(test_list)
print(mid_nod.value)
''' | true |
00b44f0765a7ae38024e85efdcd9d17982f2ca33 | Ezeaobinna/algorithms-1 | /Pending/dijkstra.py | 1,042 | 4.15625 | 4 | #!/usr/bin/python
# Date: 2018-01-27
#
# Description:
# Dijkstra's algo can be used to find shortest path from a source to destination
# in a graph. Graph can have cycles but negative edges are not allowed to use
# dijkstra algo.
#
# Implementation:
# - Initialze graph such that distance to source is set to 0 and other node is
# reachable from source with infinite distance.
# - Push all vertexes in a priority(distance 0 means highest priority) queue and
# iterate over queue till queue is empty.
# - In each iteration relax edges going out of current vertex .i.e check and
# update(if required) distance to all adjacent vertexes of fetched vertex from
# queue.
# - When loop completes we will get shortest path from source to all reachable
# vertex and non reachable remains infinite as initialized.
#
# Reference:
# https://www.geeksforgeeks.org/greedy-algorithms-set-7-dijkstras-algorithm-for-adjacency-list-representation/
#
# Complexity:
# O(E + VlogV) if fibonacci heap is used to implement priority queue.
# Pending :(
| true |
89b5f2768d44829fb6bdd7eb7ce39dadf10791d5 | ashidagithub/C1906AL1 | /03-summation.py | 957 | 4.125 | 4 | # -*- coding: UTF-8 -*-
# Filename : 03-summation.py
# author by : (学员ID)
# 目的:
# 掌握基本的赋值,加减乘除运算,输入及输出方法
# 掌握 print 代入模式
# -------------------------------
# 练习一
# 用户输入数字
# 注:input() 返回一个字符串,所以我们需要使用 float() 方法将字符串转换为数字
num1 = float(input('输入第一个数字:'))
num2 = float(input('输入第二个数字:'))
# 求和
sum = num1 + num2
# 显示计算结果
print('数字 {0} 和 {1} 相加结果为: {2}'.format(num1, num2, sum))
# 求差
sum = num1 - num2
# 显示计算结果
print('数字 {0} 和 {1} 相减结果为: {2}'.format(num1, num2, sum))
# 求积
sum = num1 * num2
# 显示计算结果
print('数字 {0} 和 {1} 相乘结果为: {2}'.format(num1, num2, sum))
# 求除
sum = num1 / num2
# 显示计算结果
print('数字 {0} 和 {1} 相除结果为: {2}'.format(num1, num2, sum))
| false |
1248e8d20a1cc116f046311c10e44a443572a871 | mikemontone/Python | /make_album2.py | 747 | 4.15625 | 4 | #!/opt/bb/bin/python3.6
def make_album(artist_name,album_title, tracks=''):
""" Builds a dictionary describing a music album. """
album = { 'artist' : artist_name , 'album' : album_title}
if tracks:
album['tracks'] = tracks
return album
#album1 = make_album('beach boys','pet sounds', tracks=14)
#album2 = make_album('jim hendrix' ,'electric ladyland')
#print(album1)
#print(album2)
while True:
print("\n Please tell my the artist's name:")
print("(enter 'q' at any time to quit)")
artist_name = input("Artist name: ")
if artist_name == 'q':
break
album_title = input("Album title: ")
if album_title == 'q':
break
made_album = make_album(artist_name,album_title)
print(made_album)
| true |
c3246f6b7419d2eef546fe82ae3809fda7201175 | mikemontone/Python | /Chapter08/sandwich_order.py | 655 | 4.125 | 4 | toppings = []
#prompt = "\nPlease tell me what toppings you want on your sandwich: "
#prompt += "\n (Enter 'quit' when you are finished adding toppings.) "
#while True:
# topping = input(prompt)
# if topping == 'quit':
# break
# else:
# print("Adding " + topping + " to your sandiwch.")
def make_sandwich(*toppings):
""" accepts toppings to make a sandwich, displays the toppings ordered. """
topping = input("Topping: ")
print("\nMaking you sandwich with the following toppings: ")
for topping in toppings:
print("-" + topping)
make_sandwich()
#make_sandwich('turkey','cheddar','pork roll','dijon aioli')
| true |
6efee5952d9eb05913d735135d2377215c54fc65 | Cherry93/coedPractices | /demos/W1/day4/03Fate.py | 916 | 4.5 | 4 | '''
·随机生成颜值
·如果颜值超过90,输出“恭喜,您的颜值简直逆天”
-----
·否则输出“呵呵,您的颜值很亲民”
-----
·如果超过90,输出“恭喜,您的颜值简直逆天”
·60~90,输出“呵呵,您的颜值很亲民”
·否则输出“我们聊天气吧”
'''
import random
looking = random.randint(0,100)
print(looking)
#1.0 单分支
# if looking > 90:
# print("恭喜,您的颜值简直逆天")
#2.0 双分支
# if looking > 90:
# print("恭喜,您的颜值简直逆天")
# else:
# print("呵呵,您的颜值很亲民")
#3.0 多分支
if looking >= 80:
pass#占茅坑表达式
print("恭喜,您的颜值简直逆天")
elif looking>=60 and looking<80:
pass
print("您的颜值很亲民")
elif looking>=40 and looking<60:
pass
print("您的颜值过得去")
else:
pass
print("我们聊聊拍森吧") | false |
e113cbc67495858f87609e4751af24b7c93f4540 | sandeep2823/projects | /Python/derek banas learning/05_Functions/05_calculate_area.py | 824 | 4.15625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 9 23:26:25 2018
@author: sandeepsingh
"""
import math
def get_area(shape):
shape = shape.lower()
if shape == "circle":
circle_area()
elif shape == "rectangle":
rectangle_area()
else:
print("Please enter rectangle or circle ")
def circle_area():
radius = float(input("PLease enter the radius: "))
area = (math.pow(radius, 2)) * math.pi
print("area of circle is {:.2f}".format(area))
def rectangle_area():
length = float(input("Please enter the length: "))
width = float(input("Please enter the width: "))
print("area of rectangle is: ", length * width)
def main():
shape = input("enter the shape to calculate area: ")
get_area(shape)
main() | true |
d893029766441bdfbf03370f60c8a7ed227dc9e7 | sandeep2823/projects | /Python/derek banas learning/01_simple_code/02_convert_miles_to_kilometers.py | 396 | 4.28125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 2 22:33:09 2018
@author: sandeepsingh
"""
# Problem : Receive miles and convert to kilometera
miles = input("Please enter the miles : ")
# Convert miles to kilometer and store into kilometer
kilometer = int(miles) * 1.60934
# Print the kilometer value
print("{} miles equals {} kilometers".format(miles , kilometer))
| true |
67c8802e4e5e7d7df8f240bd10165d10b6d26b77 | CAM603/Python-JavaScript-CS-Masterclass | /Challenges/bst_max_depth.py | 1,207 | 4.125 | 4 | # Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def maxDepth(root):
if root is None:
return 0
left = maxDepth(root.left)
right = maxDepth(root.right)
return max(left, right) + 1
def maxDepthIterative(root):
if root is None:
return 0
maximum = 1
nodes = [root]
depths = [1]
while nodes:
node = nodes.pop()
depth = depths.pop()
if node.left is None and node.right is None:
maximum = max(maximum, depth)
if node.left:
nodes.append(node.left)
depths.append(depth + 1)
if node.right:
nodes.append(node.right)
depths.append(depth + 1)
return maximum
root = TreeNode(3)
root.left = TreeNode(9)
root.right = TreeNode(20)
root.right.left = TreeNode(15)
root.right.right = TreeNode(7)
root.right.right.left = TreeNode(35)
print(maxDepth(root))
print(maxDepthIterative(root))
| true |
24db06c139aee2fcb826460d2db06b598a64634a | carlosbazilio/lp | /python/conceitos-oo.py | 2,727 | 4.3125 | 4 | '''
Autor: Carlos Bazilio
Descricao:
Este programa ilustra:
* Uma hierarquia de classes em Python e como
classes abstratas podem ser implementadas
* Definicao e uso de propriedades para
encapsulamento de atributos.
* Tratamento de Excecoes
Python disponibiliza o modulo abc para implementar
classes abstratas
ABC e a classe abstrata
abstractmethod e a anotacao para indicar qual
metodo e abstrato'''
from abc import ABCMeta, abstractmethod
# Classe abstrada em Python 2
class Iluminavel:
__metaclass__ = ABCMeta
# Metodo abstrato
@abstractmethod
def acesa(self, valor):
pass
@abstractmethod
def acesa(self):
pass
def padrao(self):
return "Comportamento padrao"
class Lampada(Iluminavel):
# Construtor com valor default
def __init__(self, t = "indefinida", p = 0, a = False):
self.potencia = p
self.tecnologia = t
self._acesa = a
# Redefinicao do metodo string herdado de object
def __str__(self):
saida = 'Lampada %s com potencia de %s watts\n' % \
(self.tecnologia, self.potencia)
saida = saida + super(Lampada, self).__str__()
return saida
# Definicao de uma propriedade (metodo get)
@property
def acesa(self):
print "Dentro do get de acesa"
return self._acesa
# Definicao de uma propriedade (metodo set)
@acesa.setter
def acesa(self, valor):
print "Dentro do set de acesa"
self._acesa = valor
def padrao(self):
return "Comportamento em Lampada \n" + \
"Comportamento da superclasse: " + \
super(Lampada, self).padrao()
# Implementacao de um decorador para verificar tipos
def verificaTipo(tipo):
def verificador(metodo_antigo):
def novo_metodo(objeto_self, objeto):
if isinstance(objeto, tipo):
metodo_antigo(objeto_self, objeto)
else:
raise TypeError("Uso indevido de tipo!")
return novo_metodo
return verificador
class Luminaria(Iluminavel):
def __init__(self, status = False):
self.lampadas = []
self._acesa = status
# Uso do decorator definido acima
@verificaTipo(Lampada)
def adicionaLampada(self, l):
self.lampadas.append(l)
@verificaTipo(Lampada)
def __add__(self, l):
self.lampadas.append(l)
def __str__(self):
saida = ''
for l in self.lampadas:
saida = saida + str(self.lampadas.index(l)) + ': ' + str(l) + '\n'
return saida
@property
def acesa(self):
status_inicial = False
for l in self.lampadas:
status_inicial = status_inicial or l.acesa
return status_inicial
@acesa.setter
def acesa(self, valor):
for l in self.lampadas:
l.acesa = valor
def listagem5Primeiras(self):
for i in range(5):
# Tratando excecoes
try:
print self.lampadas[i]
except IndexError:
print "Empty"
l1 = Lampada("led", 60)
l2 = Lampada("fluorescente", 100)
l3 = Lampada("incandescente", 120)
| false |
46652424284c4f5e8bdda17b735b6afc94959b24 | BagalDipti/Python_basics | /Inheritance.py | 1,797 | 4.28125 | 4 |
# ------------Single Inheritance-----------------------
class A:
def Show(self):
print("Parent class")
class B(A):
def Disply(self):
print("Child Class")
p=A()
c=B()
c.Show()
c.Disply()
# -----------Multiple Inheritance-------------------------------
class A:
def Show(self):
print("Parent class")
class B():
def DisplyB(self):
print(" B class")
class C(A,B):
def DisplyC(self):
print("C class")
b=B()
c=C()
b.Show()
b.DisplyB()
c.Show()
c.DisplyC()
# ------------------Multilevel Inheritance------------------
class A:
def Show(self):
print("Parent Class")
class B(A):
def DisplayB(self):
print("B class")
class C(B):
def Displayc(self):
print("C class")
a=A()
b=B()
c=C()
c.Show()
c.DisplayB()
c.Displayc()
#------------------Hierarchical Inheritance-------------------------------------------
class A:
def Show(self):
print("Parent Class")
class B(A):
def DisplayB(self):
print("Class B")
class C(A):
def DisplayC(self):
print(" Class C")
class D(A):
def DisplayD(self):
print("Class D")
b=B()
c=C()
d=D()
b.Show()
b.DisplayB()
c.Show()
c.DisplayC()
d.Show()
d.DisplayD()
#--------------Hybride Inheritance--------------------------------------
class D():
def DisplyD(self):
print("C class")
class B(D):
def DisplayB(self):
print("Class B")
class C(D):
def DisplyC(self):
print(" B class")
class A(B,C):
def DisplayA(self):
print(" Class A")
a=A()
b=B()
c=C()
d=D()
b.DisplayB()
b.DisplyD()
c.DisplyC()
c.DisplyD()
a.DisplyD()
a.DisplyC()
a.DisplayB()
d.DisplyD()
| false |
a877f7d37cac84d65a89bcd2a700785fa30ccdda | RephenSoss/ToDoList | /todolist.py | 777 | 4.25 | 4 |
def show_help():
print ('What should we pick up at the store?')
print ("""
Enter "DONE" to stop adding items.
Enter "HELP" to stop adding items.
Enter "SHOW" to stop adding items.
""")
show_help()
def add_to_list(new_item):
shop_list.append(new_item)
print("Added {}. List now had {} items.".format(new_item,len(shop_list)))
pass
# Make list
shop_list = []
# Print instructions on how to use the app
while True:
# ask for new items
new_item = raw_input('> ')
# be able to quit the app
if new_item == "DONE":
break
elif new_item == "HELP":
show_help()
continue
elif new_item == "SHOW":
shop_list()
continue
add_to_list(new_item)
def show_list():
# print out the list
print ("Here is your list: ")
for item in shop_list:
print (item)
| true |
ae55dc7e9efaee988360b0d751a853211cce037b | Karadesh/Homework | /Homework_1/Hours, minutes and seconds.py | 544 | 4.25 | 4 | #2. Пользователь вводит время в секундах.
# Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс.
# Используйте форматирование строк.
seconds = int(input('Введите количество секунд: '))
minutes = int(seconds/60)
hours = int(minutes/60)
seconds = seconds - (minutes*60)
minutes = minutes - (hours*60)
print('У нас получилось: {}:{}:{}'.format(hours , minutes, seconds)) | false |
3eddd6fc6998c0d7bd0bfdd125693754a11bb7af | rehanhkhan/Assignment2 | /Exercise_4-10.py | 914 | 4.75 | 5 | '''***********************************************************************************************
4-10. Slices: Using one of the programs you wrote in this chapter, add several lines to the end of the program that do the following:
• Print the message, The first three items in the list are:. Then use a slice to print the first three items from that program’s list.
• Print the message, Three items from the middle of the list are:. Use a slice to print three items from the middle of the list.
• Print the message, The last three items in the list are:. Use a slice to print the last three items in the list.
***********************************************************************************************'''
flavors = ["Peperoni","Chicken Fagita","Chicken Tikka", "Macaroni","BBQ","Afghani",""]
print("The first three items in the list are :")
for flavor in flavors[:3]:
print(flavor)
| true |
ad779c776ddc4fd8e4c219c65b55062cb7bdeba9 | alex3kv/PythonWebinar | /Lesson3/Task6.py | 1,369 | 4.28125 | 4 | # 6. Реализовать функцию int_func(), принимающую слово из маленьких латинских
# букв и возвращающую его же, но с прописной первой буквой. Например,
# print(int_func(‘text’)) -> Text.
#
# Продолжить работу над заданием. В программу должна попадать строка из слов,
# разделенных пробелом. Каждое слово состоит из латинских букв в нижнем
# регистре. Сделать вывод исходной строки, но каждое слово должно начинаться с
# заглавной буквы. Необходимо использовать написанную ранее функцию
# int_func().
#
#
def to_upper(symbol):
code = ord(symbol) - 32
return chr(code)
def int_func(word):
first_letter = to_upper(word[0])
return first_letter + word[1:]
def string_to_upper(value):
items = value.split()
result = int_func(items[0])
for item in items[1:]:
result += " " + int_func(item)
return result
print(int_func("text"))
input_string = "слова в нижнем регистре разделенные пробелом"
print(string_to_upper(input_string))
| false |
60dbf192f402385cdefb861e0b548aa5d65000d0 | chendddong/Jiuzhang-Ladder | /5. Kth Largest Element.py | 1,310 | 4.25 | 4 | '''
Find K-th largest element in an array.
You can swap elements in the array
Example
Example 1:
Input:
n = 1, nums = [1,3,4,2]
Output:
4
Example 2:
Input:
n = 3, nums = [9,3,2,4,8]
Output:
4
Challenge
O(n) time, O(1) extra memory.
'''
# TAG:[Quick Sort, Quick Select, Two Pointers]
class Solution:
"""
@param n: An integer
@param nums: An array
@return: the Kth largest element
"""
def kthLargestElement(self, n, nums):
# test the border for 'k' using those examples
return self.quick_select(nums, 0, len(nums) - 1, len(nums) - n + 1)
def quick_select(self, nums, start, end, k):
if start >= end:
return nums[start]
i, j = start, end
pivot = nums[(i + j) // 2]
while i <= j:
while i <= j and nums[i] < pivot:
i += 1
while i <= j and nums[j] > pivot:
j -= 1
if i <= j:
nums[i], nums[j] = nums[j], nums[i]
i += 1
j -= 1
# Go left
if j >= k - 1 and start <= j:
return self.quick_select(nums, start, j, k)
# Go right
if i <= k - 1 and i <= end:
return self.quick_select(nums, i, end, k)
# Target
return nums[k - 1]
# Takeaways: | true |
d91fd5064dcd962d29adc7e6cde8fae572a1a9ba | Minji0h/Introduce-at-CCO-with-python | /Semana3/exercicio2.py | 260 | 4.21875 | 4 | # Receba um número inteiro na entrada e imprima
# Fizz
# se o número for divisível por 3. Caso contrário, imprima o mesmo número que foi dado na entrada.
numero = int(input("Digite um numero: "))
if numero%3 == 0:
print("Fizz")
else:
print(numero) | false |
b4dd714c784a2ddc28a06849e7d2bd089d8bf6c3 | JayneJacobs/PythonHomeGrown | /decisionsComparison/defProceduresBasic (1).py | 1,367 | 4.125 | 4 | # Define a procedure, is_friend, that takes
# a string as its input, and returns a
# Boolean indicating if the input string
# is the name of a friend. Assume
# I am friends with everyone whose name
# starts with either 'D' or 'N', but no one
# else. You do not need to check for
# lower case 'd' or 'n'
def isDNfriend(person):
if person[0] == 'D':
return True
else:
if person[0] == 'N':
return True
return False
# Define a procedure, is_friend, that
# takes a string as its input, and
# returns a Boolean indicating if
# the input string is the name of
# a friend. Assume I am friends with
# everyone whose name starts with D
# and no one else. You do not need to
# check for the lower case 'd
def is_friend(person):
if person.find('D') == 0:
return True
return False
def isa_friend(person):
return person.find('D') == 0
name = 'Diane'
print 'Diane', is_friend(name)
#>>> True
name = 'fred'
print 'fred', is_friend(name)
#>>> False
name = 'Diane'
print isa_friend(name)
print 'Diane', is_friend('Diane')
#>>> True
print 'Fred', is_friend('Fred')
#>>> False
print "D or N"
print 'Diane', isDNfriend('Diane')
#>>> True
print 'Ned',isDNfriend('Ned')
#>>> True
print 'Moe' , isDNfriend('Moe')
#>>> False
#>>> True
print "D"
name = 'fred'
print 'fred', isa_friend(name)
#>>> False | true |
0ae82e92caf97c01068f029c06cb12f3cf4453b6 | cs-fullstack-2019-spring/python-review-loops-cw-cgarciapieto | /pythonreviewclasswork.py | 1,119 | 4.21875 | 4 | def main():
# exercise1
# Python program that prints all the numbers from 0 to 6 except 3 and 6.
# with an expected output of 1245
# def exercise1():
# number = 0
#
#
# for number in range(6):
# number = number + 1
#
# if number == 3:
#
# continue # continue here
#
# elif number == 6:
#
# continue
#
# print(str(number))
# excercise2
# Python program that counts the number of even and odd numbers from a series of numbers.
# def exercise2():
# numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9)
# evenCount = 0
# oddCount = 0
# for x in numbers:
# if not x % 2:
# evenCount += 1
# else:
# oddCount += 1
# print("Even numbers are :", evenCount)
# print("Odd numbers are :", oddCount)
#Python program that accepts a sequence of lines (blank line to terminate) as input and prints the lines as output after User enters a blank line to end.
def exercise3():
text = ""
text += input("type a sentence" + "/n")
print(text)
if __name__ == '__main__':
main()
| true |
045d40c58121721a843693ed35bb54a4600588b4 | Jlobblet/px277 | /Week 2/Excercises/second_col_second_row.py | 217 | 4.3125 | 4 | """Consider the 2D array ((1, 2), (3, 4)). Extract and print the second column values, then print the second row values."""
import numpy as np
array = np.array(((1, 2), (3, 4)))
print(array[:, 1])
print(array[1, :])
| true |
1cd060f2e6d05ec6e84fd6d41b456d9d7d0e9f64 | Jlobblet/px277 | /Week 2/Assessment/04.py | 525 | 4.21875 | 4 | """Write a function called "increasing(data)" that prints True if the
input array is increasing or False otherwise. Hint: np.diff() returns
the difference between consecutive elements of a sequence.
"""
import numpy as np
def increasing(data):
"""Take an array and return whether the array is strictly increasing or not.
Parameters:
------
data: numpy array to be tested
Returns:
------
Bool whether the array is strictly increasing or not.
"""
return (np.diff(data) > 0).all() == True
| true |
254fc2da95d970ab3f7b0246a3f070c11bf76234 | lixintong1992/Algorithms | /Sorting/Insert_Sort.py | 351 | 4.125 | 4 | def InsertSort(arr):
for i in range(1, len(arr)):
if arr[i - 1] > arr[i]:
temp = arr[i]
j = i
while(j > 0 and arr[j - 1] > temp):
arr[j] = arr[j - 1]
j -= 1
arr[j] = temp
arr = [1, -2, 4, 7, 6, 3, 2, 3]
# arr = [3, 2, 3, 4, 6, 7]
InsertSort(arr)
print(arr)
| false |
b0a956d04b8dd38eb03c7b73fe14f9d8c8c4806d | rramr/fa-python | /1. Functions/Fourth tasks/Task 4.py | 420 | 4.15625 | 4 | # При помощи функций map/filter/reduce из списка списков извлечь элементы, содержащиеся во вложенных списках по индексу 1.
# Например, [[1, 2, 3], [2, 3, 4], [0, 1 , 1 , 1], [0, 0]] -> [2, 3, 1, 0]
def sort(elem):
return elem[1]
lst = [[1, 2, 3], [2, 3, 4], [0, 1 , 1 , 1], [0, 0]]
lst = list(map(sort, lst))
print(lst) | false |
7641bae755f2a9ef578b210dba022c33c8e8e79b | lucascopnell/Practicals | /prac_05/hex_colours.py | 510 | 4.25 | 4 | HEX_COLOURS = {"beige": "#f5f5dc", "bisque3": "#cdb79e", "black": "#000000", "brown": "#a52a2a", "burlywood": "#deb887",
"cadetblue": "#5f9ea0", "chartreuse1": "#7fff00", "coral": "#ff7f50", "cornflowerblue": "#6495ed", "cyan3": "#00cdcd" }
colour = input("Enter colour name: ").lower()
while colour != "":
if colour in HEX_COLOURS:
print("{} hex code is {}".format(colour, HEX_COLOURS[colour]))
else:
print("Invalid colour")
colour = input("Enter colour name: ")
| false |
89680b2abb72179539bb70b06c3393ae7ac7ae25 | agnirudrasil/12-practical | /src/question_14/main.py | 1,368 | 4.21875 | 4 | """
Write a python program to create CSV file and store empno,name,salary in it. Take empno from the user
and display the corresponding name, salary from the file. Display an appropriate message if the empno is
not found.
"""
import csv
def create_csv():
with open("employee.csv", "w", newline='') as f:
cwriter = csv.writer(f)
ch = "y"
cwriter.writerow(["empno", "name", "salary"])
while ch == 'y':
empno = input("Please enter employee number: ")
name = input("Please enter employee name: ")
salary = input("Please enter employee salary: ")
cwriter.writerow([empno, name, salary])
ch = input("Do you want to add more records?(y/N) ").lower()
# Driver Code
create_csv()
def find_employee(empno):
try:
with open("employee.csv", "r") as f:
creader = csv.reader(f)
for rec in creader:
if rec[0] == empno:
return rec[-2:]
return
except FileNotFoundError:
print("File not found")
exit()
# Driver Code
empno = input("Please enter employee number to find: ")
results = find_employee(empno)
if results is not None:
print(
f"Name of the employee is {results[0]} and their salary is {results[1]}")
else:
print("Employee with than employee number not found")
| true |
b92826b10de4dbceb54160948095735fde546e4a | alejandroorca/alejandroorca.github.io | /ejercicios_pc/01.py | 434 | 4.125 | 4 | #01. Crea una función que reciba un parámetro de entrada de tipo numérico y que devuelva un booleano con valor true si el número es par y false si es impar. Ejecuta 3 llamadas de ejemplo de la función creada.
import sys
def booleano(num):
mod = num % 2
if mod == 0:
es_par = True
else:
es_par = False
return es_par
result = booleano(int(sys.argv[1]))
if result == True:
print('Es par')
else:
print('No es par')
| false |
fc8e54b728e1e5bffb00d9adb31be697b40a39cb | jason0703/TEST2 | /list-tuple.py | 745 | 4.125 | 4 | # 有序可變動列表 List
grades=[12,60,25,70,90]
print(grades)
print(grades[0])
print(grades[3])
print(grades[1:4])
grades=[12,60,25,70,90]
grades[0]=55 # 把 55 放到列表中的第一個位置
print(grades)
grades=[12,60,25,70,90]
grades[1:4]=[] # 連續刪除列表中從編號 1 到編號 4(不包括) 的資料
print(grades)
grades=[12,60,25,70,90]
grades=grades+[12,33]
print(grades)
grades=[12,60,25,70,90] # 取得列表的長度 len(列表資料)
length=len(grades)
print(length)
data=[[3,4,5],[6,7,8]]
print(data[0])
print(data[0][1])
print(data[0][0:2])
print(data)
data[0][0:2]=[5,5,5]
print(data)
# 有序不可變動列表 Tuple
data=(3,4,5)
# data[0]=5 # 錯誤︰Tuple的資料不可以變動
print(data[2])
print(data[0:2]) | false |
f8784cdefac24096ab69d20e3eef3d6867fe320b | rochaalexandre/complete-python-course | /content/3_first_milestone_project/milestone_1/app.py | 1,109 | 4.21875 | 4 | MENU_PROMPT = "\nEnter 'a' to add a movie, 'l' to see your movies, 'f' to find a movie by title, or 'q' to quit: "
movies = []
def add():
title = input("Enter the movie title: ")
director = input("Enter the movie director: ")
year = input("Enter the movie release year: ")
movies.append({'title': title, 'director': director, 'year': year})
def print_movie(movie):
print(f"Title: {movie['title']} ")
print(f"Director: {movie['director']} ")
print(f"Year: {movie['year']} ")
def list_movies():
for movie in movies:
print_movie(movie)
def find_by_title():
title = input("Enter the movie title to search: ")
for movie in filter(lambda x: x['title'] == title, movies):
print_movie(movie)
def menu():
selection = input(MENU_PROMPT)
while selection != 'q':
if selection == "a":
add();
elif selection == "l":
list_movies()
elif selection == "f":
find_by_title()
else:
print('Unknown command. Please try again.')
selection = input(MENU_PROMPT)
menu()
| false |
f7baac1dc2ae334a602291896ce6161a693ef2a5 | Username77177/Learn_py | /guide/#2_Input_Output.py | 1,242 | 4.1875 | 4 | #Input_Output (Ввод, Вывод)
#If you could print some, than write print('Some')
#Если ты хочешь что-то вывести, тогда пиши print('Что-нибудь')
b = str(97)
print("Some")
print("Что-нибудь")
print("Some value "+ b +" '3'") #Можно совмещать строки знаком "+", это называется конкатенация (пример '3')
#If u have a wish to input something in variable, than write a input('Something') function
#Если ты хочешь ввести что-либо, тогда пиши функцию input('Что-нибудь')
a = input()
# U can write anything, Python is smart language, it's know what's type of variable u are typing
print(a)
#Python умный язык, он сам понимает какого типа переменную вы ему вводите
print("Что-то ", end ='')
print("простое")
#Для того чтобы Python не переносил строки, используется функция end
#В аргументы можно записать при каких знаках строка не будет переноситься
a = input("It's for pause terminal, press Enter, to quit") | false |
65a3e5322a7bcfc2c45d4a2bc2fedf6dd52d8c93 | erdembozdg/coding | /python/python-interview/algorithms/sorting/insertion_sort.py | 461 | 4.28125 | 4 |
def insertion_sort(arr):
# For every index in array
for i in range(1,len(arr)):
# Set current values and position
currentvalue = arr[i]
position = i
while position>0 and arr[position-1]>currentvalue:
arr[position]=arr[position-1]
position = position-1
arr[position]=currentvalue
return arr
array = [5,9,3,10,45,2,0]
print(insertion_sort(array)) | true |
5aab761eaaf04322966c6c74c0fcad037477c9bc | uzairaj/Python_Programming | /Python_Tips_Tricks.py | 807 | 4.21875 | 4 | #Create a single string from all the elements in list
a = ["My", "name", "is", "Uzair"]
print(" ".join(a))
#Return Multiple Values From Functions
def x():
return 1, 2, 3, 4
a, b, c, d = x()
print(a, b, c, d)
#Find The Most Frequent Value In A List
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
print(max(set(test), key = test.count))
#Swap Variables In-Place
x, y = 8, 10
print(x, y)
x, y = y, x
print(x, y)
#Assigning multiple values in multiple variables
x, y = 10, 20
#Concatenate Strings
print('Python' + ' Coding' + ' Tips')
#Removing duplicates items from a list
listNumbers = [1, 10, 10, 2, 2, 1, 5, 10, 20,30,50,20,100]
print("Original= ", listNumbers)
listNumbers = list(set(listNumbers))
print("After removing duplicate= ", listNumbers)
| true |
14bca08dd4cd2d68fa62269829ba76f92db83d29 | george-marcus/route-planner | /student_code.py | 2,436 | 4.25 | 4 | import math
from queue import PriorityQueue
# Used Concepts found on this link
# https://www.geeksforgeeks.org/a-search-algorithm/
def shortest_path(map_grid, start_node, goal):
initial_distance = 0
road_cost = {start_node: initial_distance}
came_from = {start_node: None}
# we use a priority queue to work as an ordered key-value pair of intersection and cost
# and to hold unique values of intersections
queue = PriorityQueue()
queue.put(start_node, initial_distance)
while not queue.empty():
current_node = queue.get()
# lucky us, our goal is the current node
if current_node == goal:
backtrack_to_get_path(came_from, start_node, goal)
for next_neighbor in map_grid['roads'][current_node]:
# g() is the current actual distance from start node to target node
g_score = road_cost[current_node]
# h() "euclidean_heuristic" which is an estimate of the distance
# between current and target nodes
h_score = euclidean_heuristic(
map_grid['intersections'][current_node], map_grid['intersections'][next_neighbor])
# f() is the sum of g() and h()
f_score = g_score + h_score
# check next_neighbor's g_score and default to infinity
next_neighbors_g_score = road_cost.get(next_neighbor, float('inf'))
if f_score < next_neighbors_g_score:
# take the lower f_score and make it the g_score of the next_neighbor node
road_cost[next_neighbor] = f_score
# update f-score
f_score += h_score
# add next_neighbor node to priority queue with updated distance
queue.put(next_neighbor, f_score)
# update came_from dict with next neighbor node to come from the current node
came_from[next_neighbor] = current_node
return backtrack_to_get_path(came_from, start_node, goal)
def euclidean_heuristic(start_node, goal):
X = start_node[0] - goal[0]
Y = start_node[1] - goal[1]
return math.sqrt((X ** 2) + (Y ** 2))
def backtrack_to_get_path(came_from, start_node, goal):
node = goal
path_list = []
path_list.append(node)
while node != start_node:
node = came_from[node]
path_list.append(node)
return [node for node in reversed(path_list)]
| true |
bf967bb5919d2c0d1e4698b1439c213ed2ef7d89 | Nasir1004/-practical_python-with-daheer | /if statement.py | 202 | 4.125 | 4 | name = input('enter your name')
if name is ("sharu"):
print("sharu you are a good freind")
elif name is ("abbas"):
print('you are one of the best ')
else:
print('you are very lucky to be my freind') | true |
a9b70899b6b89662582efd58b8f1c6f7ab38b60b | Libraryman85/learn_python | /beal_katas/2_1_18.py | 1,322 | 4.25 | 4 | # strings can be in single or double quotes
# str = 'test'
# str2 = "test"
# string interpolation {}
# bool
# boolean is true/false
# bool = True
# bool_false = False
# int
# int = 1
# int = -1
# floats are decimals
# float = 1.0
# float_negative = -1.0
# casting
# output = '1' + 1
# to convert string to int
# int('1')
# turn int to str
# (1)
print(bool(0))
print(bool(1))
print(bool(.1))
print(bool('fale'))
print(bool(None))
print(bool([]))
# list data type
_list = ['Alex', 'Grande', 'Sara', 'Danie', 'Laura', 'Jen']
for name in _list:
print(name)
# for {variable_name} in <collection>:
# <action>
name = 'name'
for character in name:
print(character)
# Practice: create a function that creates in input, then prints each character of the input
person_name = input('What is your name?: ')
for character in person_name:
print(character)
def print_character(input):
for character in input:
print(character)
print_character('supercalifragilisticexpialidocious')
# == compares
# practice 2: create a function that takes 2 inputs then prints True/False whether or not the first input is contained
# within the second input
def search_character(search, find):
for character in find:
if character == search:
print(True)
search_character('a', 'purple')
| true |
662df803670dd10231be1ef40c2dccbacddb9ecc | mediassumani/TechInterviewPrep | /InterviewPrepKit/Trees/height_balanced_tree.py | 1,209 | 4.15625 | 4 | '''
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
'''
def getDepth(self, node):
left_depth = 0
right_depth = 0
curr = node
if (node.left is None) and (node.right is None):
return 0
if curr.left:
left_depth = self.getDepth(curr.left)
if curr.right:
right_depth = self.getDepth(curr.right)
return max(left_depth, right_depth) + 1
def isBalanced(self, root):
if not root:
return False
if (root.left is None) and (root.right is None):
return True
if (root.left is None) or (root.right is None):
return True
max_left_depth = self.getDepth(root.left)
max_right_depth = self.getDepth(root.right)
if (max_left_depth - max_right_depth) > 1 or (max_right_depth - max_left_depth) > 1:
return False
return True
| true |
b7c13aca4e20c253e1e792d690226138292172ee | Fusilladin/ListOverlap | /ListOverlap.py | 956 | 4.1875 | 4 | # LIST OVERLAP
a = [1, 2, 3, 5, 8, 13, 15, 21, 27, 28, 29, 30, 34, 44, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 15, 27, 43, 44, 45]
c = []
d = []
for elem in a:
if (elem in a) and (elem in b):
c.append(elem)
continue
elif (elem in a):
d.append(elem)
else:
break
print("\nThe numbers that are included in both lists are:\n{}".format(c))
# Take two lists, say for example these two:
#
# a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
# b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
# and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes.
#
# Extras:
#
# Randomly generate two lists to test this
# Write this in one line of Python (don’t worry if you can’t figure this out at this point - we’ll get to it soon)
| true |
1021858fc455addb151eee1cf4a11aedcbc787a5 | claggierk/video_rental | /Customer.py | 2,075 | 4.25 | 4 | phone_number_length = 12
dob_length = 3
class Customer(object):
"""
a Customer to a DVD rental facility
"""
def __init__(self, f_name, l_name, phone, dob, email):
"""constructor; initialize first and last names, phone #, date of birth, and email"""
self.first_name = f_name
self.last_name = l_name
if len(phone) != phone_number_length:
print " ##### Warning: Invalid phone number. Valid format: '###-###-####'"
self.phone = ""
else:
self.phone = phone
if len(dob) != dob_length: # TODO could validate the month and day and the year (within reason)
print " ##### Warning: Invalid date of birth. Valid format (use integers): '(month, day, year)'"
self.dob = (0,0,0)
else:
self.dob = dob
# TODO - validate email address
self.email = email # future: support emailing customers reports (when their video(s) are due), coupons, suggested videos
self.rented_video_IDs = []
def __str__(self):
return self.print_me()
def __repr__(self):
return self.print_me()
def print_me(self):
"""returns a string of the description of the Customer"""
return "%s %s" % (self.first_name, self.last_name)
def rent_video(self, video_ID):
"""customer rents a video (adds it to self.rented_video_IDs"""
if video_ID not in self.rented_video_IDs:
print "Customer: %s is now renting: %s" % (self, video_ID)
self.rented_video_IDs.append(video_ID)
else:
print " ##### Warning: Customer %s is already renting %s" % (self.phone, video_ID)
def return_video(self, video_ID):
"""customer returning a video (removes it from self.rented_video_IDs)"""
if video_ID in self.rented_video_IDs:
print "Customer: %s returned video: %s" % (self, video_ID)
self.rented_video_IDs.remove(video_ID)
else:
print " ##### Warning: Unexpected video returned" | true |
89ce032171309536dae16bc55a3c49fae721c86a | sanjeevseera/Hackerrank-challenges | /strings/Love-Letter_Mystery.py | 1,121 | 4.125 | 4 | """
James found a love letter that his friend Harry has written to his girlfriend.
James is a prankster, so he decides to meddle with the letter. He changes all the words in the letter into palindromes.
To do this, he follows two rules:
He can only reduce the value of a letter by , i.e. he can change d to c, but he cannot change c to d or d to b.
The letter a may not be reduced any further.
Each reduction in the value of any letter is counted as a single operation.
Find the minimum number of operations required to convert a given string into a palindrome.
For example, given the string , the following two operations are performed: cde -> cd-> cdc.
"""
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the theLoveLetterMystery function below.
def theLoveLetterMystery(s):
count = 0
for i in range(len(s)//2):
if s[i] != s[-1-i]:
count += abs(ord(s[i])-ord(s[-1-i]))
return count
if __name__ == '__main__':
q = int(input())
for q_itr in range(q):
s = input()
result = theLoveLetterMystery(s)
print(result)
| true |
29a744f875d73c04464a5d5b4c357fe1d3bb28d0 | sanjeevseera/Hackerrank-challenges | /30DaysOfCode-challenges/Day17_More_Exceptions.py | 1,039 | 4.3125 | 4 | """
Yesterday's challenge taught you to manage exceptional situations by using try and catch blocks.
In today's challenge, you're going to practice throwing and propagating an exception.
Check out the Tutorial tab for learning materials and an instructional video!
Task
Write a Calculator class with a single method: int power(int,int). The power method takes two integers,
'n' and 'p', as parameters and returns the integer result of 'n**p'. If either 'n' or 'p' is negative,
then the method must throw an exception with the message: n and p should be non-negative.
"""
#Write your code here
class Calculator:
def power(self,n,p):
if n <0 or p<0:
raise ValueError("n and p should be non-negative")
#raise Exception("n and p should be non-negative")
else:
return n**p
myCalculator=Calculator()
T=int(input())
for i in range(T):
n,p = map(int, input().split())
try:
ans=myCalculator.power(n,p)
print(ans)
except Exception as e:
print(e)
| true |
a28639b300eed5497da619b9e89bc4da7c9f9bbb | nitish24n/Topgear-Python-L1-set1 | /15th.py | 693 | 4.40625 | 4 | """Create a list of 5 names and check given name exist in the List.
a) Use membership operator (IN) to check the presence of an element.
b) Perform above task without using membership operator.
c) Print the elements of the list in reverse direction."""
names = ["hari","krishna","pawan","karan","shital"]
print("checking if pawan exists in list")
#finding using IN operator
given_name = "pawan"
if given_name in names:
print("pawan exists in list")
#without using IN operator
for x in names:
if x == given_name:
print("found name ",given_name)
#printing elements of list in reverse order
for x in reversed(names):
print(x)
| true |
b6c7db962cd190f5e9e5515e6c9a1b188cce376f | nitish24n/Topgear-Python-L1-set1 | /18th.py | 630 | 4.3125 | 4 |
"""
Using loop structures print numbers from 1 to 100. and using the same loop print numbers from 100 to 1 (reverse printing)
a) By using For loop
b) By using while loop
c) Let mystring ="Hello world"
print each character of mystring in to separate line using appropriate loop
"""
#for-loop 1 to 100
for i in range(1,101):
print(i)
#reversed order
for i in range(100,0,-1):
print(i)
#while -loop 1 to 100
i = 1
while i <= 100:
print(i)
i = i +1
#reversed order
i = 100
while i >= 1:
print(i)
i = i -1
#printing all characters in seperate line
mystring ="Hello world"
for i in mystring:
print(i)
| true |
786bc7bddf5415c7c40c964bba2e8295d1066252 | nitish24n/Topgear-Python-L1-set1 | /13th.py | 810 | 4.125 | 4 | """Write a program to find the biggest of 4 numbers.
a) Read 4 numbers from user using Input statement.
b) extend the above program to find the biggest of 5 numbers.
(PS: Use IF and IF & Else, If and ELIf, and Nested IF)"""
first,second,third,forth = input().split()
first,second,third,forth = int(first),int(second),int(third),int(forth)
biggest = first
if second > biggest:
biggest = second
if third > biggest:
biggest = third
if forth > biggest:
biggest = forth
print("biggest of four numbers is ",biggest)
a,b,c,d,e = input().split()
a,b,c,d,e = int(a),int(b),int(c),int(d),int(e)
biggest2 = a
if b > biggest2:
biggest2 = b
if c > biggest2:
biggest2 = c
if d > biggest2:
biggest2 = d
if e > biggest2:
biggest2 = e
print("biggest of five numbers is ",biggest2)
| true |
64dfaf738eda5d3d558a423170d3f86c38370b42 | FelipeGCosta/Introducao-a-Ciencia-da-Computacao-2018-2 | /Lista 4/Lista de Exercícios 4 - Gabaritos/Lista 4 - Questão E.py | 654 | 4.15625 | 4 | """ Semelhante as questões 3 e 4, porém na função quadrado_pares quando temos
todos os quadrados dos pares calculados e chegamos ao valor 1 nós chamamos
a função entrada novamente para ler o próximo valor """
def entrada():
n = int(input())
if(n == 0): #Se n for 0 então paramos de ler valores do teclado
return
else:
quadrado_pares(n)
def quadrado_pares(n):
if(n > 1):
if(n % 2 == 0):
print("%d^2 = %d"%(n,n**2))
quadrado_pares(n-2)
else:
quadrado_pares(n-1)
else: #Aqui precisamos ler o próximo valor
entrada()
entrada()
| false |
ecb479f13c16d41ab6f520d38e895bfa3ed0866f | whoislimos/Python-Codes | /Bubble_Sort.py | 582 | 4.125 | 4 | # Author: Abdulhalim Yusuf
# Date: November 12, 2015
# Project: Bubble Sort
#list = [3 , 2, 9 , 6 , 5]
list =[23 ,42 ,4 ,16 ,8 ,15]
print ("==== Bubble Sort Test begins ====\n")
print ("Unsorted List", (list))
print ("The length of this list is", (len(list)), "\n")
for j in range ((len(list)-1), 0, -1):
for i in range(j):
if (list[i] > list[i+1]):
temp = list[i]
list[i] = list[i+1]
list[i+1] = temp
print ("Every List", (list))
print ("\nSorted List", (list))
print ("\n==== Program End after printing ====")
| false |
661af70ac0304040e409c3c122327ffb9d84d648 | CHINASH29/hello-world | /duplicate.py | 261 | 4.125 | 4 | # Checking Duplicates in list
my_list = ['a', 'a', 'b', 'c', 'd', 'd', 'e', 'e', 'e']
dupes = []
for values in my_list:
if my_list.count(values) > 1:
if values not in dupes:
dupes.append(values)
print('Duplicate values are :-', dupes)
| true |
3335a9c63f02bdc696f318a8c8b81ce966be3bc9 | code-of-the-future/Python-Beginner-Tutorials-YouTube- | /Python_Types_and_Logical_Operators.py | 626 | 4.21875 | 4 | # Python Types
# Basic types in python!
print(type("Hello, world!"))
print(type(13))
print(type(4.72))
print(type(True))
# Moving to integers
print(4.72, int(4.72)) # Python rounds down!
print(4.05, int(4.05))
# Rounding up!
print(4.72, int(4.72), int(round(4.72)))
# Moving strings to integers
print("12345", int("12345"))
# Moving to floats
print(float(18))
print(float("12345"))
# Moving to strings
print(str(18))
print(str(19.5))
print(type(str(19.5)))
# Logical Operators
# There are three different logical operators; 'and', 'or', 'not'
x = 6
print(x > 0 and x < 5)
y = 24
print(y % 2 == 0 or y % 5 == 0)
| true |
bcc0f5f2518a37408bb025f494ae779ab7f373d0 | EvansWinner/math-and-coding-exercises | /praxis_stalinsort_20210119.py | 1,137 | 4.1875 | 4 | """Programming Praxis Stalin sort from https://programmingpraxis.com/2021/01/19/stalin-sort/ ."""
# Going to do a proper, non-destructive version.
def stalin(lst):
"""Sort a list by omitting any elements that are not sorted already."""
if not isinstance(lst, list):
return []
if not lst:
return []
if len(lst) == 1:
return lst
ret = [lst[0]]
for i in range(1, len(lst)):
if lst[i] >= lst[i - 1]:
ret.append(lst[i])
return ret
# Bonus
def mao(lst):
"""Given a list, return a sorted list, whether you like it or not."""
return [1, 2]
# Tests
if __name__ == "__main__":
assert stalin(1) == []
assert stalin([]) == []
assert stalin([1]) == [1]
assert stalin([1, 2, 3, 4]) == [1, 2, 3, 4]
assert stalin([1, 1, 2, 3]) == [1, 1, 2, 3]
assert stalin([2, 1, 2, 1]) == [2, 2]
assert stalin([4, 3, 2, 1]) == [4]
assert stalin([4, 4, 4, 4]) == [4, 4, 4, 4]
assert stalin([4, 3, 4, 1]) == [4, 4]
assert stalin(["sdf", "fds", "wer"]) == ["sdf", "wer"]
assert mao(["Your", "mom"]) == [1, 2]
print("All tests passed.")
| false |
c120d8292bfbc700efe17a59bfd70127bc47737b | mcburneyc/220 | /labs/lab2/lab2.py | 1,030 | 4.15625 | 4 | """
Name: Cooper McBurney
lab2.py
"""
import math
def sum_of_threes():
upperbound = eval(input("Input your Upper Bound:"))
x = 0
for num in range(3, upperbound + 1, 3):
x= x + num
print(x)
#end for loop
def multiplication_table():
for table in range(1,11):
print(table, table * 1, table * 2, table * 3, table * 4, table * 5, table * 6, table * 7, table * 8, table * 9, table * 10)
def triangle_area():
a = eval(input("Input A value:"))
b = eval(input("Input B value:"))
c = eval(input("Input C value:"))
s = (a + b + c)/2
x = s * (s-a) * (s-b) * (s-c)
print(math.sqrt (x))
def sumSquares():
a = eval(input("Input Lower Range:"))
b = eval(input("Input Upper Range:"))
num = 0
for x in range(a,b + 1):
num = x * x
print(num)
def power():
base = eval(input("Input your base:"))
exponent = eval(input("Input your exponent"))
total = 1
for num in range(exponent):
total = total * base
print (total)
| false |
effe3f32bbd6abd042f25a407bf32226630ab2e7 | EECS388-F19/lab-jcosens | /students.py | 274 | 4.125 | 4 | students = ["Daniel", "Kanu", "Olivia"]
students.sort()
print(students)
first_name = students[0]
first_name = first_name[:-1]
print(first_name)
length = 0
longest = "";
for x in students:
if len(x) > length:
longest = x;
length = len(x)
print(longest)
| true |
9b143c613b4a16b0d7653cc766dfa9d0376e46c3 | aarreza/hyperskill | /CoffeeMachine/coffee_machine_v1.py | 1,043 | 4.40625 | 4 | #!/usr/bin/env python3
# Amount of water, milk, and coffee beans required for a cup of coffee
WATER, MILK, COFFEE = (200, 50, 15)
# Enter the available amount of water, milk, and coffee beans
water_check = int(input("Write how many ml of water the coffee machine has: "))
milk_check = int(input("Write how many ml of milk the coffee machine has: "))
coffee_check = int(input("Write how many grams of coffee beans the machine has: "))
cups = int(input("Write how many cups of coffee you will need: "))
# Calculate the amount of water, milk, and coffee beans
water_amount = water_check // WATER
milk_amount = milk_check // MILK
coffee_amount = coffee_check // COFFEE
# Maximum cups that the coffee machine can make
max_cup = min([water_amount, milk_amount, coffee_amount])
if max_cup == cups:
print("Yes, I can make that amount of coffee")
elif max_cup > cups:
print(f"Yes, I can make that amount of coffee {max_cup - cups} and even excess more than that")
elif max_cup < cups:
print(f"No, I can only {max_cup} cups of coffee")
| true |
bc16f961006f820799356fb52d92594137ccf9e9 | limingwu8/ML | /NLP/demo02.py | 440 | 4.15625 | 4 | # test stopwords
# filter words which included in stopwords
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
example_sentence = "This is an example showing off stop word filtration."
stop_words = set(stopwords.words("english"))
print(stop_words)
words = word_tokenize(example_sentence)
filtered_sentence = []
for w in words:
if w not in stop_words:
filtered_sentence.append(w)
print(filtered_sentence) | true |
426474b3f01c3ca40d212b7fcb4148908bde31bb | thegreedychoice/TheMathofIntelligence | /Gradient Descent - Linear Regression/gradient_descent.py | 2,621 | 4.15625 | 4 | import numpy as np
import csv
import matplotlib.pyplot as plt
"""
The dataset represents distance cycled vs calories burned.
We'll create the line of best fit (linear regression) via gradient descent to predict the mapping.
"""
#Get Dataset
def get_data(file_name):
"""
This method gets the data points from the csv file
"""
data = []
with open(file_name, 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for line in reader:
row = map(float,[line[0], line[1]])
data.append(row)
return data
def loss(m, b, data):
"""
This method computes the loss for the given value of paramters
Error = 1/N * sum(Yi - (mXi + b))^2
"""
N = len(data)
error = 0
for i in range(N):
x = data[i][0]
y = data[i][1]
t = m * x + b
error += (y - t)**2
error = error/N
return error
def step_gradient(m,b, data, eta):
"""
This function calculates the gradient of paramters wrt Error and then
compute the new values of the paramters
"""
dE_dm = 0
dE_db = 0
N = len(data)
for i in range(N):
x = data[i][0]
y = data[i][1]
t = m * x + b
dE_dm += -1 * x * (y - t)
dE_db += -1 * (y - t)
dE_dm = (2 * dE_dm) / N
dE_db = (2 * dE_db) / N
new_m = m - eta * dE_dm
new_b = b - eta * dE_db
return [new_m, new_b]
def gradient_descent(m,b, data, num_iterations, eta):
"""
This method performs the gradient descent for a given number of iterations
"""
for i in range(num_iterations):
#Compute the Error
error = loss(m, b, data)
#Compute the gradients
[m, b] = step_gradient(m, b, data, eta)
print "Epoch No : {0} -----> Error : {1} -----> m : {2} , b : {3}".format(i,error, m, b)
return [m,b,error]
#Compute Gradient
#Update Parameters
def main():
#Get the dataset from csv file
data = get_data('data.csv')
#Intialize the Parameters for line equation y = mx + c
m = 0
b = 0
#Initialize hyperparamters
eta = 0.0001
num_iterations = 1000
#Run Gradient Descent
print "Starting gradient descent at b = {0}, m = {1}, error = {2}".format(0,0, loss(m, b, data))
print "Running....."
[m,b, error] = gradient_descent(m, b, data, num_iterations, eta)
print "Completed!"
print "After {0} iterations b = {1}, m = {2}, error = {3}".format(num_iterations, b, m, error)
#Plot the Best Fit line
points = np.asarray(data)
X_axis = points[:,0]
Y_axis = points[:,1]
plt.plot(X_axis, Y_axis, 'bo')
plt.plot(X_axis, m * X_axis + b, 'r-')
plt.axis([0,1.5* max(X_axis), 0, 1.3 * max(Y_axis)])
plt.title("Best fit : Linear Regression")
plt.text(10, 130, "m="+str(round(m,4))+" b="+str(round(b,4)))
plt.show()
if __name__ == "__main__":
main()
| true |
155c460efdfd78af00513dbb1234b069dbbe93fe | Tomology/python-algorithms-and-data-structures | /Algorithms/sorting_algorithms/quicksort.py | 1,181 | 4.1875 | 4 | """
QUICK SORT
Time Complexity
Best Case O(n log n)
Worst Case O(n^2)
Space Complexity
O(log n)
"""
def quickSort(arr, left=0, right=None):
if right == None:
right = len(arr) - 1
if left < right:
pivotIndex = pivot(arr, left, right)
# left
quickSort(arr, left, pivotIndex - 1)
# right
quickSort(arr, pivotIndex + 1, right)
print(arr)
return arr
"""
PIVOT HELPER FUNCTION
Uses the element at the 'start' index as the pivot.
All elements in the list that are less than the pivot will be moved to the left of the pivot.
All elements in the list that are greater than the pivot will be moved to the right of the pivot.
The pivot element will be at the correct index once function finishes executing.
The index of the pivot element is returned.
"""
def pivot(arr, start, end):
pivot = arr[start]
swapIdx = start
for i in range(start + 1, end + 1):
if pivot > arr[i]:
swapIdx += 1
arr[swapIdx], arr[i] = arr[i], arr[swapIdx]
arr[start], arr[swapIdx] = arr[swapIdx], arr[start]
return swapIdx
quickSort([4, 2, 6, -2, 0, 23, -10, -3, 54, 0])
| true |
282b920f62219c096f5e4123f3222efb1d3f9e08 | iApotoxin/Python-Programming | /14_whileLoop1.py | 353 | 4.125 | 4 | countNum1 = 0
while (countNum1 < 10):
print ('The countNum1 is:', countNum1)
countNum1 = countNum1 + 1
#-------------------------------------------------
countNum2 = 0
while countNum2 < 10:
print(countNum2, "True: countNum2 is less than 10")
countNum2 = countNum2 + 1
else:
print(countNum2,"False: is not less than 10") | true |
1c64a0a40c89fc22509439b01afc5aa37751789f | shreeya917/sem | /python_mine/shreeeya/PycharmProjects/-python_assignment_dec15/unpack.py | 246 | 4.15625 | 4 | # Q5. Code a Function that simply returns ("Hello", 45, 23.3)and call this function and unpack the returned values and print it.
def f():
return ["Hello", 45, 23.3]
result = list(f())
print(result)
#x,y,z=unpack() | true |
c9f958bdf9318e66ae10596c08c2ea5210020d32 | shreeya917/sem | /python_assignment_dec22/alphabetically_sort.py | 363 | 4.34375 | 4 | #Write a program that accepts a comma separated sequence of words as input
# and prints the words in a comma-separated sequence after sorting them alphabetically.
sequence=str(input("Enter the sequence of word: "))
words=sequence.split(',')
print("The unsorted input is: \n",sequence)
words.sort()
print("The sorted output is:")
print(", ".join(words))
| true |
e0b130df14c6948bd4cbf1ae47b9337caf343090 | raprocks/hackerrank-practice | /Python/leapcheck.py | 497 | 4.21875 | 4 | def is_leap(year):
"""TODO: Docstring for is_leap.
:year: TODO
:returns: TODO
The year can be evenly divided by 4, is a leap year, unless:
The year can be evenly divided by 100, it is NOT a leap year, unless:
The year is also evenly divisible by 400. Then it is a leap year.
"""
leap = False
year = int(year)
if year%4==0:
if year%100==0:
if year%400==0:
leap = True
elif year%100!=0:
leap=True
return leap
| true |
6a522630136ef49df119a198addee80a7a4cd193 | raprocks/hackerrank-practice | /FAANG/GreetMe.py | 395 | 4.15625 | 4 | name = input() # take only input as this is string
time = int(input()) # take input and convert it to integer
if time >= 0 and time <= 11: # simple if else statements based on problem statement
print("Good Morning " + name + " sir.")
elif time >= 12 and time <= 15:
print("Good Afternoon " + name + " sir.")
elif time >= 16 and time <= 23:
print("Good Evening " + name + " sir.")
| true |
af2011841db4dee24ffdc3d084b0731fdd258b98 | davidalexander3986/PythonDataStructures | /heap/test.py | 1,280 | 4.15625 | 4 |
import priorityQueue as pq
PQ = pq.PriorityQueue()
def printMenu():
print("Commands:")
print("\tEnter a to add\n\tEnter p to pop\n\tEnter d to display contents")
print("\tEnter t to top\n\tEnter Q to quit")
command = input("Please enter a command: ")
return command
def add():
number = int(input("Enter a number to add: "))
PQ.push(number)
print(str(number) + " added")
print("priority queue state is now:")
display()
def pop():
print(PQ)
item = PQ.pop()
print("Item removed was " + str(item))
display()
def display():
if PQ.size() == 0:
print("The priority queue is empty.")
else:
print(PQ)
def top():
if PQ.size() == 0:
print("The priority queue is empty")
else:
print("The top element is " + str(PQ.peek()))
def main():
print("Now running interface for Priority Queue...")
command = ""
while True:
command = printMenu()
if command == "Q":
break
elif command == "a":
add()
elif command == "p":
pop()
elif command == "t":
top()
elif command == "d":
display()
else:
print("Incorrect command!")
print()
main()
| false |
b7916840e949bb9014b48d768ffa74136c99a520 | davidalexander3986/PythonDataStructures | /Tries/test.py | 914 | 4.125 | 4 | import Trie as TST
TST = TST.Trie()
def printMenu():
print("Commands:")
print("\tEnter i to insert\n\tEnter l to lookup")
print("\tEnter Q to quit")
command = input("Please enter a command: ")
return command
def insert():
string = input("Enter a string to insert: ")
TST.insert(string)
print(string + " added.")
def lookup():
search = input("Enter a string for me to lookup: ")
result = TST.lookup(search)
if result:
print("String found!!!")
else:
print("String NOT found!!!")
def main():
print("Now running interface for Ternary Search Trie...")
command = ""
while True:
command = printMenu()
if command == "Q":
break
elif command == "i":
insert()
elif command == "l":
lookup()
else:
print("Incorrect command!")
print()
main()
| false |
21d46ef79e63a6d3ac7de06bb5d1a88b9434518c | PrhldK/NLTKTraining | /exercises/module2_2b_stopwords_NLTK.py | 766 | 4.3125 | 4 | # Module 2: Text Analysis with NLTK
# Stop Words with NLTK
# Author: Dr. Alfred
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
# print(stopwords.words('english')[0:500:25])
stop_words = set(stopwords.words("english"))
text = """ Dostoevsky was the son of a doctor.
His parents were very hard-working and deeply religious people,
but so poor that they lived with their five children in only
two rooms. The father and mother spent their evenings
in reading aloud to their children, generally from books of
a serious character."""
print(word_tokenize(text))
# Remove stop words
filtered = [word for word in word_tokenize(text.lower()) if word not in stop_words]
print("\n----- After Filtering the Stop Words -----\n")
print(filtered)
| true |
9fbb5c647713f726f2435ccfaff604c43a50d325 | Kamayo-Spencer/Assignments | /W1_A1_Q2_Spencer.py | 1,046 | 4.4375 | 4 | # Question.
# In plain English and with the Given-required-algorithm table, write a guessing game
# where the user should guess a secret number. After every guess, the problem tells the user whether their number
# was too large or small. In the end, the number of tries needed should be printed
# Given ifomation
# User should guess a number
# the program prints out whether the number was too large or too small
# The program prints out the number of tries needed
# Required solution
# Get input from the user( should be a number)
# print out whether the number is too big or too small
# print out the numbers of attempts needed.
# Algorithm
from random import randint
no1 = randint(1 , 100)
for i in range(1,4):
no = int(input("Guess a random number between 1 and 100 :"))
if no > no1:
print("Your no is too large")
elif no < no1:
print("Your number is too small")
else:
print(f"You are good at guessing. The number is {no1}")
if i == 3:
print("Sorry, you only had three tries")
| true |
de920ee9aea6686050e08e9abb6d620f954d57fb | skitoo/mysql-workbench-exporter | /mworkbenchexporter/utils.py | 513 | 4.21875 | 4 |
def camel_case(input_string):
return "".join([word.capitalize() for word in input_string.split('_')])
def lower_camel_case(input_string):
first = True
result = ""
for word in input_string.split('_'):
if first:
first = False
result += word.lower()
else:
result += word.capitalize()
return result
def pluralize(input_string):
if input_string[-1] != 's':
input_string += 's'
return input_string
| true |
1c511220f1083194e354e2d9f73199d63d812128 | Julzmbugua/bootcamp | /students.py | 1,212 | 4.1875 | 4 | student = {
'name': 'An Other',
'langs': ['Python', 'JavaScript', 'PHP'],
'age': 23
}
student2 = {
'name': 'No Name',
'langs': ['Python', 'Java', 'PHP'],
'age': 24
}
# Task 1:
# Create a function add_student that takes a student dictionary as a parameter,
# and adds the student in a list of students.
students = []
def add_student(stud):
students.append(stud)
print(len(students))
add_student(student)
add_student(student2)
print(students)
# Task 2:
# Write a function oldest_student that finds the oldest student.
# def oldest_student:
# if student.{3} > {}:
# pass
def oldest_student(students):
oldest = 0
for student in students:
if student['age'] > oldest:
oldest = student['age']
return oldest
# Print(oldest_student(students))
print(oldest_student(students))
# Write a function student_lang that takes in a parameter lang and returns a list containing names of students who know that language.
# def student_lang(lang):
# pass
def student_lang(lang):
name_list = []
for student in students:
if lang in student['langs']:
name_list.append(student['name'])
return name_list
print(student_lang("JavaScript"))
print(student_lang("PHP")) | true |
da086a88365d28d2b8172689780b0ffaf6fa17fc | agus2207/Cursos | /Python for Everybody/Extracting_Data.py | 916 | 4.15625 | 4 | #n this assignment you will write a Python program somewhat similar to https://py4e.com/code3/geoxml.py.
#The program will prompt for a URL, read the XML data from that URL using urllib and then parse and
#extract the comment counts from the XML data, compute the sum of the numbers in the file and enter the sum.
import urllib.request, urllib.parse, urllib.error
import xml.etree.ElementTree as ET
import ssl
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
url = input('Enter - ')
html = urllib.request.urlopen(url, context=ctx)
data = html.read()
#print('Retrieved', len(data), 'characters')
#print(data.decode())
tree = ET.fromstring(data)
lst = tree.findall('comments/comment')
count = 0
for item in lst:
count += int(item.find('count').text)
#print("Count:",item.find('count').text)
print(count) | true |
1af6b418d30b50f291803394b0d53006d349af09 | thelmuth/cs110-spring-2020 | /Class22/turtle_drawing.py | 958 | 4.375 | 4 | import turtle
def main():
michelangelo = turtle.Turtle()
turtle_drawing(michelangelo)
def turtle_drawing(t):
""" Write a function that takes a turtle, and then asks the user what
direction the turtle should move using the WASD keyboard keys.
The turtle should move up 30 pixels if the user enters "w", west 30
pixels if the user enters "a", etc.
This process should repeat until the user enters "quit"."""
direction = ""
distance = 30
while direction != "quit":
direction = input("Enter a direction using wasd: ")
if direction == "w":
t.setheading(90)
t.forward(distance)
elif direction == "a":
t.setheading(180)
t.forward(distance)
elif direction == "s":
t.setheading(270)
t.forward(distance)
elif direction == "d":
t.setheading(0)
t.forward(distance)
main()
| true |
d45d46386733cf5e97f8ac555f82e66e5111fde3 | thelmuth/cs110-spring-2020 | /Class04/year.py | 533 | 4.375 | 4 | """
Author: Class
Description: This program calculates the year and number of days
past Jan. 1 given some number of days.
"""
DAYS_IN_YEAR = 365
START_YEAR = 2020
def main():
days = int(input("Enter the number of days that have passed since Jan. 1 2020: "))
years = days // DAYS_IN_YEAR
current_year = years + START_YEAR
days_since_jan_1 = days % DAYS_IN_YEAR
print("The current year is", current_year)
print("And it has been", days_since_jan_1, "days since January 1st.")
main()
| true |
32d18a1cba9d4bbcd9d95e2281e5a834e678a7c2 | thelmuth/cs110-spring-2020 | /Class25/cards.py | 2,288 | 4.21875 | 4 | """
File: cards.py
Author: Darren Strash + Class!
Make playing card class for blackjack.
"""
import random
#Rank
RANKS = ["A", 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"]
#Suit
SUITS = ["D", "C", "S", "H"]
class PlayingCard:
"""Represents a single playing card from a standard deck."""
def __init__(self, rank, suit):
"""Constructor for PlayingCard class."""
self._rank = rank
self._suit = suit
def __str__(self):
"""Returns a string representation of the playing card.
NOTE: Never print anything in __str__"""
return str(self._rank) + self._suit
def __repr__(self):
"""Very similar to __str__ method, except it gives a
"computer readable" version of this object."""
return self.__str__()
def get_rank(self):
"""Return rank of this card."""
return self._rank
def get_suit(self):
"""Return the suit of this card."""
return self._suit
def is_face(self):
"""Returns True if the rank of this card is a face card."""
return self._rank == "J" or \
self._rank == "Q" or \
self._rank == "K"
class Deck:
"""Represent a deck of playing cards."""
def __init__(self):
"""Initialize a standard deck of 52 cards."""
self._deck_list = []
for rank in RANKS:
for suit in SUITS:
new_card = PlayingCard(rank, suit)
self._deck_list.append(new_card)
self.shuffle()
def shuffle(self):
"""Shuffle the deck of cards."""
random.shuffle(self._deck_list)
def __str__(self):
return str(self._deck_list)
def draw_one_card(self):
"""Remove the top card from the deck and return it."""
return self._deck_list.pop()
def main():
# card = ("A", "D")
# #card[0] -> rank
# #card[1] -> suit
#
# real_card = PlayingCard("J", "D")
# print("Rank:", real_card.get_rank(), ", Suit:", real_card.get_suit())
# print("Is Face?:", real_card.is_face())
# print(real_card)
deck = Deck()
print(deck)
a = deck.draw_one_card()
b = deck.draw_one_card()
print("first card is", a, "and second card is", b)
print(deck)
if __name__ == "__main__":
main()
| true |
252b50d29c748b3ca9d95c359a43bed3c7c5fe3b | thelmuth/cs110-spring-2020 | /Class16/grids.py | 1,653 | 4.28125 | 4 |
def main():
# Create a grid of a map for a robot in a park
map = [["grass", "puddle", "mud"],
["tree", "grass", "grass"],
["bush", "robot", "tree"],
["bush", "mud", "grass"]]
# print(map)
# print(map[2])
# print(map[2][3])
print_grid(map)
print(find_element(map, "robot"))
print(find_element(map, "tree"))
print(find_element(map, "elephant"))
print(find_adjacent_same_elements(map))
num_grid = [[1,2,3,4,5],
[5,4,1,8,3],
[4,3,3,2,1],
[7,7,7,7,7]]
print(find_element(num_grid, 8))
print(find_adjacent_same_elements(num_grid))
def print_grid(grid):
"""Nicely prints grid"""
for row in grid:
for element in row:
print("{:6s}".format(element), end=" ")
print()
def find_element(grid, target):
"""Finds the row and column numbers of target, if it is in the grid."""
for row_num in range(len(grid)):
for col_num in range(len(grid[row_num])):
if grid[row_num][col_num] == target:
return (row_num, col_num)
# Returns None if target not found
return None
def find_adjacent_same_elements(grid):
"""Finds two elements that are adjacent in the same row of the grid.
Returns (row, col) of the first one."""
for row_num in range(len(grid)):
for col_num in range(len(grid[row_num]) - 1):
if grid[row_num][col_num] == grid[row_num][col_num + 1]:
return (row_num, col_num)
return None
main()
| true |
9dca3985fd5ee606d8b6fd1c8b53bd2fcf17f1f1 | rand0musername/psiml2017-homework | /2 Basic file ops/basic_file_ops.py | 733 | 4.1875 | 4 | import re
import os
# regex that matches valid text files
FILE_PATTERN = re.compile(r"^PSIML_(\d{3}).txt$")
def count_files(root):
"""Return the number of files under root that satisfy the condition."""
num_files = 0
for dirpath, _, files in os.walk(root):
for file in files:
fmatch = FILE_PATTERN.match(file)
assert fmatch
fh = open(os.path.join(dirpath, file), 'r')
text = fh.read()
fh.close()
# compare the number of occurrences with file name
if text.count("PSIML") == int(fmatch.group(1)):
num_files += 1
return num_files
if __name__ == "__main__":
root = raw_input()
print(count_files(root))
| true |
eeb3636504db21ac1a21807038e2213a5effa2a8 | bhavanikumar10/Activities | /python_activity_5/comprehension.py | 2,067 | 4.3125 | 4 | prices = ["24", "13", "16000", "1400"]
price_nums = [int(price) for price in prices]
print(prices)
print(price_nums)
dog = "poodle"
letters = [letter for letter in dog]
print(letters)
print(f"We iterate over a string into a list: {letters}")
capital_letters = [letter.upper() for letter in letters]
# another way of doing the same thing as in line 11 is below in line 13,14,15
capital_letters = []
for letter in letters:
capital_letters.append(letter.upper())
print(capital_letters)
no_o = [letter for letter in letters if letter != 'o']
print(no_o)
# another way of doing the same thing as line 17 is below
no_o = []
for letter in letters:
if letter != 'o':
no_o.append(letter)
june_temperature = [72,65,59,87]
july_temperature = [87,85,92,79]
august_temperature = [88,77,66,100]
temperature = [june_temperature, july_temperature, august_temperature]
# to find the lowest temperature
#short hand
lowest_summer_temperature = [min(temps) for temps in temperature]
maximum_summer_temperature = [max(temps) for temps in temperature]
print(lowest_summer_temperature[0])
print(lowest_summer_temperature[1])
print(lowest_summer_temperature[2])
print("=" * 30)
# another way of doing the same finding lowest temperature is as below
#long hand
lowest_summer_temperature = []
for temps in temperature:
lowest_summer_temperature.append(min(temps))
print(sum(lowest_summer_temperature)/len(lowest_summer_temperature))
print(sum(maximum_summer_temperature)/len(maximum_summer_temperature))
print(lowest_summer_temperature[0])
print(lowest_summer_temperature[1])
print(lowest_summer_temperature[2])
# functions
def name(parameter):
return "Hello " + parameter
print (name("loc"))
def average(data):
return (sum(data1)/len(data1)) + (sum(data2)/len(data2))
# the below code will print "=" 40 times
print("=" * 40)
print(average([1,2,3,4,5],[2,3,4,5,6]))
# another way of doing it is
a = average([1,2,3,4,5],[2,3,4,5,6])
print(a)
def multiple3(a):
if(a % 3 == 0):
return True
else:
return False
print(multiple3(4))
| false |
da1721a0670435a000e319adf776fd5770b4af08 | sidherun/lpthw | /ex_15a.py | 950 | 4.25 | 4 | # This line imports argument variable module from the sys library
from sys import argv
# This line identifies the arguments required when the script runs
script, filename = argv
# This line initiates a variable, 'txt' and assigns the open function on the file we created 'ex15_samples.txt', which means the contents of the file are now represented by 'txt'
txt = open(filename)
# These lines print out the filename and then the contents of the file
print(f"Here's your file {filename}:")
print(txt.read())
# These lines print out a request for the user to input the filename again and then give the '>' prompt for the user to give a filename to map to the file_again variable
# print("Type the filename again:")
# file_again = input("> ")
# This line assigns the variable txt_again to the contents of the variable 'file_again'
# txt_again = open(file_again)
# This line prints the contents of the variable 'txt_again'
# print(txt_again.read())
| true |
bc19e0f1be946edcdc032719be76c1c888519555 | simonlc/Project-Euler-in-Python | /euler_0007 | 699 | 4.25 | 4 | #!/usr/bin/env python
"""
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see
that the 6th prime is 13.
What is the 10 001st prime number?
"""
#http://www.daniweb.com/software-development/python/code/216880/check-if-a-number-is-a-prime-number-python
def isprime(n):
"Check if integer n is a prime"
n = abs(int(n))
if n < 2:
return False
if n == 2:
return True
if not n & 1:
return False
for x in range(3, int(n**0.5)+1, 2):
if n % x == 0:
return False
return True
def main():
x = 1
n = 0
while n < 10001:
x += 1
if isprime(x):
n += 1
return x
print(main())
| true |
b064a9e9915c6a1b13993bf688dba5c09cd76e3c | richardmoonw/CRS_Bioinformatics | /Week_01/exercise04.py | 985 | 4.25 | 4 | # The careful bioinformatician should check if there are other short regions in the genome
# exhibiting multiple occurrences of a n-mer and its complement. After all, maybe therse strings
# occur as repeats throughout the entire genome, rather than just in the ori region. The goal is
# to create a program to find all occurrences of a pattern in a string.
def findPatternMatching(dna_sequence, pattern):
matching_positions = []
for position in range(0, len(dna_sequence) - len(pattern)):
if dna_sequence[position:position+len(pattern)] == pattern:
matching_positions.append(position)
return matching_positions
if __name__ == '__main__':
# If it is an extremely large input, you can better store it in a .txt file and then open and read its content from
# this program.
dna_sequence = input()
pattern = input()
matching_positions = findPatternMatching(dna_sequence, pattern)
print(*matching_positions, sep=" ")
| true |
4229331e91ef430e66bc1b0638e942680a54edf0 | EswarAleti/Chegg | /Python/Curve_GPA/GPA.py | 1,156 | 4.28125 | 4 | #importing random to generate random numbers
import random
#declare a list called GPA
GPA=[]
#These indexes denotes the random number between startFrom to endAt i.e 0 to 40
startFrom=0
endAt=40
#This function generate GPA list using random()
def generateRandomGPA():
#For 20 students
for i in range(20):
#generate a random number between startFrom, endAt i.e 0 to 40
marks=random.randint(startFrom,endAt)
#points = marks/10
GPA.append(marks/10)
def curveGPA():
global GPA
#maxGPAInList defines the maximum GPA by a student in list GPA
maxGPAInList = max(GPA)
#maxGPA defines the maximum GPA here a student cannot get 4.0 so maxGPA is 4
maxGPA = endAt/10
#Finding deviation of maxGPA to maxGPAInList of GPA list
deviation = maxGPA - maxGPAInList
#Adding the deviation to every student gpa
#round each gpa to 1 decimal point
GPA = [round(x+deviation,1) for x in GPA]
#returning the amount of curve
return deviation
generateRandomGPA()
print("Before curving")
print(GPA)
deviation = curveGPA()
print("Deviation is ",round(deviation,1))
print("After curving")
print(GPA) | true |
e8484248385457e46082e0f1f7634e1094bd7ebf | MayaGuzunov/AssignementsPythonDTU | /Exercise1.py | 534 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 24 17:22:48 2021
@author: mayaguzunov
"""
import numpy as np
def count_unique_rows(x):
row=x
unique_rows=0
row_del=x
for i in range(len(row)):
if row[i,0]==2:
row_del=np.delete(row,i,axis=0)
i=i+1
new_array=np.sum(row_del,axis=1)
count=len(np.unique(new_array,axis=0))
return count
print(count_unique_rows(np.array([[1,2,3],[1,2,3],[2,2,3],[3,2,1],[1,2,4],[4,2,3],[2,2,3],[1,4,2]])))
| false |
cf3724943d030d91f00cac381d2c92a796d74c8c | MayaGuzunov/AssignementsPythonDTU | /functions1.py | 273 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 8 22:25:35 2021
@author: mayaguzunov
"""
def evaluate_polynomial(x):
a=5
b=-7
c=3
return a*x**2+b*x+c
def evaluate_polynomial(x):
a=5
b=-7
c=3
print(a*x**2+b*x+c)
| false |
9bf2a324689448777fd5ee8f564db7be204cd442 | Da1anna/Data-Structed-and-Algorithm_python | /leetcode/其它题型/双指针/common/删除链表的倒数第N个节点.py | 1,392 | 4.125 | 4 | '''
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
'''
快慢指针+删除链表节点:基本操作
'''
from leetcode.其它题型.双指针.ListNode import *
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
#特判:
if not head:
return head
front = ListNode(-1)
front.next = head
p,q = front,front
#定位
while q.next:
q = q.next
n -= 1
if n < 0:
p = p.next
#删除
p.next = p.next.next
# cur = p.next
# tmp = cur.next
# p.next = tmp
return front.next
#测试
nums = [1,2,3,4,5]
head = list_buildNode(nums)
res = Solution().removeNthFromEnd(head,5)
print(res)
| false |
db8a366891201e235e1c0c9cfb7cac94d2ef7a55 | Da1anna/Data-Structed-and-Algorithm_python | /leetcode/其它题型/字典树/单词搜索.py | 2,190 | 4.1875 | 4 | '''
设计一个支持以下两种操作的数据结构:
void addWord(word)
bool search(word)
search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 . 或 a-z 。 . 可以表示任何一个字母。
示例:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
说明:
你可以假设所有单词都是由小写字母 a-z 组成的。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-and-search-word-data-structure-design
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
'''
思路:用典型的字典树来考虑,不太好处理‘.’这个通配符,递归(dfs)比较好处理
所以需要另写一个match函数来递归的搜索,search来调用它
'''
from collections import defaultdict
class TrieNode:
def __init__(self):
self.end = False
self.children = defaultdict(TrieNode)
class WordDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def addWord(self, word: str) -> None:
"""
Adds a word into the data structure.
"""
node = self.root
for c in word:
node = node.children[c]
node.end = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
"""
node = self.root
return self.match(node,word,0)
def match(self,node,word,index) -> bool:
'''
单独定义一个函数,便于递归处理
'''
if len(word) == index:
return node.end
c = word[index]
if c == '.':
for key in node.children:
if self.match(node.children[key],word,index+1):
return True
return False
else:
if c not in node.children:
return False
return self.match(node.children[c],word,index+1)
| false |
68dd02c6e73c8461c7af2eb5c8ed9875f5b33ff9 | AishaRiley/calculate-volume | /volumepyramid.py | 404 | 4.125 | 4 | ##Write program to calculate volume of pyramid
##Have user give the base and the height of the pyramid
def main():
print("Volume:",pyramidVolume(5, 9))
print("Expected: 300")
print("Volume:",pyramidVolume(9, 10))
print("Expected: 0")
def pyramidVolume(baseLength, height):
baseArea = baseLength * baseLength
return height * baseArea / 3
##Start program
main()
| true |
a6691db3611b04de1322f6ecf30b87a6fc83d708 | Yobretaw/AlgorithmProblems | /Py_leetcode/007_reverseInteger.py | 1,122 | 4.1875 | 4 | import sys
import math
"""
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
- If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
- Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer,
then the reverse of 1000000003 overflows. How should you handle such cases?
- For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
"""
def reverseInteger(x):
if -10 < x < 10:
return x
sign = -1 if x < 0 else 1
x = max(x, -x)
while x % 10 == 0:
x /= 10
d = 10
res = 0
while x > 0:
# check overflow
if res > (sys.maxint - x % d) / 10:
return 0
res *= 10
res += x % d
x /= 10
return sign * res
#m = sys.maxint
#print m
#print reverseInteger(-123)
#print reverseInteger(int(str(sys.maxint)[::-1]))
#print reverseInteger(int(str(sys.maxint + 1)[::-1]))
| true |
1373f3fbe475186d04a6f9ebdf7e001b1a3eb2ab | Yobretaw/AlgorithmProblems | /Py_leetcode/162_findPeakElement.py | 1,039 | 4.25 | 4 | import sys
import math
"""
A peak element is an element that is greater than its neighbors.
Given an input array where num[i] != num[i+1], find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that num[-1] = num[n] = -infi
For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.
Note:
Your solution should be in logarithmic complexity.
"""
def find_peak_element(nums):
n = len(nums)
if n < 2:
return 0 if n else -1
start = 0
end = n
while start < end:
mid = (start + end) / 2
left = nums[mid] > nums[mid - 1] if mid > 0 else True
right = nums[mid] > nums[mid + 1] if mid < n - 1 else True
if left and right:
return mid
elif left:
start = mid + 1
else:
end = mid
return -1
#a = [1, 2, 3, 1]
#a = [1, 2]
#print find_peak_element(a)
| true |
9df0e169aa2b24b89699b821127ab38962e87f98 | Yobretaw/AlgorithmProblems | /EPI/Python/BinaryTree/10_1_testIfBalanced.py | 1,575 | 4.15625 | 4 | import sys
import os
import math
import imp
Node = imp.load_source('Node', '../BST/BST.py').Node
bst_print = imp.load_source('Node', '../BST/BST.py').bst_print
"""
============================================================================================
A binary tree is said to be balanced if for each node in the tree, the difference in the
height of its left and right subtrees is at most one.
Write a function that takes as input the a binary tree and checks whether the tree is
balanced.
============================================================================================
"""
def is_balanced(root):
return is_balanced_help(root)[1]
def is_balanced_help(root):
if not root:
return (0, True)
if not root.left and not root.right:
return (1, True)
left = is_balanced_help(root.left)
if not left[1]:
return (-1, False)
right = is_balanced_help(root.right)
if not right[1]:
return (-1, False)
return (1 + max(left[0], right[0]), abs(left[0] - right[0]) <= 1)
root = Node(1)
print is_balanced(root)
root = Node(1, Node(2))
print is_balanced(root)
root = Node(1, Node(2), Node(3))
print is_balanced(root)
root = Node(1, Node(2, Node(4)), Node(3))
print is_balanced(root)
root = Node(1, Node(2, Node(4)), Node(3, Node(8)))
print is_balanced(root)
root = Node(1, Node(2, Node(4, Node(8))), Node(3, Node(8)))
bst_print(root)
print is_balanced(root)
root = Node(1, Node(2, Node(4, Node(8, None, Node(9)))), Node(3, Node(8)))
bst_print(root)
print is_balanced(root)
| true |
8462a52099b7ff85c921367ea3b26449da940299 | Yobretaw/AlgorithmProblems | /EPI/Python/Array/6_13_permuteElementsOfArray.py | 1,386 | 4.3125 | 4 | import sys
import os
import re
import math
import random
"""
============================================================================================
A permutation of an array A can be specified by an array P, where P[i] represents the location
of the element at i in the permutation. A permutation can be applied to an array to reorder the
array. For example, the permutation [2, 0, 1, 3] applied to [a, b, c, d] yields the array
[b, c, a, d]. It simple to apply a permutation to a given array if additional storge is available
to write the resulting array
Given an array A of n elements and a permutation P, apply P to A using only constant additional
storge. Use A itself to store the result.
Essentially it's bucket sort.
[2, 0, 1, 3]
[a, b, c, d]
->
[1, 0, 2, 3]
[c, b, a, d]
->
[0, 1, 2, 3]
[b, c, a, d]
============================================================================================
"""
def permutate(A, P):
n = len(A)
if n < 2:
return A
for i in range(0, n):
while i != P[i]:
a = P[i]
A[i], A[a] = A[a], A[i]
P[i], P[a] = P[a], a
A = ['a', 'b', 'c', 'd']
P = [2, 0, 1, 3]
permutate(A, P)
print A
A = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
P = [2, 6, 4, 5, 3, 7, 0, 8, 9, 1]
permutate(A, P)
print A
| true |
b75f5219b092e837b2f4dfd19691c35c73b21f75 | Yobretaw/AlgorithmProblems | /Py_leetcode/224_basic_calculator.py | 1,805 | 4.34375 | 4 | import re
"""
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open ( and closing parentheses ), the plus
+ or minus sign -, non-negative integers and empty spaces.
You may assume that the given expression is always valid.
Some examples:
"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23
"""
def calculate(s):
if len(s) < 2:
return 0 if not s else int(s[0])
# remove white spaces
s = list(s.replace(' ', ''))
# stack to store op
st = []
ops = []
curr = 0
for i, c in enumerate(s):
if c == '(':
if i > 0:
st.append(s[i - 1])
curr += (0 if s[i - 1] == '+' else 1)
elif c == ')':
if st:
op = st[-1]
curr -= (0 if op == '+' else 1)
st.pop()
elif c == '+' or c == '-':
ops.append(curr)
# revert ops if needed
count = 0
for i, c in enumerate(s):
if c == '+' or c == '-':
if ops[count] % 2 == 1:
s[i] = '+' if c == '-' else '-'
count += 1
res = 0
op = None
val = 0
s = ''.join(s).replace('(', '').replace(')', '')
for c in s:
if c == '+' or c == '-':
if op:
res += val * (1 if op == '+' else -1)
else:
res += val
op = c
val = 0
else:
val = 10 * val + int(c)
res = res + val * (1 if op != '-' else -1)
return res
if __name__ == '__main__':
print calculate("1 + 1")
print calculate(" 2-1 + 2 ")
print calculate("(1+(4+5+2)-3)+(6+8)")
print calculate("2-(1-(4+5+2)-3)+(6+8)")
print calculate("(5-(1+(5)))")
| true |
0119a76668ae12ebb589380e105137148adbc4cf | Yobretaw/AlgorithmProblems | /EPI/Python/Strings/7_4_reverseAllWordsInSentence.py | 748 | 4.15625 | 4 | import sys
import os
import re
import math
"""
============================================================================================
Implement a function for reversing the words in a string s. Assume s is stored in a array
of characters
============================================================================================
"""
def reverse(s):
n = len(s)
if n < 2:
return s
s[:] = s[::-1]
curr = 0
while curr < n:
while curr < n and s[curr].isspace():
curr += 1
start = curr
while curr < n and not s[curr].isspace():
curr += 1
s[start:curr] = s[start:curr][::-1]
s = [c for c in "Alice likes Bob"]
reverse(s)
print ''.join(s)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.