blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
bbd26c32ec4a10fc6d4d480461ef6bee10529e21 | alexkryu4kov/DreamJob | /src/app/models/profile/unknown/find_course.py | 185 | 3.578125 | 4 | def find_course(courses: list, skill: str) -> list:
return [{
'url': course['url'],
'name': course['name'],
} for course in courses if course['skill'] == skill]
|
a516efeb3427e86be2c8bf8d3920b638e4324349 | Lusarom/progAvanzada | /ejercicio14.py | 224 | 3.9375 | 4 | inchft = 12
cmin = 2.54
altura = float(input('Inserta tu altura:'))
feet = int(input('Numero en ft:'))
inch = int(input('Numero en inch:'))
cm = (feet * inchft + inch) * cmin
print('Tu altura en centimetros es:', cm)
|
60320d5057c442b10d5c2551d3b1cf8a834681f1 | AlexandraFil/Geekbrains_2.0 | /python_alg/lesson_1/lesson_1_4.py | 684 | 4.09375 | 4 | '''4. Пользователь вводит две буквы. Определить, на каких местах алфавита они стоят, и сколько между ними находится букв.'''
character_1 = input('Введите букву: ')
character_2 = input('Введите вторую букву: ')
ord_1 = ord(character_1.lower()) - 96
ord_2 = ord(character_2.lower()) - 96
if ord_1 != ord_2:
between = abs(ord_1 - ord_2) - 1
else:
between = 0
print(f'Буква {character_1} стоит на {ord_1} месте, буква {character_2} стоит на {ord_2} месте.\nМежду ними находится {between} букв.') |
10b81c13ef5e7440f94d7cbf22b005e663ae76a3 | AnneNamuli/python-code-snippets | /my_sum.py | 137 | 4 | 4 | def my_sum(x, y):
return x + y
x = input("Enter number: ")
y = input("Enter number: ")
print "The sum of X and y is %d" % my_sum(x, y) |
9285d41d2d21168a974b9c0db0d2304e28d2b936 | seanlopez/python-new-test | /第三周/源码/names.py | 1,099 | 3.796875 | 4 | __author__ = "Alex Li"
import copy
#names = "ZhangYang Guyun Xiangpeng XuLiangChen"
'''names = ["4ZhangYang", "#!Guyun","xXiangPeng",["alex","jack"],"ChenRonghua","XuLiangchen"]
print(names[0:-1:2])
print(names[::2])
print(names[:])
#range(1,10,2)
for i in names:
print(i)
name2 = copy.deepcopy(names)
print(names)
print(name2)
names[2] = "向鹏"
names[3][0] ="ALEXANDER"
print(names)
print(name2)
names.append("LeiHaidong")
names.insert(1,"ChenRonghua")
names.insert(3,"Xinzhiyu")
#names[2] ="XieDi"
#print(names[0],names[2])
#print(names[1:3]) #切片
#print(names[3]) #切片
#print(names[-2:]) #切片
#print(names[0:3]) #切片
#print(names[:3]) #切片
#delete
#names.remove("ChenRonghua")
#del names[1] =names.pop(1)
#names.pop(1)
print(names)
#print(names.index("XieDi"))
#print( names[names.index("XieDi")] )
#print(names.count("ChenRonghua"))
#names.clear()
#names.reverse()
#names.sort()
print(names)
names2 = [1,2,3,4]
#names
names.extend(names2)
#del names2
print(names,names2)'''
a =[1,2,3]
b = a
a[1] =555
b = [1,555,3] |
29899f8444c9b71edcf29370204923af672e548f | WestComputing/PyProblemsJS | /patterns/sort.py | 1,172 | 3.8125 | 4 | import random
m = int(input("How many numbers? ")) + 1
reference_numbers = []
for n in range(1, m):
reference_numbers.append(n)
random.shuffle(reference_numbers)
numbers = reference_numbers[:]
print(numbers, end=3 * "\n")
length = len(numbers)
width = len(str(m))
for i in range(length // 2):
j = length - i - 1
print("%*d <->" % (width, numbers[i]), end=" ")
numbers[i], numbers[j] = numbers[j], numbers[i]
print("%*d" % (width, numbers[i]))
print(2 * "\n", numbers, sep="")
checks = swaps = 0
swapped = True
while swapped:
swapped = False
for i in range(length - 1):
j = i + 1
checks += 1
if numbers[i] > numbers[j]:
numbers[i], numbers[j] = numbers[j], numbers[i]
swapped = True
swaps += 1
print("\nWhile:\nChecks: ", checks, "\nSwaps: ", swaps, sep="")
numbers = reference_numbers[:]
checks = swaps = 0
for i in range(length - 1):
for j in range(i + 1, length):
checks += 1
if numbers[i] > numbers[j]:
numbers[i], numbers[j] = numbers[j], numbers[i]
swaps += 1
print("\nNested For:\nChecks: ", checks, "\nSwaps: ", swaps, sep="")
|
bd5bd6bf77ba51db2e9df5ef1585b64f878dc3a1 | nekapoor7/Python-and-Django | /Python/ListPrograms/Smallest.py | 181 | 3.890625 | 4 | """Write a Python program to get the smallest number from a list."""
list1 = list(input().split())
print(list1)
small = min(int(x) for x in list1 if x == min(list1))
print(small)
|
194dab1e9eb08c13ff1c139d9ff4a9eefa590300 | dancollins/rosalind | /protein.py | 1,939 | 3.5 | 4 | '''
The 20 commonly occurring amino acids are abbreviated by using 20 letters from
the English alphabet (all letters except for B, J, O, U, X, and Z). Protein
strings are constructed from these 20 symbols. Henceforth, the term genetic
string will incorporate protein strings along with DNA strings and RNA strings.
The RNA codon table dictates the details regarding the encoding of specific
codons into the amino acid alphabet.
Given: An RNA string s corresponding to a strand of mRNA (of length at most 10
kbp).
Return: The protein string encoded by s.
'''
import fileinput
import re
# Our codon table is just taken directly from Rosalind.
codon_table ='''
UUU F CUU L AUU I GUU V
UUC F CUC L AUC I GUC V
UUA L CUA L AUA I GUA V
UUG L CUG L AUG M GUG V
UCU S CCU P ACU T GCU A
UCC S CCC P ACC T GCC A
UCA S CCA P ACA T GCA A
UCG S CCG P ACG T GCG A
UAU Y CAU H AAU N GAU D
UAC Y CAC H AAC N GAC D
UAA Stop CAA Q AAA K GAA E
UAG Stop CAG Q AAG K GAG E
UGU C CGU R AGU S GGU G
UGC C CGC R AGC S GGC G
UGA Stop CGA R AGA R GGA G
UGG W CGG R AGG R GGG G
'''
# Reformat our table for convenient translation
codon_table = codon_table.rstrip().lstrip().replace('\n', ' ')
codon_table = re.split(' *', codon_table)
codon_table = {k: v for k, v in zip(codon_table[0::2], codon_table[1::2])}
def create_protein(rna_string):
codons = [rna_string[i:i+3] for i in range(0, len(rna_string), 3)]
protein = [codon_table[x] for x in codons]
# We should stop translating at a stop codon, so we'll break the list there.
protein = protein[:protein.index('Stop')]
return ''.join(protein)
if __name__ == '__main__':
for line in fileinput.input():
print(create_protein(line.rstrip()))
|
db925f0d734a86aca445d1159d7ffd1d9f85e751 | mehulchopradev/keyur-python | /com/xyz/college/college_user.py | 679 | 3.640625 | 4 |
# Super class / Parent class / Base class
# every class in python implicilty inherits from a built in class in python called as `object`
class CollegeUser(object):
def __init__(self, name, gender):
# self - Student object, Professor object, any sub class object reference
self.name = name
self.gender = gender
def get_details(self):
# self - Student object, Professor object, any sub class object reference
# pass # if no return statement, python function returns a value None
return 'Name: {0}\nGender: {1}'.format(self.name, self.gender)
def __str__(self):
return '{0}|{1}'.format(self.name, self.gender) |
3f221208cedd69d82c8e0774ac14d60b7a994820 | enrib82/Pr-ctica-5.-Ejercicios-while-y-listas.- | /ej. 8-5.py | 770 | 4.25 | 4 | # -*- coding: cp1252 -*-
"""Enrique Ibáñez Orero - 1º DAW - Practica 5 - Ejercicio 8 - Pràctica 5.
Escribe un programa que te pida primero un número y luego te pida números hasta que la suma de los números introducidos coincida con el número inicial. El programa termina escribiendo la lista de números."""
print 'Escriba el numero limite:'
nNlimite=int(input())
print 'Escriba otro numero, menor que %s:'% str(nNlimite)
nN=int(input())
while nN > nNlimite:
print 'El numero es demasiado grande, intentelo de nuevo:'
nN=int(input())
lLista=[]
suma=nN
while suma<=nNlimite:
lLista+=[nN]
print 'Escriba otro numero:'
nN=int(input())
suma+=nN
print 'La suma de estos numeros, %s, es menor o igual a %s' % (str(lLista), str(nNlimite))
|
b9ec358e81fe19566ceffbcededa720f34afad37 | jonatanjmissora/SQLITE3_PERSONAS | /database.py | 2,258 | 3.765625 | 4 | import sqlite3
# crear una tabla
def crear_tabla():
conn = sqlite3.connect("personas.db")
c = conn.cursor()
c.execute("""CREATE TABLE listado (
nombre text,
apellido text,
edad text)
""")
conn.commit()
conn.close()
def insert_one(nombre, apellido, edad):
conn = sqlite3.connect("personas.db")
c = conn.cursor()
c.execute("INSERT INTO listado VALUES (?,?,?)", (nombre, apellido, edad))
conn.commit()
conn.close()
def insert_one_in(rowid, row):
conn = sqlite3.connect("personas.db")
c = conn.cursor()
c.execute("INSERT INTO listado VALUES (?,?,?) ", (row))
conn.commit()
conn.close()
def insert_algunos(lista):
conn = sqlite3.connect("personas.db")
c = conn.cursor()
c.executemany("INSERT INTO listado VALUES (?,?,?)", lista)
conn.commit()
conn.close()
def show_all():
conn = sqlite3.connect("personas.db")
c = conn.cursor()
c.execute("SELECT rowid, * FROM listado")
[print(row) for row in c.fetchall()]
conn.commit()
conn.close()
def borrar_id(id):
conn = sqlite3.connect("personas.db")
c = conn.cursor()
c.execute("DELETE FROM listado WHERE rowid=?", (id, ))
conn.commit()
conn.close()
def borrar_apellido(apell):
conn = sqlite3.connect("personas.db")
c = conn.cursor()
c.execute("DELETE FROM listado WHERE apellido=?", (apell, ))
conn.commit()
conn.close()
def borrar_datos():
conn = sqlite3.connect("personas.db")
c = conn.cursor()
c.execute("DELETE FROM listado")
conn.commit()
conn.close()
def borrar_tabla():
conn = sqlite3.connect("personas.db")
c = conn.cursor()
c.execute("DROP TABLE listado")
conn.commit()
conn.close()
def buscar_apellido(apell):
conn = sqlite3.connect("personas.db")
c = conn.cursor()
c.execute("SELECT rowid, * FROM listado WHERE apellido=?", (apell, ))
[print(row) for row in c.fetchall()]
conn.commit()
conn.close()
def cambiar_nombre(viejo, nuevo):
conn = sqlite3.connect("personas.db")
c = conn.cursor()
c.execute("UPDATE listado SET nombre=? WHERE nombre=?", (nuevo, viejo, ))
[print(row) for row in c.fetchall()]
conn.commit()
conn.close()
def update_renglon(data):
conn = sqlite3.connect("personas.db")
c = conn.cursor()
c.execute("UPDATE listado SET nombre=?, apellido=?, edad=? WHERE rowid=?", data)
conn.commit()
conn.close()
|
0a943c0695ead713ae4af9a6837b78ad04a3af69 | KeranSiva/100-days-of-code | /Chapter-08-Files/os_code.py | 832 | 3.5625 | 4 | import os
import shelve
# Wrangling with path
os.path.join() # Joins String into system Path
os.getcwd() # Current Working Directory
os.chdir(path="") # Change folder to path
os.makedirs() # Create new folders
os.path.abspath('.') # Return absolute path
os.path.basename() # Returns filename
os.path.dirname() #Returns dir name
os.listdir() # Return list of files in the folder
os.path.exists() # Check if path exists
os.path.isdir() # Check if dir
# Wrangling with Files
hello_file = open(path=) # Opens File
hello_file.read() # Read File as single big string
hello_file.readlines() # Read file as lines
hello_file.readline() # Read file line by line
hello_file.write() # Write to file
# Saving Variables
shel_file = shelve.open('file_name')
shel_file = hello_file # Assining saves automatically to file
shel_file.close() |
58ba8d8523f5313235cb99b770d1cdb8b371d204 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2897/60643/267678.py | 526 | 3.5 | 4 | words=input()
digits=[]
for word in words:
init=int(0)#规范每个都是32的长度
for i in range(len(word)):
alp=word[i]
temp=1<<(ord(alp)-ord('a'))#1左移相应位数 ord是char转成ASCII数字:97 chr是将ASCII转成char :a
init=init|temp#做或运算
digits.append(init)
maxLen=0
for i in range(len(words)-1):
for j in range(i+1,len(words)):
if digits[i]&digits[j]==0:
temp=len(words[i])*len(words[j])
maxLen=max(maxLen,temp)
print(maxLen) |
b7174cd98ca095b5454f7b726eb27467f9fd521f | chjfth/pyutils | /pycode/cheese/incremental_rsync/fwrite_random.py | 594 | 3.59375 | 4 | #!/usr/bin/env python3
# coding: utf-8
import os, sys
import random
def fwrite_random(filepath, offset, len):
"""Write random content to filepath, at offset, len bytes."""
fh = None
if os.path.isfile(filepath):
fh = open(filepath, "rb+")
else:
fh = open(filepath, "wb")
buf = bytearray(len)
for i in range(len):
buf[i] = random.randint(0, 255)
fh.seek(offset, os.SEEK_SET)
fh.write(buf)
fh.close()
if __name__=='__main__':
if len(sys.argv)==1:
print("Usage: fwrite_random <file> <offset> <len>")
exit(4)
fwrite_random(sys.argv[1], int(sys.argv[2]), int(sys.argv[3]))
|
16038f4f1485c216cd8e967db3769a513e04dd45 | janenicholson1/Python | /escape1.py | 148 | 3.84375 | 4 | No1 = input ("Please enter first no: ")
No2 = input ("Please enter second no: ")
No3 = int (No1)+int(No2)
print ("%s + %s = %d" %(No1,No2,No3)) |
6996b452bfa960e051217c71d59d9f9fa5058300 | Mosesvalei/Password-Locker | /userdata_test.py | 2,568 | 3.765625 | 4 | from userdata import UserData
import unittest,pyperclip
class TestUserData(unittest.TestCase):
'''
This is a test class that tests cases for creating and authenticating user data
'''
def setUp(self):
'''
Function to set initial variables for testing
'''
self.new_userdata= UserData(1,1,"Yelp","adminpass")
def tearDown(self):
'''
tear down function does clean up after each test case
'''
UserData.users_list = []
def test_init(self):
'''
test_init test case to check if objects initialized properly
'''
self.assertEqual(self.new_userdata.user_identity,1)
self.assertEqual(self.new_userdata.data_identity,1)
self.assertEqual(self.new_userdata.account_name,"Yelp")
self.assertEqual(self.new_userdata.account_key,"adminpass")
def test_save_account(self):
'''
test_save_account test case to test if userdata object is saved into users_list
'''
self.new_userdata.save_account() #create and save new_cred
self.assertEqual(len(UserData.users_list),1)
def test_password_generator(self):
'''
test_password_generator test case to test if password has been generated and saved
'''
password_list = []
password = self.new_userdata.password_generator(2)
password_list.append(password)
self.assertEqual(len(password_list),1)
def test_data_exists(self):
'''
test_data_exists test case to test if the the function checks that the data exists
'''
self.new_userdata.save_account()
test_data = UserData(2,2,"Test","admintest")
test_data.save_account()
data_exists = UserData.data_exists(2)
self.assertTrue(data_exists)
def test_display_data(self):
'''
test_display_data test case used to test if the function displays the data
'''
self.new_userdata.save_account()
test_data = UserData(2,2,"Test","admintest")
test_data.save_account()
display_data = UserData.display_data(2,2)
self.assertEqual(test_data.account_name,display_data.account_name)
def test_copy_password(self):
'''
Test to confirm that we are copying the email address from a found contact
'''
self.new_userdata.save_account()
UserData.copy_password(1,1)
self.assertEqual(self.new_userdata.account_key,pyperclip.paste())
if __name__ == "__main__":
unittest.main()
|
48f5a38f4a662fba819406efa9c93317431a0bd2 | Andr-Malcev/SP | /Lab 3/3.1 Средний уровень.py | 160 | 3.65625 | 4 | import math
k = int(input('K: '))
Y = 0
for n in range(1, k+1):
Y = Y + ((-1)**(2*n))*((n**2-9)**2)/math.factorial(3*n)
print('Сумма: ', Y)
|
610686f94709b21e8813a38b08739039f566eecf | UriSeadia/Euler-Project | /src/036_double_base_palindromes.py | 841 | 3.78125 | 4 | # The decimal number, 585 = 1001001001 (binary), is palindromic in both bases.
#
# Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.
#
# (Please note that the palindromic number, in either base, may not include leading zeros.)
import time
def is_palindrome(number_as_string: str):
return number_as_string == number_as_string[::-1]
def get_number_as_binary_string(num: int):
return '{0:b}'.format(num)
def sum_of_double_base_palindromes():
result = 0
for num in range(1, 1000000):
if is_palindrome(str(num)) and is_palindrome(get_number_as_binary_string(num)):
result += num
return result
def main():
start = time.time()
print(sum_of_double_base_palindromes())
end = time.time()
print('Seconds: ' + (str(end - start)))
main()
|
c625fe8d9dbb26452325ae750b7319529ff15486 | agni-c/ds-algo-works | /leetcode/group_anagrams.py | 464 | 3.59375 | 4 | class Solution:
def sortString(self,str):
return ''.join(sorted(str))
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
dict = {}
res=[]
for str in strs:
ss = self.sortString(str)
if ss in dict:
dict[ss].append(str)
else:
dict[ss]=[str]
for li in dict:
res.append(dict[li])
return res |
4ed601b3604793534d97909e391218fa3cfad231 | raghav94603/265151_learnings | /dictionaryUnsolved02.py | 153 | 3.734375 | 4 | user_list =list(map(int, input().split()))
nested_dict = current = {}
for i in user_list:
current[i] = {}
current = current[i]
print(nested_dict) |
92102b82c32a216a971622d3dafb8b56a36cb7c3 | xiaojiang990209/leetcode | /solved/863_saw_answer.py | 1,336 | 3.734375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def distanceK(self, root, target, K):
"""
:type root: TreeNode
:type target: TreeNode
:type K: int
:rtype: List[int]
"""
def getParentMap(root, parents):
if root.left:
parents[root.left] = root
getParentMap(root.left, parents)
if root.right:
parents[root.right] = root
getParentMap(root.right, parents)
def dfs(node, parents, K, res, visited):
if node in visited:
return
visited.add(node)
if K == 0:
res.append(node.val)
return
if node.left != None:
dfs(node.left, parents, K-1, res, visited)
if node.right != None:
dfs(node.right, parents, K-1, res, visited)
if parents[node] != None:
dfs(parents[node], parents, K-1, res, visited)
parentMap = {}
parentMap[root] = None
getParentMap(root, parents)
res = []
visited = set()
dfs(target, parentMap, K, res, visited)
return res
|
e0040825128763b60f4ebabfe00601f52f418d3a | marcinszymura/python_kurs | /homework/classes/zad_extra.py | 2,250 | 3.875 | 4 | # Przykład
# użycia:
# >> > przytnij(
# data=[1, 2, 3, 4, 5, 6, 7],
# start=lambda x: x > 3,
# stop=lambda x: x == 6,
# )
#
# [4, 5, 6]
def przytnij(data: list, start: str, stop: str) -> list:
"""
Funkcja do przycinania listy
:param data: lista
:param start: poczatek listy
:param stop: koniec listy
:return:
"""
first = list(filter(start, data))
last = list(filter(stop, data))
return [a for a in first if a <= last[0]]
print(przytnij(
data=[1, 2, 3, 4, 5, 6, 7],
start=lambda x: x > 3,
stop=lambda x: x == 6))
print('*' * 50)
# Zaimplementuj zestaw dekoratorów otaczających zwracany przez funkcję napis tagami HTML (pogrubienie, podkreślenie, przekreślenie):
#
# Przykład użycia:
# @bold
# @italic
# def foo(arg):
# return f'To jest {arg}'
def bold(func):
"""
:param func:
:return:
"""
def add_bold(*args, **kwargs):
return '<b>' + func(*args, **kwargs) + '</b>'
return add_bold
def italic(func):
"""
:param func:
:return:
"""
def add_italic(*args, **kwargs):
return '<i>' + func(*args, **kwargs) + '</i>'
return add_italic
def underline(func):
"""
:param func:
:return:
"""
def add_underline(*args, **kwargs):
return '<u>' + func(*args, **kwargs) + '</u>'
return add_underline
@underline
@italic
@bold
def foo(arg: str) -> str:
"""
przykładowa funkcja
:param arg:
:return:
"""
return f'To jest {arg}'
print(foo('dekorator'))
print('*' * 50)
# Zaimplementuj dekorator wypisujący wywołanie danej funkcji (nazwa i argumenty) oraz czas jej wykonania.
#
# Przykład użycia:
# @log
# def foo(arg):
# return f'To jest {arg}'
import time
def log(func):
"""
funkcja do mierzenia czasu wykonani adanej dunkcji
:param func:
:return:
"""
def add_log(*args, **kwargs):
start = time.time()
func(*args, **kwargs)
stop = time.time()
return f'{func.__name__}: czas wykonania: {stop - start:.2f}'
return add_log
@log
def foo(arg: str) -> str:
"""
przykładowa funkcja
:param arg:
:return:
"""
return f'To jest {arg}'
print(foo('logowanie'))
|
7ac57c1a0e6baa7ff4f2f1548bc750c2bfa1c38f | liuwq168/entity_embeddings_categorical | /entity_embeddings/util/preprocessing_utils.py | 2,226 | 4.15625 | 4 | from typing import List, Tuple
import numpy as np
import pandas as pd
from sklearn import preprocessing
from sklearn.preprocessing import LabelEncoder
def series_to_list(series: pd.Series) -> List:
"""
This method is used to convert a given pd.Series object into a list
:param series: the list to be converted
:return: the list containing all the elements from the Series object
"""
list_cols = []
for item in series:
list_cols.append(item)
return list_cols
def sample(X: np.ndarray, y: np.ndarray, n: int) -> Tuple[np.ndarray, np.ndarray]:
num_row = X.shape[0]
indices = np.random.randint(num_row, size=n)
return X[indices, :], y[indices]
def get_X_y(df: pd.DataFrame, name_target: str) -> Tuple[List, List]:
"""
This method is used to gather the X (features) and y (targets) from a given dataframe based on a given
target name
:param df: the dataframe to be used as source
:param name_target: the name of the target variable
:return: the list of features and targets
"""
X_list = []
y_list = []
for index, record in df.iterrows():
fl = series_to_list(record.drop(name_target))
X_list.append(fl)
y_list.append(int(record[name_target]))
return X_list, y_list
def label_encode(data: List) -> [np.ndarray, List[LabelEncoder]]:
"""
This method is used to perform Label Encoding on a given list
:param data: the list containing the items to be encoded
:return: the encoded np.ndarray
"""
labels_encoded = []
data_encoded = np.array(data)
for i in range(data_encoded.shape[1]):
le = preprocessing.LabelEncoder()
le.fit(data_encoded[:, i])
labels_encoded.append(le)
data_encoded[:, i] = le.transform(data_encoded[:, i])
data_encoded = data_encoded.astype(int)
return data_encoded, labels_encoded
def transpose_to_list(X: np.ndarray) -> List[np.ndarray]:
"""
:param X: the ndarray to be used as source
:return: a list of nd.array containing the elements from the numpy array
"""
features_list = []
for index in range(X.shape[1]):
features_list.append(X[..., [index]])
return features_list
|
9d9dad095529054ba235a88cfd89de9555ba88f6 | marcuslind90/python-challenges | /ctci/16-8.py | 1,811 | 3.828125 | 4 | class Solution(object):
small = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven",
"Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
"Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen",
"Nineteen"]
teens = ["", "", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy",
"Eighty", "Ninety"]
large = ["", "Thousand", "Million", "Billion"]
hundred = "Hundred"
negative = "Negative"
def convert(self, num):
"""
Convert number from integer to english language.
E.g. 192 becomes One Hundred Ninety Two
"""
if num == 0:
return self.small[0]
elif num < 0:
return "%s %s" % (self.negative, self.convert(-1 * num))
words = []
# Keep track on how many thousands that have passed.
# E.g. Thousand, Million, Billion etc.
millenials = 0
while num > 0:
if num % 1000 != 0:
chunk = "%s %s" % (
self.convertChunk(num % 1000),
self.large[millenials]
)
words.insert(0, chunk)
num = num//1000
millenials += 1
return ' '.join(words)
def convertChunk(self, num):
words = []
if num >= 100:
words.append(self.small[num//100])
words.append(self.hundred)
num %= 100
if num >= 10 and num <= 19:
words.append(self.small[num])
elif num >= 20:
words.append(self.teens[num//10])
num %= 10
if num >= 1 and num <= 9:
words.append(self.small[num])
return ' '.join(words)
s = Solution()
print(s.convert(1921)) # Should print One Hundred Twenty Three
|
c4c3906ec9f6bb3f399ca9581e91c59795718500 | Ayyanchira/DMV_NC | /Question.py | 1,020 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 20 14:34:09 2018
@author: monic
"""
class Question:
def __init__(self, question, answer1, answer2, answer3, answer4, correct_answer):
self.question = question
self.answer1 = answer1
self.answer2 = answer2
self.answer3 = answer3
self.answer4 = answer4
self.correct_answer = correct_answer
def get_question(self):
return self.question
def get_correct_answer(self):
return self.correct_answer;
def get_answer_choices(self):
answer_choices = [];
answer_choices.append(self.answer1)
answer_choices.append(self.answer2)
answer_choices.append(self.answer3)
answer_choices.append(self.answer4)
return answer_choices;
'''
q = Question("question 1", "a1","a2","a3","a4",4)
print(q.get_answer_choices())
print(q.get_question())
print(q.get_correct_answer())
'''
|
03a845d78054e766e122e783f18edac59351246f | ProgramaTICas/Comunidad-Ada | /Tema POO/MainGeneral.py | 677 | 3.734375 | 4 | from Estudiante import *
from Curso import *
#Estudiantes
Estudiante1 = Estudiante("Crisly", 22,"2013")
Estudiante2 = Estudiante("Nathalie", 17,"2015")
Estudiante3 = Estudiante("Kembly", 20,"2016")
Estudiante4 = Estudiante("Laura", 28,"2017")
Estudiante5 = Estudiante("Carolina", 10,"2018")
print(Estudiante1.getNombre())
Materia1= Materia("Conceptos de orientacion a objetos")
Materia2= Materia("Recursividad")
Materia3= Materia("POO")
Curso1 = Curso("Introduccion","2017-IC",Materia3)
Curso2 = Curso("Taller","25-IC",Materia2)
#Agregando Cursos a un estudiante
Estudiante1.AgregarCurso(Curso1)
Estudiante2.AgregarCurso(Curso1)
Estudiante2.AgregarCurso(Curso2)
|
d0e8e7e7bd289b17476dc47844595fc96a810670 | benjaminwwong/elementary-combinarotics | /Mandelbrot.py | 236 | 3.734375 | 4 | def Mandelbrot():
c = complex(float(input("Re:")),float(input("Im:")))
li = []
z = complex(0,0)
while abs(z) < 2:
z = z^2 + c
if z in li:
break
li.append(z)
print(z)
|
e2d6bde2669d4e2e1d8b9cb1074004600f919e19 | joaopmo/TP2-ALGII | /src/chr_tsp.py | 2,274 | 3.546875 | 4 | import numpy as np
import networkx as nx
from networkx.algorithms.matching import max_weight_matching
from networkx.algorithms.euler import eulerian_circuit
# Esta função aparece na documentação do Networkx mas não funcionou na minha versão.
# Por isso simplesmente copiei a implementação da fonte:
# https://networkx.org/documentation/stable/_modules/networkx/algorithms/matching.html#min_weight_matching
def min_weight_matching(G, maxcardinality=False, weight="weight"):
if len(G.edges) == 0:
return max_weight_matching(G, maxcardinality, weight)
G_edges = G.edges(data=weight, default=1)
min_weight = min([w for _, _, w in G_edges])
InvG = nx.Graph()
edges = ((u, v, 1 / (1 + w - min_weight)) for u, v, w in G_edges)
InvG.add_weighted_edges_from(edges, weight=weight)
return max_weight_matching(InvG, maxcardinality, weight)
# TSP com algoritmo de Christofides
def chr_tsp(mtx, best_lst=None):
n = np.shape(mtx)[0]
# Cria o grafo e a minimum spanning tree associada
graph = nx.from_numpy_matrix(mtx)
mst = nx.minimum_spanning_tree(graph)
# Encontra os vértices com grau ímpar na mst
odd = []
for i in range(n):
if mst.degree[i] % 2 != 0:
odd.append(i)
# Encontra o matching mínimo no subgrafo formado pelos vértices de grau ímpar
match = min_weight_matching(graph.subgraph(odd))
# Cria um multigrafo com os vértices da mst + arestas do matching mínimo
multg = nx.MultiGraph()
multg.add_weighted_edges_from([(i, j, graph[i][j]['weight']) for i, j in match])
multg.add_weighted_edges_from(mst.edges.data('weight'))
# Encontra o ciclo euleriano no multigrafo e remove os vértices duplicados
# para obter um ciclo hamiltoniano
sol = []
eul = [u for u, v in eulerian_circuit(multg, source=0)]
[sol.append(x) for x in eul if x not in sol]
# Encontra o peso total na solução produzida
best = 0.0
sol.append(0)
for i, j in zip(sol, sol[1:]):
try:
best += graph[i][j]['weight']
except ValueError:
print(f'Size: {n}')
print(f'Node: ({i}, {j})')
print(ValueError)
if best_lst is not None:
best_lst.append(best)
return best, sol
|
74cfddcd6c2707e3d554b7e21dd2234f8cfaab41 | zizouvb/codewars | /6kyu/directions_reduction.py | 485 | 3.515625 | 4 | def dirReduc(arr):
i=0
while i<len(arr)-1:
if (arr[i]=="NORTH" and arr[i+1]=="SOUTH"):
del arr[i-1:i+1]
i=0
elif arr[i]=="SOUTH" and arr[i+1]=="NORTH":
del arr[i-1:i+1]
i=0
elif arr[i]=="WEST" and arr[i+1]=="EAST":
del arr[i-1:i+1]
i=0
elif arr[i]=="EAST" and arr[i+1]=="WEST":
del arr[i-1:i+1]
i=0
else:
i+=1
return arr
|
5afaffbdbc16dfb3b2147c3af480f4ae5dd4bd44 | hansewetz/gitrep2 | /src/python/tests/add_del_str_repr/test1.py | 512 | 4.0625 | 4 | #!/usr/bin/env python
# test class
class Person:
def __init__(self, fname, lname):
self._fname = fname
self._lname = lname
def __str__(self):
return 'fname: ' + self._fname + ', lname: ' + self._lname
def __repr__(self):
return repr((self._fname, self._lname))
def __del__(self):
print('deleting Person: '+self.__repr__())
# main test program
def main():
hans = Person('hans', 'ewetz')
print(repr(hans))
if __name__ == '__main__':
main()
|
0b9bb442bc389f15a345676a93ef9011008b4300 | HighHopes/codewars | /6kyu/Find the missing term in an Arithmetic Progression.py | 1,037 | 4.25 | 4 | """An Arithmetic Progression is defined as one in which there is a constant difference between the consecutive terms of a given series of numbers. You are provided with consecutive elements of an Arithmetic Progression. There is however one hitch: exactly one term from the original series is missing from the set of numbers which have been given to you. The rest of the given series is the same as the original AP. Find the missing term.
You have to write the function findMissing(list), list will always be at least 3 numbers. The missing term will never be the first or last one.
Example
find_missing([1, 3, 5, 9, 11]) == 7"""
def find_missing(sequence):
if sequence[1] - sequence[0] == sequence[2] - sequence[1]:
prog = sequence[1] - sequence[0]
else:
prog = sequence[3] - sequence[2]
fin = list(range(sequence[0], sequence[-1] + prog, prog))
result = [i for i in fin if i not in sequence]
return result
print(find_missing([1, 2, 3, 4, 6, 7, 8, 9])) # 5
print(find_missing([1, 3, 4, 5, 6, 7, 8, 9])) # 2
|
a9a4caf86458c65669d46b741ba4970ed112a613 | DeveloperJoseph/PYTHON---DE---0---10000 | /Modulo 1/ejercicio12.py | 3,944 | 4.46875 | 4 | #PYTHON CONDITIONS AND IF STATEMENTS
#Supports the usual logical conditiions from mathematics:
# Equals: a==b
# Not Equals: a!=b
# Less than: a<b
# Less than or equal to: a<=b
# Greater than: a>b
# Greater than or equal to: a>=b
#These conditios can be used in several ways, mos commonly in "if statements" and loops,
#An "if statements" is written by using the if keyword.
print("\n#>Loading 'PYTHON CONDITIONS AND IF STATEMENTS', please wait.......")
# IF #
#In this example, we use twi variables, a and b, wich are used as part of the if
#statement to test whetter b is greater than a. As a is 50, and b is 100, we know that
#100 is greater than 50, and so we print to screen that "b" is greater than "a".
print("\n#>Loading 'IF STATEMENT'.....")
print(">> First example if statement: ")
a = 50
b = 100
if b > a:
print("> Reply: B is greater tan A")
# ELIF #
#The elif keyword is pythons way of saying 'if the previous condition were not true, then try
#this condition'.
print("\n#>Loading 'ELIF STATEMENT'.....")
#In this examplea is equal to b, so the first codition is not true, but the elif condition is true,
#so we print to screen that "B AND A, ARE EQUALS".
print(">> Second example elif statement: ")
a = 33
b = 33
if b > a:
print("> Reply: B is greater than A")
elif b == a:
print("> Reply: B and A are equal")
# ELSE #
#The else keyword catches anything which isn't caught by the preceding conditions.
print("\n#>Loading 'ELSE STATEMENT'.....")
#In this example a is greater to b, so the first condition is not true,
#also the elif condition is not true, so we go to the else condition
#to screen that " A is greater than b".
print(">> Third example else statement: ")
a = 200
b = 33
if b > a:
print("> Reply: B is greater that A.")
elif a==b:
print("> Reply: A and B are equals.")
else:
print("> Reply: A is greater than B.")
#you can also have an else without the elif:
print("\n>> You can also have an else without the elif: ")
if b > a:
print("> Reply: B is greater that A.")
else:
print("> Reply: B is not greater that A.")
# SHORT HAND IF #
#If you have only one statement to execute, you can put it on the same line
# as the if statements.
print("\n#>Loading SHORT HAND IF.....")
print(">> Fourth example short if: ")
if a > b: print("> A is greater than B por : "+str(a-b)+" puntos.")
# SHORT HAND IF...ELSE
# If you have only statement to execute, one for if, and one for else, you
# can put it alll on the same line:
print("\n#>Loading SHORT HAND IF..ELSE...")
print(">> Fourth example short if-else: ")
print("> A greater") if a > b else print("> B greater")
#You can also have multiple else statemet on the same line:
print(">> Fifth example multiple else on the same line: ")
a = 69
b = 69
print("> A greated") if a > b else print("> A and B are equals") if a ==b else print("> B greated")
# AND KEYWORD LOGICAL #
# The and keyword is a logical operator, and is used to combine conditional statements:
print("\n#>Loading AND keyword...")
print(">> Sixth example AND keyword: ")
a = 100
b = 50
c = 200
if a>b and c>a:
print(">Both conditions are True")
print("\n#>Loading OR keyword...")
print(">> Seventh example OR keyword: ")
if a > b or a > c:
print("At least one of the condition are true")
#Remenber of yesterday
print("\n##Remenber all.....")
print("Loading software Count....")
#Dictionary x with values None
x = {"College":None,"State":None}
x["College"]="ACOUNTAS ASD"#Update value for Key name 'College'
x["State"]=1#Update value for Key name 'State'
#CONDITION IF, ELIF AND ELSE IN PYTHON
if x["College"] == "ACOUNTAS ASD" and x["State"]==0:
print(">Answer: Not very perfecT.....")#Output of condition if
elif x["College"] == "ACOUNTAS ASD" and x["State"]==1:
print(">Answer: Really Very perfect!!!")#Output of condition elif
else:
print(">Answer: Not perfecT.....")#Output of condition else
print("\n Thank you for attention...")
|
d3217a7cc89e29c4ee1cdd4a7f6e8e48eb7d917c | flametest/leetcode | /merge_sorted_array.py | 1,382 | 3.921875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-10-06 10:16:09
# @Author : Jun Jiang ([email protected])
# @Link : http://example.org
# @Version : $Id$
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
total = m + n
index1 = index2 = 0
for i in range(m, m+n):
nums1[i] = float("inf")
while nums2 and index1 < total and index2 < n:
if nums1[index1] >= nums2[index2]:
self.readjust(index1, nums1, total)
nums1[index1] = nums2[index2]
index1 += 1
index2 += 1
else:
index1 += 1
print nums1
def readjust(self, index, nums1, total):
i = total - 1
while i > index:
nums1[i] = nums1[i - 1]
i -= 1
if __name__ == '__main__':
s = Solution()
# print s.merge([1, 3, 5, 0, 0, 0], 3, [2, 4, 6] , 3)
# # print s.readjust(0, [1, 3, 5, 0, 0, 0], 6)
# print s.merge([2, 4, 6, 0, 0, 0], 3, [1, 3, 5], 3)
# print s.merge([8, 9, 10, 0, 0, 0], 3, [1, 3, 5], 3)
# print s.merge([0], 0, [1], 1)
print s.merge([1, 2, 3, 0, 0, 0], 3, [2, 5, 6], 3)
|
24bbe6af2a0161825ce0e2e2c6e6d8129d1e89d7 | cmccandless/stunning-pancake | /0/2/6.py | 804 | 3.578125 | 4 | #!/usr/bin/env python
# https://projecteuler.net/problem=26
import unittest
def sieve(limit=10000):
not_prime = set()
for x in range(2, limit):
if x in not_prime:
continue
yield x
not_prime.update(range(x + x, limit, x))
def mult_order(n):
x = 10
k = 1
while x % n != 1:
x *= 10
k += 1
return k
def answer(limit=1000):
primes = list(sieve(limit))[3:]
return max(
zip(map(mult_order, primes), primes)
)[1]
def run():
# print(answer(10))
# print(answer(100))
print(answer())
class Test26(unittest.TestCase):
def test_expected(self):
expected = 983
self.assertEqual(answer(), expected)
if __name__ == '__main__':
run()
|
9725d7165436c2f58156a7d4a812a604577de254 | Qu3d45/ZeroToMasterPython | /Advent_of_Code/day1_ex2.py | 2,796 | 4.28125 | 4 | # --- Day 1: The Tyranny of the Rocket Equation --- PART 2
# Fuel itself requires fuel just like a module - take its mass, divide by three,
# round down, and subtract 2. However, that fuel also requires fuel, and that
# fuel requires fuel, and so on. Any mass that would require negative fuel should
# instead be treated as if it requires zero fuel; the remaining mass, if any, is instead
# handled by wishing really hard, which has no mass and is outside the scope of this calculation.
# So, for each module mass, calculate its fuel and add it to the total.
# Then, treat the fuel amount you just calculated as the input mass and repeat the process,
# continuing until a fuel requirement is zero or negative. For example:
# A module of mass 14 requires 2 fuel. This fuel requires no further fuel
# (2 divided by 3 and rounded down is 0, which would call for a negative fuel),
# so the total fuel required is still just 2.
# At first, a module of mass 1969 requires 654 fuel. Then, this fuel requires 216
# more fuel (654 / 3 - 2). 216 then requires 70 more fuel, which requires 21 fuel,
# which requires 5 fuel, which requires no further fuel. So, the total fuel required
# for a module of mass 1969 is 654 + 216 + 70 + 21 + 5 = 966.
# The fuel required by a module of mass 100756 and its fuel is:
# 33583 + 11192 + 3728 + 1240 + 411 + 135 + 43 + 12 + 2 = 50346.
# What is the sum of the fuel requirements for all of the modules on your spacecraft
# when also taking into account the mass of the added fuel? (Calculate the fuel requirements
# for each module separately, then add them all up at the end.)
import math
def mass_reduction(mass):
return math.floor(mass / 3) - 2
def extra_fuel(item):
sum_item = []
while item > 0:
item = math.floor(item / 3) - 2
if item > 0:
sum_item.append(item)
return sum_item
# sum of nested list in Python with "flatten" also works with nested tuples and sets
def flatten(L):
'''Flattens nested lists or tuples with non-string items'''
for item in L:
try:
for i in flatten(item):
yield i
except TypeError:
yield item
# open file with inputs
my_list = open("day1_my_input.txt", "r")
my_mass = []
for line in my_list:
# append and convert string to int
my_mass.append(int(line))
# Test if values are ok
# print(list(map(mass_reduction, my_mass)))
# passing each number in the list to the function and creat a new list
fuel_module = list(map(mass_reduction, my_mass))
extra_fuel = list(map(extra_fuel, fuel_module))
print(sum(flatten(fuel_module)))
a = sum(flatten(fuel_module))
print(sum(flatten(extra_fuel)))
b = sum(flatten(extra_fuel))
# sum all the values
total_fuel = a + b
print(total_fuel)
# Result = 5218616
|
6772c89c166a3ca70077a1537a2862d679d90227 | viniielopes/uri | /iniciante/1164.py | 335 | 3.6875 | 4 | qtd = int(input())
for i in range(qtd):
n = int(input())
valor = 0
for j in range(n):
valor += j
if valor == n:
print("{} eh perfeito".format(n))
break
elif valor > n:
print("{} nao eh perfeito".format(n))
valor = n
break
if valor != n:
print("{} nao eh perfeito".format(n))
|
0b87f654fc99f7513e8ebb73bb02d65bad0cd8df | avinash-rath/pythonlab | /facprime.py | 282 | 4.03125 | 4 | nu = int(input('enter the number: '))
i=1
k=0
print('the factors are')
while i<=nu:
if nu%i==0:
print(i)
k=k+1
i=i+1
print('the number of factors are ',k)
if k==2:
print('the number is a prime number')
else:
print('the number is not a prime number')
|
773908b47bfe0590d18f79bfe3e0a3c60510982a | songyingxin/python-algorithm | /回溯法/leetcode/leetcode_22_parenthesesGenerates.py | 1,432 | 3.8125 | 4 | class Solution:
def generateParenthesis(self, n):
result = []
item = []
left_num = 0
right_num = 0
self.back_track(n*2, item, left_num, right_num, result)
return result
def back_track(self, n, item, left_num, right_num, result):
"""
left_num : 左括号数量
right_num: 右括号数量
"""
if n == 0:
if left_num == right_num:
result.append(''.join(item))
return
left_item = item.copy()
left_item.append('(')
self.back_track(n-1, left_item, left_num+1, right_num, result)
if left_num > right_num:
right_item = item.copy()
right_item.append(')')
self.back_track(n-1, right_item, left_num, right_num+1, result)
# 解法2
class Solution:
def generateParenthesis(self, n):
result = []
self.back_track("", n, n, result)
return result
def back_track(self, item, left_num, right_num, result):
if left_num == right_num == 0:
result.append(item)
return
if left_num > 0:
self.back_track(item+'(', left_num-1, right_num, result)
if left_num < right_num:
self.back_track(item + ')', left_num, right_num-1, result)
if __name__ == "__main__":
n = 3
print(Solution().generateParenthesis(n))
|
85a26045a4935e2f21754e65d8a954ffd2dddf49 | msps9341012/leetcode | /linkedlist/reorderList.py | 1,459 | 3.921875 | 4 | from linkedlist import SingleLinkedList,ListNode
'''
def reorderList(head):
if head==None:
return None
length=0
node=head
while node.next:
node=node.next
length=length+1
fast=head
slow=head
dummy=ListNode(0)
node=dummy
while length>0:
for i in range(length):
fast=fast.next
length=length-2
next_node=slow.next
slow.next=fast
node.next=slow
node=fast
slow=fast=next_node
if length<0:
node.next=None
else:
node.next=slow
node.next.next=None
return dummy.next
'''
def reorderList(head):
if not head:
return
slow, fast = head, head
while fast and fast.next:
slow=slow.next
fast=fast.next.next
#reverse
previous=None
tmp=slow.next
slow.next=None
while tmp:
next=tmp.next
tmp.next=previous
previous=tmp
tmp=next
print(previous.data)
node=head
while node and previous:
tmp=previous
tmp2=node.next
previous=previous.next
tmp.next=node.next
node.next=tmp
node=tmp2
l=SingleLinkedList()
l.add_list_item(4)
l.add_list_item(3)
l.add_list_item(2)
l.add_list_item(1)
l.printall()
reorderList(l.root)
l.printall()
'''
r=reorderList(l.root)
tmp=""
node=r
while node is not None:
tmp=tmp+str(node.data)+'->'
node=node.next
print(tmp[:-2])
'''
|
8cb6d0552df6cbd44d7462aa9a0fdc5b91f90474 | denny61302/100_Days_of_Code | /Day19 Racing Game/main.py | 1,371 | 4.1875 | 4 | from turtle import Turtle, Screen
import random
colors = ["red", "yellow", "green", "blue", "black", "purple"]
turtles = []
for _ in range(6):
new_turtle = Turtle(shape="turtle")
turtles.append(new_turtle)
is_race_on = False
screen = Screen()
screen.setup(width=500, height=400)
user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win?")
if user_bet:
is_race_on = True
index = 0
for turtle in turtles:
turtle.penup()
turtle.color(colors[index])
turtle.goto(x=-230, y=-170 + index * 50)
index += 1
while is_race_on:
for turtle in turtles:
if turtle.xcor() > 230:
is_race_on = False
winner_color = turtle.pencolor()
if winner_color == user_bet:
print("You win")
else:
print(f"You lose, the winner is {winner_color} turtle")
turtle.forward(random.randint(0, 10))
# def forward():
# turtle.forward(10)
#
#
# def backward():
# turtle.backward(10)
#
#
# def clock():
# turtle.right(5)
#
#
# def counter_clock():
# turtle.left(5)
#
#
# def reset():
# turtle.reset()
#
#
# screen.listen()
# screen.onkey(key="w", fun=forward)
# screen.onkey(key="s", fun=backward)
# screen.onkey(key="a", fun=counter_clock)
# screen.onkey(key="d", fun=clock)
# screen.onkey(key="c", fun=reset)
screen.exitonclick() |
6ddf9fda36be46b2b7ed586b4c86e25991da7263 | BolotZhusupekov07/sorting_algorithms_visualized | /test.py | 4,929 | 4.21875 | 4 | import unittest
import random
def bubble_sort(arr):
if len(arr) == 1:
return
swapped = True
while swapped:
swapped = False
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
arr[i], arr[i + 1] = arr[i + 1], arr[i]
swapped = True
def insertion_sort(arr):
for i in range(len(arr)):
insert_num = arr[i]
j = i - 1
while j >= 0 and arr[j] > insert_num:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = insert_num
def selection_sort(arr):
for i in range(len(arr)):
lowest_value_index = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[lowest_value_index]:
lowest_value_index = j
arr[i], arr[lowest_value_index] = arr[lowest_value_index], arr[i]
def merge(arr, left_index, right_index, middle):
left_copy = arr[left_index:middle + 1]
right_copy = arr[middle + 1: right_index + 1]
left_copy_index = 0
right_copy_index = 0
sorted_index = left_index
while left_copy_index < len(left_copy) and right_copy_index < len(right_copy):
if left_copy[left_copy_index] <= right_copy[right_copy_index]:
arr[sorted_index] = left_copy[left_copy_index]
left_copy_index += 1
else:
arr[sorted_index] = right_copy[right_copy_index]
right_copy_index += 1
sorted_index += 1
while left_copy_index < len(left_copy):
arr[sorted_index] = left_copy[left_copy_index]
left_copy_index += 1
sorted_index += 1
while right_copy_index < len(right_copy):
arr[sorted_index] = right_copy[right_copy_index]
right_copy_index += 1
sorted_index += 1
def merge_sort(arr, left_index, right_index):
if left_index >= right_index:
return
middle = (right_index + left_index) // 2
merge_sort(arr, left_index, middle)
merge_sort(arr, middle + 1, right_index)
merge(arr, left_index, right_index, middle)
def shell_sort(arr):
n = len(arr)
gap = n // 2
while gap > 0:
for i in range(gap, n):
temp = arr[i]
j = i
while j >= gap and arr[j - 1] > temp:
arr[j] = arr[j - 1]
j -= 1
arr[j] = temp
gap //= 2
def odd_even_sort(arr):
is_sorted = 0
while is_sorted == 0:
is_sorted = 1
for i in range(0, len(arr) - 1, 2):
if arr[i] > arr[i + 1]:
arr[i], arr[i + 1] = arr[i + 1], arr[i]
is_sorted = 0
for i in range(1, len(arr) - 1, 2):
if arr[i] > arr[i + 1]:
arr[i], arr[i + 1] = arr[i + 1], arr[i]
is_sorted = 0
return
def heapify(list_, heap_size, index):
largest = index
left = index * 2 + 1
right = index * 2 + 2
if left < heap_size and list_[largest] < list_[left]:
largest = left
if right < heap_size and list_[largest] < list_[right]:
largest = right
if largest != index:
list_[index], list_[largest] = list_[largest], list_[index]
heapify(list_, heap_size, largest)
def heap_sort(list_):
heap_size = len(list_)
for i in range(heap_size, -1, -1):
heapify(list_, heap_size, i)
for i in range(heap_size - 1, 0, -1):
list_[0], list_[i] = list_[i], list_[0]
heapify(list_, i, 0)
test_list_1 = [x for x in range(10)]
test_list_2 = [x for x in range(10)]
test_list_3 = [x for x in range(10)]
test_list_4 = [x for x in range(10)]
test_list_5 = [x for x in range(10)]
test_list_6 = [x for x in range(10)]
test_list_7 = [x for x in range(10)]
random.shuffle(test_list_1)
random.shuffle(test_list_2)
random.shuffle(test_list_3)
random.shuffle(test_list_4)
random.shuffle(test_list_5)
random.shuffle(test_list_6)
random.shuffle(test_list_7)
bubble_sort(test_list_1)
insertion_sort(test_list_2)
selection_sort(test_list_3)
merge_sort(test_list_4, 0, len(test_list_4) - 1)
shell_sort(test_list_5)
heap_sort(test_list_6)
odd_even_sort(test_list_7)
class Test(unittest.TestCase):
def test_bubble_sort(self):
self.assertListEqual(test_list_1, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
def test_insertion_sort(self):
self.assertListEqual(test_list_2, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
def test_selection_sort(self):
self.assertListEqual(test_list_3, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
def test_merge_sort(self):
self.assertListEqual(test_list_4, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
def test_shell_sort(self):
self.assertListEqual(test_list_5, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
def test_heap_sort(self):
self.assertListEqual(test_list_6, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
def test_odd_even_sort(self):
self.assertListEqual(test_list_7, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
if __name__ == '__main__':
unittest.main()
|
445c2ba495aa233a2f51c4eecfd4c24e4530f8ee | Teldrin89/DBPythonTut | /LtP16_re_part2.py | 908 | 4.375 | 4 | import re
# to match zero or one specific string use re.compile function and
# and a "+" with additional string to be matched and "?" that
# will be used to find either 0 or 1 of the specified additional
# string
# create a random string
randStr = "cat cats"
# use re.compile function to set a criteria to match both words
regex = re.compile("[cat]+s?")
# use re.findall on randStr to find both words using the regex
# criteria set before
matches = re.findall(regex, randStr)
# printout all matches find in random string
for i in matches:
print(i)
print()
# to match 0 or more of set characters use "*"
# new random string
randStr2 = "doctor doctors doctor's"
# use re.compile to set the criteria
regex2 = re.compile("[doctor]+['s]*")
# use re.findall to get all matching results from random string
matches2 = re.findall(regex2, randStr2)
# printout the results
for j in matches2:
print(j)
print()
|
8b61395ec01da85c353f99895a5bcaca02ac0746 | vromanuk/algorithms-and-ds | /Recursion/reverse.py | 296 | 3.984375 | 4 | def reverse(string: str) -> str:
if string:
return reverse(string[1:]) + string[0]
else:
return string
if __name__ == '__main__':
assert reverse('kayak') == 'kayak'
assert reverse('l') == 'l'
assert reverse('follow') == 'wollof'
assert reverse('') == ''
|
03be2797f975e6575c39185079494d6b29f0f754 | rakibsarwer/Python-Problem-Solving-Shubin-s-Book-First-part1 | /posNeg.py | 147 | 4.0625 | 4 | num = input("Enter Your Number :")
numb = int(num)
if(numb>=0):
print(numb, " is Positive Number")
else:
print(numb," is negetive Number") |
92ba36c3d647c9481493b9a8fa7a804cb225fab2 | okellogabrielinnocent/data_structure_gab | /reverse_array.py | 860 | 4.5 | 4 | # program to reverse an array or string
# method 1
# 1) Initialize start and end indexes as start = 0, end = n-1
# 2) In a loop, swap arr[start] with arr[end] and change start and end as follows :
# start = start + 1, end = end - 1
def reverse_list(arr, start, end):
while start < end:
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
# method 2
# 1) Initialize start and end indexes as start = 0, end = n-1
# 2) Swap arr[start] with arr[end]
# 3) Recursively call reverse for rest of the array.
def reverseList(arr, start, end):
if start >= end:
return
arr[start], arr[end] = arr[end], arr[start]
reverseList(arr, start+1, end-1)
# Method 3
# Using Python List slicing
def reverse_list_slice(arr):
return( A[::-1])
arr = [1,2,3,4,5,6,7,8,9]
reverse_list(arr, 0,9)
reverseList(arr, 0, 5)
reverse_list_slice()
|
c39a26b1ccfb8028fdd176eb070dfbcc09f2bfa6 | akashghanate/OpenCV | /Basics/drawImageShapes.py | 1,077 | 3.765625 | 4 | import cv2
import numpy as np
#create a black image
image=np.zeros((512,512,3),np.uint8)
#draw a diagonal line blue and thickness 5 pixel
cv2.line(image,(0,0),(511,511),(255,0,0),5)
cv2.imshow("Line",image)
#draw rectangle
# if you put thickness as -1 it fills the rectangle
image=np.zeros((512,512,3),np.uint8)
cv2.rectangle(image,(100,100),(300,250),(255,0,0),5)
cv2.imshow("rectangle",image)
#draw circle
image=np.zeros((512,512,3),np.uint8)
cv2.circle(image,(300,300),100,(0,250,0),3)
cv2.imshow("circle",image)
#draw any polygon using an array of points using numpy array
image=np.zeros((512,512,3),np.uint8)
#define points for polygon
pts=np.array([[10,50], [400,50], [90,200], [50,500]],np.int32)
#reshape the points in form required by polylines function
pts=pts.reshape((-1,1,2))
cv2.polylines(image,[pts],True,(0,0,255),0)
cv2.imshow("polygon",image)
#Add text
image=np.zeros((512,700,3),np.uint8)
cv2.putText(image,'Hi this is a example text',(150,150),cv2.FONT_HERSHEY_SIMPLEX,1,(250,250,0),0)
cv2.imshow("TEXT",image)
cv2.waitKey()
cv2.destroyAllWindows() |
96baae166cab4dea3ae1556a6148285f47f37015 | Allen-Maharjan/CHATBOT | /answer.py | 2,097 | 3.546875 | 4 | def answer(*args):
question = args[0]
name = args[1]
program = ''
answers = open('Answers.txt','r')
line = answers.readlines()
if (name == 'ss' or (name == 'co' or program == 'cm') ):
if(question=='who'):
return(line[4])
elif(question == 'where'):
return(line[5])
elif(question == 'how'):
return(line[6])
if (name == 'dbg' or (name == 'hod' or program =='dons')):
if(question=='who'):
return(line[8])
elif(question == 'where'):
return(line[9])
elif(question == 'how'):
return(line[10])
if (name == 'brj' or (name == 'hod' or program =='doese')):
if(question=='who'):
return(line[0])
elif(question == 'where'):
return(line[1])
elif(question == 'how'):
return(line[2])
if (name == 'kj' or (name == 'dean' or program == 'sos')):
if(question=='who'):
return(line[12])
elif(question == 'where'):
return(line[13])
elif(question == 'how'):
return(line[14])
if (name == 'bkb' or (name == 'hod' or program == 'docse')):
if(question=='who'):
return(line[20])
elif(question == 'where'):
return(line[21])
elif(question == 'how'):
return(line[22])
if (name == 'dt' or (name == 'hod' or program == 'dome')):
if(question=='who'):
return(line[24])
elif(question == 'where'):
return(line[25])
elif(question == 'how'):
return(line[26])
if (name == 'pmp' or (name == 'hod' or program == 'docage')):
if(question=='who'):
return(line[28])
elif(question == 'where'):
return(line[29])
elif(question == 'how'):
return(line[30])
if (name == 'rj' or (name == 'hod' or program == 'doce')):
if(question=='who'):
return(line[32])
elif(question == 'where'):
return(line[33])
elif(question == 'how'):
return(line[34])
#if (name == 'db' or (name == 'hod' or program == 'doeaee')):
# if (name == 'rj' or (name == 'hod' or program == 'doce')):
# if(question=='who'):
# return(line[36])
# elif(question=='where'):
# return(line[37])
# elif(question=='how'):
# return(line[38]) |
d94c8758afe17ebc63efe16ad989cc9c5d4b0578 | eric496/leetcode.py | /linked_list/147.insertion_sort_list.py | 2,440 | 3.984375 | 4 | """
Sort a linked list using insertion sort.
Algorithm of Insertion Sort:
Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
It repeats until no input elements remain.
Example 1:
Input: 4->2->1->3
Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0
Output: -1->0->3->4->5
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
# Solution 1
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
sentinel = ListNode(-1)
sentinel.next = head
insert = None
while head and head.next:
if head.val > head.next.val:
insert = head.next
start = sentinel
while start.next.val < insert.val:
start = start.next
head.next = insert.next
insert.next = start.next
start.next = insert
else:
head = head.next
return sentinel.next
# Solution 2: TLE
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
sentinel = ListNode(None)
sentinel.next = head
prev = sentinel
cur = head
while cur:
nxt = cur.next
while prev.next and prev.next.val < cur.val:
prev = prev.next
cur.next = prev.next
prev.next = cur
prev = sentinel
cur = nxt
return sentinel.next
# Solution 3: TLE
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
sentinel = ListNode(float("-inf"))
sentinel.next = head
cur = sentinel
while cur:
nxt = cur.next
walk = sentinel
while walk and walk.next:
if cur is walk.next:
break
elif walk.val < cur.val <= walk.next.val:
second = walk.next
walk.next = cur
cur.next = second
break
else:
walk = walk.next
cur = nxt
return sentinel.next
|
896d79610d503e7511604a83f2762910aeca4290 | jesuisundev/leet-code-fun | /easy/67-add-binary/solution.py | 685 | 4.125 | 4 | class Solution(object):
def addBinary(self, a, b):
"""
- Convert a and b into integers x and y, x will be used to keep an answer, and y for the carry.
- Carry non -zero
- While carry is nonzero: y != 0:
- Current answer without carry is XOR of x and y: answer = x^y.
- Current carry is left-shifted AND of x and y: carry = (x & y) << 1.
- Job is done, prepare the next loop: x = answer, y = carry.
"""
x, y = int(a, 2), int(b, 2)
while y:
answer = x ^ y
carry = (x & y) << 1
x, y = answer, carry
return bin(x)[2:]
print(Solution().addBinary('11', '1011')) |
b64e7b00c319081154b8031ad721a738ed5370d8 | Stoggles/AdventofCode | /2015/day12.py | 568 | 3.5625 | 4 | import json
def decode_elements(element, ignore_red=False):
global total
if isinstance(element, list):
for item in element:
decode_elements(item, ignore_red)
if isinstance(element, dict):
if ignore_red and "red" in element.values():
return
for key in element.keys():
decode_elements(element[key], ignore_red)
if isinstance(element, int):
total += element
return
with open('input12.txt') as file:
parsed_json = json.load(file)
total = 0
decode_elements(parsed_json)
print total
total = 0
decode_elements(parsed_json, True)
print total
|
dc95ecd1b7d1e802f2509ce612ce607e997e38da | PoonamGhutukade/Machine-learning | /Week4/Pandas/panda_series.py | 3,587 | 3.5 | 4 | import pandas as pd
import re
from Week4.Utility.Util import UtilClass
class PandaSeries:
def __init__(self):
self.obj1 = UtilClass()
def calling(self):
while True:
try:
print()
print("1. Create and display a one-dimensional array using Pandas module.""\n"
"2. Convert a Panda module Series to Python list ""\n"
"3. Add, subtract, multiple and divide two Pandas Series""\n"
"4. Get the powers of an array values element-wise""\n"
"5. Exit")
ch = input("Enter choice:")
choice = int(ch)
if ch.isdigit():
if choice == 1:
size = input("Enter the size for list:")
panada1d_series = self.obj1.create_series(size)
print("One-dimensional array using Pandas Series:\n", panada1d_series)
print("_______________________________________________________________________________")
elif choice == 2:
size = input("Enter the size for list:")
panada1d_series1 = self.obj1.create_series(size)
string = str(panada1d_series1)
if re.match(string, 'None'):
# If set is empty create again and then show its iteration again
print("Empty series")
continue
else:
print("Pandas Series:\n", panada1d_series1)
print("Panda series to list: ", self.obj1.conversion(panada1d_series1))
print("_______________________________________________________________________________")
elif choice == 3:
series1 = pd.Series([2, 4, 6, 8, 10])
series2 = pd.Series([1, 3, 5, 7, 9])
self.obj1.series_operations(series1, series2)
print("_______________________________________________________________________________")
elif choice == 4:
panda_series = pd.Series([1, 2, 3, 4])
print("Original panda series :", panda_series)
print("Power of 2 for all elements: ", self.obj1.series_power(panda_series))
print("_______________________________________________________________________________")
elif choice == 5:
exit()
print("_______________________________________________________________________________")
else:
print("Plz enter valid choice: ")
acc = str(input("IF you want to continue: type yes "))
if re.match(acc, 'y'):
continue
elif re.match(acc, 'yes'):
continue
elif re.match(acc, 'n'):
break
elif re.match(acc, 'no'):
break
else:
print("Give proper input")
continue
else:
raise ValueError
except ValueError as e:
print("\nInvalid Input", e)
# create class object to call its methods
obj = PandaSeries()
obj.calling()
|
c46cde35a9fc6e67b6fc341ba7f1c33c685b8caf | ElKroko/progra-usm-exes | /Certamen 1/EA_2_banco.py | 1,503 | 4.03125 | 4 | # hacer un programa que simule el proceso de evaluacion crediticia de un banco
# se debe validar que la edad minima de la persona es 18 anos, que sus ingresos son mayores a sus egresos,
# y que al final del mes la persona pueda pagar la cuota de su prestamo.
# La cuota esta definida como el monto pedido entre el numero de meses
# en que se desea pagar dicho prestamo.
edad = int(raw_input('Ingrese su edad: '))
ing = int(raw_input('Ingrese sus ingresos: '))
out = int(raw_input('Ingrese sus egresos: '))
saldo = ing - out
import math
if edad >= 18:
if saldo > 0:
print 'El cliente esta aprobado para pedir un credito con una cuota de valor maximo ',saldo,'mensuales.'
total = float(raw_input('Ingrese el monto de su credito a pedir: '))
min_cuotas = total / saldo
print 'La cantidad minima de cuotas que usted debe pedir es de ', math.ceil(min_cuotas), 'para poder pedir su credito.'
cuota = int(raw_input('Por favor ingrese la cantidad de cuotas que desea pedir: '))
pagar = total / cuota
if cuota >= min_cuotas:
print 'Felicidades, su credito ha sido aprobado.'
print 'Usted debera pagar un total de ', pagar, 'mensual.'
else:
print 'Lo sentimos, la cantidad de cuotas ingresada no es suficiente.'
else:
print 'Lo sentimos, usted no cumple los requisitos para pedir un credito'
else:
print 'Lo sentimos, usted no cumple el requisito minimo de edad.' |
0812c0ae86f6fb8dc5547661c9e76c8c3e874591 | LordOfTheThunder/Coding | /Companies/Google/findShortestPath/findShortestPath.py | 2,637 | 4.46875 | 4 | # Company: Google
# Question: You are given an M by N matrix consisting of booleans that represents a board. Each True boolean represents a wall. Each False boolean represents a tile you can walk on.
#
# Given this matrix, a start coordinate, and an end coordinate, return the minimum number of steps required to reach the end coordinate from the start. If there is no possible path, then return null. You can move up, left, down, and right. You cannot move through walls. You cannot wrap around the edges of the board.
# Example:
"""
Given this matrix, a start coordinate, and an end coordinate, return the minimum number of steps required to reach the end coordinate from the start. If there is no possible path, then return null. You can move up, left, down, and right. You cannot move through walls. You cannot wrap around the edges of the board.
For example, given the following board:
[[f, f, f, f],
[t, t, f, t],
[f, f, f, f],
[f, f, f, f]]
and start = (3, 0) (bottom left) and end = (0, 0) (top left), the minimum number of steps required to reach the end is 7, since we would need to go through (1, 2) because there is a wall everywhere else on the second row.
"""
# Solution:
def find_shortest_path(maze, start_point, end_point):
visited = [[0] * len(maze) for i in maze]
globals = {'steps' : 0}
def find_shortest_path_aux(maze, start_point, end_point):
if start_point[0] < 0 or start_point[1] < 0 or \
start_point[0] >= len(maze) or \
start_point[1] >= len(maze) or \
visited[start_point[0]][start_point[1]] or \
maze[start_point[0]][start_point[1]]:
return float("inf")
if start_point == end_point:
return globals['steps']
visited[start_point[0]][start_point[1]] = 1
globals['steps'] += 1
left = find_shortest_path_aux(maze, (start_point[0], start_point[1] - 1), end_point)
right = find_shortest_path_aux(maze, (start_point[0], start_point[1] + 1), end_point)
up = find_shortest_path_aux(maze, (start_point[0] - 1, start_point[1]), end_point)
down = find_shortest_path_aux(maze, (start_point[0] + 1, start_point[1]), end_point)
visited[start_point[0]][start_point[1]] = 0
globals['steps'] -= 1
return min(left, right, up, down)
return find_shortest_path_aux(maze, start_point, end_point)
if __name__ == "__main__":
maze = [[0, 0, 0, 0],
[1, 1, 0, 1],
[0, 0, 0, 0],
[0, 0, 0, 0]]
start_point = (3, 0)
end_point = (0, 0)
print(find_shortest_path(maze, start_point, end_point))
|
2b84e8438831e873eccb54531f71c97c5484ff0e | ksopyla/Matplotlib_examples | /2.Plot_features/2.1_Colors_and_lines.py | 595 | 4.03125 | 4 | # 2.1 Changing colors and line widths
# import necessary libraries
import matplotlib.pyplot as pl
import numpy as np
n = 256
X = np.linspace(-np.pi, np.pi, n, endpoint=True)
C, S = np.cos(X), np.sin(X)
# create a new figure with dimensions 10x8 inches, set dpi to 80
pl.figure(figsize=(10, 8), dpi=80)
# plot cosine using blue color, line width of 2 px, dotted
pl.plot(X, C, color="blue", linewidth=3, linestyle=":")
# plot sine using red color, line width of 2.5 px, dashed
pl.plot(X, S, color="red", linewidth=2.5, linestyle="--")
print("2.2 Changing line colors and widths")
pl.show() |
89012147a797696ed86a7dcc8247f4e8c72a26ba | AlexandruGG/CS50x-Problem-Sets | /Problem Set 6/bleep/bleep.py | 1,459 | 3.890625 | 4 | from cs50 import get_string
from sys import argv
def main():
# If the user doesn't provide exactly one argument, print usage and exit
while len(argv) != 2:
print("Usage: python bleep.py dictionary")
exit(1)
# Get the list of banned words from the dictionary provided
bannedWords = getBannedWords(argv[1])
# Get the text message from the user
text = get_string("What message would you like to censor?\n")
# Get the list of words from the text input
wordList = text.split()
# Censor the message based on the list of banned words
censoredMessage = censorMessage(wordList, bannedWords)
print(censoredMessage)
# Function which opens the file passed in and reads each line, adding words
# into a 'set' data structure
def getBannedWords(dictionary):
words = set()
file = open(dictionary, "r")
for line in file:
words.add(line.strip())
file.close()
return words
# Function which returns a censored message based on a word list and
# a set of banned words passed in
def censorMessage(wordList, bannedWords):
censoredList = []
for word in wordList:
if word.lower() in bannedWords:
censoredList.append("*" * len(word))
else:
censoredList.append(word)
return " ".join(censoredList)
if __name__ == "__main__":
main()
|
688be7192a98c96a6351ecbe6c467676c9921a00 | KushRawat/CN-DSA-Python | /Practice_1/LLt_swapTwoNodes.py | 1,895 | 3.53125 | 4 | from sys import stdin
#Following is the Node class already written for the Linked List
class Node :
def __init__(self, data) :
self.data = data
self.next = None
# def swapNodes(head, i, j) :
def swapNodes(head, i, j):
if i == j:
return head
currNode = head
prev = None
firstnode = None
secondNode = None
firstNodePrev = None
secondNodePrev = None
pos = 0
while currNode is not None:
if pos == i:
firstNodePrev = prev
firstNode = currNode
elif pos == j:
secondNodePrev = prev
secondNode = currNode
prev = currNode
currNode = currNode.next
pos += 1
if firstNodePrev is not None:
firstNodePrev.next = secondNode
else:
head = secondNode
if secondNodePrev is not None:
secondNodePrev.next = firstNode
else:
head = firstNode
currentFirstNode = secondNode.next
secondNode.next = firstNode.next
firstNode.next = currentFirstNode
return head
#Taking Input Using Fast I/O
def takeInput() :
head = None
tail = None
datas = list(map(int, stdin.readline().rstrip().split(" ")))
i = 0
while (i < len(datas)) and (datas[i] != -1) :
data = datas[i]
newNode = Node(data)
if head is None :
head = newNode
tail = newNode
else :
tail.next = newNode
tail = newNode
i += 1
return head
def printLinkedList(head) :
while head is not None :
print(head.data, end = " ")
head = head.next
print()
#main
t = int(stdin.readline().rstrip())
while t > 0 :
head = takeInput()
i_j = stdin.readline().strip().split(" ")
i = int(i_j[0])
j = int(i_j[1])
newHead = swapNodes(head, i, j)
printLinkedList(newHead)
t -= 1 |
c423aaa0024c802bb69b9b9b54588909adb34a3a | bksaini078/DynamicProgramming | /HackerRank/shape_classes_area.py | 1,092 | 4.28125 | 4 | '''Problem Description
The program takes the radius from the user and finds the area of the circle using classes.
Problem Solution
1. Take the value of radius from the user.
2. Create a class and using a constructor initialise values of that class.
3. Create a method called as area which returns the area of the class and a method called as perimeter which returns the perimeter of the class.
4. Create an object for the class.
5. Using the object, call both the methods.
6. Print the area and perimeter of the circle.
7. Exit'''
import math
class Rectangle:
def __init__(self,length,width):
self.length= length
self.width= width
def area(self):
return self.length*self.width
class Circle:
def __init__(self, radius):
self.radius= radius
def area(self):
return math.pi*(self.radius**2)
if __name__=='__main__':
len= 10
wid= 20
radius =5
rect_area= Rectangle(len,wid)
cir_area= Circle(radius)
print(rect_area.area())
print(cir_area.area())
print(rect_area.area())
# print(Circle.area(radius))
|
98b0c8e2fcf48de999230700efff5f78f4daef19 | navnath-auti/College | /Sem4/Python'/exp8/Minheritance.py | 438 | 3.953125 | 4 |
class Father:
fathername = ""
def show_father(self):
print(self.fathername)
class Mother:
mothername = ""
def show_mother(self):
print(self.mothername)
class Son(Father, Mother):
def show_parent(self):
print("Father :", self.fathername)
print("Mother :", self.mothername)
s1 = Son() # Object of Son class
s1.fathername = "Joseph Joester"
s1.mothername = "Lily"
s1.show_parent() |
5b8ae5c0e9c4b7f86561645ea0bde42f26034702 | DVDBZN/Schoolwork | /CS136 Database Programming With SQL/PythonPrograms/Midterm/Midterm Program.py | 2,932 | 4.125 | 4 | #Define the function that processes the budget
def processBudget(incomes, expenses):
totalIncome = sum(incomes)
totalExpenses = sum(expenses)
#Difference is income minue expenses
#If expenses are greater, the difference will be negative
difference = totalIncome - totalExpenses
#Print out totals for the user
print "\nTotal income: $" + str(totalIncome)
print "Total expenses: $" + str(totalExpenses)
#Return difference to main()
return difference
#Define main() function
def main():
#Variables
incomes = []
expenses = []
userInput = 0
#Instructions
print "Enter your income and expenses."
print "To stop, enter a negative value.\n"
#Loop until user enters negative value
while userInput > -1:
#Exception handling to handle invalid data types
try:
#Accept user input as a float
userInput = float(raw_input("Enter your income: $"))
#If user enteres a string, do not append to list
#It skips the list append using the continue keyword
except:
print "Invalid data type. Enter numeric values."
continue
#If last user input was not negative, append to incomes list
if userInput > -1:
incomes.append(userInput)
#Otherwise, reset userInput for next loop and exit this loop
else: #userInput <= -1
userInput = 0
#Put a line break between income and expenses input
print
break
#Loop until user enters negative value
while userInput > -1:
#Exception handling to handle invalid data types
try:
#Accept user input as a float
userInput = float(raw_input("Enter your expense: $"))
#If user enteres a string, do not append to list
#It skips the list append using the continue keyword
except:
print "Invalid data type. Enter numeric values."
continue
#If last user input was not negative, append to incomes list
if userInput > -1:
expenses.append(userInput)
#Otherwise, exit this loop
else: #userInput <= -1
#Put a line break after inputs
print
break
#Net income is equal to return value of processBudget method
netIncome = processBudget(incomes, expenses)
print "\nNet income: $" + str(netIncome)
#Print advice based on net income
if netIncome > 0:
print "\nGood work on your money management skills."
elif netIncome == 0:
print "\nWell, you are neither earning, nor gaining."
print "Either earn more or spend less to get out of stagnation."
else:
print "\nYou are losing money! Either spend less or earn more."
#Hold the program open to see final output
raw_input()
#Call main() function to start program
main()
|
8aba28dfeb8d1532b54ba3bc10fb284535af2372 | spaulen/IntroToProg-Python | /HomeInventory.py | 4,448 | 3.890625 | 4 | # ------------------------------------------------------------------------ #
# Title: Assignment 05
# Description: Working with Dictionaries and Files
# When the program starts, load each "row" of data
# in "ToDoToDoList.txt" into a python Dictionary.
# Add each dictionary "row" to a python list "table"
# ChangeLog (Who,When,What):
# RRoot,01.01.2020,Created started script
# Susan Paulen,11.16.2020,Added code to complete Assignment 5 Step 1
# Load ToDoList.txt data into lstTable via dicRow
# Susan Paulen,11.16.2020,Added code to complete Assignment 5 Step 3
# Show the current items in the lstTable
# Susan Paulen,11.16.2020,Added code to complete Assignment 5 Step 4
# Add a New Item from User Input
# Susan Paulen,11.16.2020,Added code to complete Assignment 5 Step 5
# Remove an existing item from User Input
# Susan Paulen,11.16.2020,Added code to complete Assignment 5 Step 6
# Save lstTable Data to File
# Susan Paulen,11.16.2020,Added code to complete assignment 5 Step 7
# Exit Program
# ------------------------------------------------------------------------ #
# -- Data -- #
# declare variables and constants
objFile = "ToDoList.txt" # An object that represents a file
strData = "" # A row of text data from the file
strItem = "" # An item's name
strValue = "" # An item's value
strMenu = "" # A menu of user options
strChoice = "" # Capture the user option selection
dicRow = {} # A row of data separated into elements of a dictionary {Item,Value}
lstTable = [] # A list that acts as a 'table' of rows
# -- Processing -- #
# Step 1 - When the program starts, load any data you have
# in a text file called ToDoList.txt into a python list of dictionaries rows (like Lab 5-2)
# TODO: Done
try:
objFile = open("ToDoList.txt", "r")
print("ITEM | VALUE")
for row in objFile:
strItem, strValue = row.split(",")
dicRow = {"Item": strItem, "Value": strValue.strip()}
lstTable.append(dicRow)
print(dicRow["Item"] + ' | ' + dicRow["Value"])
objFile.close
except:
print("There is no previous ToDoList.txt available. It will be created upon Save.")
# -- Input/Output -- #
# Step 2 - Display a menu of choices to the user
while (True):
print("""
1) Show current data
2) Add a new item
3) Remove an existing item
4) Save Data to File
5) Exit Program
""")
strChoice = str(input("Which option would you like to perform? [1 to 5] - "))
print() # adding a new line for looks
# Step 3 - Show the current items in the table
if (strChoice.strip() == '1'):
# TODO: Done
for objRow in lstTable:
print(objRow["Item"] + ' | ' + objRow["Value"])
continue
# Step 4 - Add a new item to the list/Table
elif (strChoice.strip() == '2'):
# TODO: Done
strItem = input("Item: ")
strValue = input("Value: ")
lstTable.append({"Item": strItem, "Value": strValue})
continue
# Step 5 - Remove an existing item from the list/Table
elif (strChoice.strip() == '3'):
# TODO: Done
strItem = input("Item to Remove: ")
for objRow in lstTable:
if objRow["Item"].lower() == strItem.lower():
lstTable.remove(objRow)
print("Item Removed")
# Step 6 - Save items and values to the ToDoList.txt file
elif (strChoice.strip() == '4'):
# TODO: Done
objFile = open("ToDoList.txt", "w") # This saves the text file to same py location
for row in lstTable:
objFile.write(str(row["Item"]) + "," + str(row["Value"]) + "\n")
objFile.close()
#objFile = open("ToDoList.txt", "w")
#for objRow in lstTable:
# objFile.write(str(objRow["Item"]) + ',' + str(objRow["Value"])+ '\n')
#objFile.close
print("Data Saved to ToDoList.txt")
continue
# Step 7 - Exit program
elif (strChoice.strip() == '5'):
# TODO: Done
print("Exiting Program")
# Delay the message so the user has time to read it
import time
x = 0
while x < 3:
time.sleep(3)
x = x+1
break # Exit the program
|
43abc5454962902e38547c9f93e248dc30e2d11c | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/PYTHON_PRAC/projecteuler/euler035.py | 1,006 | 3.796875 | 4 | #!/usr/bin/env python
"""
Solution to Project Euler Problem 35
http://projecteuler.net/
by Apalala <[email protected]>
(cc) Attribution-ShareAlike
http://creativecommons.org/licenses/by-sa/3.0/
The number, 197, is called a circular prime because all digit_rotations of the digits:
197, 971, and 719, are themselves prime.
There are thirteen such primes below 100:
2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
How many circular primes are there below one million?
"""
from primality import is_prime, primes_upto
from digits import digit_rotations
def is_circular_prime(n):
return "0" not in str(n) and all(is_prime(r) for r in digit_rotations(n))
def count_circular_primes(m):
return sum(is_circular_prime(n) for n in primes_upto(m))
def test():
assert [197, 971, 719] == list(digit_rotations(197))
assert is_circular_prime(197)
assert 13 == count_circular_primes(10 ** 2)
def run():
print(count_circular_primes(10 ** 6))
if __name__ == "__main__":
test()
run()
|
fabb52ae22af327e9874223e5861cd6e58b423a8 | virenkhandal/internpursuit-ml | /round1.py | 3,906 | 3.578125 | 4 | from os import major
import pandas as pd
def round1_filter(students, employer):
filtered = students
drop = set()
"""
Majors/Minors filter
"""
employer_majors = employer['Majors/Minors'].values[0].split(';')
# print(employer["Name"].values.tolist()[0], ": ", employer['Majors/Minors'].values[0])
for index in range(len(filtered.index)):
row = filtered.iloc[[index]]
if isinstance(row['Majors/Minors'].values[0], str):
student_majors = row['Majors/Minors'].values[0].split(';')
if not set(student_majors).isdisjoint(set(employer_majors)):
# print(row['Name'].values.tolist()[0], ": ", row['Majors/Minors'].values[0])
pass
if set(student_majors).isdisjoint(set(employer_majors)):
drop.add(index)
"""
Citizenship filter
"""
employer_citizenship = employer['Citizenship'].values[0].split(';')
for index in range(len(filtered.index)):
row = filtered.iloc[[index]]
student_citizenship = row['Citizenship'].values[0]
if student_citizenship[0:3] == "Int":
student_citizenship = "International Student"
if student_citizenship not in employer_citizenship:
drop.add(index)
"""
Work hours filter
"""
employer_hours = employer['Full Time or Part Time (Choose weekly hours)'].values[0].split(';')
for index in range(len(filtered.index)):
row = filtered.iloc[[index]]
student_hours = row['Full Time or Part Time Student'].values[0]
if student_hours == "Part Time Student (3-11 hours)":
student_hours = "Part time (3-11 hours)"
if student_hours == "Full Time Student (12+ hours)":
student_hours = "Full time (12 + hours)"
if student_hours not in employer_hours:
drop.add(index)
"""
Flexible schedule filter
"""
employer_flex = employer['Flex Schedule (check all that apply)'].values[0].split(';')
for index in range(len(filtered.index)):
row = filtered.iloc[[index]]
student_flex = row['Remote, Onsite, Flex Options - Check your preferences'].values[0].split(';')
if len(student_flex) == 1 and student_flex[0] == "Flex Hours - adjust to student school & work schedule":
if "Flex Hours - adjust to student school & work schedule" not in employer_flex:
drop.add(index)
"""
Work location filter - nothing right now
"""
"""
School credit filter
"""
employer_cred = employer['Credit or Non-Credit '].values[0].split(';')
for index in range(len(filtered.index)):
row = filtered.iloc[[index]]
s = 'Credit or Noncredit Internship (Requires a full semester commitment)'
if str(row[s].values[0]) == 'nan':
row[s].values[0] = 'Non-Credit - Think of this like a volunteer role'
student_cred = row['Credit or Noncredit Internship (Requires a full semester commitment)'].values[0].split(';')
if student_cred[0] == 'Non-Credit - Think of this like a volunteer role':
break
elif student_cred[0] not in employer_cred:
drop.add(index)
"""
Academic calendar filter
"""
employer_cal = employer['Which semester are you seeking interns working with you'].values[0].split(';')
employer_cal = [x.lower() for x in employer_cal]
for index in range(len(filtered.index)):
row = filtered.iloc[[index]]
student_cal = row['Which semester are you seeking an internship?'].values[0].split(';')
if (len(student_cal) == 1 and student_cal[0] == 'flexible') or 'On demand' in employer_cal:
break
if set(student_cal).isdisjoint(set(employer_cal)):
drop.add(index)
filtered = filtered.drop(list(drop))
filtered.reset_index(inplace=True)
return filtered |
2200de03b30819967b47fffa348e9290ec0f3b69 | danting123/lab02 | /number_list.py | 1,210 | 4.09375 | 4 |
def find_reverse(numbers):
#TODO: find the reverse of the list
return numbers[::-1]
def find_max(numbers):
#TODO: find the maximum of the list
return max(numbers)
def find_min(numbers):
#TODO: find the minimum of the list
return min(numbers)
def find_sum(numbers):
#TODO: find the sum of all the numbers in the list
return sum(numbers)
def find_average(numbers):
#TODO: find the average of all the numbers in the list
return sum(numbers)/len(numbers)
def find_descending(numbers):
#TODO: numbers sorted in descending order
return sorted(numbers,reverse = True)
def second_smallest(numbers):
#TODO: find the second smallest
min_1 = 10000
min_2 = 10000
master = set(numbers)
for num in master:
if num <= min_1:
min_2 = min_1
min_1 = num
elif num < min_2:
min_2 = num
return min_2
def kth_smallest(numbers, k):
#TODO: find the kth smallest number in the list
number = set(numbers)
number = sorted(number)
return number[k-1]
if __name__ == '__main__':
# If you are testing, place your print statements here
pass
|
f242f626659c959acafe60ccf056df4d588d45f4 | EduardoFF/easy_cozmo | /easy_cozmo/line_detection_utils.py | 10,286 | 3.578125 | 4 | import numpy as np
import cv2
import math
import sys
def auto_canny(image, sigma=0.33):
# compute the median of the single channel pixel intensities
v = np.median(image)
# apply automatic Canny edge detection using the computed median
lower = int(max(0, (1.0 - sigma) * v))
upper = int(min(255, (1.0 + sigma) * v))
edged = cv2.Canny(image, lower, upper)
# return the edged image
return edged
def mycanny(image):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (3, 3), 0)
return auto_canny(blurred)
def grayscale(img):
"""Applies the Grayscale transform
This will return an image with only one color channel
but NOTE: to see the returned image as grayscale
(assuming your grayscaled image is called 'gray')
you should call plt.imshow(gray, cmap='gray')"""
return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# Or use BGR2GRAY if you read an image with cv2.imread()
def gaussian_blur(img, kernel_size):
"""Applies a Gaussian Noise kernel"""
return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)
def weighted_img(img, initial_img, α=0.8, β=1., λ=0.):
"""
`img` is the output of the hough_lines(), An image with lines drawn on it.
Should be a blank image (all black) with lines drawn on it.
`initial_img` should be the image before any processing.
The result image is computed as follows:
initial_img * α + img * β + λ
NOTE: initial_img and img must be the same shape!
"""
return cv2.addWeighted(initial_img, α, img, β, λ)
def region_of_interest(img, vertices):
mask = np.zeros_like(img)
match_mask_color = 255
cv2.fillPoly(mask, vertices, match_mask_color)
masked_image = cv2.bitwise_and(img, mask)
return masked_image
def draw_lines(img, lines, color=[255, 255, 0], thickness=6):
line_img = np.zeros(
(
img.shape[0],
img.shape[1],
3
),
dtype=np.uint8
)
img = np.copy(img)
if lines is None:
return
for line in lines:
for x1, y1, x2, y2 in line:
cv2.line(line_img, (x1, y1), (x2, y2), color, thickness)
img = cv2.addWeighted(img, 0.8, line_img, 1.0, 0.0)
return img
# Auto-paramter Canny edge detection adapted from:
# http://www.pyimagesearch.com/2015/04/06/zero-parameter-automatic-canny-edge-detection-with-python-and-opencv/
#def auto_canny(img, sigma=0.33):
# blurred = cv2.GaussianBlur(img, (3, 3), 0)
# v = np.median(blurred)
# lower = int(max(0, (1.0 - sigma) * v))
# upper = int(min(255, (1.0 + sigma) * v))
# edged = cv2.Canny(blurred, lower, upper)
# return edged
def average_lines(lines, h_y, centered=True, mid_x = 160, max_y = 240):
xs = []
ys = []
for line in lines:
if len(line) == 0:
continue
for l in line:
if len(l) != 4:
continue
(x1, y1, x2, y2) = l
if x1 != x2:
slope = (y2 - y1) / (x2 - x1)
if math.fabs(slope) < 0.5:
continue
xs.extend([x1, x2])
ys.extend([y1, y2])
if len(ys) < 3:
return None
poly = np.poly1d(np.polyfit(
ys,
xs,
deg=1
))
if centered:
h_y = int(max_y / 2)
h_x = int(poly(h_y))
b_y = max_y
b_x = mid_x
line = [h_x, h_y, mid_x, b_y]
return line
return None
""" expects an opencv image (BGR) """
def pipeline(image, **kwargs):
"""
An image processing pipeline which will output
an image with the lane lines annotated.
"""
height, width, channels = image.shape
gray_image = grayscale(image)
img_hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
mymask = gray_image
BLUE = False
YW=False
if BLUE:
lower_blue=np.array([100,150,0],np.uint8)
upper_blue=np.array([140,255,255],np.uint8)
mask_blue = cv2.inRange(img_hsv, lower_blue, upper_blue)
mask_blue_image = cv2.bitwise_and(gray_image, mask_blue)
mymask = mask_blue_image
if YW:
lower_yellow = np.array([20, 100, 100], dtype = "uint8")
upper_yellow = np.array([30, 255, 255], dtype="uint8")
mask_yellow = cv2.inRange(img_hsv, lower_yellow, upper_yellow)
mask_white = cv2.inRange(gray_image, 200, 255)
mask_yw = cv2.bitwise_or(mask_white, mask_yellow)
mask_yw_image = cv2.bitwise_and(gray_image, mask_yw)
mymask = mask_yw_image
kernel_size = 5
gauss_gray = gaussian_blur(mymask,kernel_size)
# print("image has size {0} {1}".format(height,width))
cannyed_image = auto_canny(gauss_gray, sigma=0.3)
# region_of_interest_vertices = [
# (0, height),
# (0, 0.75*height),
# (width / 2, height / 2),
# (width, 0.75*height),
# (width, height)
# ]
region_of_interest_vertices = [
(0.10*width, height),
(0.10*width, 0.50*height),
#(width / 2, height / 2),
(0.90*width, 0.50*height),
(0.90*width, height)
]
# image_cvt = image.astype(np.uint8)
# gray_image = cv2.cvtColor(image_cvt, cv2.COLOR_RGB2GRAY)
#gray_image = cv2.cvtColor(image_cvt, cv2.COLOR_RGB2GRAY)
#cannyed_image = cv2.Canny(gray_image, 100, 200)
# cannyed_image = auto_canny(gray_image)
cropped_image = region_of_interest(
cannyed_image,
np.array(
[region_of_interest_vertices],
np.int32
),
)
# return cv2.cvtColor(cannyed_image, cv2.COLOR_GRAY2BGR)
# return cv2.cvtColor(mymask, cv2.COLOR_GRAY2BGR)
# return cv2.cvtColor(gauss_gray, cv2.COLOR_GRAY2BGR)
# return cv2.cvtColor(cropped_image, cv2.COLOR_GRAY2BGR)
# return cropped_image
#rho and theta are the distance and angular resolution of the grid in Hough space
h_rho = kwargs.get("rho", 10)
h_theta_div = kwargs.get("theta_div",60)
h_threshold = kwargs.get("threshold", 30)
h_minLineLength= kwargs.get("minLineLength",15)
h_maxLineGap = kwargs.get("maxLineGap",5)
lane_detection = kwargs.get("lane_detection", True)
lines = cv2.HoughLinesP(
cropped_image,
rho=h_rho,
theta=np.pi/h_theta_div,
threshold=h_threshold,
lines=np.array([]),
minLineLength=h_minLineLength,
maxLineGap=h_maxLineGap
)
#print(lines)
left_line_x = []
left_line_y = []
right_line_x = []
right_line_y = []
if lines is not None and len(lines) > 0:
line_image = image
if lane_detection:
for line in lines:
for x1, y1, x2, y2 in line:
# if line is almost vertical, count it both as left and right
if abs(x2 - x1) < 2:
left_line_x.extend([x1, x2])
left_line_y.extend([y1, y2])
right_line_x.extend([x1, x2])
right_line_y.extend([y1, y2])
continue
slope = (y2 - y1) / (x2 - x1)
if math.fabs(slope) < 0.5:
continue
if slope <= 0:
left_line_x.extend([x1, x2])
left_line_y.extend([y1, y2])
else:
right_line_x.extend([x1, x2])
right_line_y.extend([y1, y2])
min_y = int(image.shape[0] * (2 / 5))
max_y = int(image.shape[0])
left_lane = []
try:
poly_left = np.poly1d(np.polyfit(
left_line_y,
left_line_x,
deg=1
))
left_x_start = int(poly_left(max_y))
left_x_end = int(poly_left(min_y))
left_lane = [left_x_start, max_y, left_x_end, min_y]
except:
pass
right_lane = []
try:
poly_right = np.poly1d(np.polyfit(
right_line_y,
right_line_x,
deg=1
))
right_x_start = int(poly_right(max_y))
right_x_end = int(poly_right(min_y))
right_lane = [right_x_start, max_y, right_x_end, min_y]
except:
pass
# print("Left lane ", left_lane)
# print("Right lane ", right_lane)
lines = []
if len(left_lane):
lines.append([left_lane])
if len(right_lane):
lines.append([right_lane])
if kwargs['draw_lines']:
# print("Drawing lines...")
image = draw_lines(
image,
lines,
color=[255,0,0],
thickness=10
)
if kwargs['single_line_output']:
if len(lines) >= 2:
if (left_lane[3] - left_lane[1]) < 2:
lines = [[left_lane]]
else:
ml = 1.0/((left_lane[2] - left_lane[0])/(left_lane[3] - left_lane[1]))
mr = 1.0/((right_lane[2] - right_lane[0])/(right_lane[3] - right_lane[1]))
xi = (ml*left_lane[0] - mr*right_lane[0] - left_lane[1]+right_lane[1])/(ml - mr)
yi = ml*(xi - left_lane[0]) + left_lane[1]
al = math.atan2(left_lane[3] - left_lane[1],
left_lane[2] - left_lane[0])
ar = math.atan2(right_lane[3] - right_lane[1],
right_lane[2] - right_lane[0])
mi = (math.sin(al)+math.sin(ar))/(math.cos(al) + math.cos(ar))
yi2 = max_y
xi2 = (max_y -yi + mi*xi)/mi
linei = [int(xi), int(yi), int(xi2), int(yi2)]
lines=[[linei]]
if kwargs['draw_single_line']:
# print("Drawing lines...")
image = draw_lines(
image,
lines,
color=[0,0,255],
thickness=10
)
return lines, image
return [[[]]], image
|
c8d10c824ab7672a3d2eccfc17ebcd94e91a769c | ateitelbaum/PrecipitationCrimeCorrelation | /pdfPlot.py | 1,304 | 3.828125 | 4 | #creates a double bar graph of average weekly violent crime rate during dry weather and precipitation
#!/usr/bin/env python3
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import random
import math
import numpy as np
fig, ax = plt.subplots()
def plot(crimes, dryMeans, precipMeans):
N = 8
ind = np.arange(N)+2 # the x locations for the groups
width = 0.35 # the width of the bars
rects1 = ax.bar(ind, dryMeans, width, color='b')
rects2 = ax.bar(ind + width, precipMeans, width, color='r')
# add some text for labels, title and axes ticks
ax.set_ylabel('Crimes Committed')
ax.set_title('Average Weekly Violent Crime Rate in Dry Weather and Precipitation')
ax.set_xticks(ind + width / 2)
ax.set_xticklabels((crimes), fontsize = 6)
ax.legend((rects1[0], rects2[0]), ('Precipitation', 'Dry'))
autolabel(rects1)
autolabel(rects2)
# Save the plot into a PDF file
fig.savefig("plot.pdf")
def autolabel(rects):
"""
Attach a text label above each bar displaying its height
"""
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
'%.2f' % float(height),
ha='center', va='bottom', fontsize = 5)
|
f8e557139f3219403131f735470fbf3cb1f69b0f | ahad-emu/python-code | /Coding/21_zip.py | 303 | 4.5 | 4 | mylist1 = [1, 2, 3]
mylist2 = ['a', 'b', 'c']
#two list zip together
list3 = list(zip(mylist1, mylist2))
print(list3)
#print two list as a tuple
for item in zip(mylist1, mylist2):
print(item)
#print one value of the tuple in zip function
for item,value in zip(mylist1, mylist2):
print(value)
|
1f85dea17ea5a1a35f736b0f88416cb90c51621e | nozma/the_self_taught_programmer_challenges | /ch06/prob05.py | 193 | 3.75 | 4 | # -*- coding:utf-8 -*-
def main():
strlist = ["The", "fox", "jumped", "over", "the", "fence", "."]
print(" ".join(strlist[:-1]) + strlist[-1])
if __name__ == '__main__':
main()
|
8580e8f1871ba117604ad11f891dc112276bd22d | AgentT30/InfyTq-Foundation_Courses | /Programming Funcamentals Using Python/Day 9/luhn_algorithm.py | 994 | 3.84375 | 4 | def validate_credit_card_number(card_number):
# start writing your code here
double = []
card_number = str(card_number)
for i in range(0, len(card_number), 2):
number_double = int(card_number[i]) * 2
if number_double > 9:
number_double = str(number_double)
double.append(int(number_double[0]) + int(number_double[1]))
else:
double.append(int(card_number[i]) * 2)
double.reverse()
# print(double)
num_sum = sum(double)
# print(num_sum)
step_2 = []
for i in range(1, len(card_number), 2):
step_2.append(int(card_number[i]))
total_sum = sum(step_2) + num_sum
if total_sum % 10 == 0:
return True
else:
return False
# 4539869650133101 #1456734512345698 # #5239512608615007
card_number = 1456734512345698
result = validate_credit_card_number(card_number)
if(result):
print("credit card number is valid")
else:
print("credit card number is invalid")
|
72befd201c3966b5467279235e23d534b258dabe | joaquim-fps/ufrj-alg-grafos-2017-2 | /Lista 2/egipcio.py | 900 | 4.1875 | 4 | from fractions import Fraction
def get_fraction():
while True:
fraction = input().split('/')
num = int(fraction[0])
den = int(fraction[1])
if den >= num:
return Fraction(num,den)
def format_fractions(fractions):
formatted_fractions = []
for divisor in fractions:
formatted_fractions.append("1/"+str(divisor))
return formatted_fractions
def egyptian():
fraction = get_fraction()
egyptian_fractions = []
divisor = 1
while fraction != 0:
unit_fraction = Fraction(1,divisor)
# A primeira fração unitária menor ou igual à outra fração
if unit_fraction <= fraction:
egyptian_fractions.append(divisor)
fraction = fraction - unit_fraction
divisor = divisor + 1
return format_fractions(egyptian_fractions)
|
d46a2254a1ee57f8a15a59393c30160440503b8b | notagamer12/Python2020 | /rectangles_07.py | 2,717 | 3.90625 | 4 | from points import Point
class Rectangle:
"""Klasa reprezentująca prostokąty na płaszczyźnie."""
def __init__(self, x1, y1, x2, y2):
# Chcemy, aby x1 < x2, y1 < y2.
if x1 >= x2 or y1 >= y2:
raise ValueError("prawidłowe współrzędne powinny spełniać warunek x1 < x2, y1 < y2")
self.pt1 = Point(x1, y1)
self.pt2 = Point(x2, y2)
def __str__(self): # "[(x1, y1), (x2, y2)]"
return "[({0}, {1}), ({2}, {3})]".format(self.pt1.x, self.pt1.y, self.pt2.x, self.pt2.y)
def __repr__(self): # "[(x1, y1), (x2, y2)]"
return "Rectangle({0}, {1}, {2}, {3})".format(self.pt1.x, self.pt1.y,self.pt2.x, self.pt2.y)
def __eq__(self, other): # obsługa rect1 == rect2
return self.pt1 == other.pt1 and self.pt2 == other.pt2
def __ne__(self, other): # obsługa rect1 != rect2
return not self == other
def center(self): # zwraca środek prostokąta
x_cent = (self.pt1.x + self.pt2.x) / 2
y_cent = (self.pt1.y + self.pt2.y) / 2
return Point(x_cent, y_cent)
def area(self): # pole powierzchni
a = self.pt2.x - self.pt1.x
b = self.pt2.y - self.pt1.y
return a * b
def move(self, x, y): # przesunięcie o (x, y)
x1 = self.pt1.x + x
y1 = self.pt1.y + y
x2 = self.pt2.x + x
y2 = self.pt2.y + y
return Rectangle(x1, y1, x2, y2)
def intersection(self, other): # część wspólna prostokątów
p1 = self.pt1 #(x1,y1)
p2 = self.pt2 #(x2,y2)
p3 = other.pt1 #(x3, y3)
p4 = other.pt2 #(x4,y4)
x5 = max(p1.x, p3.x)
y5 = max(p1.y, p3.y)
x6 = min(p2.x, p4.x)
y6 = min(p2.y, p4.y)
if x5 > x6 or y5 > y6:
return None
return Rectangle(x5, y5, x6, y6)
def cover(self, other): # prostąkąt nakrywający oba
p1 = self.pt1
p2 = self.pt2
p3 = other.pt1
p4 = other.pt2
x5 = min(p1.x, p3.x)
y5 = min(p1.y, p3.y)
x6 = max(p2.x, p4.x)
y6 = max(p2.y, p4.y)
return Rectangle(x5, y5, x6, y6)
def make4(self): # zwraca krotkę czterech mniejszych
cent = self.center()
rect1 = Rectangle(self.pt1.x, self.pt1.y, cent.x, cent.y)
rect2 = Rectangle(self.pt1.x, cent.y, cent.x, self.pt2.y)
rect3 = Rectangle(cent.x, self.pt1.y, self.pt2.x, cent.y)
rect4 = Rectangle(cent.x, cent.y, self.pt2.x, self.pt2.y)
return [rect1, rect2, rect3, rect4]
|
199a597227b3c1d99aeb13f32ee9f0010384ea15 | sunghyungi/pandas_study | /data_structor/df_apply_min_max.py | 675 | 3.625 | 4 | import seaborn as sns
print("# titanic 데이터셋에서 age, fare 2개 열을 선택하여 데이터프레임 만들기")
titanic = sns.load_dataset('titanic')
df = titanic.loc[:, ['age', 'fare']]
print(df.head()).
print()
# 사용자 함수 정의
def min_max(x):
return x.max() - x.min()
print("# 데이터프레임의 각 열을 인수로 전달하면 시리즈를 반환")
result = df.apply(min_max)
print(result, type(result), sep='\n')
def add_two_obj(a, b):
return a + b
print("# 데이터프레임의 2개 열을 선택하여 적용")
print("# x=df, a=df['age'], b=df['ten']")
df['add'] = df.apply(lambda x: add_two_obj(x['age'], x['ten']), axis=1) |
b544a47378d2c15b62119c2cb5231417d71739e8 | raunakpalit/myPythonLearning | /DataStructures/array_advance_game.py | 673 | 4.125 | 4 | # Array Advance Game
# You are given an array of non-negative integers. For example:
# [3, 3, 1, 0, 2, 0, 1]
# Each number represents the maximum you can advance in the array.
# Is it possible to advance from the start of the array to the last element?
# Example of Unwinnable: [3, 2, 0, 0, 2, 0, 1]
def array_advance(A):
furthest_reached = 0
last_idx = len(A) - 1
i = 0
while i <= furthest_reached and furthest_reached < last_idx:
furthest_reached = max(furthest_reached, A[i] + i)
i += 1
return furthest_reached >= last_idx
A1 = [2, 3, 1, 0, 2, 0, 1]
print(array_advance(A1))
A2 = [3, 2, 0, 0, 2, 0, 1]
print(array_advance(A2))
|
e3eeaef48c75541f8b39a62843862cea9864d7b3 | JulietaCaro/Programacion-I | /Trabajo Practico 8/Conjuntos/Ejercicio 8.py | 1,900 | 4.3125 | 4 | # Definir un conjunto con números enteros entre 0 y 9. Luego solicitar valores al usuario y eliminarlos del conjunto mediante
# el método remove, mostrando el contenido del conjunto luego de cada eliminación. Finalizar el proceso al ingresar -1.
# Utilizar manejo de excepciones para evitar errores al intentar quitar elementos inexistentes.
def main():
conjunto = {0,1,2,3,4,5,6,7,8,9}
while True:
try:
num = int(input("Ingrese un numero a eliminar: "))
if num == -1:
break
if num not in conjunto:
raise ValueError("Ese numero no está en el conjunto")
if not type(num) is int:
raise TypeError("Se espera el ingreso de un numero")
if num in conjunto:
conjunto.remove(num)
print(conjunto)
except ValueError as mensaje:
print(mensaje)
except TypeError as error:
print(error)
def main2():
conjunto = {1,2,3,4,5,6,7,8,9,0}
while True:
try:
num = int(input("Ingrese un numero: "))
if num == -1:
break
assert (num in conjunto), "El numero no está en el conjunto"
assert (num>0),"Se espera el ingreso de un positivo"
conjunto.remove(num)
print(conjunto)
except AssertionError as error:
print(error)
except ValueError:
print("Se espera el ingreso de un numero")
def main3():
conjunto = {0,1,2,3,4,5,6,7,8,9}
while True:
try:
num = int(input("Ingrese un numero: "))
if num == -1:
break
conjunto.remove(num)
print(conjunto)
except KeyError:
print("Ese numero ya se eliminó")
main3() |
7dc63c84ccc58f3bf4bf239bf7a7ddb11165b31d | charlesfracchia/SDIP-Arduino | /demo2/send_time_to_arduino.py | 3,312 | 3.765625 | 4 | '''
Receives OBMP data from Arduino and prints to the screen.
Sends the current time to the Arduino to sync timestamps for OBMP.
Instructions:
1) First run the Arduino code: e.g., OBMPduino_demo1_v2
2) Then run this script via
python send_time_to_arduino.py
3) Follow the instructions printed to the terminal
4) Once you've set up the serial connection, the terminal should start printing OBMP with the correct start-time and relative time values
'''
import os
import serial
from serial.tools import list_ports
import time
import calendar
import json
TIME_HEADER = "T" # Header sent to Arduino with time-sync signal
TIME_REQUEST = 7 # ASCII bell character
def main():
'''Determine the serial port to communicate with'''
print "Which of these serial ports is the Arduino attached to?"
ports = list_serial_ports()
for i in range(len(ports)): # display the list of ports to the command line for the user
print str(i) + " : " + ports[i]
var = raw_input("Enter the number as 0 to N-1 where N is the number of serial ports: ")
port = ports[int(var)]
print port
ser = serial.Serial(port, 19200) # establish a serial connection at 19200 baud rate
'''Receive output from Arduino. If a time sync request, send the current time.
Otherwise, process successive lines of output as JSON object, pretty-printing them to the command line.'''
line = ""
while(True):
c = ser.read() # read a single character from the serial port
if ord(c) == TIME_REQUEST: # do a time sync
# Greenwich mean time
gmtime_in_seconds = calendar.timegm(time.gmtime()) # Greenwich mean time in seconds
time_str = TIME_HEADER + str(gmtime_in_seconds) + "\n" # time-sync response string to send to arduino
ser.write(time_str) # print time_str
else: # echo the serial port if it's not doing a time sync
if c == "\n": # check for the end of a line
if line[0] == "{": # this is a crude sanity-check test for correct JSON
j = json.loads(line) # convert string to JSON objsect
s = json.dumps(j, sort_keys=False, indent=4, separators=(',', ': ')) # pretty print JSON object as string
print s
print "\n"
else: # ignore input that fails crude sanity-check test for correct JSON
# print line
# print "\n"
pass
line = "" # start building up a new line of text from the serial input
else:
line += c # add the most-recently received character from the serial port to the line of text
'''Find all available serial ports on the computer. The Arduino will show up as a serial port.'''
def list_serial_ports():
# Windows
if os.name == 'nt':
# Scan for available ports.
available = []
for i in range(256):
try:
s = serial.Serial(i)
available.append('COM'+str(i + 1))
s.close()
except serial.SerialException:
pass
return available
else:
# Mac / Linux
return [port[0] for port in list_ports.comports()]
if __name__ == '__main__':
main() |
06d7e7b95f2c78c2f84dcafc0522f002229b0e5b | Mayuri0612/Data_Structures-Python | /Dynamic/uglyNum.py | 1,067 | 4.1875 | 4 | # ugly umber are those numbers which is inly divisible by 2,3 and 5
# Function to get the nth ugly number
def getNthUglyNo(n):
ugly = [0] * n # To store ugly numbers
# 1 is the first ugly number
ugly[0] = 1
# i2, i3, i5 will indicate indices for 2,3,5 respectively
i2 = i3 =i5 = 0
# set initial multiple value
nextmul2 = 2
nextmul3 = 3
nextmul5 = 5
# start loop to find value from ugly[1] to ugly[n]
for l in range(1, n):
# choose the min value of all available multiples
ugly[l] = min(nextmul2, nextmul3, nextmul5)
# increment the value of index accordingly
if ugly[l] == nextmul2:
i2 += 1;
nextmul2 = ugly[i2] * 2
if ugly[l] == nextmul3:
i3 += 1;
nextmul3 = ugly[i3] * 3
if ugly[l] == nextmul5:
i5 += 1;
nextmul5 = ugly[i5] * 5
return ugly[-1]
def main():
n = int(input());
print(getNthUglyNo(n) )
if __name__ == '__main__':
main() |
196db266b6a98c691175b8cb448961355e045245 | jamesro/Project-Euler | /Problem09.py | 588 | 4.3125 | 4 | """
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
def PythagoreanTriplet(product):
for i in range(1,999):
for j in range(1,999):
for k in range(1,999):
if (i + j + k == product):
if ((i**2 + j**2) == k**2):
return (i*j*k)
break
if __name__ == "__main__":
print(PythagoreanTriplet(1000)) |
0e5311b73b1dbc2e57263ddf3091fa5e00b1e75b | shander3377/virtual_Atm | /Atm.py | 1,002 | 3.875 | 4 | class atm(object):
def __init__(self, cardnumber, pin):
self.cardnumber = cardnumber
self.pin = pin
def checkBlance(self):
print("You have 3lakh money in ur bank account")
def withdraw(self, amount):
newAmount = 300000-amount
print("Your have withdrawn " + str(amount) + " inr From you bank balance, Your remaining bank balace is: " + str(newAmount))
def main():
cardNumber = input("Type your card number: ")
pinNumber = input("Type your pin number: ")
new_user = atm(cardNumber, pinNumber)
print("What you want to do?")
print("1. Check Blance 2.withdraw money")
print("type 1 or 2")
act = int(input("Enter your activity: "))
if(act==1):
new_user.checkBlance()
elif (act==2):
ammount = int(input("Enter amount to withdraw: "))
new_user.withdraw(ammount)
else:
print("Enter a valid activity number")
if __name__ == "__main__":
main()
|
cf15c9c50c4b04850a4d9ea75fd36206e0862c45 | devesh-bhushan/python-assignments | /assignment-5/Q-6 commonElements.py | 615 | 3.96875 | 4 | """
program to count the common elements in the string
"""
lst = list([])
element = int(input("enter the no of elements in the list 1 - "))
for i in range(element):
data = eval(input("enter the data in the list 1 - "))
lst.append(data)
lst2 = list([])
element2 = int(input("enter the no of elements in the list 2 - "))
for i in range(element2):
data2 = eval(input("enter the data in the list 2 - "))
lst2.append(data2)
count = 0
for i in range(element):
for j in range(element2):
if lst[i] == lst2[j]:
count += 1
print("the number of similar elements in the list are", count) |
05a210942870fc404146d68b67ad0112e36f71fe | Denisss21/Denis.k | /concatenation.py | 181 | 4.15625 | 4 | print("Hi, today you are studying what's this concatenation")
a = str(input("Enter the first word: "))
b = str(input("Enter the second word: "))
print("Result is: ")
print(a+' '+b)
|
2ee2bf74517462d8f1af667ebe770b245212d910 | Lgt2x/PPC-Projet | /market_simulation/server_utils/city.py | 1,810 | 3.53125 | 4 | """
City object, to simulate a bunch of houses consuming electricity
"""
from multiprocessing import Barrier
from random import randint, random
from colorama import Fore, Style, Back
from .serverprocess import ServerProcess
from .home import Home
from .sharedvars import SharedVariables
class City(ServerProcess):
"""
City object, used to simulate a group of electricity-consuming houses
Basically creates a bunch of home processes
"""
def __init__(
self,
shared_variables: SharedVariables,
ipc_key_houses: int,
nb_houses: int,
average_conso: int,
max_prod: int,
):
super().__init__(shared_variables)
self.nb_houses = nb_houses
# once all the houses has called the barrier, we just need the city's call
self.home_barrier = Barrier(self.nb_houses + 1)
self.homes = [
Home(
house_type=randint(1, 3), # type of house
ipc_key=ipc_key_houses,
home_barrier=self.home_barrier,
weather_shared=shared_variables.weather_shared,
average_conso=average_conso,
prod_average=int(max_prod * random()),
pid=home_pid + 1, # can't be null
)
for home_pid in range(self.nb_houses)
]
print(
f"\nStarting city with {Fore.BLACK}{Back.WHITE}{self.nb_houses}{Style.RESET_ALL} houses"
)
for home in self.homes:
home.start()
def update(self):
"""
For the update phase, the city
"""
self.home_barrier.wait()
def kill(self) -> None:
"""
Kills softly the process
"""
print(f"{Fore.RED}Stopping city{Style.RESET_ALL}")
super().kill()
|
8e9fdbdb19c30e506c62147408202d82f85fbcb3 | sai-pher/Programming_Basics_in_Python | /resources/tool_kits/M3_Tool_Kit.py | 2,445 | 4.28125 | 4 | # TODO: Write Milestone 3 tool kit
from typing import List, Tuple
class Person:
# Instance variable type annotations.
# These do not define the variable, only provide a suggestion for what the type should be
# to allow the developer to know how to work with the variable.
#
# This also allows us to "predefine" our instance variables
# and gives our code clearer structure
__contact: List[Tuple[str, int]]
__name: str
__age: int
__gender: str
# Constructor definition with type annotation for clarity
def __init__(self, name: str, age: int, gender_num: int):
"""
The constructor method for the person class to instantiate a new person object.
:param name: The name of a given person
:param age: The age of a given person
:param gender_num: An int indicating the gender of a new person.
0 is female, 1 is male, and all else is other.
"""
self.__name = name
self.__age = age
if gender_num == 0:
self.__gender = "female"
elif gender_num == 1:
self.__gender = "male"
else:
self.__gender = "other"
self.__contacts = list()
def get_age(self):
return self.__age
def get_gender(self):
return self.__gender
def add_contact(self, name: str, number: int):
self.__contacts.append((name, number))
def show_contacts(self) -> str:
"""
Method to show contacts of each person object.
:return: A list of the contacts as a string.
"""
if self.__contacts.__len__() == 0:
return "Sorry. i have no contacts."
else:
contacts = ""
for contact in self.__contacts:
contacts += "{} : {}\n".format(contact[0], contact[1])
return "My contacts are:\n{}".format(contacts)
# ==================================================================
group = list()
def add_person(group_list, name, age, gender):
new_person = Person(name=name, age=age, gender_num=gender)
group_list.append(new_person)
def avg_age(group_list):
sums = 0
for i in group_list:
sums += i.get_age()
avg = sums / len(group_list)
return avg
add_person(group, "red", 10, 0)
add_person(group, "rde", 12, 0)
add_person(group, "ree", 14, 1)
add_person(group, "rdd", 17, 1)
print(avg_age(group))
|
d6394fbaeb6c067f56afc3ae057e0492dc76a9f5 | mronowska/python_code_me | /zadania_na_zajeciach/zad8.py | 297 | 3.921875 | 4 | lista_for = []
lista_while = []
#for
for i in range (0, 101):
if i % 3 == 0 and i % 2 == 0:
print(i)
lista_for.append(i)
#while
i = 0
while i <= 100:
if i % 2 == 0 and i % 3 == 0:
print(i)
lista_while.append(i)
i += 1
print(lista_for == lista_while) |
d5697a757422776a49ed4378692a3bac6c8c61fa | htmlfarmer/valua | /csv.py | 823 | 3.625 | 4 | # https://www.geeksforgeeks.org/xml-parsing-python/
import csv
def saveFile(filename, url):
# url of rss feed
url = 'http://www.hindustantimes.com/rss/topnews/rssfeed.xml'
# creating HTTP response object from given url
resp = requests.get(url)
# saving the xml file
with open('topnewsfeed.xml', 'wb') as f:
f.write(resp.content)
def savetoCSV(newsitems, filename):
# specifying the fields for csv file
fields = ['guid', 'title', 'pubDate', 'description', 'link', 'media']
# writing to csv file
with open(filename, 'w') as csvfile:
# creating a csv dict writer object
writer = csv.DictWriter(csvfile, fieldnames=fields)
# writing headers (field names)
writer.writeheader()
# writing data rows
writer.writerows(newsitems) |
c304be6542e39edc6b73ceb321135dfb4e9ccd94 | swapnilshinde367/python-learning | /for_loop.py | 727 | 4.1875 | 4 | # pylint: skip-file
# for loop, use of else in for loop
arrstrName = 'Swapnil'
for strLetter in arrstrName :
print strLetter
arrstrFruitNames = [ 'Mango', 'Apple', 'Guava', 'Jackfruit' ]
for strFruitName in arrstrFruitNames :
print strFruitName
# For index
arrstrFruitNames = [ 'Mango', 'Apple', 'Guava', 'Jackfruit' ]
for intIndex in range( len( arrstrFruitNames ) ) :
print arrstrFruitNames[intIndex]
# Use of else: Else in for loop will be called when the all the iterations are completed it cannot enter the if condition
for intI in range( 10, 20 ) :
for intJ in range( 2, intI ) :
if( 0 == intI % intJ ) :
print '%d = %d * %d' % ( intI, intJ, intI/intJ )
break
else :
print str( intI ) + ' is prime' |
21eebb17417a82d13c51e2f744279daea1f76d32 | lcacciagioni/hackerrank | /algorithms/warmup/diagonaldifference/diagonaldifference.py | 664 | 3.78125 | 4 | #!/usr/bin/env python3
# This script will try to solve the problem described in:
# https://www.hackerrank.com/challenges/diagonal-difference
def diag_diff(matrix, size):
sum_first_diag = 0
sum_second_diag = 0
for i in range(size):
for j in range(size):
if i == j:
sum_first_diag += int(matrix[i][j])
sum_second_diag += int(matrix[i][-(j+1)])
result = abs(sum_first_diag - sum_second_diag)
return result
if __name__ == '__main__':
N = int(input())
input_matrix = list()
for _ in range(N):
input_matrix.append(list(input().split()))
print(diag_diff(input_matrix, N)) |
5d955bec5b68b472f4b4d4bc51509d1accd84877 | RuslanaGural/python_labs | /Gural_Task_4-2.py | 379 | 3.546875 | 4 | #Створення прикладних програм на мові Python. Лабораторна робота № 4.2. Гураль Руслана. FI-9119
import math
print('''' Створення прикладних програм на мові Python. Лабораторна робота №4.2
Гураль Руслана. FI-9119''')
x = int(input('x = '));
y = int(math.log10(x) + 1);
print('y = ', y);
|
fb3fff8c948adb2a63db1f0a6f53d4b852e25ab9 | jjloftin/cs303e | /combos.py | 233 | 3.65625 | 4 | def subsets(a,b,lo):
hi = len(a)
if(lo == hi):
print(b)
return
else:
c = b[:]
b.append(a[lo])
subsets(a,c, lo + 1)
subsets(a,b, lo + 1)
def main():
a = ['a', 'b', 'c']
b = []
subsets(a,b,0)
main() |
6118a5a6f4d4aac127cfd4883e553dc04ef68088 | aasparks/cryptopals-py-rkt | /cryptopals-py/set1/c4.py | 1,745 | 3.5 | 4 | """
**Challenge 4**
*Detect single-character XOR*
One of the 60-character strings in this file has been encrypted by
single-character XOR. Find it.
"""
import c1, c2, c3
import unittest
DEBUG = False
## It'll be a little slow but I think the best approach
## here will be running challenge3 on all 60 lines.
def detect_xor(file):
"""
Finds the line that is encrypted with single byte XOR
Args:
file: The file to read lines from
Returns:
The pair containing the line from the file that was detected, and the
decryption key for it.
"""
best_score = 0
best_key = 0
best_ct = 0
idx = 0
for line in file:
idx += 1
ct = c1.hextoascii(line.strip())
key = c3.single_byte_xor(ct)
pt = c2.xorstrs(ct, bytes([key]) * len(ct))
scr = c3.score(pt)
if DEBUG:
print('Line: ' + str(idx))
print('Key: ' + str(key))
print('PT: ' + str(pt))
print('Score: ' + str(scr))
# Single byte XOR should return a key of 0 when the ciphertext is not
# XOR encrypted. Thus we should be able to stop as soon as we get a key
# that is not 0.
if scr > 0:
return ct, key
raise RuntimeException('no suitable line found')
class TestDetectXOR(unittest.TestCase):
def setUp(self):
self.file = open('../../testdata/4.txt')
def tearDown(self):
self.file.close()
def test_challenge_4(self):
ct, key = detect_xor(self.file)
pt = c2.xorstrs(ct, bytes([key]) * len(ct))
self.assertEqual(key, 53)
self.assertEqual(pt, b'Now that the party is jumping\n')
if __name__ == "__main__" :
unittest.main()
|
ec0bc00a7411b98e8519df2ac816c19e93a2cab4 | Sarthak-Singhania/Work | /Class 11/untitled8.py | 247 | 3.640625 | 4 | def search(l,n,x):
for i in range (n):
if l[i]==x:
return i
return -1
a=[2,3,10,40,4]
l=sorted(a)
x=10
n=len(l);
result=search(l,n,x)
if result==-1:
print('Not found')
else:
print('Found',x,'at',result+1) |
979b1f505a3dc5aba934e5cf5f7dbcbffd989025 | adambjorgvins/pricelist | /flights.py | 653 | 3.875 | 4 |
def check_grade(grades:int):
grade = []
sum_of_grades = sum(grade)
if sum_of_grades / len(grades) < 5:
return False
else:
return True
def read_line(line):
name_grade = line.strip().split(" ")
name = name_grade[0]
grade = name_grade[1:]
pass_fail = check_grade(grade)
if pass_fail:
return name[True]
else:
return name[False]
def read_file(file_name):
with open(file_name, "r", encoding="utf-8") as dataFile:
for line in dataFile:
read_line(line)
def main():
file = input("Enter file")
read_file(file)
main() |
b098997ee60f7fa1039fa9b66c2d34b17bb141dd | MarcBalle/MUSI | /AIV/Flujo_optico/Ejercicio3/main.py | 4,991 | 3.515625 | 4 | ## EJERCICIO 3 - EYE TOY ##
## Marc Balle Sánchez ##
## Se desarrolla un programa que, empleando la cámara integrada en el ordenador, permite la interacción
## con una pelota flotante en la pantalla a través del movimiento corporal.
## Cada vez que la pelota sea golpeada, esta cambiará de color y se desplazará hacia abajo.
## Para considerar que la pelota ha sido golpeada, el movimiento de golpeo debe poseer una magnitud mayor
## a un determinado umbral. De esta forma se evita que cualquier movimiento ínfimo interaccione con la
## pelota.
## Cuando la pelota golpee alguno de los límites de la pantalla, esta aparecerá en algún punto aleatorio
## y se moverá con una dirección y velocidad aleatoria.
## Se recomienda no hacer movimientos bruscos e interaccionar principalmente con las manos.
## Pulsar la tecla 'q' para finalizar
import time
import numpy as np
import cv2 as cv
## movimiento de la pelota con la ecuación de movimiento rectilíneo uniforme (MRU)
def movement (x,y,vx,vy,t,shape):
if x >= shape[0] or x <= 0 or y >= shape[1] or y<=0: #si toca un límite
return np.random.randint(0,shape[0]+1), np.random.randint(0,shape[1]+1), np.random.randint(-20,20), np.random.randint(-20,20) # x, y, vx, vy
x_new = x + vx*t #MRU
y_new = y + vy*t
return int(x_new), int(y_new), vx, vy
#def event(color):
# color = np.random.randint(0, 255, (1, 3))
# return tuple(map(tuple, color))[0]
# función que maneja la interacción con la pelota
def interaction (diff, LK_p, cen, thresh = 20):
#diff = vector movimiento del cuerpo respecto la malla estática
# LK_p = puntos devueltos por calcOpticalFlowPyrLK
# cen = centro del círculo
# thresh = umbral mínimo para considerar un movimiento como significativo.
diff = diff.reshape((diff.shape[0], 2))
diff_norm = np.linalg.norm(diff, axis = 1) # norma del vector movimiento
filt = np.where(diff_norm > thresh, True, False) # solo movimiento con norma o magnitud mayor a thresh
LK_p_filt = LK_p.reshape((LK_p.shape[0],2))[filt] #filtramos los movimientos
return (LK_p_filt.astype(int) == cen).any() # si algún movimiento coincide con el centro de la pelota, return True
# LK parameters
lk_params = dict( winSize = (25,25), # tamaño adecuado al problema.
maxLevel = 2,
criteria = (cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 10, 0.03))
cap = cv.VideoCapture(0) # se abre al cámara
ret, old_frame = cap.read() # se lee el primer frame
old_gray = cv.cvtColor(old_frame, cv.COLOR_BGR2GRAY) # se pasa a escala de grises
height, width = old_gray.shape # se guardan las dimensiones del frame
grid = np.dstack(np.meshgrid(np.arange(width, step = 20), np.arange(height, step = 20))).reshape((-1,1,2)) #se crea la malla sobre la que se calcula el flujo
color = np.random.randint(0,255,(grid.shape[0] + 50,3)) #colores para la malla (en caso de querer visualizarla)
# parámetros iniciales de la pelota
x = int(width/2) #centro de la pantalla
y = int(height/2)
vx = 20
vy = 15
color_ball = (255,0,0)
while(True):
start = time.time() # necesario para calcular un delta del tiempo, para el movimiento de la pelota según MRU
ret, frame = cap.read() # se lee el siguiente frame
mask = np.zeros_like(frame) # se renueva la máscara cada vez (con fines de representar el flujo, si se desea)
frame_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) # frame a escala de grises
# calculate optical flow
p1, st, err = cv.calcOpticalFlowPyrLK(old_gray, frame_gray, grid.astype('float32'), None, **lk_params) # se calcula el flujo
##############################
# Si se quiere dibujar las lineas de flujo sobre la malla, descomentar esta parte y cambiar frame por img en cv.circle y cv.imshow
#for i, (new, old) in enumerate(zip(p1, grid)):
# a, b = new.ravel()
# c, d = old.ravel()
# mask = cv.line(mask, (a, b), (c, d), color[i].tolist(), 2)
#img = cv.add(frame, mask)
##############################
cv.circle(frame, center = (x,y), radius = 40, color = color_ball, thickness= -1) # se dibuja la pelota
if interaction(p1-grid, p1, np.array([x,y]), 20): #se analiza si hay interacción
# cambio de color de la pelota
color_ball = np.random.randint(0, 255, (3,))
color_ball = (int(color_ball [0]), int(color_ball [1]), int(color_ball [2]))
color_ball = tuple(color_ball)
#cambio de posición de la pelota
x = x +50
y = y +50
# Se actualiza el frame anterior al actual
old_gray = frame_gray.copy()
# Se muestra por pantalla el frame
cv.imshow('frame',frame)
if cv.waitKey(30) & 0xFF == ord('q'): # finaliza
break
end = time.time() # necesario para el cálculo del delta del tiempo
# se actualiza la posición y velocidad de la pelota
x, y, vx, vy = movement (x,y,vx,vy,start-end, (width, height)) # start - end = delta del tiempo
cap.release()
cv.destroyAllWindows() |
aa6d64a031e1925a7bfeef2016bcd53b7fc94936 | pflun/advancedAlgorithms | /rotateArray.py | 426 | 3.96875 | 4 | # multiple rotate: https://mnmunknown.gitbooks.io/algorithm-notes/content/522_string.html
class Solution(object):
def rotate(self, nums, k):
second = nums[k:]
second.extend(nums[:k])
return second
def rotate2(self, nums, k):
i = 0
while i < k:
nums.append(nums.pop(0))
i += 1
return nums
test = Solution()
print test.rotate([1,2,3,4,5,6,7], 3) |
5a20183c03a95bef104778255bf486dd6a42b14d | SeelamVenkataKiran/PythonTests | /Pandas/Test40p.py | 3,124 | 4.03125 | 4 | import pandas as pd
import numpy as np
#x = pd.read_csv("I:\\GitContent\\Datasets\\Bank_full.csv")
#reading from web to create dataframe
x = pd.read_csv('https://raw.githubusercontent.com/ajaykuma/Datasets/master/Bank_full.csv')
df = pd.DataFrame(x)
print(df.columns)
print(x.values)
df[df.age > 80]
df[df.age > 80].education
df[df.age > 80].education.unique()
df.mean()
df.median()
df.mode(axis=1)
df.mode(axis=0)
df[(df.age > 80) & (df.marital=='married')]
df[(df.age > 80) & (df.marital=='married')].sort_values('balance',ascending=False)
df[(df.age.isin(['82','15','17','35']))].head()
df.groupby(['age','y']).size()
df.groupby(['age','y']).size()
#count displays number of non-null/NAN values
df.groupby(['age','y']).count()
#If we want to use different fields for sorting, or DESC instead of ASC
# we want to sort by our calculated field (size), this field needs to become part of
# the DataFrame. After grouping in Pandas, we get back a different type, called
# a GroupByObject.
# So we need to convert it back to a DataFrame. With .reset_index(), we restart
# row numbering for our data frame.
df.groupby(['marital', 'y']).size().to_frame('size').reset_index().sort_values(['marital', 'size'], ascending=[True, False])
#additionally filter grouped data using a HAVING condition. In Pandas,
# you can use .filter() and provide a Python function (or a lambda)
# that will return True if the group should be included into the result.
df[df.marital == 'married'].groupby('y').filter(lambda g: len(g) > 1000) \
.groupby('y').size().sort_values(ascending=False)
#creating new df
df1 = df.groupby(['age','y']).count()
#now getting top N records
df1.nlargest(10, columns='marital')
#getting the next 10 after the top 10
df1.nlargest(20, columns='marital').tail(10)
df[df.y == 'yes'].agg({'age':['mean']})
df.groupby('y').agg({'age':['mean']})
#Use .merge() to join Pandas dataframes. You need to provide which columns to join on
# (left_on and right_on), and join type: inner (default),
# left (corresponds to LEFT OUTER in SQL), right (RIGHT OUTER),
# or outer (FULL OUTER).
df2 = df[(df.age.isin(['82','15','17','35']))]
df2.merge(df[df.y == 'yes'][['age']], left_on='age', right_on='age', how='inner')[['age','marital','y']]
pd.concat([df[df.y == 'no'][['age', 'job','balance']], df[df.y == 'yes'][['job', 'contact']]])
#if inserting (via concat)
df1 = pd.DataFrame({'id': [1, 2], 'name': ['Harry ', 'Ron ']})
df2 = pd.DataFrame({'id': [3], 'name': ['Peter']})
df3 = pd.concat([df1, df2]).reset_index(drop=True)
df3
df.to_csv(...) # csv file
df.to_hdf(...) # HDF5 file
df.to_pickle(...) # serialized object
df.to_sql(...) # to SQL database
df.to_excel(...) # to Excel sheet
df.to_json(...) # to JSON string
df.to_html(...) # render as HTML table
df.to_feather(...) # binary feather-format
df.to_latex(...) # tabular environment table
df.to_stata(...) # Stata binary data files
df.to_msgpack(...) # msgpack (serialize) object
df.to_gbq(...) # to a Google BigQuery table.
df.to_string(...) # console-friendly tabular output.
df.to_clipboard(...) # clipboard that can be pasted into Excel
|
d2089fc8cabdb12fad6bffd289f830c4c34e5f3e | python-for-humanists-penn/Python_for_Humanists_Working_Group | /2_19_2018/Florian_activity_for_2_19_2018.py | 917 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 19 13:11:03 2018
@author: florian
"""
"""
Activity - Using what we just learned, first, write a method
that prints the first 500 characters from your text.
Then, break those 500 characters into a list of lines.
"""
# solution:
def first_500_characters():
import os
import codecs
os.chdir("C:\\Users\\florian\\Desktop\\Penn_DH_2017\\Python for Humanists\\Python for Humanists Working Group\\2_11_2018")
f = codecs.open('Kleist', 'r', 'utf-8')
characters = f.read()
print(characters[:500])
first_500_characters()
characters[:500].splitlines()
# ctrl + 4 = commenting out:
#==============================================================================
# text
# text
#==============================================================================
|
35a58f6da9a484ef52faf39ddcc92e4a86e92ef1 | mythopoeic/Python | /Hacker Rank/namedtuple.py | 265 | 3.890625 | 4 | from collections import namedtuple
N = int(raw_input())
Students = namedtuple('Students',raw_input())
mySum = 0
for i in range(N):
grade = Students(*raw_input().strip().split())
mySum += int(grade.MARKS)
average = mySum/float(N)
print "%.2f" % average |
ef310c2ca36c047cbbc8ce38850ed3395bf53a6b | gschen/sctu-ds-2020 | /1906101019-贾佳/Day0529/lab01.py | 1,872 | 4.0625 | 4 | class Node():
#构造函数
def __init__(self,data):
#定义属性
self.data = data
self.next = None
# n1 n2 n3
n = Node(-1)
n1 = Node(1)
print(n1.data)
print(n1.next)
n2 = Node(2)
n3 = Node(3)
#n1 -> n2 -> n3
n1.next = n2
n2.next = n3
print(n1.next.next.data)
#单链表
#增加一个结点,删除一个结点,查找等操作/函数
class LinkList():
#1、单链表的构造函数
def __init__(self):
#属性
self.head = Node(-1)
# 2.1.头插法操作
def headInsert(self):
head = self.head
#head -> q
q = Node(1)
head.next = q
#head ->2 -> 1
q = Node(2)
q.next = head.next
head.next = q
#head -> 3 -> 2 -> 1
q = Node(3)
q.next = head.next
head.next = q
#2.2、头插法的改进
def headInsertV2(self):
head = self.head
for i in range(1,101):
q = Node(i)#构造一个新节点,数据域为i
q.next = head.next
head.next = q
# 3.打印所有节点
def printList(self):
p = self.head
#若不打印头节点 p = self.head.next
while p != None:
print(p.data)
p = p.next
# 4.1 尾插法
def tailInsert(self):
#始终使用p来表示单链表的尾结点
p = self.head
q = Node(1)
p.next = q
p = q # 当前链表的尾节点变为了q
q = Node(2)
p.next = q
p = q
q = Node(3)
p.next = q
p = q
# 4.2 尾插法改进版
def tailInsertV2(self):
p = self.head
for i in range(1,101):
q = Node(i)
p.next = q
p = q
List = LinkList()
List.tailInsert()
List.printList()
|
135792b96beaca673e3799c8c0fde6fbdd813833 | Pypy233/python | /homework/static_end/1/problem.py | 409 | 3.609375 | 4 | class Solution():
def solve(self, A):
return [i for i in A if self.prime(i)]
#judge whether x is prime or not
def prime(self, x):
if x == 1 or x == 2 or x == 3:
return True
if x == 4:
return False
if x <= 0:
return False
for i in range(2, x/2):
if x % i == 0:
return False
return True |
3d7914c52eb9a1b6bc43f05cb34649b2c1ed6782 | ati-ozgur/course-python | /2022/examples-in-class-2022-09-16/example_if_wrong2.py | 203 | 3.671875 | 4 | born_year = 2010
# indentation is mixed tabs and spaces are used together
# it will not work
if born_year > 1997:
print("You have born in 1998 or greater")
print("You have born in 1998 or greater") |
bd154e75fb79591d69162290cb93aa372b402fdc | nvnavaneeth/3D-segmentation-visualizer | /utils.py | 954 | 3.5 | 4 | import numpy as np
from matplotlib import pyplot as plt
import nibabel
COLORMAP = [(0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1)]
def load_img(file_path):
"""
Reads a nifty image volume and returns it as a numpy array.
Output dimensions: [depth, y, x]
"""
img = nibabel.load(file_path).get_data()
return img.transpose(2,0,1)
def color_code_segmentation(seg_map):
"""
Converts segmentation map to an RGB image with a unique color for each
label.
"""
# Stack the segmentation map to form 3 channels.
color_seg = np.stack((seg_map, seg_map, seg_map), axis = 3)
labels = np.unique(seg_map)
for i in range(len(labels)):
color_seg[seg_map == labels[i]] = COLORMAP[i]
return color_seg
def min_max_normalize(arr):
"""
Scales all values of 'arr' to the range [0,1]
"""
min_val = np.min(arr)
max_val = np.max(arr)
return (arr- min_val)/ (max_val - min_val)
|
e2ac2c818ac4a7e03d31326c119fe1c279f51ab2 | neilaronson/fraud_detection_case_study | /data_cleaning_with_os.py | 6,249 | 3.5625 | 4 | import pandas as pd
import numpy as np
from sklearn.preprocessing import scale
from sklearn.model_selection import train_test_split
from itertools import izip
class DataCleaning(object):
"""An object to clean and wrangle data into format for a model"""
def __init__(self, filepath, training=True):
"""Reads in data
Args:
fileapth (str): location of file with csv data
"""
self.df = pd.read_json(filepath)
self.df['fraud'] = self.df['acct_type'].isin(['fraudster_event', 'fraudster', 'fraudster_att'])
Y = self.df.pop('fraud').values
X = self.df.values
cols = self.df.columns
X_train, X_test, y_train, y_test = train_test_split(X, Y, train_size=.8, random_state=123)
self.training = pd.DataFrame(X_train, columns=cols)
self.y_train = self.training['fraud']
self.test = pd.DataFrame(X_test, columns=cols)
self.y_test = self.test['fraud']
if training:
self.df = self.training
else:
print "using test data"
self.df = self.test
def make_target_variable(self):
"""Create the churn column, which is our target variable y that we are trying to predict
A customer is considered churned if they haven't taken trip in last 30 days"""
self.df['last_trip_date'] = pd.to_datetime(self.df['last_trip_date'])
self.df['Churn'] = (self.df.last_trip_date < '2014-06-01').astype(int)
def dummify(self, columns):
"""Create dummy columns for categorical variables"""
dummies = pd.get_dummies(self.df[columns], prefix=columns)
self.df = self.df.drop(columns, axis=1)
self.df = pd.concat([self.df,dummies], axis=1)
def drop_date_columns(self):
"""Remove date columns from feature matrix, avoid leakage"""
self.df.drop('last_trip_date', axis=1, inplace=True)
self.df.drop('signup_date', axis=1, inplace=True)
def get_column_names(self):
"""Get the names of columns currently in the dataframe"""
return list(self.df.columns.values)
def cut_outliers(self, col):
"""Remove numerical data more than 3x outside of a column's std"""
std = self.df[col].std()
t_min = self.df[col].mean() - 3*std
t_max = self.df[col].mean() + 3*std
self.df = self.df[(self.df[col] >= t_min) & (self.df[col] <= t_max)]
def drop_na(self):
"""Generic method to drop all rows with NA's in any column"""
self.df = self.df.dropna(axis=0, how='any')
def make_log_no_trips(self):
"""Transform the number of trips column to log scale"""
self.df['log_trips'] = self.df[(self.df['trips_in_first_30_days'] != 0)].trips_in_first_30_days.apply(np.log)
self.df['log_trips'] = self.df['log_trips'].apply(lambda x: 0 if np.isnan(x) else x)
def drop_columns_for_regression(self):
"""Drop one of the dummy columns for when using a regression model"""
self.df = self.df.drop(['phone_iPhone', 'city_Astapor'], axis=1)
def mark_missing(self, cols):
"""Fills in NA values for a column with the word "missing" so that they won't be dropped later on"""
for col in cols:
self.df[col].fillna('missing', inplace=True)
def drop_all_non_numeric(self):
self.df = self.df.head(1000)
self.df = self.df[['fraud', 'body_length', 'channels', 'num_payouts', 'org_twitter']]
#self.df.drop(['approx_payout_date', 'country', ])
def div_count_pos_neg(self, X, y):
"""Helper function to divide X & y into positive and negative classes
and counts up the number in each.
Parameters
----------
X : ndarray - 2D
y : ndarray - 1D
Returns
-------
negative_count : Int
positive_count : Int
X_positives : ndarray - 2D
X_negatives : ndarray - 2D
y_positives : ndarray - 1D
y_negatives : ndarray - 1D
"""
negatives, positives = y == 0, y == 1
negative_count, positive_count = np.sum(negatives), np.sum(positives)
X_positives, y_positives = X[positives], y[positives]
X_negatives, y_negatives = X[negatives], y[negatives]
return negative_count, positive_count, X_positives, \
X_negatives, y_positives, y_negatives
def oversample(self, X, y, tp):
"""Randomly choose positive observations from X & y, with replacement
to achieve the target proportion of positive to negative observations.
Parameters
----------
X : ndarray - 2D
y : ndarray - 1D
tp : float - range [0, 1], target proportion of positive class observations
Returns
-------
X_undersampled : ndarray - 2D
y_undersampled : ndarray - 1D
"""
if tp < np.mean(y):
return X, y
neg_count, pos_count, X_pos, X_neg, y_pos, y_neg = self.div_count_pos_neg(X, y)
positive_range = np.arange(pos_count)
positive_size = (tp * neg_count) / (1 - tp)
positive_idxs = np.random.choice(a=positive_range,
size=int(positive_size),
replace=True)
X_positive_oversampled = X_pos[positive_idxs]
y_positive_oversampled = y_pos[positive_idxs]
X_oversampled = np.vstack((X_positive_oversampled, X_neg))
y_oversampled = np.concatenate((y_positive_oversampled, y_neg))
return X_oversampled, y_oversampled
def clean(self, regression=False):
"""Executes all cleaning methods in proper order. If regression, remove one
dummy column and scale numeric columns for regularization"""
self.drop_all_non_numeric()
self.drop_na()
y = self.df.pop('fraud').values
if regression:
self.drop_columns_for_regression()
for col in ['avg_dist', 'avg_rating_by_driver', 'avg_surge', 'surge_pct', 'trips_in_first_30_days', 'weekday_pct']:
self.df[col] = scale(self.df[col])
X = self.df.values
X_oversampled, y_oversampled = self.oversample(X, y, tp=0.3)
return X_oversampled, y_oversampled
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.