blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
d9657338aa5ce5c4be2b5f189f5d6ea7b3bae1a6
|
anti401/python1
|
/python1-lesson1/easy-2.py
| 555
| 4.21875
| 4
|
# coding : utf-8
# Задача-2: Исходные значения двух переменных запросить у пользователя.
# Поменять значения переменных местами. Вывести новые значения на экран.
a = input('A = ')
b = input('B = ')
print('Вы ввели A = ' + str(a) + ' и B = ' + str(b))
# перестановка значений через временную переменную
t = a
a = b
b = t
print('А теперь A = ' + str(a) + ' и B = ' + str(b))
| false
|
4ef007bae17e06e2f2f81f160d2d07e8e029375f
|
kahnadam/learningOOP
|
/Lesson_2_rename.py
| 688
| 4.3125
| 4
|
# rename files with Python
import os
def rename_files():
#(1) get file names from a folder
file_list = os.listdir(r"C:\Users\adamkahn\learningOOP\lesson_2_prank")
#find the current working directory
saved_path = os.getcwd()
print("Current Working Directory is "+saved_path)
#change directory to the one with the files
os.chdir(r"C:\Users\adamkahn\learningOOP\lesson_2_prank")
#(2) for each file, rename file
for file_name in file_list:
print("Old Name - "+file_name)
print("New Name - "+file_name.translate(None, "0123456789"))
os.rename(file_name,file_name.translate(None, "0123456789"))
#return to original working directory
os.chdir(saved_path)
rename_files()
| true
|
966c55fb0d234a61e5b66999b41be525a979d8c9
|
MarcusVinix/Cursos
|
/curso-de-python/funcoes_def/criando_as_proprias_funcoes.py
| 1,062
| 4.34375
| 4
|
print("Sem usar funções, a soma é: ", (5+6))
def soma(num1, num2):
print("Usando funções (DEF), a soma é: ", (num1+num2))
def subtracao(num1, num2):
print("Usando funções (DEF), a subtração é: ", (num1 - num2))
def divisao(num1, num2):
print("Usando funções (DEF), a divisão é: ", (num1 / num2))
def multiplicacao(num1, num2):
print("Usando funções (DEF), a multiplicação é: ", (num1 * num2))
soma(23, 45)
subtracao(89, 56)
divisao(87, 54)
multiplicacao(34, 3)
#usando comando return
def soma1(num1, num2):
return(num1+num2)
valor1 = 70
valor2 = 80
print("Usando funções (DEF) com return, a soma é ", soma(8,7))
print("Usando funções (DEF) com return, a soma é ", soma(valor1,valor2))
def numeroPar(numero):
return(numero % 2 == 0)
print("O numero 4 é par? ", numeroPar(4))
print("O numero 5 é par? ", numeroPar(5))
def parOuImpar(numero1):
if numeroPar(numero1):
return "par"
else:
return "impar"
print("O numero 7 é ", parOuImpar(7))
print("O numero 8 é ", parOuImpar(8))
| false
|
7118bf76fbb295f78247342b3b341f25d2d0a5c0
|
adikadu/DSA
|
/implementStack(LL).py
| 1,181
| 4.21875
| 4
|
class Stack:
def __init__(self):
self.top = None
self.bottom = None
self.length = 0
def node(self, value):
return {
"value": value,
"next": None
}
def peek(self):
if not self.length: return "Stack is empty!!!"
return self.top["value"]
def push(self, value):
node = self.node(value)
node["next"] = self.top
self.top = node
if not self.length: self.bottom = node
self.length+=1
def pop(self):
if not self.length:
print("Stack is empty!!!")
return
node = self.top
if self.length==1:
self.top = None
self.bottom = None
else: self.top = self.top["next"]
self.length -= 1
node["next"] = None
return node
def isEmpty(self):
return not bool(self.length)
def traverse(self):
if not self.length:
print("Stack is empty!!!")
return
x = self.top
for i in range(self.length):
print(x["value"])
x = x["next"]
stack = Stack()
print("Empty:",end=" ")
stack.traverse()
stack.push(1)
stack.push(2)
stack.push(3)
print("Three values:", end=" ")
stack.traverse()
print("peek=", end=" ")
print(stack.peek())
stack.pop()
print("Two values:", end=" ")
stack.traverse()
print("peek=", end=" ")
print(stack.peek())
| true
|
c27205377f4de9ef50f141c30b502a795c6dc118
|
wmjpillow/Algorithm-Collection
|
/how to code a linked list.py
| 2,356
| 4.21875
| 4
|
#https://www.freecodecamp.org/news/python-interview-question-guide-how-to-code-a-linked-list-fd77cbbd367d/
#Nodes
#1 value- anything strings, integers, objects
#2 the next node
class linkedListNode:
def __init__(self,value,nextNode=None):
self.value= value
self.nextNode= nextNode
def insertNode(head, valuetoInsert):
currentNode= head
while currentNode is not None:
if currentNode.nextNode is None:
currentNode.nextNode= linkedListNode(valuetoInsert)
return head
currentNode= currentNode.nextNode
#Delete node function
def deleteNode(head, valueToDelete):
currentNode= head
previousNode= None
while currentNode is not None:
if currentNode.value == valueToDelete:
if previousNode is None:
newHead = currentNode.nextNode
currentNode.nextNode = None
return newHead
previousNode.nextNode = currentNode.nextNode
return head
previousNode = currentNode
currentNode = currentNode.nextNode
return head # Value to delete was not found.
# "3" -> "7" -> "10"
node1 = linkedListNode("3") # "3"
node2 = linkedListNode("7") # "7"
node3 = linkedListNode("10") # "10"
node1.nextNode = node2 # node1 -> node2 , "3" -> "7"
node2.nextNode = node3 # node2 -> node3 , "7" -> "10"
# node1 -> node2 -> node3
head = node1
print "*********************************"
print "Traversing the regular linkedList"
print "*********************************"
# Regular Traversal
currentNode = head
while currentNode is not None:
print currentNode.value,
currentNode = currentNode.nextNode
print ''
print "*********************************"
print "deleting the node '7'"
newHead = deleteNode(head, "10")
print "*********************************"
print "traversing the new linkedList with the node 7 removed"
print "*********************************"
currentNode = newHead
while currentNode is not None:
print currentNode.value,
currentNode = currentNode.nextNode
print ''
print "*********************************"
print "Inserting the node '99'"
newHead = insertNode(newHead, "99")
print "*********************************"
print "traversing the new linkedList with the node 99 added"
print "*********************************"
currentNode = newHead
while currentNode is not None:
print currentNode.value,
currentNode = currentNode.nextNode
| true
|
ca845b51f55cef583bfc6b9ff05741d56f474fec
|
mbravofuentes/Codingpractice
|
/python/IfStatement.py
| 625
| 4.21875
| 4
|
import datetime
DOB = input("Enter your DOB: ")
CurrentYear = datetime.datetime.now().year
Age = CurrentYear-int(DOB) #This will change the string into an integer
if(Age>=18):
print("Your age is {} and you are an adult".format(Age))
if(Age<=18):
print("Your age is {} and you are a Kid".format(Age))
#In Python, if statements are included in "Blocks" which is just where the code is going to be running
#in that case, blocks run by spaces/indents
#If and Else Statements
num = input("Put in a number: ")
if (int(num) >= 0):
print("This is a positive number")
else:
print("This number is negative")
| true
|
4ad51b29bc544a7061347b6808da4fa6896e2a6b
|
StanislavHorod/LV-431-PythonCore
|
/Home work 2/2(3 task)_HW.py
| 401
| 4.15625
| 4
|
try:
first_word = str(input("Write 1 word/numb: "))
second_word = str(input("Write 2 word/numb: "))
first_word, second_word = second_word, first_word
print("The first word now: " + first_word +
"\nThe second word now: " + second_word)
if first_word == " " or second_word == " ":
raise Exception("There is an empty lines")
except Exception as exi:
print(exi)
| false
|
6e07857a742c76f44fef1489df67d00f8b118cf6
|
sanjaykumardbdev/pythonProject_2
|
/59_Operator_overloading.py
| 1,272
| 4.46875
| 4
|
#59 Python Tutorial for Beginners | Operator Overloading | Polymorphism
a = 5
b = 6
print(a+b)
print(int.__add__(a, b))
a = '5'
b = '6'
print(a+b)
print(str.__add__(a, b))
print(a.__str__()) # when u r calling print(a) behind it is calling like this : print(a.__str__())
print('-----------------------------')
class Student:
def __init__(self, m1, m2):
self.mk1 = m1
self.mk2 = m2
def __add__(self, other):
m1 = self.mk1 + other.mk1
m2 = self.mk2 + other.mk2
s3 = Student(m1, m2)
return s3
def __gt__(self, other):
#s1 = self.mk1 + other.mk1
#s2 = self.mk2 + other.mk2
s1 = self.mk1 + self.mk2
s2 = other.mk1 + other.mk2
if s1 > s2:
return True
else:
return False
def __str__(self):
#print(self.mk1, self.mk2)
return( '{} {}'.format(self.mk1, self.mk2))
s1 = Student(30, 3)
s2 = Student(3, 3)
print("Str overloading----------------------------------")
print()
print(s1.__str__())
print(s2.__str__())
print()
print("Done----------------------------------")
# Student.__add__(s1,s2)
s3 = s1 + s2
print(s3.mk1)
s4 = s1 + s2
print(s4.mk2)
if s1 > s2:
print('s1 Wins')
else:
print('s2 wins')
| false
|
9bb1168da52c3bdbb7015f7a61f515b10dc69267
|
ubercareerprep2019/Uber_Career_Prep_Homework
|
/Assignment-2/src/Part2_NumberOfIslands.py
| 2,348
| 4.28125
| 4
|
from typing import List, Tuple, Set
def number_of_islands(island_map: List[List[bool]]) -> int:
"""
[Graphs - Ex5] Exercise: Number of islands
We are given a 2d grid map of '1's (land) and '0's (water). We define an island as a body of land surrounded by
water and is formed by connecting adjacent lands horizontally or vertically. We may assume all four edges of the
grid are all surrounded by water. We need to write a method to find the number of islands in such a map.
Write a method number_of_islands(bool[][] island_map) that returns the number of islands in a 2dmap. For this
exercise you can think of a true in the island_map representing a '1' (land) and a false in the island_map
representing a '0' (water).
"""
counter: int = 0
visited: Set[Tuple[int, int]] = set()
for x in range(len(island_map)):
for y in range(len(island_map[x])):
if island_map[x][y] and (x, y) not in visited:
counter += 1
stack: List[Tuple[int, int]] = [(x, y)]
while stack:
node = stack.pop() # dfs
if node in visited:
continue
visited.add(node)
stack.extend(get_outward_edges(island_map, node))
return counter
def get_outward_edges(island_map: List[List[bool]], vertex: Tuple[int, int]) -> List[Tuple[int, int]]:
x, y = vertex
output: List[Tuple[int, int]] = []
for x1, y1 in [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]:
if x1 < 0 or y1 < 0:
continue
if x1 >= len(island_map) or y1 >= len(island_map[x1]):
continue
if island_map[x1][y1]:
output.append((x1, y1))
return output
def main():
island_map1 = [[True, True, True, True, False],
[True, True, False, True, False],
[True, True, False, False, False],
[False, False, False, False, False]]
assert number_of_islands(island_map1) == 1
island_map2 = [[True, True, False, False, False],
[True, True, False, False, False],
[False, False, True, False, False],
[False, False, False, True, True]]
assert number_of_islands(island_map2) == 3
if __name__ == "__main__":
main()
| true
|
bd829c3ee9c8593b97d74d5a1820c050013581f0
|
lepy/phuzzy
|
/docs/examples/doe/scatter.py
| 924
| 4.15625
| 4
|
'''
==============
3D scatterplot
==============
Demonstration of a basic scatterplot in 3D.
'''
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
def randrange(n, vmin, vmax):
'''
Helper function to make an array of random numbers having shape (n, )
with each number distributed Uniform(vmin, vmax).
'''
return (vmax - vmin)*np.random.rand(n) + vmin
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
n = 100
# For each set of style and range settings, plot n random points in the box
# defined by x in [23, 32], y in [0, 100], z in [zlow, zhigh].
for c, m, zlow, zhigh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]:
xs = randrange(n, 23, 32)
ys = randrange(n, 0, 100)
zs = randrange(n, zlow, zhigh)
ax.scatter(xs, ys, zs, c=c, marker=m)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()
| true
|
529738259a0398c322cda396cfc79a6b3f5b38d3
|
nancydyc/algorithms
|
/backtracking/distributeCandies.py
| 909
| 4.21875
| 4
|
def distributeCandies(candies, num_people):
"""
- loop through the arr and add 1 more candy each time
- at the last distribution n, one gets n/remaining candies
- until the remaining of the candies is 0
- if no candy remains return the arr of last distribution
>>> distributeCandies(7, 4)
[1, 2, 3, 1]
>>> distributeCandies(10, 3)
[5, 2, 3]
"""
arr = [0] * num_people
candy = 0
while candies > 0:
for i in range(len(arr)):
candy += 1
candies -= candy
if candies >= 0:
arr[i] += candy
else:
candies += candy
arr[i] += candies
return arr
return arr
#################################################
if __name__ == "__main__":
import doctest
if doctest.testmod().failed == 0:
print('Suceeded!')
| true
|
f0fa4b9c13b33806a80c6582e15bda397fafe5b9
|
JonRivera/cs-guided-project-time-and-space-complexity
|
/src/demonstration_1.py
| 1,053
| 4.3125
| 4
|
"""
Given a sorted array `nums`, remove the duplicates from the array.
Example 1:
Given nums = [0, 1, 2, 3, 3, 3, 4]
Your function should return [0, 1, 2, 3, 4]
Example 2:
Given nums = [0, 1, 1, 2, 2, 2, 3, 4, 4, 5]
Your function should return [0, 1, 2, 3, 4, 5].
*Note: For your first-pass, an out-of-place solution is okay. However, after
solving out-of-place, try an in-place solution with a space complexity of O(1).
For that solution, you will need to return the length of the modified `nums`.
The length will tell the user where the end of the array is after removing all
of the duplicates.*
"""
# Track Time for Code to Execute:
t0 = time.time()
# CODE BLOCK
t1 = time.time()
time1 = t1 - t0
import time
# Understand
# Remove Duplicates for given list
# Plan
# Need a way of tracking repeated elements
# If we have a repeated element then remove it from list.pop based on index
# Option#2:Can simply convert given list to set and then reconvert it back to a list
def remove_duplicates(nums):
nums = list(set(nums))
return nums
| true
|
0e9bb8e8d914754431f545af8cf6358012c52ca1
|
MikeyABedneyJr/python_exercises
|
/challenge7.py
| 677
| 4.1875
| 4
|
'''
Write one line of Python that takes a given list and makes a new list that has only the even elements of this list in it. http://www.practicepython.org/exercise/2014/03/19/07-list-comprehensions.html
'''
import random
from random import randint
given_list = random.sample(xrange(101),randint(1, 101))
# even_numbers = [number % 2 == 0 for number in given_list]
# This only prints [false, true, false,...] and not actual values
even_numbers = [number for number in given_list if number % 2 == 0]
# This says even_numbers = [number] and "number" is determined by all the logic that follows it (i.e the for loop and if statement)
print given_list, "\n\n", even_numbers
| true
|
e6a688b5a85a54fedd45925b8d263ed5f79a5b41
|
shardul1999/Competitive-Programming
|
/Sieve_of_Eratosthenes/Sieve_of_Eratosthenes.py
| 1,018
| 4.25
| 4
|
# implementing the function of Sieve of Eratosthenes
def Sieve_of_Eratosthenes(n):
# Creating a boolean array and
# keeping all the entries as true.
# entry will become false later on in case
# the number turns out to be prime.
prime_list = [True for i in range(n+1)]
for number in range(2,n):
# It is a prime if prime_list[number] doesn't change.
if (prime_list[number] == True):
# Updating the multiples of the "number" greater
# than or equal to the square of this number.
# all the numbers which are multiple of "number" and
# are less than number2 have already been marked.
for i in range(number * number, n+1, number):
prime_list[i] = False
# To print all the prime numbers
for i in range(2, n+1):
if prime_list[i]:
print(i)
# Driver Function
if __name__=='__main__':
n = 40
print("The prime numbers less than or equal to ",end="")
print(n," are as follows: - ")
Sieve_of_Eratosthenes(n)
| true
|
30aad0e938f726ba882dddb5f6b66cb3f9140011
|
javad-torkzadeh/courses
|
/python_course/ch5_exercise3.py
| 553
| 4.21875
| 4
|
'''
Author: Javad Torkzadehmahani
Student ID: 982164624
Instructor: Prof. Ghafouri
Course: Advanced Programming (Python)
Goal: working with function
'''
def get_students_name ():
names = []
for _ in range (0 , 6):
X = input("Enter your name: ")
names.append(X)
return names
def include_odd_indexes (names):
odd_names = []
for odd_index in range (1, 6, 2):
odd_names.append(names[odd_index])
return odd_names
names = get_students_name()
odd_names = include_odd_indexes(names)
print("your odd indexes are: ",odd_names )
| false
|
548e5b007a816be6cbbc83d3675a03a97fd65758
|
javad-torkzadeh/courses
|
/python_course/ch6_exercise2.py
| 817
| 4.1875
| 4
|
'''
Author: Javad Torkzadehmahani
Student ID: 982164624
Instructor: Prof. Ghafouri
Course: Advanced Programming (Python)
Goal: working with collection
'''
my_matrix = []
for i in range (0 , 3):
row = []
for j in range(0 , 2):
X = float(input("Enter (%d , %d): " %(i , j)))
row.append(X)
my_matrix.append(row)
print("The matrix is: ", my_matrix)
for row_counter in range(0,len(my_matrix)):
row_average = sum(my_matrix[row_counter]) / len(my_matrix[0])
print("row %d average is: %f" %(row_counter , row_average))
for column_counter in range (0, len(my_matrix[0])):
column_sum = 0
for row_counter in range(0, len(my_matrix)):
column_sum = column_sum + my_matrix[row_counter][column_counter]
print("Column %d average is: %f" % (column_counter, column_sum / len(my_matrix)))
| false
|
bb8cb835b829d3d25ed0546c702f38bb840e1157
|
Vansh-Arora/Python
|
/fibonacci.py
| 202
| 4.21875
| 4
|
# Return the nth term of fibonacci sequence.
def fibonacci(n):
if n==1:
return 1
elif n==0:
return 0
return fibonacci(n-1)+fibonacci(n-2)
print(fibonacci(int(input())))
| false
|
b0d523e2c88a10526e3ebb98ac771ad84d352260
|
TPOCTO4KA/Homework-Python
|
/Задание 4 Урок 1.py
| 607
| 4.15625
| 4
|
'''
Пользователь вводит целое положительное число.
Найдите самую большую цифру в числе.
Для решения используйте цикл while и арифметические операции.
'''
while True:
number = input('Введите положительное число, пустая строка - окончание \n')
if number == '':
print('ну ты дурной')
break
else:
m = 0
for i in number:
if m < int(i):
m = int(i)
print(m)
| false
|
a888361d9dd3b74a13385787fb297d2246d44c43
|
TPOCTO4KA/Homework-Python
|
/Задание 2 Урок 2.py
| 868
| 4.28125
| 4
|
'''
Для списка реализовать обмен значений соседних элементов, т.е.
Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д.
При нечетном количестве элементов последний сохранить на своем месте.
Для заполнения списка элементов необходимо использовать функцию input()
'''
user_answer = input 'Введите список через запятую'
user_list = user_answer.split(',') # Разделение введенного списка по заяпятой
print user_list
idx = 0 # Вводим индекс
while idx < len(user_list[:-1]):
user_list[idx], user_list[idx+1] = user_list[idx+1], user_list[idx]
idx += 2
print user_list
| false
|
94a4e95a13557630c6e6a551f297a934b01e72f1
|
gadamsetty-lohith-kumar/skillrack
|
/N Equal Strings 09-10-2018.py
| 836
| 4.15625
| 4
|
'''
N Equal Strings
The program must accept a string S and an integer N as the input. The program must print N equal parts of the string S if the string S can be divided into N equal parts. Else the program must print -1 as the output.
Boundary Condition(s):
2 <= Length of S <= 1000
2 <= N <= Length of S
Example Input/Output 1:
Input:
whiteblackgreen 3
Output:
white black green
Explanation:
Divide the string whiteblackgreen into 3 equal parts as white black green
Hence the output is white black green
Example Input/Output 2:
Input:
pencilrubber 5
Output:
-1
'''
#Your code below
a=(input().split())
l=len(a[0])
k=int(a[1])
m=l/k
if(l%k==0):
for i in range (0,l):
print(a[0][i],end="")
if (i+1)%(m)==0:
print(end=" ")
else:
print("-1")
| true
|
cb332c445ab691639f8b6fb76e25bf95ba5f7af4
|
gadamsetty-lohith-kumar/skillrack
|
/Remove Alphabet 14-10-2018.py
| 930
| 4.28125
| 4
|
'''
Remove Alphabet
The program must accept two alphabets CH1 and CH2 as the input. The program must print the output based on the following conditions.
- If CH1 is either 'U' or 'u' then print all the uppercase alphabets except CH2.
- If CH1 is either 'L' or 'l' then print all the lowercase alphabets except CH2.
- For any other values of CH1 then print INVALID.
Example Input/Output 1:
Input:
U v
Output:
A B C D E F G H I J K L M N O P Q R S T U W X Y Z
Example Input/Output 2:
Input:
L C
Output:
a b d e f g h i j k l m n o p q r s t u v w x y z
'''
#Your code below
l=input().split()
if l[0] in ('UuLl'):
if l[0]=='U' or l[0]=='u':
s='A'
l[1]=l[1].upper()
elif l[0]=='L' or l[0]=='l':
s='a'
l[1]=l[1].lower()
for i in range (0,26):
if s!=l[1]:
print(s,end=" ")
s=chr(ord(s)+1)
else:
print("INVALID")
| true
|
51edd7c35ccfe2b7d07bcbfe97395f0c88c251fa
|
TAMU-BMEN207/Apple_stock_analysis
|
/OHLC_plots_using_matplotlib.py
| 2,535
| 4.25
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 13 21:20:18 2021
@author: annicenajafi
Description: In this example we take a look at Apple's stock prices and write a
program to plot an OHLC chart. To learn more about OHLC plots visit
https://www.investopedia.com/terms/o/ohlcchart.asp
#Dataset Source:
downloaded from Kaggle ==> https://www.kaggle.com/meetnagadia/apple-stock-price-from-19802021?select=AAPL.csv
#Make sure you have studied: Numpy, Matplotlib, Pandas
"""
#import necessary modules
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
#Read csv file using pandas
df = pd.read_csv("/Users/annicenajafi/Downloads/AAPL.csv")
#let's take a look at our data
df.head()
'''
Let's only look at recent data more specifically from 2020 to the most recent data
But first we have to convert our date column to datetime type so we would be able to
treat it as date
'''
df['Date'] = pd.to_datetime(df['Date'])
df = df[df['Date'].dt.year > 2020]
#Hold on let's look at the dataframe again
df.head()
#Hmmm... Do you see that the index starts at 10100?
#Question: what problems may it cause if we don't reset the index?!
#Let's fix it so it starts from 0 like the original df
df.reset_index(inplace=True)
df.head()
#Let's define the x axis
x_vals = np.arange(0,len(df['Date']))
fig, ax = plt.subplots(1, figsize=(50,10))
'''
Let's iterate through the rows and plot a candle stick for every date
What we do is we plot a vertical line that starts from the low point and ends
at the high point for every date
'''
for idx, val in df.iterrows():
#Change the color to red if opening price is more than closing price
#Otherwise change it to green
if val['Open'] > val['Close']:
col = 'red'
else:
col ='green'
plt.plot([x_vals[idx], x_vals[idx]], [val['Low'], val['High']], color=col)
#add a horizontal line to the left to show the openning price
plt.plot([x_vals[idx], x_vals[idx]-0.05],
[val['Open'], val['Open']],
color=col)
#add a horizontal line to the right to show the closing price
plt.plot([x_vals[idx], x_vals[idx]+0.05],
[val['Close'], val['Close']],
color=col)
#Change the x axis tick marks
plt.xticks(x_vals[::50], df.Date.dt.date[::50])
#change the y label
plt.ylabel('USD')
#Change the title of the plot
plt.title('Apple Stock Price', loc='left', fontsize=20)
#let's show the plot
plt.show()
'''
Texas A&M University
BMEN 207
Fall 2021
'''
| true
|
68bb040d0e9828fc34660de7b3d0d4ffa6e36d2d
|
s-nilesh/Leetcode-May2020-Challenge
|
/14-ImplementTrie(PrefixTree).py
| 1,854
| 4.40625
| 4
|
#PROBLEM
# Implement a trie with insert, search, and startsWith methods.
# Example:
# Trie trie = new Trie();
# trie.insert("apple");
# trie.search("apple"); // returns true
# trie.search("app"); // returns false
# trie.startsWith("app"); // returns true
# trie.insert("app");
# trie.search("app"); // returns true
# Note:
# You may assume that all inputs are consist of lowercase letters a-z.
# All inputs are guaranteed to be non-empty strings.
#SOLUTION
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.children = {}
self.marker = '$'
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: void
"""
cur = self.children
for c in word:
if c not in cur:
cur[c] = {}
cur = cur[c]
cur[self.marker] = True
def __search__(self, word):
cur = self.children
for c in word:
if c not in cur:
return False
cur = cur[c]
return cur
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
found = self.__search__(word)
return found and len(found) > 0 and self.marker in found
def startsWith(self, prefix):
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
if len(prefix) == 0: return True
found = self.__search__(prefix)
return found and len(found) > 0
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
| true
|
d532d34c6b8d7c523ec14f8dc974ffc4eef4ddf2
|
shensg/porject_list
|
/python3/python_dx/pyc2.py
| 882
| 4.125
| 4
|
class Start():
name = 'hello'
age = 0
# 区分开 '类变量' '实际变量'
# 类变量和类关联在一起的
# 实际变量是面向对象的
def __init__(self, name, age): #构造函数 __int__是双下滑线 '_'
# 构造函数
# 初始化对象的属性
self.name = name
self.age = age
# print('student')
def do_homework(self): #普通函数
print('homework')
# 行为 和 特征
# class Printer():
# def print_file(self):
# print('name:' + self.name)
# print('age:' + str(self.age))
start1 = Start('蓝色', 18)
print(start1.name)
start2 = Start('红色', 16)
print(start2.name,start2.age)
# start3 = Start('兰', 15)
print(Start.name)
# print(id(start1))
# print(id(start2))
# print(id(start3))
# start1.print_file()
| false
|
e8b6ef6df71a327b6575593166873c6576f78f7b
|
SirazSium84/100-days-of-code
|
/Day1-100/Day1-10/Bill Calculator.py
| 911
| 4.1875
| 4
|
print("Welcome to the tip calculator")
total_bill = float(input("What was the total bill? \n$"))
percentage = int(input(
"What percentage tip would you like to give ? 10, 12 or 15?\n"))
people = int(input("How many people to split the bill? \n"))
bill_per_person = (total_bill + total_bill * (percentage)/100)/(people)
print("Each person should pay : ${:.2f}".format(bill_per_person))
# # print(123_567_789)
# # 🚨 Don't change the code below 👇
# age = input("What is your current age?")
# # 🚨 Don't change the code above 👆
# # Write your code below this line 👇
# def time_left(age):
# years_left = 90 - int(age)
# months_left = years_left * 12
# weeks_left = years_left * 52
# days_left = years_left * 365
# return days_left, weeks_left, months_left
# days, weeks, months = time_left(age)
# print(f"You have {days} days, {weeks} weeks, and {months} months left")
| true
|
24a69e38cdc2156452898144165634fd6579ef6c
|
keyurgolani/exercism
|
/python/isogram/isogram.py
| 564
| 4.375
| 4
|
def is_isogram(string):
"""
A function that, given a string, returns if the string is an isogram or not
Isogram is a string that has all characters only once except hyphans and
spaces can appear multiple times.
"""
lookup = [0] * 26
# Assuming that the string is case insensitive
string = string.lower()
for char in string:
if 'a' <= char <= 'z':
index = ord(char) - ord('a')
if lookup[index] == 0:
lookup[index] = 1
else:
return False
return True
| true
|
6cad9846462ac6a7aa725031f48f3cb593ed1815
|
marianohtl/LogicaComPython
|
/CV Python - Mundo 1/exe042.py
| 1,559
| 4.3125
| 4
|
#Desafio35
from math import fabs
a = int(input('Digite um número que represente uma medida de um dos lados de um triãngulo: '))
b = int(input('Digite a medida referente ao outro lado: '))
c = int(input('Typing the mitters of other side the triangle: '))
n = 0
if fabs(a - b) < c and (a + b) > c:
print ('Temos um triângulo!')
else:
if fabs(c - b) < a and (c + b) > a:
print('Temos um triângulo!')
else:
if fabs(a - c) < b and (c + a) > b:
print('Temos um triângulo!')
else:
print('Não temos um triângulo!')
# Não compreendi o porquê da ausência da necessidade de verificar o oposto de a-b >>> (b-a)
"""
if math.fabs(a - b) < c and (a + b) > c:
print('As medidas adicionadas formam um triângulo!')
else:
if math.fabs(b - a) < c and (b + a) > c:
print('As medidas adicionadas geram um triângulo!')
else:
n = n + 1
print(n)
if math.fabs(c - b) < a and (c + b) > a:
print('As medidas adicionadas formam um triângulo!')
else:
if math.fabs(b - c) < a and (b + c) > a:
print('As medidas adicionadas geram um triângulo!')
else:
n = n+1
print(n)
if math.fabs(a - c) < a and (a + c) > a:
print('As medidas adicionadas formam um triângulo!')
else:
if math.fabs(c - a) < a and (c + a) > a:
print('As medidas adicionadas formam um triÂngulo!')
else:
n = n+1
print(n)
if n == 3:
print('Que pena! Não é possível fazer um triângulo com tais medidas... ')"""
| false
|
8af76392fb8ade32aa16f998867a9312303cd2fa
|
porigonop/code_v2
|
/linear_solving/Complex.py
| 2,070
| 4.375
| 4
|
#!/usr/bin/env python3
class Complex:
""" this class represent the complex number
"""
def __init__(self, Re, Im):
"""the numer is initiate with a string as "3+5i"
"""
try:
self.Re = float(Re)
self.Im = float(Im)
except:
raise TypeError("please enter a correct number")
def __str__(self):
""" allow the user to print the complex number
"""
if self.Im < 0:
return str(self.Re) + str(self.Im) + "i"
return str(self.Re) + "+" + str(self.Im) + "i"
def __repr__(self):
""" allow the user to print the complex number
"""
if self.Im < 0:
return str(self.Re) + str(self.Im) + "i"
return str(self.Re) + "+" + str(self.Im) + "i"
def multiplicate_by(self, number):
"""allow the multiplication
"""
answerRE = 0
answerIm = 0
if type(number) is Complex:
Re = self.Re
answerRe = Re * number.Re -\
self.Im * number.Im
answerIm = Re * number.Im +\
self.Im * number.Re
else:
try:
number = float(number)
except:
raise TypeError("please enter a valid number")
answerRe = self.Re * number
answerIm = self.Im * number
return Complex(answerRe, answerIm)
def divide_by(self, number):
"""allow the division
"""
answerRE = 0
answerIm = 0
if type(number) is Complex:
numerator = self.multiplicate_by(Complex(number.Re, - number.Im))
answerRe = numerator.divide_by(number.Re **2 + number.Im **2).Re
answerIm = numerator.divide_by(number.Re **2 + number.Im **2).Im
else:
try:
number = float(number)
except:
raise TypeError("please enter a valid number")
answerRe = self.Re / number
answerIm = self.Im / number
return Complex(answerRe, answerIm)
def sum_by(self, number):
"""allow addition and subtraction
"""
answerRe = 0
answerIm = 0
if type(number) is Complex:
answerRe = self.Re + number.Re
answerIm = self.Im + number.Im
else:
try:
number = float(number)
except:
raise TypeError("please enter a valid number")
answerRe = self.Re + number
answerIm = self.Im
return Complex(answerRe, answerIm)
| true
|
af2c02c975c53c1bd12955b8bbe72bac35ab54fd
|
BryanBain/Statistics
|
/Python_Code/ExperimProbLawOfLargeNums.py
| 550
| 4.1875
| 4
|
"""
Purpose: Illustrate how several experiments leads the experimental probability
of an event to approach the theoretical probability.
Author: Bryan Bain
Date: June 5, 2020
File: ExperimProbLawOfLargeNums.py
"""
import random as rd
possibilities = ['H', 'T']
num_tails = 0
num_flips = 1_000_000 # change this value to adjust the number of coin flips.
for _ in range(num_flips):
result = rd.choice(possibilities) # flip the coin
if result == 'T':
num_tails += 1
print(f'The probability of flipping tails is {num_tails/num_flips}')
| true
|
d2e63bfba6fdfa348260d81a84628cacc6243a18
|
Yasthir01/Bootcamp-Tasks-and-Projects-Part1
|
/Level 1/Task 7/investment_calculator.py
| 986
| 4.125
| 4
|
"""A program on an Investment Calculator"""
import math
# user inputs
# the amount they are depositing
P = int(input("How much are you depositing? : "))
# the interest rate
i = int(input("What is the interest rate? : "))
# the number of years of the investment
t = int(input("Enter the number of years of the investment: "))
# simple or compound interest
interest = input("Enter either 'Simple' or 'Compound' interest: ").lower()
# the 'r' variable is the interest divided by 100
r = i / 100
# check if the user entered either Simple or Compound and perform the relevant calculations
# Simple Interest Formula : A = P*(1+r*t) N.B. A is the total received or accumulated amount
if interest == 'simple':
A = P * (1 + r*t)
elif interest == 'compound':
# Compound Interest Formula : A = P* math.pow((1+r),t)
A = P * math.pow((1 + r), t) # t is the power
# print out the Accrued amount ie. the received or accumulated amount
print(f"The Accrued amount is : {round(A, 2)}")
| true
|
720fefd121f1bc900454dcbfd668b12f0ad9f551
|
Yasthir01/Bootcamp-Tasks-and-Projects-Part1
|
/Level 1/Task 2/conversion.py
| 445
| 4.25
| 4
|
"""Declaring and printing out variables of different data types"""
# declare variables
num1 = 99.23
num2 = 23
num3 = 150
string1 = "100"
# convert the variables
num1 = int(num1) # convert into an integer
num2 = float(num2) # convert into a float
num3 = str(num3) # convert into a string
string1 = int(string1) # convert string to an integer
# print out the variables with new data types
print(num1)
print(num2)
print(num3)
print(string1)
| true
|
1143957f959a603f694c7ed6012acf2f7d465a4c
|
Yasthir01/Bootcamp-Tasks-and-Projects-Part1
|
/Level 1/Task 7/control.py
| 258
| 4.125
| 4
|
"""Program that evaluates a person's age"""
# take in user's age
age = int(input("Please enter in your age: "))
# evaluate the input
if age >= 18:
print("You are old enough!")
elif age >= 16:
print("Almost there")
else:
print("You're just too young!")
| true
|
aa41b93ab44deded12fa4705ea497d2c6bbc74e8
|
Yasthir01/Bootcamp-Tasks-and-Projects-Part1
|
/Level 1/Task 10/logic.py
| 648
| 4.1875
| 4
|
"""A program about fast food service"""
menu_items = ['Fries', 'Beef Burger', 'Chicken Burger', 'Nachos', 'Tortilla', 'Milkshake']
print("***MENU***")
print("Pick an item")
print("1.Fries\n2.Beef Burger\n3.Chicken Burger\n4.Nachos\n5.Tortilla\n6.Milkshake")
choice = int(input("\nType in number: "))
for i in menu_items:
if choice == i:
print(f"You have chosen {choice}") # Nothing gets printed out
"""The reason why it doesn't print out is because when we are looping through the list it is
printing out the strings, not the positions.
So, if we are going to compare a string and an integer then it wont reach the print statement"""
| true
|
ac6d9333960c992aef690fa764d7f98ffdc9963c
|
Yasthir01/Bootcamp-Tasks-and-Projects-Part1
|
/Level 1/Task 17/animal.py
| 815
| 4.1875
| 4
|
"""Inheritance in Python"""
class Animal(object):
def __init__(self, numteeth,spots,weight):
self.numteeth = numteeth
self.spots = spots
self.weight = weight
class Lion(Animal):
def __init__(self, numteeth, spots, weight):
super().__init__(numteeth, spots, weight)
self.type()
def type(self):
"""Determine type of lion based on weight"""
if self.weight < 80:
self.lion_type = 'Cub'
elif self.weight < 120:
self.lion_type = 'Female'
elif self.weight > 120:
self.lion_type = 'Male'
class Cheetah(Animal):
def __init__(self, numteeth, spots, weight, prey):
super().__init__(numteeth, spots, weight)
self.prey = prey
# lion object
lion1 = Lion(30, 0, 130)
print(lion1.lion_type)
# cheetah object
cheetah = Cheetah(20, 5, 100, ['Buffalo', 'Gazelle'])
print(cheetah.prey)
| false
|
7eafe6d1231ff66b56fdeab6c409922e82ec5691
|
purvajakumar/python_prog
|
/pos.py
| 268
| 4.125
| 4
|
#check whether the nmuber is postive or not
n=int(input("Enter the value of n"))
if(n<0):
print("negative number")
elif(n>0):
print("positive number")
else:
print("The number is zero")
#output
"""Enter the value of n
6
positive number"""
| true
|
0fc620866a5180d3a6d0d51547d74896a6d3c193
|
ky822/assignment7
|
/yl3068/questions/question3.py
| 734
| 4.3125
| 4
|
import numpy as np
def result():
print '\nQuestion Three:\n'
#Generate 10*3 array of random numbers in the range [0,1].
initial = np.random.rand(10,3)
print 'The initial random array is:\n{}\n'.format(initial)
#Question a: pick the number closest to 0.5 for each row
initial_a = abs(initial-0.5).min(axis=1)
#Question b: find the column for each of the numbers closest to 0.5
colunm_ix = (abs(initial-0.5).argsort())[:,0]
#Question c: a new array containing numbers closest to o.5 in each row
row_ix = np.arange(len(initial))
result = initial[row_ix, colunm_ix]
print 'The result array containing numbers closest to 0.5 in each row of initial array is:\n{}\n'.format(result)
| true
|
39e36aeb85538a4be57dd457d005fd12bc642e25
|
ky822/assignment7
|
/ql516/question3.py
| 1,927
| 4.1875
| 4
|
# -*- coding: utf-8 -*-
import numpy as np
def array_generate():
"""
generate a 10x3 array of random numbers in range[0,1]
"""
array = np.random.rand(10,3)
return array
def GetClosestNumber(array):
"""
for each row, pick the number closest to .5
"""
min_index = np.argmin(np.abs(array-0.5),1)
closest_array = array[np.arange(10),min_index]
return closest_array
def GetClosestNumberBySort(array):
"""
Generte an array contain the numbers closest to 0.5 in each rows
Argument
========
array: numpy array
Return
======
an array contain the closest numbers
Example
=======
>>>array1 = array_generate()
>>>array1
array([[ 0.63665097, 0.50696162, 0.76121097],
[ 0.68714886, 0.20228392, 0.52424866],
[ 0.3275332 , 0.76667842, 0.41314787],
[ 0.05645787, 0.6146244 , 0.69211519],
[ 0.13655137, 0.84564668, 0.57381465],
[ 0.65070546, 0.7825995 , 0.67390848],
[ 0.23796975, 0.97312122, 0.87593416],
[ 0.39804522, 0.30356075, 0.79707104],
[ 0.45504483, 0.28996881, 0.71733035],
[ 0.94605093, 0.65489037, 0.54693193]])
>>>print GetClosestNumberBySort(array1)
array[ 0.50696162 0.52424866 0.41314787 0.6146244 0.57381465 0.65070546
0.23796975 0.39804522 0.45504483 0.54693193]
"""
row_number = 10
array_abs = np.abs(array-0.5)
array_sorted_index = np.argsort(array_abs)
sorted_array = array[np.arange(row_number).reshape((row_number,1)),array_sorted_index]
closest_array = sorted_array[:,0]
return closest_array
def main():
array = array_generate()
print array
#print "get closest number: \n",GetClosestNumber(array)
print "get closest number for each row: \n", GetClosestNumberBySort(array)
if __name__ == "__main__":
main()
| true
|
7d82924a9a4123d5a340cbbd352ddea2bd4b3e18
|
ky822/assignment7
|
/wl1207/question1.py
| 694
| 4.125
| 4
|
import numpy as np
def function():
print "This is the answer to question1 is:\n"
array = np.array(range(1,16)).reshape(3,5).transpose()
print "The 2-D array is:\n",array,"\n"
array_a = array[[1,3]]
print "The new array contains the 2nd column and 4th rows is:\n", array_a, "\n"
array_b = array[:, 1]
print "The new array contains the 2nd column is:\n",array_b, "\n"
array_c = array[1:4, :]
print "The new array contains all the elements in the rectangular section is:\n", array_c, "\n"
array_d = array[np.logical_and(array>=3, array<=11)]
print "The new array contains all the elements between 3 and 11 is:\n", array_d, "\n"
if __name__ =='__main__':
function()
| true
|
81f5a75d870f8e67f5694b03307f80a98a879c0d
|
f287772359/pythonProject
|
/practice_9.py
| 2,983
| 4.125
| 4
|
from math import sqrt
# 动态
# 在类中定义的方法都是对象方法(都是发送给对象的消息)
# 属性名以单下划线开头
class Person(object):
def __init__(self, name, age):
self._name = name
self._age = age
# 访问器 - getter方法
@property
def name(self):
return self._name
# 访问器 - getter方法
@property
def age(self):
return self._age
# 修改器 - setter方法
@age.setter
def age(self, age):
self._age = age
def play(self):
if self._age <= 16:
print('%s正在玩飞行棋.' % self._name)
else:
print('%s正在玩斗地主.' % self._name)
class Person(object):
# 限定Person对象只能绑定_name, _age和_gender属性
__slots__ = ('_name', '_age', '_gender')
def __init__(self, name, age):
self._name = name
self._age = age
@property
def name(self):
return self._name
@property
def age(self):
return self._age
@age.setter
def age(self, age):
self._age = age
def play(self):
if self._age <= 16:
print('%s正在玩飞行棋.' % self._name)
else:
print('%s正在玩斗地主.' % self._name)
# 静态
# 实际上,写在类中的方法并不需要都是对象方法,例如定义一个“三角形”类,
# 通过传入三条边长来构造三角形,
# 用于验证三条边是否构成三角形的方法显然不是对象方法
class Triangle(object):
def __init__(self, a, b, c):
self._a = a
self._b = b
self._c = c
@staticmethod
def is_valid(a, b, c):
return a + b > c and b + c > a and a + c > b
def perimeter(self):
return self._a + self._b + self._c
def area(self):
half = self.perimeter() / 2
return sqrt(half * (half - self._a) *
(half - self._b) * (half - self._c))
def main():
a, b, c = 3, 4, 5
# 静态方法和类方法都是通过给类发消息来调用的
if Triangle.is_valid(a, b, c):
t = Triangle(a, b, c)
print(t.perimeter())
# 也可以通过给类发消息来调用对象方法但是要传入接收消息的对象作为参数
# print(Triangle.perimeter(t))
print(t.area())
# print(Triangle.area(t))
else:
print('无法构成三角形.')
# person = Person('王大锤', 22)
# person.play()
# person._gender = '男'
# print(person._gender) # slots限定了绑定的属性,gender可以赋值并输出,但需要加单下划线
# person._is_gay = True # slots中没有这个属性,所以添加此属性,赋值以及输出
# print(person._is_gay)
# person = Person('王大锤', 12)
# person.play()
# person.age = 22
# person.play()
# person.name = '白元芳' # AttributeError: can't set attribute
if __name__ == '__main__':
main()
| false
|
6779c9a4de1ac252d6c913d5de26aff3cbc64153
|
Kamilet/learning-coding
|
/python/ds_reference.py
| 534
| 4.25
| 4
|
print('Simple Assignment')
shoplist = ['apple', 'mango', 'carrot', 'banana']
# mylist只是指向同一对象的另一名称
mylist = shoplist
# 购买了apple删除
del shoplist[0] #和在mylist中删除效果一样
print('shoplist is', shoplist)
print('my list is', mylist)
#注意打印结果
#二者指向同一对象,则会一致
print('Copy by making a full slice')
mylist = shoplist[:] #复制完整切片
#删除第一个项目
del mylist[0]
print('shoplist is', shoplist)
print('my list is', mylist)
#此时已经不同
| false
|
ae63f36897ced379ec1f7b20bc399182c36682c5
|
Kamilet/learning-coding
|
/python/ds_str_methods.py
| 305
| 4.1875
| 4
|
#这是一个字符串对象
name = 'Kamilet'
if name.startswith('Kam'):
print('Yes, the string starts with "Kam"')
if 'a' in name:
print('Yes, contains "a"')
if name.find('mil') != -1:
print('Yes, contains "mil"')
delimiter='_*_'
mylist = ['aaa', 'bbb', 'ccc', 'ddd']
print(delimiter.join(mylist))
| true
|
5b01a489805c58909979dae65c04763df722bfaa
|
Sauvikk/practice_questions
|
/Level6/Trees/Balanced Binary Tree.py
| 1,233
| 4.34375
| 4
|
# Given a binary tree, determine if it is height-balanced.
#
# 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.
# Return 0 / 1 ( 0 for false, 1 for true ) for this problem
#
# Example :
#
# Input :
# 1
# / \
# 2 3
#
# Return : True or 1
#
# Input 2 :
# 3
# /
# 2
# /
# 1
#
# Return : False or 0
# Because for the root node, left subtree has depth 2 and right subtree has depth 0.
# Difference = 2 > 1.
from Level6.Trees.BinaryTree import BinaryTree
class Solution:
def is_balanced(self, root):
if root is None:
return True
if self.get_depth(root) == -1:
return False
return True
def get_depth(self, root):
if root is None:
return 0
left = self.get_depth(root.left)
right = self.get_depth(root.right)
if left == -1 or right == -1:
return -1
if abs(left - right) > 1:
return -1
return max(left, right) + 1
A = BinaryTree()
A.insert(100)
A.insert(102)
A.insert(96)
res = Solution().is_balanced(A.root)
print(res)
| true
|
9cea8f90b8556dcacec43dd9ae4a7b4500db2114
|
Sauvikk/practice_questions
|
/Level6/Trees/Sorted Array To Balanced BST.py
| 951
| 4.125
| 4
|
# Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
#
# Balanced tree : 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.
# Example :
#
#
# Given A : [1, 2, 3]
# A height balanced BST :
#
# 2
# / \
# 1 3
from Level6.Trees.BinaryTree import BinaryTree, Node
class Solution:
def generate_bt(self, num, start, end):
if start > end:
return None
mid = int((start+end)/2)
node = Node(num[mid])
node.left = self.generate_bt(num, start, mid-1)
node.right = self.generate_bt(num, mid+1, end)
return node
def solution(self, num):
if num is None or len(num) == 0:
return num
return self.generate_bt(num, 0, len(num)-1)
res = Solution().solution([1, 2, 3, 4, 5, 6, 7])
BinaryTree().pre_order(res)
| true
|
7708927408c989e6d7d6a297eb62d27ca489ee49
|
Sauvikk/practice_questions
|
/Level6/Trees/BinaryTree.py
| 2,379
| 4.15625
| 4
|
# Implementation of BST
class Node:
def __init__(self, val): # constructor of class
self.val = val # information for node
self.left = None # left leef
self.right = None # right leef
self.level = None # level none defined
self.next = None
# def __str__(self):
# return str(self.val) # return as string
class BinaryTree:
def __init__(self): # constructor of class
self.root = None
def insert(self, val): # create binary search tree nodes
if self.root is None:
self.root = Node(val)
else:
current = self.root
while 1:
if val < current.val:
if current.left:
current = current.left
else:
current.left = Node(val)
break
elif val > current.val:
if current.right:
current = current.right
else:
current.right = Node(val)
break
else:
break
def bft(self): # Breadth-First Traversal
self.root.level = 0
queue = [self.root]
out = []
current_level = self.root.level
while len(queue) > 0:
current_node = queue.pop(0)
if current_node.level > current_level:
current_level += 1
out.append("\n")
out.append(str(current_node.val) + " ")
if current_node.left:
current_node.left.level = current_level + 1
queue.append(current_node.left)
if current_node.right:
current_node.right.level = current_level + 1
queue.append(current_node.right)
print(''.join(out))
def in_order(self, node):
if node is not None:
self.in_order(node.left)
print(node.val)
self.in_order(node.right)
def pre_order(self, node):
if node is not None:
print(node.val)
self.pre_order(node.left)
self.pre_order(node.right)
def post_order(self, node):
if node is not None:
self.post_order(node.left)
self.post_order(node.right)
print(node.val)
| true
|
4a0eca90de3ce7fb0ab6decb0ec6aadb32c1a9fa
|
Sauvikk/practice_questions
|
/Level6/Trees/Identical Binary Trees.py
| 998
| 4.15625
| 4
|
# Given two binary trees, write a function to check if they are equal or not.
#
# Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
#
# Return 0 / 1 ( 0 for false, 1 for true ) for this problem
#
# Example :
#
# Input :
#
# 1 1
# / \ / \
# 2 3 2 3
#
# Output :
# 1 or True
from Level6.Trees.BinaryTree import BinaryTree
class Solution:
def solution(self, rootA, rootB):
if rootA == rootB:
print('h')
return True
if rootA is None or rootB is None:
return False
# if rootA is None and rootB is None:
# return True
return ((rootA.val == rootB.val) and self.solution(rootA.left, rootB.left) and
self.solution(rootA.right, rootB.right))
A = BinaryTree()
A.insert(100)
A.insert(102)
A.insert(96)
B = BinaryTree()
B.insert(100)
B.insert(102)
B.insert(96)
res = Solution().solution(A.root, B.root)
print(res)
| true
|
8bf85ec04b5f5619a235f1506b7226597a75bef0
|
Kaushikdhar007/pythontutorials
|
/kaushiklaptop/NUMBER GUESS.py
| 766
| 4.15625
| 4
|
n=18
print("You have only 5 guesses!! So please be aware to do the operation\n")
time_of_guessing=1
while(time_of_guessing<=5):
no_to_guess = int(input("ENTER your number\n"))
if no_to_guess>n:
print("You guessed the number above the actual one\n")
print("You have only", 5 - time_of_guessing, "more guesses")
time_of_guessing = time_of_guessing + 1
elif no_to_guess<n:
print("You guessed the number below the actual one\n")
print("You have only",5-time_of_guessing,"more guesses")
time_of_guessing=time_of_guessing+1
continue
elif no_to_guess==n:
print("You have printed the actual number by guessing successfully at guess no.",time_of_guessing)
break
| true
|
be99bff4b371868985a64a79a23e34be58a0831f
|
KrishnaPatel1/python-workshop
|
/theory/methods.py
| 1,722
| 4.28125
| 4
|
def say_hello():
print("Hello")
print()
say_hello()
# Here is a method that calculates the double of a number
def double(number):
result = number * 2
return result
result = double(2)
print(result)
print()
# Here is a method that calculates the average of a list of numbers
def average(list_of_numbers):
total = 0
number_of_items_in_list = 0
average = 0
for number in list_of_numbers:
number_of_items_in_list = number_of_items_in_list + 1
total = total + number
average = total/number_of_items_in_list
return average
a_bunch_of_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = average(a_bunch_of_numbers)
print(result)
print()
# Challenge 1
# Create a function that takes a number
# it returns the negative of the number
# Note, use print(method) to print out the value
print("Challenge 1:")
# Challenge 2
# Imagine you are given some product that has some cost to it (e.g. $14.99)
# calculate the tax of the product and and it to the cost of the product
# return the total cost of the product
# assume the tax is 15%
# Note, use print() to print out the result of the method
print()
print("Challenge 2:")
# Challenge 3
# Create a method that
# takes in a student's test score and the total amount of points in the test
# returns the result of the student in percentage
print()
print("Challenge 3:")
# Challenge 4
# Create a method that:
# takes in one number
# if even, print the number and state that it is even
# if odd, print the number and state that it is odd
# if less than zero, print the number and state that it is negative
# if the number is a combination of the above conditions, then print both conditions (e.g. -2 is even and negative)
print()
print("Challenge 4:")
| true
|
06bea009748a261e7d0c893a18d60e4b625d6243
|
hoanghuyen98/fundamental-c4e19
|
/Session05/homeword/Ex_1.py
| 1,302
| 4.25
| 4
|
inventory = {
'gold' : 500,
'pouch': ['flint', 'twine', 'gemstone'],
'backpack' : ['xylophone', 'dagger', 'bedroll', 'bread loaf']
}
# Add a Key to inventory called 'pocket' and Set the value of 'pocket' to be a list
print("1: Add a Key to inventory called 'pocket' and Set the value of 'pocket' to be a list ")
print()
print(" =====>> List ban đầu : ")
print(inventory)
inventory['pocket'] = ['seashell', 'strange', 'berry', 'lint']
print(" =====>> List sau khi thêm : ")
print(inventory)
print()
print("* "*20)
# Then remove('dagger') from the list of items stored under the 'backpack' key
print("2: Then remove('dagger') from the list of items stored under the 'backpack' key")
print()
key = "backpack"
if key in inventory:
value = inventory[key]
value.pop(1)
print(" =====>> List sau khi xóa value dagger của key 'backpack ")
print()
print(inventory)
else:
print(" not found ")
print()
print("* "*20)
# Add 50 to the number stored under the 'gold' key.
print("3: Add 50 to the number stored under the 'gold' key.")
print()
key_1 = 'gold'
if key_1 in inventory:
inventory[key_1] += 50
print(" =====>> List sau khi thêm 50 vào 500 ")
print()
print(inventory)
print()
else:
inventory[key_1] = 50
print(inventory)
| true
|
05ba21e69dab1b26f1f98a48fc3c186d37f8097b
|
hoanghuyen98/fundamental-c4e19
|
/Session02/Homeword/BMI.py
| 373
| 4.25
| 4
|
height = int(input("Enter the height : "))
weight = int(input("Enter the weight : "))
BMI = weight/((height*height)*(10**(-4)))
print("BMI = ", BMI)
if BMI < 16:
print("==> Severely underweight !!")
elif BMI < 18.5:
print("==> Underweight !!")
elif BMI < 25:
print("==> Normal !!")
elif BMI < 30:
print("==> Overweight !!")
else :
print("==> Obese !!")
| false
|
e1139905c3f17bd9e16a51a69853a0923160c84f
|
bbaja42/projectEuler
|
/src/problem14.py
| 1,496
| 4.15625
| 4
|
'''
The following iterative sequence is defined for the set of positive integers:
n n/2 (n is even)
n 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 40 20 10 5 16 8 4 2 1
It can be seen that this sequence (starting at 13 and finishing at 1)
contains 10 terms.
Although it has not been proved yet (Collatz Problem),
it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.
'''
#Contains maximum chain length for each found origin number
cache_numbers = {}
def find_start_number():
'''
Find start number with largest chain
Uses cache for found numbers as an optimization
'''
max_value = 1
index = 0
for i in range(2, 1000000):
cache_numbers[i] = calc_chain(i)
if cache_numbers[i] > max_value:
max_value = cache_numbers[i]
index = i
return index
def calc_chain(n):
if n in cache_numbers:
return cache_numbers[n]
if n == 1:
return 1
result = 1
if (n % 2 == 0):
result += calc_chain(n // 2)
else:
result += calc_chain(3 * n + 1)
return result
print ("Chain is {}".format(find_start_number()))
import timeit
t = timeit.Timer("find_start_number", "from __main__ import find_start_number")
print ("Average running time: {} seconds".format(t.timeit(1000)))
| true
|
d38ca5318a0687d16c49517fcaf6cac030cc1601
|
sys-ryan/python-django-fullstack-bootcamp
|
/10. Python Level One/string.py
| 598
| 4.40625
| 4
|
# STRINGS
mystring = 'abcdefg'
print(mystring)
print(mystring[0])
# Slicing
print(mystring[:3])
print(mystring[2:5])
print(mystring[:])
print(mystring[::2])
# upper
print(mystring.upper())
# capitalize
print(mystring.capitalize())
# split
mystring = 'Hello World'
x = mystring.split()
print(x)
mystring = 'Hello/World'
x = mystring.split('/')
print(x)
# Print Formatting
x = "Insert another string here: {}".format("<INSERTED STRING>")
print(x)
x = "Item one : {} \nItem Two : {}".format("dog", "cat")
print(x)
x = "Item one : {y} \nItem Two : {x}".format(x = "dog", y = "cat")
print(x)
| false
|
dee3f47d3b1befb9835946b10a6b96a711383dbd
|
drednout5786/Python-UII
|
/hwp_5/divisor_master.py
| 1,945
| 4.125
| 4
|
def is_prime(a):
"""
:param a: число от 1 до 1000
:return: простое или не простое число (True/False)
"""
if a % 2 == 0:
return a == 2
d = 3
while d * d <= a and a % d != 0:
d += 2
return d * d > a
def dividers_list(a):
"""
:param a: число от 1 до 1000
:return: список делителей числа
"""
div_list = []
for i in range(1, a + 1):
if a % i == 0: div_list.append(i)
return div_list
def simple_dividers(a):
"""
:param a: число от 1 до 1000
:return: список простых делителей числа
"""
d_list = dividers_list(a)
smpl_div_list = []
l = len(d_list)
for i in range(l):
if is_prime(d_list[i]):
smpl_div_list.append(d_list[i])
return smpl_div_list
def max_simple_dividers(a):
"""
:param a: число от 1 до 1000
:return: самый большой простой делитель числа
"""
return max(simple_dividers(a))
def max_dividers(a):
"""
:param a: число от 1 до 1000
:return: самый большой делитель (не обязательно простой) числа
"""
return max(dividers_list(a))
def canonical_decomposition(a):
"""
:param a: число от 1 до 1000
:return: каноническое разложение числа на простые множители
"""
a_begin = a
sd = simple_dividers(a)
lsd = len(sd)
# print("sd = ", sd)
con_dec = []
# print("con_dec = ", con_dec)
for i in range(1, lsd):
while a_begin % sd[i] == 0:
con_dec.append(sd[i])
a_begin = a_begin/sd[i]
lcd = len(con_dec)
con_dec_txt = str(con_dec[0])
for i in range(1, lcd):
con_dec_txt = "{}*{}".format(con_dec_txt, con_dec[i])
return con_dec_txt
| false
|
fc846895589cb0b3d0227622ca53c4c6a62b61bc
|
Mahedi522/Python_basic
|
/strip_function.py
| 384
| 4.34375
| 4
|
# Python3 program to demonstrate the use of
# strip() method
string = """ geeks for geeks """
# prints the string without stripping
print(string)
# prints the string by removing leading and trailing whitespaces
print(string.strip())
# prints the string by removing geeks
print(string.strip(' geeks'))
a = list(map(int, input().rstrip().split()))
print(a)
print(type(a[1]))
| true
|
0b9e842cbeb52e819ecc2a10e135008f4380f8ed
|
monadplus/python-tutorial
|
/07-input-output.py
| 1,748
| 4.34375
| 4
|
#!/user/bin/env python3.7
# -*- coding: utf8 -*-
##### Fancier Output Formatting ####
year = 2016
f'The current year is {year}'
yes_votes = 1/3
'Percentage of votes: {:2.2%}'.format(yes_votes)
# You can convert any variable to string using:
# * repr(): read by the interpreter
# * str(): human-readable
s = "Hello, world."
str(s)
repr(s)
#### Formatted String Literals ####
name = 'arnau'
f'At least 10 chars: {name:10}' # adds whitespaces
# * !a ascii()
# * !s str()
# * !r repr()
f'My name is {name!r}'
#### The String format() Method ####
'{1} and {0}'.format('spam', 'eggs')
'This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible')
# :d for decimal format
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; ''Dcab: {0[Dcab]:d}'.format(table))
print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
#### Reading and Writing Files #####
# By default is opened for text mode
#f = open('foo', 'x') # 'a' to append instead of erasing
# 'r+' reading/writing
# 'b' for binary mode
# 'x' new file and write
#f.write("Should not work")
#f.close()
with open('lore.txt', 'r') as f:
# print(f.readline())
# print(f.read(100))
# print(f.read())
for line in f:
print(line, end='')
f = open('lore.txt', 'rb+')
f.write(b'0123456789abcdef')
f.seek(5) # Go to the 6th byte in the file
f.read(1)
f.seek(-3, 2) # Go to the 3rd byte before the end
f.read(1)
#### JSON ####
import json
json.dumps([1, 'simple', 'list'])
f = open('foo.json', 'r+')
json.dump(['i', 'simple', 'list'], f)
f.seek(0) # rewind
x = json.load(f)
print(x)
f.close()
| true
|
c6145249ef56fe9890f142f597766fdb55200466
|
Ahmad-Saadeh/calculator
|
/calculator.py
| 810
| 4.125
| 4
|
def main():
firstNumber = input("Enter the first number: ")
secondNumber = input("Enter the second number: ")
operation = input("Choose one of the operations (*, /, +, -) ")
if firstNumber.isdigit() and secondNumber.isdigit():
firstNumber = int(firstNumber)
secondNumber = int(secondNumber)
if operation == "*":
print("The answer is {}".format(firstNumber * secondNumber))
elif operation == "/":
print("The answer is {}".format(firstNumber / secondNumber))
elif operation == "+":
print("The answer is {}".format(firstNumber + secondNumber))
elif operation == "-":
print("The answer is {}".format(firstNumber - secondNumber))
else:
print("Invalid Operation!")
else:
print("Invalid Numbers!")
if __name__ == '__main__':
main()
| true
|
4f603beccd737bea2d9ebd9d92bf3013dc91b9d1
|
surajkumar0232/recursion
|
/binary.py
| 233
| 4.125
| 4
|
def binary(number):
if number==0:
return 0
else:
return number%2+10 * binary(number//2)
if __name__=="__main__":
number=int(input("Enter the numner which binary you want: "))
print(binary(number))
| true
|
86cbf381166e71e7b50d958c67cc156f81426078
|
ksambaiah/python
|
/educative/fr.py
| 208
| 4.15625
| 4
|
friends = ["xyz", "abc", "234", "123", "Sam", "Har"]
print(friends)
for y in friends:
print("Hello ", y)
for i in range(len(friends)):
print("Hello ", friends[i])
z = "Hello ".join(friends)
print(z)
| false
|
0cf3d8481c243de3b9d354ad30ce1a281461aca4
|
ksambaiah/python
|
/educative/find_string_anagrams.py
| 439
| 4.375
| 4
|
#!/usr/bin/env python3
import itertools
'''
'''
def find_string_anagrams(str, pattern):
arr = []
for p in itertools.permutations(pattern):
p = "".join(p)
#arr.append(str.find(p))
if p in str:
arr.append(str.index(p))
arr.sort()
return arr
if __name__ == '__main__':
str = "thitrisisstringirtritrti"
pattern = "tri"
print(str, pattern)
print(find_string_anagrams(str,pattern))
| false
|
4afc4191fd6650dac57415404d36803373e071e4
|
ksambaiah/python
|
/hackerRank/arraySum.py
| 436
| 4.125
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 23 00:41:04 2020
@author: samkilar
"""
def addArray(arr):
y = 0
for i in range(len(arr)):
y = y + arr[i]
return y
if __name__ == "__main__":
# We are taking array, later we do take some random values
arr = [0, 1, -100, -200, 300, 999999, 9, 99, 0, 2, 22, 45, -9, 99999]
print("Adding all emements of array", addArray(arr))
| false
|
4647a038acd767895c4fd6cdbfcc130ef60a87ce
|
shreeyash-hello/Python-codes
|
/leap year.py
| 396
| 4.1875
| 4
|
while True :
year = int(input("Enter year to be checked:"))
string = str(year)
length = len(string)
if length == 4:
if(year%4==0 and year%100!=0 or year%400==0):
print("The year is a leap year!")
break
else:
print("The year isn't a leap year!")
break
else:
print('enter appropriate year')
| true
|
b74ba7ee11dafa4f0482c903eeee240142181873
|
bengovernali/python_exercises
|
/tip_calculator_2.py
| 870
| 4.1875
| 4
|
bill = float(input("Total bill amount? "))
people = int(input("Split how many ways? "))
service_status = False
while service_status == False:
service = input("Level of service? ")
if service == "good":
service_status = True
elif service == "fair":
service_status = True
elif service_status == "bad":
service_status = True
def calculate_tip(bill, service):
if service == "good":
tip_percent = 0.20
elif service == "fair":
tip_percent = 0.15
elif service == "bad":
tip_percent = 0.10
tip_amount = bill * tip_percent
print("Tip amount: $%.2f" % tip_amount)
total_amount = bill + tip_amount
print("Total amount: $%.2f" % total_amount)
amount_per_person = total_amount / people
print("Amount per person: $%.2f" % amount_per_person)
calculate_tip(bill, service)
| true
|
7626ba157020a6e67630d783a958221ad18ace0d
|
0xJinbe/Exercicios-py
|
/Ex 021.py
| 1,241
| 4.3125
| 4
|
"""Faça um programa que calcule as raízes de uma equação do segundo grau, na forma ax2 + bx + c. O programa deverá pedir os valores de a, b e c e fazer as consistências, informando ao usuário nas seguintes situações:
Se o usuário informar o valor de A igual a zero, a equação não é do segundo grau e o programa não deve fazer pedir os demais valores, sendo encerrado;
Se o delta calculado for negativo, a equação não possui raizes reais. Informe ao usuário e encerre o programa;
Se o delta calculado for igual a zero a equação possui apenas uma raiz real; informe-a ao usuário;
Se o delta for positivo, a equação possui duas raiz reais; informe-as ao usuário;"""
import math
print('Programa que acha as raizes de ax2 + bx + c = 0')
a = int(input('Coeficiente a: '))
if (a==0):
print('A == 0. A equação não é do segundo grau')
else:
b = int(input('Coeficiente b: '))
c = int(input('Coeficiente c: '))
delta = b*b - 4*a*c
if delta < 0:
print('Delta menor que zero, raízes imaginárias.')
elif delta == 0:
raiz = -b/(2*a)
print('Delta=0 , raiz = ', raiz)
else:
raiz1 = (-b + math.sqrt(delta)) / 2*a
raiz2 = (-b - math.sqrt(delta)) / 2*a
print('Raízes: ', raiz1, raiz2)
| false
|
d3379c4e3a7e371830181a9c671d33b77048399e
|
0xJinbe/Exercicios-py
|
/Ex 025.py
| 652
| 4.125
| 4
|
"""Faça um Programa para leitura de três notas parciais de um aluno. O programa deve calcular a média alcançada por aluno e presentar:
A mensagem "Aprovado", se a média for maior ou igual a 7, com a respectiva média alcançada;
A mensagem "Reprovado", se a média for menor do que 7, com a respectiva média alcançada;
A mensagem "Aprovado com Distinção", se a média for igual a 10."""
nt_1 = int(input('Entre com valor trimestre 1: '))
nt_2 = int(input('Entre com o valor trimesre 2: '))
nt_3 = int(input('Entre om o valor trimestre 3: '))
tt = nt_1 + nt_2 + nt_3
mm = tt / 3
print(mm)
if mm >= 7:
print('Apr.')
else:
print('Rep.')
| false
|
e54410cf9db5300e6ef5c84fd3432b1723c017c6
|
MeganTj/CS1-Python
|
/lab5/lab5_c_2.py
| 2,836
| 4.3125
| 4
|
from tkinter import *
import random
import math
# Graphics commands.
def draw_line(canvas, start, end, color):
'''Takes in four arguments: the canvas to draw the line on, the
starting location, the ending location, and the color of the line. Draws a
line given these parameters. Returns the handle of the line that was drawn
on the canvas.'''
start_x, start_y = start
end_x, end_y = end
return canvas.create_line(start_x, start_y, end_x, end_y, fill = color,
width = 3)
def draw_star(canvas, n, center, color):
'''Takes in four arguments: the canvas to draw the line on, the number of
points that the star has (a positive odd integer no smaller than 5), the
center of the star, and the color of the star. Draws a star pointed
vertically upwards given these parameters and with a randomly chosen radius
between 50 to 100 pixels. Returns a list of the handles of all the lines
drawn.'''
points = []
lines = []
r = random.randint(50, 100)
center_x, center_y = center
theta = (2 * math.pi) / n
for p in range(n):
x = r * math.cos(theta * p)
y = r * math.sin(theta * p)
points.append((y + center_x, -x + center_y))
increment = int((n - 1) / 2)
for l in range(n):
end_index = (l + increment) % n
lines.append(draw_line(canvas, points[l], points[end_index], color))
return lines
def random_color():
'''Generates random color values in the format recognized by the tkinter
graphics package, of the form #RRGGBB'''
seq = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c',
'd', 'e', 'f']
rand = '#'
for i in range(6):
rand += random.choice(seq)
return rand
# Event handlers.
def key_handler(event):
'''Handle key presses.'''
global stars
global color
global n
key = event.keysym
if key == 'q':
exit_python(event)
if key == 'c':
color = random_color()
if key == 'plus':
n += 2
if key == 'minus':
if n >= 7:
n -= 2
if key == 'x':
for lines in stars:
for line in lines:
canvas.delete(line)
stars = []
def button_handler(event):
'''Handle left mouse button click events.'''
global stars
lines = draw_star(canvas, n, (event.x, event.y), color)
stars.append(lines)
def exit_python(event):
'''Exit Python.'''
quit()
if __name__ == '__main__':
root = Tk()
root.geometry('800x800')
canvas = Canvas(root, width=800, height=800)
canvas.pack()
stars = []
color = random_color()
n = 5
# Bind events to handlers.
root.bind('<Key>', key_handler)
canvas.bind('<Button-1>', button_handler)
# Start it up.
root.mainloop()
| true
|
f84fdef224b8a97d88809dcf45fb0f574dc61ed4
|
SnarkyLemon/VSA-Projects
|
/proj06/proj06.py
| 2,181
| 4.15625
| 4
|
# Name:
# Date:
# proj06: Hangman
# -----------------------------------
# Helper code
# (you don't need to understand this helper code)
import random
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
# print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# line: string
line = inFile.readline()
# wordlist: list of strings
wordlist = string.split(line)
# print " ", len(wordlist), "words loaded."
return wordlist
def choose_word(wordlist):
"""
wordlist (list): list of words (strings)
Returns a word from wordlist at random
"""
return random.choice(wordlist)
# end of helper code
# -----------------------------------
# actually load the dictionary of words and point to it with
# the wordlist variable so that it can be accessed from anywhere
def hangman():
wordlist = load_words()
word = choose_word(wordlist)
l = len(word)
# print l
ans_list = ["_"]*l
print ans_list
numguess = 6
print l, "letters long."
print word
while numguess > 0:
guess = raw_input("Guess a letter or word ")
for letter in guess:
if letter in word:
for num in range(len(word)):
if guess == word[num]:
ans_list[num] = guess
print "You've guessed correctly."
print ans_list
print str(ans_list)
if guess == word:
print("Wow I'm impressed")
if str(ans_list) == word:
print "You've correctly guessed the word. Also, this took like 6 hours to make, so no big deal."
elif guess not in word:
numguess -= 1
print ("Sorry, that's incorrect")
if numguess == 0:
print "sorry, out of tries"
if ans_list == word:
print "You win"
print ans_list
print str(ans_list), "is the string answer list"
hangman()
| true
|
d7736ee0897218affa62d98dbb4117ff96d59818
|
djmgit/Algorithms-5th-Semester
|
/FastPower.py
| 389
| 4.28125
| 4
|
# function for fast power calculation
def fastPower(base, power):
# base case
if power==0:
return 1
# checking if power is even
if power&1==0:
return fastPower(base*base,power/2)
# if power is odd
else:
return base*fastPower(base*base,(power-1)/2)
base=int(raw_input("Enter base : "))
power=int(raw_input("Enter power : "))
result=fastPower(base,power)
print result
| true
|
ca5fa437808e1935217bc2230a062cdd1a28e7d3
|
nilasissen/python-rookie
|
/india.py
| 607
| 4.28125
| 4
|
#!/usr/local/bin/python
print 'Legal age in INDIA'
driving_age=16
voting_age=18
smoking_age=19
marriage_age=21
age = int(raw_input('enter your age :) '))
def get_age(age):
"""this program will teach you about the if and else and elif statements """
if age >= marriage_age:
print 'you can get marriad,smoke,vote,and drive '
elif age >= smoking_age:
print 'you cant smoke,vote,drive '
elif age >= voting_age:
print 'you can only vote and driving '
elif age >= drive_age:
print 'you can driving '
else:
print 'you cant even vote'
| false
|
1496c17e367409805481ebc32afc64d50f5449ce
|
JIAWea/Python_cookbook_note
|
/07skipping_first_part_of_an_iterable.py
| 1,321
| 4.15625
| 4
|
# Python cookbook学习笔记
# 4.8. Skipping the First Part of an Iterable
# You want to iterate over items in an iterable, but the first few items aren’t of interest and
# you just want to discard them.
# 假如你在读取一个开始部分是几行注释的源文件。所有你想直接跳过前几行的注释
from itertools import dropwhile
with open('/etc/passwd') as f:
for line in dropwhile(lambda line: line.startswith('#'), f):
print(line, end='')
# 迭代器和生成器是不能使用标准的切片操作的,因为它们的长度事先我们并不知道 (并且也没有实现索引)。
# 函数 islice() 返回一个可以生成指定元素的迭代器,它通过遍历并丢弃直到切片开始索引位置的所有元素。
# 然后才开始一个个的返回元素,并直到切片结束索引位置。
from itertools import islice
items = ['a', 'b', 'c', 1, 6, 8, 10]
for x in islice(items, 3, None)
print(x)
# 1
# 6
# 8
# 10
# 4.12 不同集合上元素的迭代
# itertools.chain() 方法可以用来简化这个任务。它接受一个可迭代对象列表作为输入,并返回一个迭代器
from itertools import chain
a = [1, 2, 3, 4]
b = ['x', 'y', 'z']
for x in chain(a, b):
print(x)
# 1
# 2
# 3
# 4
# x
# y
# z
| false
|
c1b83c2ac9d096558fa7188d269cc55f2a25ecf1
|
tolu1111/Python-Challenge
|
/PyBank.py
| 2,088
| 4.1875
| 4
|
#Import Dependencies perform certain functions in python
import os
import csv
# define where the data is located
bankcsv = os.path.join("Resources", "budget_data.csv")
# define empty lists for Date, profit/loss and profit and loss changes
Profit_loss = []
Date = []
PL_Change = []
# Read csv file
with open(bankcsv, newline= '') as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
csvheader = next(csvreader)
# calculate the values for the profit/loss and the dates
# store respective values in appropraite lists created earlier
for row in csvreader:
Profit_loss.append(float(row[1]))
Date.append(row[0])
#Print the calculated values
print("Financial Analysis")
print("-----------------------------------")
print(f"Total Months: {len(Date)}")
print(f"Total Revenue: {sum(Profit_loss)}")
#Calculate the average revenue change, the greatest revenue increase and the greatest revenue decrease
for i in range(1,len(Profit_loss)):
PL_Change.append(Profit_loss[i] - Profit_loss[i-1])
avg_PL_Change = (sum(PL_Change)/len(PL_Change))
max_PL_Change = max(PL_Change)
min_PL_Change = min(PL_Change)
max_PL_Change_date = str(Date[PL_Change.index(max(PL_Change)) + 1])
min_PL_Change_date = str(Date[PL_Change.index(min(PL_Change)) + 1])
# print the calculated values
print(f"Avereage Revenue Change: {round(avg_PL_Change,2)}")
print(f"Greatest Increase in Revenue: {max_PL_Change_date}, {max_PL_Change}")
print(f"Greatest Decrease in Revenue: {min_PL_Change_date}, {min_PL_Change}")
#export text file
p = open("PyBank.txt","w+")
p.write("Financial Analysis\n")
p.write("-----------------------------------\n")
p.write(f"Total Months: {len(Date)}\n")
p.write(f"Total Revenue: {sum(Profit_loss)}\n")
p.write(f"Avereage Revenue Change: {round(avg_PL_Change,2)}\n")
p.write(f"Greatest Increase in Revenue: {max_PL_Change_date}, {max_PL_Change}\n")
p.write(f"Greatest Decrease in Revenue: {min_PL_Change_date}, {min_PL_Change}\n")
p.close()
| true
|
cfa342710536f41de8ec8967c38b8fc1b23a3fd6
|
krishna07210/com-python-core-repo
|
/src/main/py/10-StringMethods/String-working.py
| 850
| 4.21875
| 4
|
def main():
print('This is a string')
s = 'This is a string'
print(s.upper())
print('This is a string'.upper())
print('This is a string {}'.format(42))
print('This is a string %d' % 42)
print(s.find('is'))
s1 = ' This is a string '
print(s1.strip())
print(s1.rstrip())
s2 = ' This is a string\n'
print(s2.rstrip('\n'))
print(s.isalnum())
print('thisisasting'.isalnum())
a,b =1,3
print('this is {}, that is {}'.format(a,b))
s = 'this is {}, that is {}'
print(s.format(5,9))
print(s.center(80))
s1 = 'this is %d, that is %d' % (a,b)
print(s1 )
a,b =42,35
print('this is {}, that is {}'.format(b,a))
print('this is {1}, that is {0}'.format(b,a))
print('this is {bob}, that is {fred}'.format(bob=a,fred=b))
if __name__ == "__main__": main()
| false
|
317e92540d3a6e00bec3dcddb29669fe4806c7fa
|
Frank1963-mpoyi/REAL-PYTHON
|
/FOR LOOP/range_function.py
| 2,163
| 4.8125
| 5
|
#The range() Function
'''
a numeric range loop, in which starting and ending numeric values are specified. Although this form of for loop isn’t directly built into Python, it is easily arrived at.
For example, if you wanted to iterate through the values from 0 to 4, you could simply do this:
'''
for n in (0, 1, 2, 3, 4):
print(n)
# This solution isn’t too bad when there are just a few numbers.
# But if the number range were much larger, it would become tedious
# pretty quickly.
'''
Happily, Python provides a better option—the built-in range() function,
which returns an iterable that yields a sequence of integers.
range(<end>) returns an iterable that yields integers starting with 0,
up to but not including <end>:
'''
print()
x = range(5)
print(x)
print(type(x))
print(range(0, 15))
# Note that range() returns an object of class range, not a list or tuple of the values. Because a range object is an iterable, you can obtain the values by iterating over them with a for loop:
x = range(5)
list(x)
tuple(x)
print(list(x))
print(tuple(x))
for n in x:
print(n)
# However, when range() is used in code that is part of a larger application,
# it is typically considered poor practice to use list() or tuple() in this way.
# Like iterators, range objects are lazy—the values in the specified range are not
# generated until they are requested. Using list() or tuple() on a range object forces
# all the values to be returned at once. This is rarely necessary, and if the list is long,
# it can waste time and memory.
print(list(range(5, 20, 3)))
#range(<begin>, <end>, <stride>) returns an iterable that yields integers starting with
# <begin>, up to but not including <end>. If specified, <stride> indicates an amount to skip
# between values (analogous to the stride value used for string and list slicing):
#If <stride> is omitted, it defaults to 1:
print( list(range(5, 10, 1)))
print( list(range(5, 10)))# if stride is omiited the default is one
print(list(range(-5, 5))) # [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
print(list(range(5, -5)))#[]
print(list(range(5, -5, -1)))# [5, 4, 3, 2, 1, 0, -1, -2, -3, -4]
| true
|
1eec2e1904286641b7140f572c19f7b860c3427e
|
Frank1963-mpoyi/REAL-PYTHON
|
/WHILE LOOP/whileloop_course.py
| 2,036
| 4.25
| 4
|
''' Iteration means executing the same block of code over and over, potentially many times. A programming structure that implements iteration is called a loop'''
'''
In programming, there are two types of iteration, indefinite and definite:
With indefinite iteration, the number of times the loop is executed isn’t
specified explicitly in advance. Rather, the designated block is executed
repeatedly as long as some condition is met.
With definite iteration, the number of times the designated block will be
executed is specified explicitly at the time the loop starts.
while <expr>:
<statement(s)>
<statement(s)> represents the block to be repeatedly executed, often referred
to as the body of the loop. This is denoted with indentation, just as in an if statement.
'''
a = 0# initialise
while a <= 5: # to check Boolean condition if its True it will execute the body
# then when a variale will do addition it will be 0+1=1 go again to check the condition like new value
# of a = 1 and 1<=5 True it print and add again 1+1=2 2<=5, 2+1= 3 , 3<=5, until 6<=5 no the condition become false
# and the loop terminate
print(a)# you can print the a value for each iteration
# print("Frank") or you can print Frank the number of the iterations
a = a + 1# increment to make the initialize condition become false in order to get out of the loop
#Note : Note that the controlling expression of the while loop is tested first,
# before anything else happens. If it’s false to start with, the loop body will never
# be executed at all:
family = ['mpoyi', 'mitongu', 'kamuanya', 'sharon', 'ndaya', 'mbuyi', 'tshibuyi']
while family:#When a list is evaluated in Boolean context, it is truthy if it has elements in it and falsy if it is empty
print(family.pop(-1)) # for every iteration it will remove the last element in the list until the list is finish
#Once all the items have been removed with the .pop() method and the list is empty, a is false, and the loop terminates.
| true
|
cf38d3bf5f83a42c436e46a934f2557763ab0ff4
|
utkarsht724/Pythonprograms
|
/Replacestring.py
| 387
| 4.65625
| 5
|
#program to replace USERNAME with any name in a string
import re
str= print("Hello USERNAME How are you?")
name=input("Enter the name you want to replace with USERNAME :") #taking input name from the user
str ="Hello USERNAME How are you?"
regex =re.compile("USERNAME")
str = regex.sub(name,str) #replace Username with input name by using regular expression
print(str)
| true
|
f81f22047a6538e19c1ef847ef365609646ed2df
|
utkarsht724/Pythonprograms
|
/Harmonicno.py
| 296
| 4.46875
| 4
|
#program to display nth harmonic value
def Harmonic(Nth):
harmonic_no=1.00
for number in range (2,Nth+1): #iterate Nth+1 times from 2
harmonic_no += 1/number
print(harmonic_no)
#driver_code
Nth=int(input("enter the Nth term")) #to take Nth term from the user
print(Harmonic(Nth))
| true
|
5b74b55cbc8f0145d125993fc7ac34702d8954f7
|
rawatrs/rawatrs.github.io
|
/python/prob1.py
| 819
| 4.15625
| 4
|
sum = 0
for i in range(1,1000):
if (i % 15 == 0):
sum += i
elif (i % 3 == 0):
sum += i
elif (i % 5 == 0):
sum += i
print "Sum of all multiples of 3 or 5 below 1000 = {0}".format(sum)
'''
**** Consider using xrange rather than range:
range vs xrange
The range function creates a list containing numbers defined by the input. The xrange function creates a number generator. You will often see that xrange is used much more frequently than range. This is for one reason only - resource usage. The range function generates a list of numbers all at once, where as xrange generates them as needed. This means that less memory is used, and should the for loop exit early, there's no need to waste time creating the unused numbers. This effect is tiny in smaller lists, but increases rapidly in larger lists.
'''
| true
|
6936a4fbce24ffa6be02883497224eb0fc6ad7e5
|
nirmalshajup/Star
|
/Star.py
| 518
| 4.5625
| 5
|
# draw color filled star in turtle
import turtle
# creating turtle pen
t = turtle.Turtle()
# taking input for the side of the star
s = int(input("Enter the length of the side of the star: "))
# taking the input for the color
col = input("Enter the color name or hex value of color(# RRGGBB): ")
# set the fillcolor
t.fillcolor(col)
# start the filling color
t.begin_fill()
# drawing the star of side s
for _ in range(5):
t.forward(s)
t.right(144)
# ending the filling of color
t.end_fill()
| true
|
cd03b7b76bfb8c217c0a82b3d48321f8326cc017
|
jnassula/calculator
|
/calculator.py
| 1,555
| 4.3125
| 4
|
def welcome():
print('Welcome to Python Calculator')
def calculate():
operation = input('''
Please type in the math operation you would like to complete:
+ for addition
- for substraction
* for multiplication
/ for division
** for power
% for modulo
''')
number_1 = int(input("Enter your first number: "))
number_2 = int(input("Enter your second number: "))
#Addition
if operation == '+':
print(f'{number_1} + {number_2} = ')
print(number_1 + number_2)
#Subtraction
elif operation == '-':
print(f'{number_1} - {number_2} = ')
print(number_1 - number_2)
#Multiplication
elif operation == '*':
print(f'{number_1} * {number_2} = ')
print(number_1 * number_2)
#Division
elif operation == '/':
print(f'{number_1} / {number_2} = ')
print(number_1 / number_2)
#Power
elif operation == '**':
print(f'{number_1} ** {number_2} = ')
print(number_1 ** number_2)
#Modulo
elif operation == '%':
print(f'{number_1 % number_2} = ')
print(number_1 % number_2)
else:
print('You have not typed a valid operator, please run the program again.')
again()
def again():
calc_again = input('''
Do you want to calculate again?
Please type Y for YES or N for NO.''')
if calc_again.upper() == 'Y':
calculate()
elif calc_again.upper() == 'N':
print('See you later.')
else:
again()
welcome()
calculate()
| true
|
6741dfd84673f751765d5b93a377a462b82da315
|
BatuhanAktan/SchoolWork
|
/CS121/Assignment 4/sort_sim.py
| 2,852
| 4.21875
| 4
|
'''
Demonstration of time complexities using sorting algorithms.
Author: Dr. Burton Ma
Edited by: Batuhan Aktan
Student Number: 20229360
Date: April 2021
'''
import random
import time
import a4
def time_to_sort(sorter, t):
'''
Returns the times needed to sort lists of sizes sz = [1024, 2048, 4096, 8192]
The function sorts the slice t[0:sz] using the sorting function
specified by the caller and records the time required in seconds.
Because a slice is sorted instead of the list t, the list t is not modified by
this function. The list t should have at least 8192 elements.
The times are returned in a list of length 4 where the times in seconds
are formatted strings having 4 digits after the decimal point making it easier to
print the returned lists.
Parameters
----------
sorter : function
A sorting function from the module a4.
t : list of comparable type
A list of elements to slice and sort.
Returns
-------
list of str
The times to sort lists of lengths 1024, 2048, 4096, and 8192.
Raises
------
ValueError
If len(t) is less than 8192.
'''
if len(t) < 8192:
raise ValueError('not enough elements in t')
times = []
for sz in [1024, 2048, 4096, 8192]:
# slice t
u = t[0:sz]
# record the time needed to sort
tic = time.perf_counter()
sorter(u)
toc = time.perf_counter()
times.append(f'{toc - tic:0.4f}')
return times
list8192 = list(range(8192))
def sim_sorted():
print(time_to_sort(a4.selection_sort, list8192), "Selection Sort")
print(time_to_sort(a4.insertion_sort, list8192), "Insertion Sort 1")
print(time_to_sort(a4.insertion_sort2, list8192), "Insertion Sort 2")
print(time_to_sort(a4.merge_sort, list8192), "Merge Sort")
def sim_partial():
a4.partial_shuffle(list8192)
print(time_to_sort(a4.selection_sort, list8192), "Selection Sort")
print(time_to_sort(a4.insertion_sort, list8192), "Insertion Sort 1")
print(time_to_sort(a4.insertion_sort2, list8192), "Insertion Sort 2")
print(time_to_sort(a4.merge_sort, list8192), "Merge Sort")
def sim_reverse():
list8192.reverse()
print(time_to_sort(a4.selection_sort, list8192), "Selection Sort")
print(time_to_sort(a4.insertion_sort, list8192), "Insertion Sort 1")
print(time_to_sort(a4.insertion_sort2, list8192), "Insertion Sort 2")
print(time_to_sort(a4.merge_sort, list8192), "Merge Sort")
def sim_shuffled():
random.shuffle(list8192)
print(time_to_sort(a4.selection_sort, list8192), "Selection Sort")
print(time_to_sort(a4.insertion_sort, list8192), "Insertion Sort 1")
print(time_to_sort(a4.insertion_sort2, list8192), "Insertion Sort 2")
print(time_to_sort(a4.merge_sort, list8192), "Merge Sort")
sim_shuffled()
sim_reverse()
sim_partial()
sim_sorted()
| true
|
a38ccc08bc8734389f11b1a6a9ac15eca5b7d53a
|
sammhit/Learning-Coding
|
/HackerRankSolutions/quickSortPartion.py
| 521
| 4.1875
| 4
|
#!/bin/python3
import sys
#https://www.hackerrank.com/challenges/quicksort1/problem
def quickSort(arr):
pivot = arr[0]
left = []
right = []
for i in arr:
if i>pivot:
right.append(i)
if i<pivot:
left.append(i)
left.append(pivot)
return left+right
# Complete this function
if __name__ == "__main__":
n = int(input().strip())
arr = list(map(int, input().strip().split(' ')))
result = quickSort(arr)
print (" ".join(map(str, result)))
| true
|
d3d50cb016ef1554a59452a806d959796ef53b45
|
quangvinh86/Python-HackerRank
|
/Python_domains/2-Basic-Data-Types-Challenges/Code/Ex2_4.py
| 297
| 4.21875
| 4
|
#!/usr/bin/env python3
def find_second_largest(integer_list):
return sorted(list(set(integer_list)))[-2]
if __name__ == '__main__':
# n = int(input())
# arr = map(int, input().split())
integer_list = map(int, "1 -4 0 -2 -4".split())
print(find_second_largest(integer_list))
| false
|
78a204b4a7ddcc8d39cab0d2c92430d292ad204a
|
bswood9321/PHYS-3210
|
/Week 03/Exercise_06_Q4_BSW.py
| 1,653
| 4.34375
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 7 19:50:39 2019
@author: Brandon
"""
import numpy as np
import numpy.random as rand
import matplotlib.pyplot as plt
def walk(N):
rand.seed()
x = [0.0]
y = [0.0]
for n in range(N):
x.append(x[-1] + (rand.random() - 0.5)*2.0)
y.append(y[-1] + (rand.random() - 0.5)*2.0)
return np.array(x), np.array(y)
M, N = 0, 1000 #Setting variables for later
Distance = list() #Creating an empty list to hold the distances we will record
Walker = list() #Creating an empty list of the number of steps each walker takes
while(M<=99):
walker1=walk(N) #Our walkers
Distance.append(np.sqrt((walker1[0][-1]**2)+(walker1[1][-1]**2))) #Appending the Distance list with the distances of each walker
Walker.append(N) # Appending the Walker list with the number of steps the walker has taken
M = M+1 #Increasing our M value to progress the while loop
N = N+45 #Increasing our N value to change our walker's number of steps
plt.plot(Walker, Distance, 'r+')
plt.xlabel("Number of steps")
plt.ylabel("Distance from the origin")
plt.show()
# By looking at the plot we receive, we can fairly well determine that the distance
# from the origin is fairly random, and does not necessarily increase, decrease, or
# stagnate as the N value of the walker changes.This is exactly as I imagined would happen.
# there is no reason why the distance should stay around any particular number. In fact,
# I believe if we plotted the average dsitance for several iterations of this code, we would find
# a similar plot of seemingly random values.
| true
|
70fe8fdf2f0d12b61f21f5d9bd825d2f0a0ec93f
|
LiuJLin/learn_python_basic
|
/ex32.py
| 639
| 4.53125
| 5
|
the_count = [1, 2, 3, 4, 5]
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
#this first kind of for-loop goes through a list
for number in the_count:
print("This is count %d"% number)
#also we can go through mixed lists too
#notice we have use %r since we don't know what's in it
for i in change:
print("I got %r"% i)
#we can also build lists, first start with an empty one
elements = []
#the use the range function to do 0 to 5 counts
for i in range(0, 6):
print("Adding %d to the list."% i)
#append is a function that lists Understanding
elements.append(i)
for i in elements:
print("Elements was: %d"% i)
| true
|
8b8945a9936304593b65b5648bcb882365ba5ad3
|
Phongkaka/python
|
/TrinhTienPhong_92580_CH05/Exercise/page_145_exercise_06.py
| 469
| 4.1875
| 4
|
"""
Author: Trịnh Tiến Phong
Date: 31/10/2021
Program: page_145_exercise_06.py
Problem:
6. Write a loop that replaces each number in a list named data with its absolute value
* * * * * ============================================================================================= * * * * *
Solution:
Display result:
[21, 12, 20, 5, 26, 11]
"""
data = [21, -12, 20, 0, -5, 26, -11]
for item in range(0, len(data)):
data[item] = abs(data[item])
print(data)
| true
|
fc399182e128c75611add67a65ddfe18d180dc55
|
gamershen/everything
|
/hangman.py
| 1,151
| 4.25
| 4
|
import random
with open(r'C:\Users\User\Desktop\תכנות\python\wordlist.txt', 'r') as wordfile:
wordlist = [line[:-1] for line in wordfile] # creates a list of all the words in the file
word = random.choice(wordlist) # choose random word from the list
letterlist = [letter for letter in word] # the word converted into a list of letters
secretlist = ['_' for letter in word] # the secret word as ( _ _ _ )
print('start playing\n')
print(' '.join(secretlist) + '\n')
def start_playing():
guess = input('guess a letter: ')
while len(guess) > 1 or (not (guess >= 'a' and guess <= 'z')) and (not (guess >= 'A' and guess <= 'Z')):
guess = input('that aint a letter,guess a letter: ') # char validation
[secretlist.pop(i) and secretlist.insert(i, char) for i, char in enumerate(word) if guess == char] # if guess is correct show the letter
print('\n' + ' '.join(secretlist))
for i in range(15):
start_playing()
print('tries left: ' + str(14 - i))
if letterlist == secretlist:
print('you won!')
break
if not letterlist == secretlist:
print(f'you lost! the word was: {word}')
| true
|
e0d6812a81d0a65fb8998b63ac1af09247fc803e
|
Nihilnia/June1-June9
|
/thirdHour.py
| 1,283
| 4.21875
| 4
|
""" 7- Functions """
def sayHello():
print("Hello")
def sayHi(name = "Nihil"):
print("Hi", name)
sayHello()
sayHi()
def primeQ(number):
if number == 0 or number == 1:
print(number, "is not a Primer number.")
else:
divs = 0
for f in range(2, number):
if number % f == 0:
divs += 1
if divs == 0:
print(number, "is a Primer number.")
else:
print(number, "is not a Primer number.")
primeQ(13)
# return() Expression
def hitMe():
firstNumber = int(input("Give me a number: "))
secondNumber = int(input("Give me the second number: "))
return firstNumber + secondNumber
print("Result:", hitMe())
# Flexible parameters - we know it.
""" 8- Lambda Expressions """
#Short way to create a function
def Nihil1():
print("Gimme tha Power")
Nihil2 = lambda: print("Gimme tha Power x2")
Nihil1()
Nihil2()
#Another Example
divideNumbers = lambda a, b: float(a/b) #If we won't write anything, it means return
print(divideNumbers(12, 2))
#Last Example
""" Finding are of circle (A = pi * r**2) """
findCircle = lambda r: 3.14 * (r ** 2)
print(findCircle(r = 2.5))
| true
|
af4c141fc364f89f4d1ad14541b368c164f40b81
|
stephenfreund/PLDI-2021-Mini-Conf
|
/scripts/json_to_csv.py
| 1,116
| 4.15625
| 4
|
# Python program to convert
# JSON file to CSV
import argparse
import csv
import json
def parse_arguments():
parser = argparse.ArgumentParser(description="MiniConf Portal Command Line")
parser.add_argument("input", default="data.json", help="paper file")
parser.add_argument("out", default="data.csv", help="embeddings file to shrink")
return parser.parse_args()
if __name__ == "__main__":
args = parse_arguments()
# Opening JSON file and loading the data
# into the variable data
with open(args.input) as json_file:
data = json.load(json_file)
# now we will open a file for writing
data_file = open(args.out, "w")
# create the csv writer object
csv_writer = csv.writer(data_file)
# Counter variable used for writing
# headers to the CSV file
count = 0
for emp in data:
if count == 0:
# Writing headers of CSV file
header = emp.keys()
csv_writer.writerow(header)
count += 1
# Writing data of CSV file
csv_writer.writerow(emp.values())
data_file.close()
| true
|
ae7922f1cd7be6def39e113f61390b4ceebcb016
|
gngoncalves/cursoemvideo_python_pt1
|
/desafio18.py
| 510
| 4.1875
| 4
|
from math import sin, cos, tan, radians
num = int(input('Insira um ângulo: '))
print('Valores em Rad:')
print('O seno de {}º é {:.2f}.'.format(num,sin(num)))
print('O cosseno de {}º é {:.2f}.'.format(num,cos(num)))
print('A tangente de {}º é {:.2f}.\n'.format(num,tan(num)))
print('Valores em Deg:')
print('O seno de {}º é {:.2f}.'.format(num,sin(radians(num))))
print('O cosseno de {}º é {:.2f}.'.format(num,cos(radians(num))))
print('A tangente de {}º é {:.2f}.'.format(num,tan(radians(num))))
| false
|
f49b75b94eeceac8906b6f812c706f31439e8240
|
gngoncalves/cursoemvideo_python_pt1
|
/desafio09.py
| 616
| 4.125
| 4
|
num = int(input('Insira um número inteiro: '))
n1 = num*1
n2 = num*2
n3 = num*3
n4 = num*4
n5 = num*5
n6 = num*6
n7 = num*7
n8 = num*8
n9 = num*9
n10 = num*10
print('Tabuada de {0}:'.format(num))
print('-'*12)
print('{} x 1 = {:2}'.format(num,n1))
print('{} x 2 = {:2}'.format(num,n2))
print('{} x 3 = {:2}'.format(num,n3))
print('{} x 4 = {:2}'.format(num,n4))
print('{} x 5 = {:2}'.format(num,n5))
print('{} x 6 = {:2}'.format(num,n6))
print('{} x 7 = {:2}'.format(num,n7))
print('{} x 8 = {:2}'.format(num,n8))
print('{} x 9 = {:2}'.format(num,n9))
print('{} x 10 = {:2}'.format(num,n10))
print('-'*12)
| false
|
c64c542b57107c06de2ce0751075a81fcb195b61
|
DmitriiIlin/Merge_Sort
|
/Merge_Sort.py
| 1,028
| 4.25
| 4
|
def Merge (left,right,merged):
#Ф-ция объединения и сравнения элементов массивов
left_cursor,right_cursor=0,0
while left_cursor<len(left) and right_cursor<len(right):
if left[left_cursor]<=right[right_cursor]:
merged[left_cursor+right_cursor]=left[left_cursor]
left_cursor+=1
else:
merged[left_cursor+right_cursor]=right[right_cursor]
right_cursor+=1
for left_cursor in range(left_cursor,len(left)):
merged[left_cursor+right_cursor]=left[left_cursor]
for right_cursor in range(right_cursor,len(right)):
merged[left_cursor+right_cursor]=right[right_cursor]
return merged
def MergeSort(array):
#Основная рекурсивная функция
if len(array)<=1:
return array
mid=len(array)//2
left,right=MergeSort(array[:mid]),MergeSort(array[mid:])
return Merge(left,right,array.copy())
"""
a=[2,45,1,4,66,34]
print(MergeSort(a))
print(a)
"""
| true
|
1605bc14384fc7d8f74a0af5f3eb1b03f23b1cd5
|
Oussema3/Python-Programming
|
/encryp1.py
| 343
| 4.28125
| 4
|
line=input("enter the string to be encrypted : ")
num=int(input("how many letters you want to shift : "))
while num > 26:
num = num -26
empty=""
for char in line:
if char.isalpha() is True:
empty=chr(ord(char)+num)
print(empty, end = "")
else:
empty=char
print(empty,end="")
| true
|
aa3efd739891956cf40b7d50c8e4b8211039eccd
|
Oussema3/Python-Programming
|
/conditions2.py
| 417
| 4.1875
| 4
|
#if elif
age = input("please enter your age :")
age = int(age)
if age > 100:
print("no such age haha")
exit
else:
if age <= 13:
print("you are a kid")
elif age >13 and age < 18:
print("You are a teenager")
elif age >= 18 and age < 27:
print("You are young enough")
elif age >= 27 and age < 50:
print("you are adult")
else:
print("you are old ")
| false
|
162acf35104d849e124d88a07e13fbdbc58e261b
|
stevewyl/chunk_segmentor
|
/chunk_segmentor/trie.py
| 2,508
| 4.15625
| 4
|
"""Trie树结构"""
class TrieNode(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.data = {}
self.is_word = False
class Trie(object):
def __init__(self):
self.root = TrieNode()
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: void
"""
node = self.root
for letter in word:
child = node.data.get(letter)
if not child:
node.data[letter] = TrieNode()
node = node.data[letter]
node.is_word = True
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
node = self.root
for letter in word:
node = node.data.get(letter)
if not node:
return False
return node.is_word # 判断单词是否是完整的存在在trie树中
def starts_with(self, prefix):
"""
Returns if there is any word in the trie
that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
node = self.root
for letter in prefix:
node = node.data.get(letter)
if not node:
return False
return True
def get_start(self, prefix):
"""
Returns words started with prefix
:param prefix:
:return: words (list)
"""
def _get_key(pre, pre_node):
words_list = []
if pre_node.is_word:
words_list.append(pre)
for x in pre_node.data.keys():
words_list.extend(_get_key(pre + str(x), pre_node.data.get(x)))
return words_list
words = []
if not self.starts_with(prefix):
return words
if self.search(prefix):
words.append(prefix)
return words
node = self.root
for letter in prefix:
node = node.data.get(letter)
return _get_key(prefix, node)
if __name__ == '__main__':
tree = Trie()
tree.insert('深度学习')
tree.insert('深度神经网络')
tree.insert('深度网络')
tree.insert('机器学习')
tree.insert('机器学习模型')
print(tree.search('深度学习'))
print(tree.search('机器学习模型'))
print(tree.get_start('深度'))
print(tree.get_start('深度网'))
| true
|
eb1ba8ee65ab19dad296f9793e0a0f6ba6230100
|
LeilaBagaco/DataCamp_Courses
|
/Supervised Machine Learning with scikit-learn/Chapter_1/1-k-nearest-neighbors-fit.py
| 2,163
| 4.28125
| 4
|
# ********** k-Nearest Neighbors: Fit **********
# Having explored the Congressional voting records dataset, it is time now to build your first classifier.
# In this exercise, you will fit a k-Nearest Neighbors classifier to the voting dataset, which has once again been pre-loaded for you into a DataFrame df.
# In the video, Hugo discussed the importance of ensuring your data adheres to the format required by the scikit-learn API.
# The features need to be in an array where each column is a feature and each row a different observation or data point - in this case, a Congressman's voting record.
# The target needs to be a single column with the same number of observations as the feature data. We have done this for you in this exercise.
# Notice we named the feature array X and response variable y: This is in accordance with the common scikit-learn practice.
# Your job is to create an instance of a k-NN classifier with 6 neighbors (by specifying the n_neighbors parameter) and then fit it to the data.
# The data has been pre-loaded into a DataFrame called df.
# ********** Exercise Instructions **********
# 1 - Import KNeighborsClassifier from sklearn.neighbors.
# 2 - Create arrays X and y for the features and the target variable. Here this has been done for you.
# Note the use of .drop() to drop the target variable 'party' from the feature array X as well as the use of the .values attribute to ensure X and y are NumPy arrays.
# Without using .values, X and y are a DataFrame and Series respectively; the scikit-learn API will accept them in this form also as long as they are of the right shape.
# 3 - Instantiate a KNeighborsClassifier called knn with 6 neighbors by specifying the n_neighbors parameter.
# ********** Script **********
# Import KNeighborsClassifier from sklearn.neighbors
from sklearn.neighbors import KNeighborsClassifier
# Create arrays for the features and the response variable
y = df['party'].values
X = df.drop('party', axis=1).values
# Create a k-NN classifier with 6 neighbors
knn = KNeighborsClassifier(n_neighbors=6)
# Fit the classifier to the data
knn.fit(X, y)
| true
|
160fdeed8bd2c5b06b68270bad80a238962bcb67
|
Arthyom/PythonX-s
|
/metodos.py
| 867
| 4.25
| 4
|
#### revizando los metodos de las structuras principales
# diccionarios
D = {1:"alfredo", 2:"aldo", 3:"alberto",4:"angel"}
print D.has_key(9)
print D.items()
print D.keys()
##print D.pop(1)
#lista = [1,2]
#print D.pop(1[0,1])
print D.values()
print D
# cadenas
cadena = "esta es una cadena de prueba esta cadena es una prueba"
print cadena.count('esta')
print cadena.find('una')
print cadena.partition(',')
print cadena.replace('e', 'E')
print cadena
print cadena.split(' ')
# listas
lst = [1,2,3,4,5,6,7,8]
print lst.append(1)
print lst
print lst.count(1)
print lst.index(4)
print lst.insert(3,12)
print lst
print lst.pop(3)
print lst.pop()
print lst.pop()
print lst.pop()
print lst
it = [1,'3',1,"cadena"]
print lst.extend(it)
#lst.append(1,'3',1,"cadena")
lst.remove("cadena")
print lst
lst.reverse()
print lst
lst.sort(reverse=True)
print lst
| false
|
2e98af33d4218cbf5c05240826e5916e19fb931e
|
Rainlv/LearnCodeRepo
|
/Pycode/Crawler_L/threadingLib/demo1.py
| 949
| 4.15625
| 4
|
# 多线程使用
import time
import threading
def coding():
for x in range(3):
print('正在写代码{}'.format(threading.current_thread())) # 当前线程名字
time.sleep(1)
def drawing(n):
for x in range(n):
print('正在画画{}'.format(threading.current_thread()))
time.sleep(1)
if __name__ == "__main__":
t1 = threading.Thread(target=coding) # 传入的函数不含(),是coding不是coding()
t2 = threading.Thread(target=drawing,name='drawingThread',args=(3,))
# name参数给线程命名,arg=()参数是在函数需要传参时用的
t1.start()
t2.start()
print(threading.enumerate()) # 查看当前所有的线程
t1.join() # 插队,在主线程前,先运行t1、t2线程,保证先运行完t1和t2再进行下面的print
t2.join()
# 这是主线程
print(threading.enumerate()) # 查看当前所有的线程
| false
|
39d5510129b23fc19a86740a018f61f19638570c
|
duchamvi/lfsrPredictor
|
/utils.py
| 599
| 4.28125
| 4
|
def bitToInt(bits):
"""Converts a list of bits into an integer"""
n = 0
for i in range (len(bits)):
n+= bits[i]*(2**i)
return n
def intToBits(n, length):
"""Converts an integer into a list of bits"""
bits = []
for i in range(length):
bits.append(n%2)
n = n//2
return bits
def stringToInt(str_input):
"""Checks that the input string is an integer then converts it"""
try:
int_input = int(str_input)
except:
print("That's not a valid input, please enter an integer next time")
exit(0)
return int_input
| true
|
04320d7cad5a0aff770a50170feb284ac231117d
|
Lukasz-MI/Knowledge
|
/Basics/02 Operators/math operators.py
| 718
| 4.25
| 4
|
# math operators
a = 12
b = 7
result = a + b; print(result)
result = a - b; print(result)
result = a * b; print(result)
result = a / b; print(result)
result = a % b; print(result)
result = a % 6; print(result)
result = a ** 3; print(result) # 12*12*12
result = a // b; print(result)
#assignment operators
a = 12
a += 1 # a = a +1
print(a)
a-= 1
print(a)
a*= 3
print(a)
a/= 4
print(a)
a%= 4
print(a)
a**= 7
print(a)
a+= 8
print(a)
a = int(a)
print(a)
a//= 4
print(a)
# comparison operators
b = 10 == 9 ; print(b) # False
print (10 != 8) # True - 10 does not equal 8
print (9 >= 9) # True
print (2<2) # False
print (17 < 10) # False
if 10 >5:
print("Yay!")
c= 14
if c > a:
print ("damn!")
| false
|
8e0148c31c798685c627b54d2d3fe90df4553443
|
Lukasz-MI/Knowledge
|
/Basics/01 Data types/06 type - tuple.py
| 907
| 4.28125
| 4
|
data = tuple(("engine", "breaks", "clutch", "radiator" ))
print (data)
# data [1] = "steering wheel" # cannot be executed as tuple does not support item assignment
story = ("a man in love", "truth revealed", "choice")
scene = ("new apartment", "medium-sized city", "autumn")
book = story + scene + ("length",) # Tuple combined
print (book)
print(len(book))
print(type(book)) # <class 'tuple'>
emptyTuple = ()
print(emptyTuple)
print(type(emptyTuple)) # <class 'tuple'>
print (book [-1])
print (book [len(book) -1])
print (book [3:])
print(book[::2])
cars = (("KIA", "Hyundai", "Mazda") , ("bmw", "mercedes", "Audi"))
print(cars)
print(cars[0][0]) # first tuple, first value - KIA
if "Mazda" in cars[0]:
print ("Yupi!")
# del cars [0] - single element deletion not allowed
del cars
# print(cars) - whole tuple deleted - NameError: name 'cars' is not defined
tuplex3 = book * 3
print(tuplex3)
| true
|
164fcb27549ae14c058c7eaf3b6c47b58d198e6d
|
Dan-krm/interesting-problems
|
/gamblersRuin.py
| 2,478
| 4.34375
| 4
|
# The Gambler's Ruin
# A gambler, starting with a given stake (some amount of money), and a goal
# (a greater amount of money), repeatedly bets on a game that has a win probability
# The game pays 1 unit for a win, and costs 1 unit for a loss.
# The gambler will either reach the goal, or run out of money.
# What is the probability that the gambler will reach the goal?
# How many bets does it take, on average, to reach the goal or fall to ruin?
import random as random
import time as time
stake = 10 # Starting quantity of currency units
goal = 100 # Goal to reach in currency units
n_trials = 10000 # Number of trials to run
win_prob = 0.5 # Probability of winning an individual game
def gamble(cash, target_goal, win_probability):
"""
A single trial of a gambler playing games until they reach their goal or run out of money.
cash: the gambler's initial amount of currency units
goal: the number of currency units to reach to be considered a win
win_prob: the likelihood of winning a single game
return: a tuple (outcome, bets):
- outcome: the outcome of the trial (1 for success, 0 for failure)
- bets: number of bets placed
"""
# play games until the goal is reached or no more currency units remain
bets = 0 # number of bets placed
while 0 < cash < target_goal:
bets += 1
if random.random() < win_probability:
cash += 1
else:
cash -= 1
# return tuple of trial outcome, number of bets placed
if cash == target_goal:
return 1, bets
else:
return 0, bets
def display_gamble():
print("\nQuestion 2: Gamblers Ruin\n")
# run a number of trials while tracking trial wins & bet counts
bets = 0 # total bets made across all games from all trials
wins = 0 # total trials won
start = time.time() # time when we started the simulation
for t in range(n_trials):
w, b = gamble(stake, goal, win_prob)
wins += w
bets += b
end = time.time() # time when we stopped the simulation
duration = end - start
# display statistics of the trials
print('Stake:', stake)
print('Goal:', goal)
print(str(100 * wins / n_trials) + '% were wins')
print('Average number of bets made:', str(bets / n_trials))
print('Number of trials:', n_trials)
print('The simulation took:', duration, 'seconds (about', n_trials/duration, 'trials per second)')
| true
|
8babc659615885331c025a366d21e21dd701ee2c
|
Ckk3/functional-programming
|
/imperative.py
| 1,583
| 4.46875
| 4
|
def get_names(peoples_list):
'''
Function to get all names in a list with dictionaries
:param peoples_list: list with peoples data
:return: list with all names
'''
for people in peoples_list:
names_list.append(people['name'])
return names_list
def search_obese(peoples_list):
'''
Function to get people with BMI higher than 30 in as list with dictionaries
:param peoples_list: list with peoples data
:return: list with obese people
'''
for people in peoples_list:
if people['bmi'] >= 30:
people_with_obesity.append(people)
return people_with_obesity
peoples = [{'name': 'Joao', 'bmi': 27},
{'name': 'Cleiton', 'bmi': 21},
{'name': 'Julia', 'bmi': 16},
{'name': 'Carlos', 'bmi': 43},
{'name': 'Daniela', 'bmi': 31}
]
#Geting names
names_list = []
names_list = get_names(peoples_list=peoples)
other_names_list = get_names(peoples_list=peoples)
print(f'Names: {names_list}')
print(f'Other names: {other_names_list}')
#Geting people with obesity
people_with_obesity = []
people_with_obesity = search_obese(peoples_list=peoples)
other_people_with_obesity = search_obese(peoples_list=peoples)
print(f'Peoples with obesity: {people_with_obesity}')
print(f'Other peoples with obesity: {other_people_with_obesity}')
#Geting higher BMI
bmi_list = []
for people in peoples:
if people['bmi'] >= 30:
bmi_list.append(int(people['bmi']))
higher_bmi = 0
for bmi in bmi_list:
if higher_bmi < bmi:
higher_bmi = bmi
print(f'Higher BMI: {higher_bmi}')
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.