blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
8c50d89d21208b725c0f86b36697d32791223160
John15321/Random
/HackerRank/Python/Basic Data Types/list-comprehensions.py
326
3.609375
4
''' https://www.hackerrank.com/challenges/list-comprehensions/problem ''' if __name__ == '__main__': # Input x = int(input()) y = int(input()) z = int(input()) n = int(input()) print([[xs, ys, zs] for xs in range(0, x+1) for ys in range(0, y+1) for zs in range(0, z+1) if(zs+xs+ys != n)])
56a4f8ba6ee9c1c01ad3baf88510aa8fab1dde46
ikosolapov1983/Homework6
/la_song.py
596
3.828125
4
def la(s=3, count=3, z=0): """ Функция принимает три значения в формате int: s - количество строк count - количество слогов z - знак в конце, если 1 , то выводит "!", во всех остальных случаях "." return возвращает сформированную песню la """ word = 'La' p = (word + '-') * count p = p[:-1] p = (p + '\n') * s if z == 1: p = p[:-1] + '!' else: p = p[:-1] + '.' return p print(la())
b3c4493c7570550f289abd21cf5d5ac92d16bc8e
matveyplevako/adventofcode
/adventofcode2019/day13/second.py
4,582
3.65625
4
from collections import defaultdict from time import sleep SHOW_GAME = False PLAY = False with open("input.txt") as inp: text = dict((ind, elem) for ind, elem in enumerate(inp.read().split(","))) opcodes = defaultdict(int, text) opcodes[0] = '2' def calculate_position(platform_and_ball): platform, ball = platform_and_ball if SHOW_GAME and not PLAY: sleep(0.2) if platform < ball: return '1' elif platform > ball: return '-1' else: return '0' def next_move(platform_and_ball): position = 0 base = 0 while position < len(opcodes): op = opcodes[position] if len(op) > 2: C = int(op[-3]) else: C = 0 if len(op) > 3: B = int(op[-4]) else: B = 0 if len(op) > 4: A = int(op[-5]) else: A = 0 op = int(op[-2:]) if op == 99: break first = int(opcodes[position + 1]) if op == 3: if PLAY: assert SHOW_GAME, "You have to turn screen on" n = input('waiting for input:\n') else: n = calculate_position(platform_and_ball) if C == 0: opcodes[first] = n elif C == 2: opcodes[first + base] = n else: raise Exception('cannot assign value to int') position += 2 elif op == 4: if C == 0: yield opcodes[first] elif C == 2: yield opcodes[base + first] else: yield str(first) position += 2 elif op == 9: if C == 0: base += int(opcodes[first]) elif C == 2: base += int(opcodes[first + base]) else: base += first position += 2 else: if C == 0: first = int(opcodes[first]) if C == 2: first = int(opcodes[first + base]) second = int(opcodes[position + 2]) if B == 0: second = int(opcodes[second]) if B == 2: second = int(opcodes[second + base]) result = int(opcodes[position + 3]) if A == 2: result += base if op == 1: opcodes[result] = str(first + second) if op == 2: opcodes[result] = str(first * second) if op == 7: opcodes[result] = '1' if first < second else '0' if op == 8: opcodes[result] = '1' if first == second else '0' position += 4 if op == 5: if first: position = second else: position -= 1 if op == 6: if not first: position = second else: position -= 1 def main(): grid = defaultdict(lambda: defaultdict(int)) platform_and_ball = [0, 0] gen = next_move(platform_and_ball) x_max, y_max = 0, 0 score = -1 while True: try: # x - from left, y - from top x = int(next(gen)) y = int(next(gen)) x_max = max(x, x_max) y_max = max(y, y_max) tile = int(next(gen)) if tile == 3: platform_and_ball[0] = x if tile == 4: platform_and_ball[1] = x if x == -1 and y == 0: score = tile if SHOW_GAME: print('\n\n') print("SCORE:", score) print('\n\n') continue grid[y][x] = tile if SHOW_GAME: for i in range(int(y_max) + 2): for j in range(int(x_max) + 2): elem = grid[i][j] if elem == 0: print(' ', end='') elif elem == 1: print('#', end='') elif elem == 2: print('.', end='') elif elem == 3: print('—', end='') else: print('*', end='') print() except StopIteration: break print(score) if __name__ == '__main__': main()
594b890e09cb8cf130f02eeb901679e2891289c1
singhpraveen2010/experimental
/poly_point_check.py
2,251
4.28125
4
""" To check if a point P lies within the N sided polygon: Step 1: Area of the polygon = sum of area of N-2 triangles formed by the polygon points. Step 2: Area Covered by P = sum of areas of N triangles formed by P and any two adjasecnt sides of the ploygon. If areas obtain from step 1 and 2 are equal then P lies with the polygon, else outside. """ import sys def area(point_1, point_2, point_3): return abs(point_1[0] * (point_2[1] - point_3[1]) + point_2[0] * (point_3[1] - point_1[1]) + point_3[0] * (point_1[1] - point_2[1])) def get_coordinate(data): l = data.split(",") return tuple([int(c) for c in l]) def check_within(): points = [] c = int(raw_input("Nth sided polygon:: ")) if c > 4 or c < 3: print("Program only works for rectangle and triangles") sys.exit(1) for i in range(c): data = raw_input("Enter the polygon point:: ") point = get_coordinate(data) points.append(point) test_data = raw_input("Enter the point to check:: ") test_point = get_coordinate(test_data) points.append(test_point) if c == 3: poly_area = area(points[0], points[1], points[2]) else: poly_area = area(points[0], points[1], points[2]) + \ area(points[1], points[2], points[3]) while(True): point_area = 0 if c == 3: point_area += area(points[-1], points[0], points[1]) point_area += area(points[-1], points[0], points[2]) point_area += area(points[-1], points[1], points[2]) else: point_area += area(points[-1], points[0], points[1]) point_area += area(points[-1], points[0], points[2]) point_area += area(points[-1], points[1], points[3]) point_area += area(points[-1], points[2], points[3]) if poly_area == point_area: print("Point lies with polygon") else: print("Point does not lies with ploygon") print("Lets check another point") test_data = raw_input("Enter the point to check:: ") test_point = get_coordinate(test_data) points[-1] = test_point def main(): check_within() if __name__ == '__main__': main()
3d654cf6ee4fc428687bd96a4692063860489916
thamilanban-MM/Python-Programming
/Beginner Level/positive and negative.py
170
3.953125
4
a=raw_input("") if a.isdigit(): if (int(a)>0): print("Positive") elif (int(a)<0): print("Negative") else: print("Zero") else: print("enter the invalid number")
f1c2e70d612f11ef5d983d39e2782f4f488f7776
NishKoder/Python-Repo
/Chapter 3/dry.py
515
3.921875
4
# DRY - Dont Repeat YourSelf Principle import random winning_number = random.randint(1, 100) gusse = 1 game_over = False number = int(input("Enter gussing number: ")) while not game_over: # can use break also if number == winning_number: print(f"you win, have guss {gusse}") game_over = True else: if number > winning_number: print("Too High") else: print("Too Low") gusse += 1 number = int(input("Enter gussing again number: "))
4a35eaea491e54ab4e65a6d5a1ce69bd6ad4dba2
cgreggescalante/ads-class-pub-patches
/src/exercises/recursion/recursion_functions.py
564
3.578125
4
#!/usr/bin/env python3 """ `recursion` implementation @author: """ def gcd(a: int, b: int) -> int: """Greatest Common Denominator""" raise NotImplementedError def diamond_ite(levels: int) -> None: """Print a diamond""" raise NotImplementedError def diamond_rec(levels: int) -> None: """Print a diamond""" raise NotImplementedError def hourglass_ite(levels: int) -> None: """Print an hourglass""" raise NotImplementedError def hourglass_rec(levels: int) -> None: """Print an hourglass""" raise NotImplementedError
8b346f4336605d751e603e377ccac10adbfc051c
acheval/python
/lirmm-fr/exercice4.2.1.py
683
3.609375
4
#!/bin/python3 # Reprenez le script et faites que le seuil et la longueur lg soient # saisis (plutôt qu'écrits dans le script) # Déclarer une variable lg dans laquelle vous mémoriser la longueur # d'une ORF d'un ARN print("Enter the value for lg: ") lg = int(input()) # Déclarer une variable seuil dans laquelle vous mémorisez la valeur # 75 print("Enter the value for the threshold: ") seuil = int(input()) # Écriver une structure conditionnelle pour vérifier que lg est # supérieure au seuil et afficher un message "ORF valide" dans ce # cas, et un message "ORF invalide" dans le cas contraire if lg > seuil: print("ORF valide") else: print("ORF invalide")
0cf2d491058e88dd23ad9653a89e85e038826a86
ronin2448/coursera_courses
/discrete_opt_2014/discrete_opt_course/hw1/rulesSolver.py
4,606
3.796875
4
#!/usr/bin/python # -*- coding: utf-8 -*- from collections import namedtuple from operator import attrgetter Item = namedtuple("Item", ['index', 'value', 'weight']) def parse_data(input_data): # parse the input lines = input_data.split('\n') firstLine = lines[0].split() item_count = int(firstLine[0]) capacity = int(firstLine[1]) items = [] for i in range(1, item_count+1): line = lines[i] parts = line.split() items.append(Item(i-1, int(parts[0]), int(parts[1]))) return (capacity, items) def solve_it_orig(input_data): # Modify this code to run your optimization algorithm # parse the input lines = input_data.split('\n') firstLine = lines[0].split() item_count = int(firstLine[0]) capacity = int(firstLine[1]) items = [] for i in range(1, item_count+1): line = lines[i] parts = line.split() items.append(Item(i-1, int(parts[0]), int(parts[1]))) # a trivial greedy algorithm for filling the knapsack # it takes items in-order until the knapsack is full value = 0 weight = 0 taken = [0]*len(items) for item in items: if weight + item.weight <= capacity: taken[item.index] = 1 value += item.value weight += item.weight # prepare the solution in the specified output format output_data = str(value) + ' ' + str(0) + '\n' output_data += ' '.join(map(str, taken)) return output_data def solve_it_via_rules(input_data): # Modify this code to run your optimization algorithm # parse the input (capacity, items) = parse_data(input_data) # a trivial greedy algorithm for filling the knapsack # it takes items in-order until the knapsack is full # value = 0 # weight = 0 # taken = [0]*len(items) # # sortedItemList = sorted(items, key=attrgetter('value'), reverse=True) # print items # print sortedItemList # # for item in sortedItemList: # if weight + item.weight <= capacity: # taken[item.index] = 1 # value += item.value # weight += item.weight # # # prepare the solution in the specified output format # output_data = str(value) + ' ' + str(0) + '\n' # output_data += ' '.join(map(str, taken)) # return output_data # return solve_via_grabbing_most_valuable_items(capacity, items) return solve_via_grabbing_most_useful_items(capacity, items) def solve_via_grabbing_most_valuable_items(capacity, items): value = 0 weight = 0 taken = [0]*len(items) sortedItemList = sorted(items, key=attrgetter('value'), reverse=True) print items print sortedItemList for item in sortedItemList: if weight + item.weight <= capacity: taken[item.index] = 1 value += item.value weight += item.weight # prepare the solution in the specified output format output_data = str(value) + ' ' + str(0) + '\n' output_data += ' '.join(map(str, taken)) return output_data def solve_via_grabbing_most_useful_items(capacity, items): value = 0 weight = 0 taken = [0]*len(items) print items sortedItemList = sorted(items, key= lambda x : ((x.value*1.0)/x.weight)*1.0, reverse=True) print sortedItemList prevValue = -1 for item in sortedItemList: if prevValue == -1: prevValue = (item.value*1.0)/item.weight curVal = (item.value*1.0)/item.weight print curVal if prevValue < curVal: print "ERROR!" else: prevValue =curVal if weight + item.weight <= capacity: taken[item.index] = 1 value += item.value weight += item.weight # prepare the solution in the specified output format output_data = str(value) + ' ' + str(0) + '\n' output_data += ' '.join(map(str, taken)) return output_data def solve_via_DP(capacity, items): output_data = "" return output_data import sys if __name__ == '__main__': file_location = './data/ks_30_0' input_data_file = open(file_location, 'r') input_data = ''.join(input_data_file.readlines()) input_data_file.close() print "Default" print solve_it_orig(input_data) print "My soloution" print solve_it_via_rules(input_data)
cfa688cd74a69dcbd9fe083c67b7771de9b137c4
PrawahK/ye-le-bro
/beginnerapp.py
2,038
3.671875
4
# Imports required import json import pandas as pd final_data = {'label': '', 'id': '', 'link': '', 'children': []} def csv_to_json_convertor(): """This function is to upload the CSV file into the Program""" try: df = pd.read_csv('data.csv') #Reading Csv. except FileNotFoundError: print("File was not found!") df.dropna(how='all', inplace=True) #dropping the null rows df.fillna(0, inplace=True) #Placing 0 where there is empty columns records = df.to_dict('records') # print(records) try: final_data['label'] = records[0]['Level 1 - Name'] final_data['id'] = records[0]['Level 1 - ID'] final_data['link'] = records[0]['Level 1 - URL'] except: print("Root node error.") return level2_ids = [] level3_ids = [] for record in records: if record['Level 2 - ID'] and not record['Level 2 - Name'] == 0 and record['Level 2 - ID'] not in level2_ids: level2_ids.append(record['Level 2 - ID']) final_data['children'].append( {'label': record['Level 2 - Name'], 'link': record['Level 2 URL'], 'id': (record['Level 2 - ID']), 'children': []}) if record['Level 3 - ID'] and not record['Level 3 - Name'] == 0 and record['Level 3 - ID'] not in level3_ids: level3_ids.append(record['Level 3 - ID']) level2_child = next(target for target in final_data['children'] if target["id"] == record['Level 2 - ID']) level2_child['children'].append( {'label': record['Level 3 - Name'], 'link': record['Level 3 URL'], 'id': (record['Level 3 - ID']), 'children': []}) """Dumping the data into Json text format """ with open('struct.json', 'w') as f: json.dump(final_data, f, indent=4) print('Stuct.json file has been created.') print(final_data) print('bye bye') return final_data csv_to_json_convertor()
e6b8b40eda822c168957b06a1e5ba8d423e7a635
Shivvrat/Text-Classification-using-NB-and-LR
/multi_nomial_naive_bayes.py
4,865
3.515625
4
from decimal import Decimal from math import log10 as log def train_multinomial_NB(spam_email_bag_of_words, ham_email_bag_of_words, text_in_all_document, spam_mail_in_all_documents, ham_mail_in_all_documents, size_of_total_dataset, size_of_spam_dataset, size_of_ham_dataset, total_file_dictionary): """ This is the main algorithm to train the multinomial Naive Bayes :param total_file_dictionary: This is the list containing all the words in the training examples :param spam_email_bag_of_words: This is the list of all words in each spam document (1st value is for first document and so on) :param ham_email_bag_of_words: This is the list of all words in each ham document (1st value is for first document and so on) :param text_in_all_document: This is the total text in all documents with their frequencies :param spam_mail_in_all_documents: This is the total text in all spam documents with their frequencies :param ham_mail_in_all_documents: This is the total text in all ham documents with their frequencies :param size_of_total_dataset: This is total number of files in all dataset :param size_of_spam_dataset: This is total number of files in all spam dataset :param size_of_ham_dataset: This is total number of files in all ham dataset :return: prior and conditional probability for both spam and ham(all these values are in log) """ no_of_docs = size_of_total_dataset # We will first do it for the spam no_of_spam_docs = size_of_spam_dataset # We create the variables to store the values prior = {} conditional_probability = {} conditional_probability["spam"] = {} conditional_probability["ham"] = {} conditional_probability_of_non_occurring_word = {} conditional_probability_of_non_occurring_word["spam"] = {} conditional_probability_of_non_occurring_word["ham"] = {} value = Decimal(no_of_spam_docs / float(no_of_docs)) # First we calculate the priors for the spam and ham dataset prior["spam"] = log(value) no_of_ham_docs = size_of_ham_dataset total_number_of_words_in_ham = sum(ham_mail_in_all_documents.itervalues()) prior["ham"] = log(no_of_ham_docs / float(no_of_docs)) total_number_of_words_in_spam = sum(spam_mail_in_all_documents.itervalues()) # Now we calculate the values for the conditional probabilities for each_word in list(spam_mail_in_all_documents): conditional_probability["spam"][each_word] = log((spam_mail_in_all_documents[each_word] + 1) / ( float(total_number_of_words_in_spam + len(text_in_all_document)))) # Now we will do the same procedure for ham docs for each_word in list(ham_mail_in_all_documents): conditional_probability["ham"][each_word] = log((ham_mail_in_all_documents[each_word] + 1) / ( float(total_number_of_words_in_ham + len(text_in_all_document)))) # These are the values for the conditional probabilities whose words are not in the training dataset conditional_probability_of_non_occurring_word["ham"] = log( 1 / (float(total_number_of_words_in_ham + len(text_in_all_document)))) conditional_probability_of_non_occurring_word["spam"] = log( 1 / (float(total_number_of_words_in_spam + len(text_in_all_document)))) return prior, conditional_probability, conditional_probability_of_non_occurring_word def test_multinomial_naive_bayes(prior, conditional_probability, conditional_probability_of_non_occurring_word, an_email_bag_of_words_test): """ :param conditional_probability_of_non_occurring_word: This is the conditional probability for each word in the testing set which is not in the training data :param prior: This is the prior for all classes :param conditional_probability: This is the conditional probability for each word in vocabulary in spam and ham data :param an_email_bag_of_words_test: This is the given test instance we want to classify :return: the class of the given email """ score = {} for each_class in list(prior): score[each_class] = prior[each_class] for each_word in list(an_email_bag_of_words_test): if an_email_bag_of_words_test[each_word] != 0: try: score[each_class] += conditional_probability[each_class][each_word] # This is the case if the word was not in the train data and thus the laplace pruning gives this result except KeyError: score[each_class] += conditional_probability_of_non_occurring_word[each_class] # Here we are taking spam as 1 and ham as -1 if score["spam"] > score["ham"]: return 1 else: return 0
39f5c82349c6cfd7f747d20600e0fbea505beff0
633-1-ALGO/introduction-python-ninotchkanovelle
/12.1- Exercice - Listes et Tableaux/liste1.py
808
3.796875
4
# Problème : Réaliser une table de multiplication de taile 10x10 en utilisant la liste fournie. # Résultat attendu : un affichage comme ceci : 1 2 3 4 5 6 7 8 9 10 # 1 1 2 3 4 5 6 7 8 9 10 # 2 2 4 6 8 10 12 14 16 18 20 # . . . . . . . . . . . # Indication : L'alignement rectiligne n'est pas une contrainte, tant que la table est visible ligne par ligne c'est ok. # Si vous êtes perfectionnistes faites vous plaisir. liste = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] i = 0 n = len(liste) j = 1 somme = 0 while i < n: i= i+ 1 somme=0; while j < n: somme = liste[i]*liste[j] print(somme) j=j+1
8fcde055e710a0680df8dc858b03b2060821ea70
nbiadrytski-zz/python-training
/dive_into_p3/classic_iterator/abstract_aggr_iter.py
742
3.953125
4
import abc class Aggregate(abc.ABC): def iterator(self): """ Returns iterator """ pass class Iterator(abc.ABC): def __init__(self, collection, cursor): self._collection = collection self._cursor = cursor @abc.abstractmethod def first(self): """ Returns iterator to the beginning of Aggregate. Same as reset. """ pass @abc.abstractmethod def next(self): """ Goes to the next element of aggregate. Raises StopIteration when the end of iteration is achieved. """ pass @abc.abstractmethod def current(self): """ Returns current element. """ pass
e516d988442f9a0cec923e637a26e1559150f6b3
noecaserez/Ejercicio-Python
/ejercicios3/ejercicio04.py
923
4.03125
4
""" Ejercicio 4: Crear una función que, a partir de 4 números, devuelva el mayor producto de dos de ellos. Imprimir resultado por pantalla. """ #ejercicio 4 def producto(): producto_numeros = [] for i in range(4): numero = int(input("Ingrese un número: ")) producto_numeros.append(numero) producto_numeros.sort() for num in producto_numeros: if num == 0: producto_numeros.pop(num) producto_mayor = producto_numeros[-2] * producto_numeros[-1] else: producto_mayor = producto_numeros[-2] * producto_numeros[-1] #si le quito el else la funcion da error, porque? print(producto_mayor) producto() """ esta funcion te pide 4 numeros, los ordena en una nueva lista de menor a mayor y los dos ultimos osea los dos mayores son multiplicados en una lista [-2] siendo el -2 el ante ultimo [-1] siendo -1 el índice del último elemento """
85a867614ba9aa64fe90119092f3fb3dc02d4624
beginner-codes/beginnerpy-pypi
/beginnerpy/challenges/daily/c50_circular_shift.py
1,677
3.890625
4
import unittest from typing import List def circular_shift(lst1: List[int], lst2: List[int], n: int) -> bool: return False # Put your code here!!! class TestCircularShift(unittest.TestCase): def test_1(self): self.assertTrue( circular_shift( [1, 2, 3, 4], [3, 4, 1, 2], 2 ) ) def test_2(self): self.assertTrue( circular_shift( [1, 1], [1, 1], 6 ) ) def test_3(self): self.assertFalse( circular_shift( [0, 1, 2, 3, 4, 5], [3, 4, 5, 2, 1, 0], 3 ) ) def test_4(self): self.assertFalse( circular_shift( [0, 1, 2, 3], [1, 2, 3, 1], 1 ) ) def test_5(self): self.assertTrue( circular_shift( list(range(32)), list(range(32)), 0 ) ) def test_6(self): self.assertTrue( circular_shift( [1, 2, 1], [1, 2, 1], 3 ) ) def test_7(self): self.assertTrue( circular_shift( [5, 7, 2, 3], [2, 3, 5, 7], -2 ) ) def test_8(self): self.assertFalse( circular_shift( [1, 2, 3, 4], [3, 4, 1, 2], 1 ) ) if __name__ == "__main__": unittest.main()
437e3c2ae356b9323d58830cc4567d3adf38b228
priscilamarques/pythonmundo1
/desafio10.py
331
4.03125
4
##Desafio 10 #Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos dólares ela pode comprar. #Considerar dólar no valor de 3.27 real = float(input('Quanto de dinheiro vocë tem na carteira: R$ ')) dolar = real/3.27 print('Com R${:.2f} você pode comprar US${:.2f} dolares.'.format(real,dolar))
84bbba243a108cf43ea4e2fa9ae9ec35ba16b15b
rpandey94/Housing-Price_Prediction-Web-Application
/Prediction_application.py
4,356
3.875
4
# Housing price prediction web application import os import joblib import locale import numpy as np import pandas as pd import streamlit as st # Reading data from csv file_path = os.path.join("datasets", "housing") def fetch_data(file_path=file_path): file_path = os.path.join(file_path, "housing.csv") return pd.read_csv(file_path) # Fetching housing data df = fetch_data() # Collecting data ocean_proximity = st.sidebar.selectbox( 'What type of location do you want?', ('NEAR OCEAN', 'NEAR BAY', 'ISLAND', 'INLAND', '<1H OCEAN')) total_rooms = st.sidebar.number_input('Total Rooms (within a block)', 600) total_bedrooms = st.sidebar.number_input('Total Bedrooms (within a block)', 200) housing_median_age = st.sidebar.number_input('Median House Age In Years (within a block)', 1) population = st.sidebar.number_input('Number of people (within a block)', 400) households = st.sidebar.number_input('Total number of households (within a block)', 100) median_income = st.sidebar.number_input('Income Of Households (within a block) (measured in tens of thousands of US Dollars)', 0.4999, 15.0001) # filter on ocean proximity proximity_map = df[df["ocean_proximity"] == ocean_proximity] # Adding a title to the web page st.write(""" # California Housing Price Prediction Web Application ## Housing Blocks on Map """) # Data on Geo Map map_data = proximity_map[["latitude", "longitude"]] st.map(map_data) # Show Raw data and column description if st.checkbox('Show Raw Data And Column Description'): st.write(""" ## The California Housing Price Dataset """) st.write(df) st.write(""" ## Column Descriptions 1. longitude: A measure of how far west a house is; a higher value is farther west 2. latitude: A measure of how far north a house is; a higher value is farther north 3. housing_median_age: Median age of a house within a block; a lower number is a newer building 4. total_rooms: Total number of rooms within a block 5. total_bedrooms: Total number of bedrooms within a block 6. population: Total number of people residing within a block 7. households: Total number of households, a group of people residing within a home unit, for a block 8. median_income: Median income for households within a block of houses (measured in tens of thousands of US Dollars) 9. median_house_value: Median house value for households within a block (measured in US Dollars) 10. ocean_proximity: Location of the house w.r.t ocean/sea """) # Making a map to display location of block for which median price will be predicted st.write(""" ## Make Prediction """) label = list(zip(proximity_map["latitude"], proximity_map["longitude"])) location = st.selectbox('Select From Available Geo Coordinates Of Blocks For Predicting House Price: ', label, index=1) latitude = location[0] longitude = location[1] lst = [location[0]] lst2 = [location[1]] lst = [float(i) for i in lst] lst2 = [float(i) for i in lst2] geo_map = pd.DataFrame(list(zip(lst, lst2)), columns =['latitude', 'longitude']) st.map(geo_map, zoom=5) st.write('Map is showing the location of the block for which prediction will be generated', geo_map) # Making predictions my_model_loaded = joblib.load("Saved_Models/my_model.pkl") if (ocean_proximity == "<1H OCEAN"): ocean_proximity_list = [1, 0, 0, 0, 0] elif (ocean_proximity == "INLAND"): ocean_proximity_list = [0, 1, 0, 0, 0] elif (ocean_proximity == "NEAR OCEAN"): ocean_proximity_list = [0, 0, 1, 0, 0] elif (ocean_proximity == "NEAR BAY"): ocean_proximity_list = [0, 0, 0, 1, 0] elif (ocean_proximity == "ISLAND"): ocean_proximity_list = [0, 0, 0, 0, 1] else: ocean_proximity_list = [0, 0, 0, 0, 0] rooms_per_household = total_rooms / households population_per_household = population / households features = [longitude, latitude, housing_median_age, total_rooms, total_bedrooms, population, households, median_income, rooms_per_household, population_per_household] + ocean_proximity_list features = np.array(features) features = features.reshape(1, -1) prediction = my_model_loaded.predict(features) value = prediction[0] locale.setlocale( locale.LC_ALL, '' ) if st.button('Predict House Price'): st.write("House price is " + str(locale.currency( value, grouping=True ))) st.write(""" ### © Rishav Pandey 2020 """)
aa378a188bce0e97a0545221e65f148838b3650c
angelavuong/python_exercises
/coding_challenges/whats_your_name.py
536
4.1875
4
''' Name: What's Your Name? Task: You are given the first name and last name of a person on two different lines. Your task is to read them and print the following: Hello <firstname> <lastname>! You just delved into python. Sample Input: Guido Rossum Sample Output: Hello Guido Rossum! You just delved into python. ''' def print_full_name(a, b): print("Hello " + a + " " + b + "! You just delved into python.") if __name__ == '__main__': first_name = raw_input() last_name = raw_input() print_full_name(first_name, last_name)
272b35169a8186623afc046957907e556272894d
bartlomiejmusial/EtchASketch
/main.py
971
3.75
4
from turtle import Turtle, Screen from random import choice tim_turtle = Turtle() tim_turtle.color('red') screen = Screen() colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'] def move_forward(): tim_turtle.forward(10) def move_backward(): tim_turtle.backward(10) def turn_left(): tim_turtle.color(choice(colors)) tim_turtle.left(10) def turn_right(): tim_turtle.color(choice(colors)) tim_turtle.right(10) def clear_drawing(): tim_turtle.speed(50) while tim_turtle.pos() != (0, 0): tim_turtle.undo() screen.onkey(key="w", fun=move_forward) screen.onkey(key="Up", fun=move_forward) screen.onkey(key="s", fun=move_backward) screen.onkey(key="Down", fun=move_backward) screen.onkey(key="a", fun=turn_left) screen.onkey(key="Left", fun=turn_left) screen.onkey(key="d", fun=turn_right) screen.onkey(key="Right", fun=turn_right) screen.onkey(key="c", fun=clear_drawing) screen.listen() screen.exitonclick()
581e84c236a90f762f49ab4f7d60270dd174d962
mayaragualberto/Introducao-CC-com-Python
/Parte1/Semana3/Ex2.py
104
4.1875
4
Num=int(input("Digite um número inteiro: ")) Num2=Num%3 if Num2==0: print("Fizz") else: print(Num)
b2c7b6c17aff069b0dce4fa23f71ee9be3b20e3b
CodeHemP/CAREER-TRACK-Data-Scientist-with-Python
/17_Cleaning Data in Python [Part - 2]/1_exploring-your-data/02_further-diagnosis.py
978
4.40625
4
''' Further diagnosis In the previous exercise, you identified some potentially unclean or missing data. Now, you'll continue to diagnose your data with the very useful .info() method. The .info() method provides important information about a DataFrame, such as the number of rows, number of columns, number of non-missing values in each column, and the data type stored in each column. This is the kind of information that will allow you to confirm whether the 'Initial Cost' and 'Total Est. Fee' columns are numeric or strings. From the results, you'll also be able to see whether or not all columns have complete data in them. The full DataFrame df and the subset DataFrame df_subset have been pre-loaded. Your task is to use the .info() method on these and analyze the results. INSTRUCTIONS 50XP -Print the info of df. -Print the info of the subset dataframe, df_subset. ''' # Print the info of df print(df.info()) # Print the info of df_subset print(df_subset.info())
e7f79141b1c99c0cf9cb7ac02035951b8478d89e
kondraschovAV1999/TAU.LAB1
/Week5.py
806
4.28125
4
# Кортежы # myTuple = [1, 2, 3] # Создаем кортеж # print(myTuple[1]) # sTuple = [4, 5, 6] # print(myTuple + sTuple) # print(len(myTuple)) # myTuple = (1, (2, 3), (4,)) # print(myTuple[1][0]) # man = ('Ivan', 'Ivanov', 28) # print(man[-1]) # myTuple = 1, 2, 3 # a, b, c = myTuple # print(b) # Цикл For # a = 1 # b = 2 # a, b = b, a # print(a, b) # Функция range # myRange = range(10) # Правая граница не включается # print(tuple(myRange)) # Команда tuple создает кортеж # for color in ('red', 'green', 'yellow'): # print(color, 'apple') # for i in range(25): # print(i) # for i in range(10, 0, -1): # print(i, end=' ') for i in range(1, 11): for j in range(1, 11): print(i * j, end=' ') print()
f61e21078ff70c21dcecadf1376fa0fece79bdef
Irisviel-0/a1
/myq1.py
754
3.796875
4
grid_map = [] # Put the map in a list as a two-dimentional data for num in range(1, 11): ''' The for loop will generate each column of the map at a time ''' grid_map.append([x+str(num) for x in "ABCDEFGHIJ"]) def find_my_neighbourhood(x, y): ''' Using the provided coordinates to locate the neighbourhood ''' return grid_map[int(x)][int(y)] def find_all_restaurants_in_neighbourhood(x, y): ''' To find all restaurants in specific area ''' place = find_my_neighbourhood(x, y) return [place + 'CR', place + 'MR'] if __name__ == "__main__": for i in range(1,100): for j in range(1,100): print(find_my_neighbourhood(i/10,j/10)) print(find_all_restaurants_in_neighbourhood(i/10,j/10))
071908e13f42cd0bd31078670c9767da344301e2
YX-Zang/Leetcode
/35 Search Insert Position.py
275
3.671875
4
class Solution: def searchInsert(self, nums, target) -> int: insert_index = [] for index in range(len(nums)): if target <= nums[index]: insert_index.append(index) return min(insert_index) if insert_index else len(nums)
d52b191e847741019af1f0d7fb97b21b7e39acbd
kprahman/py_book_exercises
/ch18/recursive summation.py
1,133
3.859375
4
def r_sum(nested_list): tot = 0 for element in nested_list: if type(element) == type([]): tot += r_sum(element) else: tot += element return tot print(r_sum([1,2,[3,4],5])) def r_max(nxs): """Find the maximum in a recursive structure of lists within other lists. Precondition: No lists or sublists are EMPTY""" largest = None for i,e in enumerate(nxs): if type(e) == type([]): val = r_max(e) else: val = e if i == 0 or val > largest: largest = val return largest def r_max_book(nxs): largest = None first_time = True for e in nxs: if type(e) == type([]): val = r_max(e) else: val = e if first_time or val > largest: largest = val first_time = False return largest import time t0 = time.clock() r_max([2, 9, [1, 13], 8, 6]) t1 = time.clock() print("That took {} seconds".format(t1-t0)) t0 = time.clock() r_max_book([2, 9, [1, 13], 8, 6]) t1 = time.clock() print("That took {} seconds".format(t1-t0))
e7feae75caba9ef62735362f9733c783df5081ad
rafaelperazzo/programacao-web
/moodledata/vpl_data/303/usersdata/285/67370/submittedfiles/testes.py
355
3.9375
4
# -*- coding: utf-8 -*- #COMECE AQUI ABAIXO nota 1 = float (input('digite sua primeira nota')) print('nota1') nota 2 = float (input('digite sua segunda nota:')) print('nota2') nota 3 = float (input('digite sua terceira nota:')) print('nota3') nota 4 = float (input('digite sua quarta nota:')) print('nota4') media = (nota1+nota2+nota3+nota4)/4
ec7d6ae153fd3c2fec30b3eb377f4b84d52bdc0e
culeo/LeetCode
/Python/DynamicProgramming/test_paint_house_ii.py
1,861
3.875
4
# coding: utf-8 def min_cost(costs): """ 265 Paint House II(房屋染色 II) There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. The cost of painting each house with a certain color is represented by a n x k cost matrix. For example, costs[0][0] is the cost of painting house 0 with color 0; costs[1][2] is the cost of painting house 1 with color 2, and so on... Find the minimum cost to paint all houses. Example Input: costs = [[14,2,11],[11,14,5],[14,3,10]] Output: 10 Explanation: The three house use color [1,2,1] for each house. The total cost is 10. https://leetcode.com/problems/paint-house-ii https://www.lintcode.com/problem/paint-house-ii/description """ if len(costs) == 0: return 0 if len(costs) == 1: return min(costs[0]) n = len(costs) k = len(costs[0]) f = [[0] * k for i in range(n+1)] for i in range(1, n+1): min1, min2 = 0x7FFFFF, 0x7FFFFF idx1, idx2 = 0, 0 for j in range(k): if f[i-1][j] < min1: min2 = min1 idx2 = idx1 min1 = f[i-1][j] idx1 = j elif f[i-1][j] < min2: min2 = f[i-1][j] idx2 = j for j in range(k): f[i][j] = costs[i-1][j] if j == idx1: f[i][j] += min2 else: f[i][j] += min1 return min(f[n]) print min_cost([[14,2,11],[11,14,5],[14,3,10]]) def test_min_cost_1(): assert 10 == min_cost([[14,2,11],[11,14,5],[14,3,10]]) def test_min_cost_2(): assert 5 == min_cost([[5]])
de6ef0dc791e399c7820fe5ff47a0fd54778da12
tgtn007/LeetCodeCompany
/OA/treeBottom.py
851
3.625
4
def treeBottom(tree): i, j = split(tree) l = tree[j+1:i+1] r = tree[i+2:len(tree)-1] if l == r == "()": return [int(tree[1:j])] if depth(l) < depth(r): return treeBottom(r) if depth(l) > depth(r): return treeBottom(l) return treeBottom(l) + treeBottom(r) def depth(tree): if tree == "()": return 0 i, j = split(tree) l = tree[j+1:i+1] r = tree[i+2:len(tree) - 1] return 1 + max(depth(l), depth(r)) def split(tree): x = 0 y = 0 for j in range(1, len(tree)): if not tree[j].isdigit(): break for i in range(j + 1, len(tree)): if tree[i] == "(": x += 1 if tree[i] == ")": y += 1 if x == y: break return i, j
bef1fb739bad571413b6fe1ab26c8abefce36552
AcrobatAHA/HackerRank-problem-solving
/HackerRank Transpose and Flatten problem in Python Numpy.py
172
3.5
4
import numpy n,m = map(int,input().split()) my_array = numpy.array([input().split() for i in range(n)],int) print(numpy.transpose(my_array)) print(my_array.flatten())
3bbfe1ffc0d068df8a01dfc148b897f8fb97fe4e
karthi1015/Antler
/PyRevit Extension/Antler.extension/lib/frange/frange.py
3,491
4.46875
4
import numpy as _np class frange(): """ Return an object can be used to generate a generator or an array of floats from start (inclusive) to stop (exclusive) by step. This object stores the start, stop, step and length of the data. Uses less memory than storing a large array. Example ------- An example of how to use this class to generate some data is as follows for some time data between 0 and 2 in steps of 1e-3 (0.001):: you can create an frange object like so $ time = frange(0, 2, 1e-3) you can print the length of the array it will generate $ printlen(time) # prints length of frange, just like an array or list you can create a generator $ generator = time.get_generator() # gets a generator instance $ for i in generator: # iterates through printing each element $ print(i) you can create a numpy array $ array = time.get_array() # gets an array instance $ newarray = 5 * array # multiplies array by 5 you can also get the start, stop and step by accessing the slice parameters $ start = time.slice.start $ stop = time.slice.stop $ step = time.slice.step """ def __init__(self, start, stop, step): """ Intialises frange class instance. Sets start, top, step and len properties. Parameters ---------- start : float starting point stop : float stopping point step : float stepping interval """ self.slice = slice(start, stop, step) self.len = self.get_array().size return None def get_generator(self): """ Returns a generator for the frange object instance. Returns ------- gen : generator A generator that yields successive samples from start (inclusive) to stop (exclusive) in step steps. """ s = self.slice gen = drange(s.start, s.stop, s.step) # intialises the generator return gen def get_array(self): """ Returns an numpy array containing the values from start (inclusive) to stop (exclusive) in step steps. Returns ------- array : ndarray Array of values from start (inclusive) to stop (exclusive) in step steps. """ s = self.slice array = _np.arange(s.start, s.stop, s.step) return array # def __array__(self): # supposedly allows numpy to treat object itself as an array but it doesn't work? # array = self.get_array() # return array def __len__(self): return self.len def drange(start, stop, step): """ A generator that yields successive samples from start (inclusive) to stop (exclusive) in step intervals. Parameters ---------- start : float starting point stop : float stopping point step : float stepping interval Yields ------ x : float next sample """ x = start if step > 0: while x + step <= stop: # produces same behaviour as numpy.arange yield x x += step elif step < 0: while x + step >= stop: # produces same behaviour as numpy.arange yield x x += step else: raise ZeroDivisionError("Step must be non-zero")
118249f215fbe9a293e5ec301f6af734c17ec9d1
kyletruong/epi
/9_binary_trees/4_lca_with_parent.py
454
3.578125
4
# Given p and q, find their least common ancestor # Nodes have a parent field def lca(p, q): def height(node): ht = 0 while node.parent: node = node.parent ht += 1 return ht p_ht, q_ht = height(p), height(q) diff = abs(p_ht - q_ht) if q_ht > p_ht: p, q = q, p for _ in range(diff): p = p.parent while p is not q: p, q = p.parent, q.parent return p
3459c92c734d443fa780a15d137408a5ded728b5
nkLintcodeTeam/problems
/others/union_find_sets/union_find_sets.py
969
3.609375
4
class UnionFindSet: def __init__(self, n): self.parents=[] self.ranks=[] for i in range(n): self.parents.append(i) self.ranks.append(0) def connected(self, a, b): return self.find(a)==self.find(b) def find(self, x): if x!=self.parents[x]: self.parents[x]=self.find(self.parents[x]) return self.parents[x] def union(self, x, y): px=self.find(x) py=self.find(y) if px==py: return if self.ranks[px]>self.ranks[py]: self.parents[py]=px if self.ranks[px]<self.ranks[py]: self.parents[px]=py if self.ranks[px]==self.ranks[py]: self.parents[py]=px self.ranks[px]+=1 t=UnionFindSet(5) print t.find(0) print t.find(1) t.union(0, 1) print t.find(0) print t.find(1) t.union(2, 3) t.union(0, 2) t.union(0, 2) print t.parents print t.ranks print t.connected(0, 3)
0e72b53aea0bfbe9fc503a61579ff219d00bfd9d
boonchu/python3lab
/coursera.org/python1/week3/clock-face-sample.py
2,211
3.90625
4
# A simplified Clock example. Just draw the "second" hand # import simplegui import math import time # Game constants WIDTH = 220 HIGHT = 220 # Some extra features is_analog = True # Toggle analog display, default to yes mode_str = ["Analog", "Digital"] # Human readable output def draw_clock_hand(canvas, center, length, w, color, degrees): """ Compute line start and end based on the angle in degrees """ end = [0, 0] end[0] = center[0] + length * math.sin(math.radians(degrees)) end[1] = center[1] - length * math.cos(math.radians(degrees)) canvas.draw_line(center, end, w, color) def draw_clock_face(canvas, center, radius, color): """ Draw the clock dial based on the center and radius """ ns = [0, 0] ne = [0, 0] for i in range(60): if i % 5 == 0: len = radius / 10 + 1 else: len = radius / 20 + 1 ns[0] = center[0] + (radius - len) * math.sin(math.radians(i*6)) ns[1] = center[1] - (radius - len) * math.cos(math.radians(i*6)) ne[0] = center[0] + radius * math.sin(math.radians(i*6)) ne[1] = center[1] - radius * math.cos(math.radians(i*6)) canvas.draw_line(ns, ne, 2, color) # define draw handler def draw(canvas): seconds = int(time.time()) % 60 if is_analog: text_size = 24 text_start = [WIDTH/2-10, HIGHT-10] else: text_size = 64 text_start = [WIDTH/2-30, HIGHT/2] canvas.draw_text(str(seconds), text_start, text_size, "Crimson") # Just for fun, draw the clocks if is_analog: ps = [WIDTH/2, HIGHT/2] canvas.draw_circle(ps, 80, 2, "Gray") canvas.draw_circle(ps, 2, 1, "Gray", "Crimson") draw_clock_face(canvas, ps, 80, "Gray") degrees = seconds * 6 draw_clock_hand(canvas, ps, 70, 2, "Crimson", degrees) def clock_mode(): global is_analog is_analog = not is_analog mode_button.set_text(mode_str[is_analog]) # create frame frame = simplegui.create_frame("Stopwatch: a game of reflexes", WIDTH, HIGHT) frame.set_draw_handler(draw) # register event handlers mode_button = frame.add_button(mode_str[is_analog], clock_mode, 75) # start frame frame.start()
a37efeb00867935de1d3217653b02ef56f76996e
saathvik2006/learning_python
/Functions/integer_multiplication.py
383
4
4
def get_int(z): int(z) return z def mult(x,y): counter=1 product=0 while counter<=y: product+=x counter+=1 return product a=int(input("What is your number? ")) b=int(input("What do you want to multiply by? ")) print (mult(a,b)) x_input=input("What is your number? ") y_input=input("What is your multiplier? ") x=get_int(x_input) y=get_int(y_input) print (mult(x,y))
028e8fabbfd356d4f4097bc6c3867c4b848cc29c
ryfeus/lambda-packs
/H2O/ArchiveH2O/past/types/olddict.py
2,721
4.125
4
""" A dict subclass for Python 3 that behaves like Python 2's dict Example use: >>> from past.builtins import dict >>> d1 = dict() # instead of {} for an empty dict >>> d2 = dict(key1='value1', key2='value2') The keys, values and items methods now return lists on Python 3.x and there are methods for iterkeys, itervalues, iteritems, and viewkeys etc. >>> for d in (d1, d2): ... assert isinstance(d.keys(), list) ... assert isinstance(d.values(), list) ... assert isinstance(d.items(), list) """ import sys from past.utils import with_metaclass _builtin_dict = dict ver = sys.version_info[:2] class BaseOldDict(type): def __instancecheck__(cls, instance): return isinstance(instance, _builtin_dict) class olddict(with_metaclass(BaseOldDict, _builtin_dict)): """ A backport of the Python 3 dict object to Py2 """ iterkeys = _builtin_dict.keys viewkeys = _builtin_dict.keys def keys(self): return list(super(olddict, self).keys()) itervalues = _builtin_dict.values viewvalues = _builtin_dict.values def values(self): return list(super(olddict, self).values()) iteritems = _builtin_dict.items viewitems = _builtin_dict.items def items(self): return list(super(olddict, self).items()) def has_key(self, k): """ D.has_key(k) -> True if D has a key k, else False """ return k in self # def __new__(cls, *args, **kwargs): # """ # dict() -> new empty dictionary # dict(mapping) -> new dictionary initialized from a mapping object's # (key, value) pairs # dict(iterable) -> new dictionary initialized as if via: # d = {} # for k, v in iterable: # d[k] = v # dict(**kwargs) -> new dictionary initialized with the name=value pairs # in the keyword argument list. For example: dict(one=1, two=2) # """ # # if len(args) == 0: # return super(olddict, cls).__new__(cls) # # Was: elif isinstance(args[0], newbytes): # # We use type() instead of the above because we're redefining # # this to be True for all unicode string subclasses. Warning: # # This may render newstr un-subclassable. # elif type(args[0]) == olddict: # return args[0] # # elif isinstance(args[0], _builtin_dict): # # value = args[0] # else: # value = args[0] # return super(olddict, cls).__new__(cls, value) def __native__(self): """ Hook for the past.utils.native() function """ return super(oldbytes, self) __all__ = ['olddict']
8b268e178041d28659547d8bd13e7ebace79f00d
ankiyong/Before_TIL
/string_func.py
2,290
3.625
4
#len() : 문자열의 길이 반환 str = "erwer" print(len(str)) #count() : 문자열 내에 있는 특정 문자의 개수 반환 print(str.count('e')) #find() : 문자열 내에서 문자열이 존재하는지 여부와 문자열의 시작 위치를 반환한다. ##문자열이 존재하면 시작위치 반환 / 미존재시 -1 반환 crawling = 'Data Crawling is Fun' print(crawling.find('Fun')) #문자열의 시작 위치 반환 print(crawling.find('a')) #중복 문자 존재 시 가장 앞의 문자 위치 반환 print(crawling.find('z')) #-1 반환 #index() : 문자열 내에서 특정 문자열의 시작 위치 반환 crawling = 'Data Crawling is Fun' print(crawling.index('Fun')) #find 함수와 비슷한 기능 #split : 구분자를 기분으로 문자열을 나눔 #나눈결과를 list로 만들어 반환한다 string = "Python Programming" print(string.split('-')) names = "홍길동, 이몽룡, 성춘향, 변학도" names_split = names.split(',') print(names_split) #['홍길동', ' 이몽룡', ' 성춘향', ' 변학도'] colors = 'red:blue:yellow:green' colors_split = colors.split(':' ) print(colors_split) #['red', 'blue', 'yellow', 'green'] #replace() : 전체 문자열에서 특정 문자열을 찾아 다른 문자열로 변경해주는 함수 #문자열.replace(찾는 문자열, 변경할 문자열) course = 'Java Programming' #Java => Python print(course.replace('Java','Python')) #Python Programming #join() :d 각 문자 사이에 특정 문자를 삽입하는 함수 a = '---' b = 'abc' print(b.join(a)) #-abc-abc- print('-'.join(b)) #a-b-c #upper: 대문자로 /lower: 소문자로 /capicalize: 문장의 첫 문자를 대문자로 /title : 단어의 첫 문자를 재문자로 string = 'this is MY DOG' print(string.upper()) print(string.lower()) print(string.capitalize()) print(string.title()) #공백 제거 #strip : 양쪽 공백 제거 / lstrip : 왼쪽 공백 / rstrip : 오른쪽 공백 제거 s1 = ' hello ' print('test',s1.strip(),'test') print(s1.lstrip(),"test") print("tset",s1.rstrip()) #isalpga : 문자 여부 결과 반환 #isdigit : 숫자 여부 결과 반환 #isspace : 하나의 문자에 대해서 공백 여부 결과 반환 #isalnum : 문자나 숫자 여부에 대한 결과 반환 #True/False로 반환됨
0c95f23d38f9782f75cdc11eadf45a37f9e3a98a
XinliJing/leetcode
/98. 验证二叉搜索树.py
644
3.875
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None #学习学习 class Solution(object): def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ return self.validBST(root, -2**32, 2**32-1) def validBST(self, root, small, large): if root is None: return True if small >= root.val or large <= root.val: return False return self.validBST(root.left, small, root.val) and self.validBST(root.right, root.val, large)
368a5666061028fd45f09b804ebd9281203ad1ca
devjackluo/Learn-Python
/LearnPython/basics/pythonConditionals.py
876
3.96875
4
# if statement x = 6 y = 9 z = 4 a = 2 b = 6 if x > y: print("x greater than y") if x > z: print('nest statement x > z') if x < y: print("x less than y") if x > z: print('\tnest statement x > z') print("") # python can do multiple conditions at once... wtf if z < y > x > a: print('y greather than z and greather than x and greather a && x greather than a') a = 7 print("") if z < y > x > a: print('y greather than z and greather than x and greather a && x greather than a') else: print('something was not right, a became greather than x') print("") if b == a: print('b equals a') elif b == z: print('b equals z') elif b == y: print('b equals y') elif b != x: print('b !equals x') else: print('b not equal to anything above') if b == x: print('\tnested if: b equals x however') print("")
d6d2192ab16613aa3a74ff67560b696972defb1b
KetanChopade/OCFM
/sql_operation.py
345
3.765625
4
import sqlite3 as sql conn = sql.connect("onlineclasse.sqlite2") curs = conn.cursor() def createCourseTable(): curs.execute("create table course(cno number primary key ,course_name text , faculty_name text ,class_date date ,class_time text, fee real , duration number )") conn.close() print("table is created") createCourseTable()
347b8627d410f9d6f5190dfeebbc770eb7a9cd6e
juniorppb/arquivos-python
/ExerciciosPythonMundo1/48. Ordem da Apresentação.py
334
3.71875
4
import random a1 = str(input('Qual o nome do primeiro aluno?')) a2 = str(input('QUal o nome do segundo aluno?')) a3 = str(input('Qual o nome do terceiro aluno?')) a4 = str(input('Qual o nome do quarto aluno?')) nomes = [a1, a2, a3, a4] ordem = random.shuffle(nomes) print('Qual a ordem para a apresentação do trabalho') print(nomes)
2f63c4ea2bbf04b5b370a39b63bb382400cee03d
eduardox23/CPSC-115
/lab 03-11-2010/tion.py
671
3.796875
4
# # File: tion.py # Author: Vlad Burca # Lab Section: Wednesday # # Created: 11/03/2010 # Last Modified: 11/03/2010 # # Exercise 1.2 # def isaSuffix(word, suff): if word[len(word)-len(suff):] == suff: return True else: return False def getSuffix(list, suff): suff_list = [] for word in list: if isaSuffix(word, suff): suff_list.append(word) return suff_list f = open('crosswords.txt') list = [] for line in f: word = line.strip() list.append(word) suff_list = getSuffix(list, 'om') print " In the official list of crosswords, the list of words that contain 'tion'\ as a suffix is: \n ", suff_list
bd260f44a1128dc5a445b33b9a64d3727b8a0b9a
hupipi96/pyldpc
/pyldpc/ldpc_images.py
10,715
3.578125
4
import numpy as np from .imagesformat import int2bitarray, bitarray2int, Bin2Gray, Gray2Bin, RGB2Bin, Bin2RGB from .codingfunctions import Coding from .decodingfunctions import Decoding_BP_ext, Decoding_logBP_ext, DecodedMessage from .ldpcalgebra import Bits2i, Nodes2j, BitsAndNodes import scipy import warnings __all__=['ImageCoding','ImageDecoding','int2bitarray','bitarray2int','Bin2Gray', 'Gray2Bin','RGB2Bin','Bin2RGB','BER','ImageCoding_rowbyrow','ImageDecoding_rowbyrow'] def ImageCoding(tG,img_bin,snr): """ CAUTION: SINCE V.0.7 Image coding and decoding functions TAKES TRANSPOSED CODING MATRIX tG. IF G IS LARGE, USE SCIPY.SPARSE.CSR_MATRIX FORMAT TO SPEED UP CALCULATIONS. Codes a binary image (Therefore must be a 3D-array). Each pixel (k bits-array, k=8 if grayscale, k=24 if colorful) is considered a k-bits message. If the original binary image is shaped (X,Y,k). The coded image will be shaped (X,Y,n) Where n is the length of a codeword. Then a gaussian noise N(0,snr) is added to the codeword. Remember SNR: Signal-Noise Ratio: SNR = 10log(1/variance) in decibels of the AWGN used in coding. Of course, showing an image with n-bits array is impossible, that's why if the optional argument show is set to 1, and if Coding Matrix G is systematic, showing the noisy image can be possible by gathering the k first bits of each n-bits codeword to the left, and the redundant bits to the right. Then the noisy image is changed from bin to uint8. Remember that in this case, ImageCoding returns a tuple: the (X,Y,n) coded image, and the noisy image (X,Y*(n//k)). Parameters: G: Coding Matrix G - (must be systematic to see what the noisy image looks like.) See CodingMatrix_systematic. img_bin: 3D-array of a binary image. SNR: Signal-Noise Ratio, SNR = 10log(1/variance) in decibels of the AWGN used in coding. Returns: (default): Tuple: noisy_img, coded_img """ n,k = tG.shape height,width,depth = img_bin.shape if k!=8 and k!= 24: raise ValueError('Coding matrix must have 8 xor 24 rows ( grayscale images xor rgb images)') coded_img = np.zeros(shape=(height,width,n)) noisy_img = np.zeros(shape=(height,width,k),dtype=int) for i in range(height): for j in range(width): coded_byte_ij = Coding(tG,img_bin[i,j,:],snr) coded_img[i,j,:] = coded_byte_ij systematic_part_ij = (coded_byte_ij[:k]<0).astype(int) noisy_img[i,j,:] = systematic_part_ij if k==8: noisy_img = Bin2Gray(noisy_img) else: noisy_img = Bin2RGB(noisy_img) return coded_img,noisy_img def ImageDecoding(tG,H,img_coded,snr,max_iter=1,log=1): """ CAUTION: SINCE V.0.7 Image coding and decoding functions TAKES TRANSPOSED CODING MATRIX tG. IF G IS LARGE, USE SCIPY.SPARSE.CSR_MATRIX FORMAT (IN H AND G) TO SPEED UP CALCULATIONS. Image Decoding Function. Taked the 3-D binary coded image where each element is a codeword n-bits array and decodes every one of them. Needs H to decode. A k bits decoded vector is the first k bits of each codeword, the decoded image can be transformed from binary to uin8 format and shown. Parameters: tG: Transposed coding matrix tG. H: Parity-Check Matrix (Decoding matrix). img_coded: binary coded image returned by the function ImageCoding. Must be shaped (heigth, width, n) where n is a the length of a codeword (also the number of H's columns) snr: Signal-Noise Ratio: SNR = 10log(1/variance) in decibels of the AWGN used in coding. log: (optional, default = True), if True, Full-log version of BP algorithm is used. max_iter: (optional, default =1), number of iterations of decoding. increase if snr is < 5db. """ n,k = tG.shape height, width, depth = img_coded.shape img_decoded_bin = np.zeros(shape=(height,width,k),dtype = int) if log: DecodingFunction = Decoding_logBP_ext else: DecodingFunction = Decoding_BP_ext systematic = 1 if not (tG[:k,:]==np.identity(k)).all(): warnings.warn("In LDPC applications, using systematic coding matrix G is highly recommanded to speed up decoding.") systematic = 0 BitsNodes = BitsAndNodes(H) for i in range(height): for j in range(width): decoded_vector = DecodingFunction(H,BitsNodes,img_coded[i,j,:],snr,max_iter) if systematic: decoded_byte = decoded_vector[:k] else: decoded_byte = DecodedMessage(tG,decoded_vector) img_decoded_bin[i,j,:] = decoded_byte if k==8: img_decoded = Bin2Gray(img_decoded_bin) else: img_decoded = Bin2RGB(img_decoded_bin) return img_decoded def ImageCoding_rowbyrow(tG,img_bin,snr): """ CAUTION: SINCE V.0.7 Image coding and decoding functions TAKE TRANSPOSED CODING MATRIX tG. USE SCIPY.SPARSE.CSR_MATRIX FORMAT (IN H AND G) TO SPEED UP CALCULATIONS. K MUST BE EQUAL TO THE NUMBER OF BITS IN ONE ROW OF THE BINARY IMAGE. USE A SYSTEMATIC CODING MATRIX WITH CodingMatrix_systematic. THEN USE SCIPY.SPARSE.CSR_MATRIX() -------- Codes a binary image (Therefore must be a 3D-array). Each row of img_bin is considered a k-bits message. If the image has a shape (X,Y,Z) then the binary image will have the shape (X,k). The coded image will be shaped (X+1,n): - The last line of the coded image stores Y and Z so as to be able to construct the decoded image again via a reshape. - n is the length of a codeword. Then a gaussian noise N(0,snr) is added to the codeword. Remember SNR: Signal-Noise Ratio: SNR = 10log(1/variance) in decibels of the AWGN used in coding. ImageCoding returns a tuple: the (X+1,n) coded image, and the noisy image (X,Y,Z). Parameters: tG: Transposed Coding Matrix G - must be systematic. See CodingMatrix_systematic. img_bin: 3D-array of a binary image. SNR: Signal-Noise Ratio, SNR = 10log(1/variance) in decibels of the AWGN used in coding. Returns: (default): Tuple: coded_img, noisy_img """ n,k = tG.shape height,width,depth = img_bin.shape if not type(tG)==scipy.sparse.csr_matrix: warnings.warn("Using scipy.sparse.csr_matrix format is highly recommanded when computing row by row coding and decoding to speed up calculations.") if not (tG[:k,:]==np.identity(k)).all(): raise ValueError("G must be Systematic. Solving tG.tv = tx for images has a O(n^3) complexity.") if width*depth != k: raise ValueError("If the image's shape is (X,Y,Z) k must be equal to 8*Y (if Gray ) or 24*Y (if RGB)") img_bin_reshaped = img_bin.reshape(height,width*depth) coded_img = np.zeros(shape=(height+1,n)) coded_img[height,0:2]=width,depth for i in range(height): coded_img[i,:] = Coding(tG,img_bin_reshaped[i,:],snr) noisy_img = (coded_img[:height,:k]<0).astype(int).reshape(height,width,depth) if depth==8: return coded_img,Bin2Gray(noisy_img) if depth==24: return coded_img,Bin2RGB(noisy_img) def ImageDecoding_rowbyrow(tG,H,img_coded,snr,max_iter=1,log=1): """ CAUTION: SINCE V.0.7 ImageDecoding TAKES TRANSPOSED CODING MATRIX tG INSTEAD OF G. USE SCIPY.SPARSE.CSR_MATRIX FORMAT (IN H AND G) TO SPEED UP CALCULATIONS. -------- Image Decoding Function. Taked the 3-D binary coded image where each element is a codeword n-bits array and decodes every one of them. Needs H to decode and tG to solve tG.tv = tx where x is the codeword element decoded by the function itself. When v is found for each codeword, the decoded image can be transformed from binary to uin8 format and shown. Parameters: tG: Transposed Coding Matrix ( SCIPY.SPARSE.CSR_MATRIX FORMAT RECOMMANDED ) H: Parity-Check Matrix (Decoding matrix).( SCIPY.SPARSE.CSR_MATRIX FORMAT RECOMMANDED) img_coded: binary coded image returned by the function ImageCoding. Must be shaped (heigth, width, n) where n is a the length of a codeword (also the number of H's columns) snr: Signal-Noise Ratio: SNR = 10log(1/variance) in decibels of the AWGN used in coding. log: (optional, default = True), if True, Full-log version of BP algorithm is used. max_iter: (optional, default =1), number of iterations of decoding. increase if snr is < 5db. """ n,k = tG.shape width,depth = img_coded[-1,0:2] img_coded = img_coded[:-1,:] height,N = img_coded.shape if N!=n: raise ValueError('Coded Image must have the same number of columns as H') if depth !=8 and depth != 24: raise ValueError('type of image not recognized: third dimension of the binary image must be 8 for grayscale, or 24 for RGB images') if not (tG[:k,:]==np.identity(k)).all(): raise ValueError("G must be Systematic. Solving tG.tv = tx for images has a O(n^3) complexity") if not type(H)==scipy.sparse.csr_matrix: warnings.warn("Used H is not a csr object. Using scipy.sparse.csr_matrix format is highly recommanded when computing row by row coding and decoding to speed up calculations.") img_decoded_bin = np.zeros(shape=(height,k),dtype = int) if log: DecodingFunction = Decoding_logBP_ext else: DecodingFunction = Decoding_BP_ext BitsNodes = BitsAndNodes(H) for i in range(height): decoded_vector = DecodingFunction(H,BitsNodes,img_coded[i,:],snr,max_iter) img_decoded_bin[i,:] = decoded_vector[:k] if depth==8: img_decoded = Bin2Gray(img_decoded_bin.reshape(height,width,depth)) if depth==24: img_decoded = Bin2RGB(img_decoded_bin.reshape(height,width,depth)) return img_decoded def BER(original_img_bin,decoded_img_bin): """ Computes Bit-Error-Rate (BER) by comparing 2 binary images. The ratio of bit errors over total number of bits is returned. """ if not original_img_bin.shape == decoded_img_bin.shape: raise ValueError('Original and decoded images\' shapes don\'t match !') height, width, k = original_img_bin.shape errors_bits = sum(abs(original_img_bin-decoded_img_bin).reshape(height*width*k)) total_bits = np.prod(original_img_bin.shape) BER = errors_bits/total_bits return(BER)
eb146576d941042e899d27823d966b6161fa0d19
efitr/CS-2-Tweet-Generator
/Practicando Tweet GIT/JC3dictionary.py
772
3.59375
4
import os import sys import random import time def get_words_list(): start_time = time.time() with open("/usr/share/dict/words", 'r') as directory: file_content = directory.read() string_list = file_content.split("\n") return string_list num = 10 def randomize(num, string_list): #''' version 1 ''' #random_words = [random.choice(string_list) for i in range(num)] #''' version 2 ''' # random_words = [] # for i in range(num): random_words.append(random.choice(string_list)) #''' version 3 ''' # random_sentence = ' '.join(random_words) elapsed_time = time.time() - start_time print(random_sentence) return random_sentence def main(): string_list = get_words_list() randomize(num, string_list) main()
1826a2b0036ca8723a843fd0e686891bc57af711
borntyping/diceroll
/diceroll/evaluate.py
2,355
3.5
4
""" The Expression class """ from diceroll.components import UnrolledDice, Operator class Expression (object): """ A diceroll expression object, and the evaluator for it """ def __init__ (self, tokens): self.depth = 0 self.tokens = list(tokens) def __repr__ (self): return repr(self.tokens) def log (self, message, depth=0, **values): """ Print a message at a set depth """ print ("{depth}"+message).format( depth = ' ' * (self.depth + depth), tokens = self.tokens, **values ) @staticmethod def single (iterable): """ Returns a single item from a iterable if possible >>> single([1]) 1 >>> single([1, 2, 3]) [1, 2, 3] """ return iterable[0] if len(iterable) == 1 else iterable def evaluate (self, **modifiers): """ The parse action for dice expressions (``expr`` in the below grammar) Rolls the UnrolledDice objects, and then calls the following operators """ self.depth = modifiers.get('depth', 1) # If verbose==False, ignore all logging calls if not modifiers.get('verbose', False): self.log = lambda *a, **k: None self.log("Evaluating the expression: {tokens!r}", depth=-1) # Roll the dice, and evaluate sub-expressions for i in xrange(len(self.tokens)): if isinstance(self.tokens[i], Expression): self.tokens[i] = self.tokens[i].evaluate(depth=self.depth+1, **modifiers) elif isinstance(self.tokens[i], UnrolledDice): dice = self.tokens[i] self.tokens[i] = self.tokens[i].evaluate() self.log("Rolled {n}d{s}: {roll}", n=dice.n, s=dice.sides, roll=list(self.tokens[i])) # Call the operators l = 0 while l < len(self.tokens): op = self.tokens[l] if isinstance(op, Operator): # The arguments are the previous and next tokens, # with no next token if the operator only takes 1 term args = [self.tokens[l-1]] if not op.terms < 2: args += [self.tokens[l+1]] result = op(*args) # The new token list is the token list with the argument tokens # and the operator replaced with the operators result self.tokens = self.tokens[:l-1] + [result] + self.tokens[l+op.terms:] self.log("Called {operator}: {result}", operator=op.__class__.__name__, result=result) else: # The location only needs to move on if no operator was called l += 1 return Expression.single(self.tokens)
da94f8c14bac692267dfec2063b1bcd699eaa827
Jesta398/project
/datastruvctures/polymorphism/quest2.py
276
3.859375
4
class Parent1: def m1(self): print("inside parent1") class Parent2: def m1(self): print("inside parent2") class child(Parent1,Parent2):#chils is inheriting parent1 and parent2 def m3(self): print("inside child") c=child() c.m3() c.m1()
12957cc9783edc931406d64790a6dfc710218ebb
mcxu/code-sandbox
/PythonSandbox/src/misc/string_to_sentence.py
2,203
3.75
4
''' Word Break Problem ? Given a string of words, and a dictionary of words. Turn the string into a sentence and return it. If this cannot be done, then return None. Example: s = "hellothere" dictionary = {"hello", "there} output: "hello there" Example: s = "hellothere" dictionary = {"hello", "the"} output: None (Since "there" is a not a word in the dictionary, the whole sentence cannot be converted.) ''' class StringToSentence: ''' Let n = len(s) d = len of longest word in dictionary. Time: O(n^n): Since for loop calls stringToSentence n times recursively. Space: O(n*d): For some substring that exists in dictionary, d means there is a new level of recursion. starting from the (last+1)th char from that substring till the end of s. Not sure if this analysis is correct. ''' def stringToSentence(self, s, dictionary): if not s or s in dictionary: return s for i in range(len(s)): substr = s[:i+1] if substr in dictionary: nextWord = self.stringToSentence(s[i+1:], dictionary) if nextWord: return substr + " " + nextWord # for cases where there are no substr in dictionary return None def test1(self): s = "hellothere" #dictionary = set(["hello", "them"]) #dictionary = set(["hello", "there"]) dictionary = set(["hello", "the", "there"]) res = self.stringToSentence(s, dictionary) print("res: ", res) def test2(self): s = "hellothereafter" #dictionary = set(["hello", "them"]) #dictionary = set(["hello", "there"]) dictionary = set(["hello", "there", "the", "after"]) res = self.stringToSentence(s, dictionary) print("res: ", res) def test3(self): s = "hellothereeveraftertomorrow" #dictionary = set(["hello", "them"]) #dictionary = set(["hello", "there"]) dictionary = set(["hello", "there", "aft", "ever", "morrow", "to", "the", "after"]) res = self.stringToSentence(s, dictionary) print("res: ", res) prob = StringToSentence() prob.test1() prob.test2() prob.test3()
8aa84971370311efe755e2e59ccd72017310e681
yanivn2000/Python
/Syntax/module3/04_while1.py
73
3.59375
4
count=0 while count < 10: print(f"The count is:{count}") count+=1
2fa7679b67cde147f90900ad9b0bc543f6edc6c2
AlberVini/exp_regulares
/aulas_exemplos/aula07.py
1,274
3.796875
4
# shorthand # \w para encontrar -> [a-zA-Z0-9À-ú] # \W negação [^a-zA-Z0-9À-ú] # \d para encontrar só números -> [0-9] # \D negação [^0-9] # \s [\r\n\f\t] # \S negação, bom para eliminar espaços de strings # \b borda, capta uma palavra com determinado começo ou final # \b para encontrar uma palavra com determinado número de caracteres # \B estranho mas tem a função de não encontrar uma borda import re texto = ''' João trouxe flores para sua amada namorada em 10 de janeiro de 1970, Maria era o nome dela. Foi um ano excelente na vida de joão. Teve_ALGO 5 filhos, todos adultos atualmente. maria, hoje sua esposa, ainda faz aquele café com pão de queijo nas tardes de domingo. Também né! Sendo a boa mineira que é, nunca esquece seu famoso pão de queijo. Não canso de ouvir a Maria: "Joooooooooãooooooo, o café tá prontinho aqui. Veeemm"! ''' # print(re.findall(r'[a-zA-Z0-9À-ú]+', texto)) # print(re.findall(r'\w+', texto)) # print(re.findall(r'[0-9]+', texto)) print(re.findall(r'\d+', texto)) print(re.findall(r'\S+', texto)) print(re.findall(r'\bt\w+', texto, flags=re.I)) # begin print(re.findall(r'\w+da\b', texto, flags=re.I)) # tail print(re.findall(r'\b\w{7}\b', texto)) # linha 9 print(re.findall(r'atual\w{2}\B', texto))
3622642192c03e6e654acde4bc9d8253f24e42a2
AGauchat/clase01
/58052-agustin-gauchat/clase01/test_decimal_numbers.py
2,408
3.671875
4
import unittest from decilam_numbers import decimal_to_roman class TestsDecimalNumbers(unittest.TestCase) : def test_decimal_1_to_roman(self): roman_number = decimal_to_roman(1) self.assertEqual(roman_number, "I") def test_decimal_2_to_roman(self): roman_number = decimal_to_roman(2) self.assertEqual(roman_number, "II") def test_decimal_3_to_roman(self): roman_number = decimal_to_roman(3) self.assertEqual(roman_number, "III") def test_decimal_4_to_roman(self): roman_number = decimal_to_roman(4) self.assertEqual(roman_number, "IV") def test_decimal_9_to_roman(self): roman_number = decimal_to_roman(9) self.assertEqual(roman_number, "IX") def test_decimal_24_to_roman(self): roman_number = decimal_to_roman(24) self.assertEqual(roman_number, "XXIV") def test_decimal_43_to_roman(self): roman_number = decimal_to_roman(43) self.assertEqual(roman_number, "XLIII") def test_decimal_58_to_roman(self): roman_number = decimal_to_roman(58) self.assertEqual(roman_number, "LVIII") def test_decimal_72_to_roman(self): roman_number = decimal_to_roman(72) self.assertEqual(roman_number, "LXXII") def test_decimal_87_to_roman(self): roman_number = decimal_to_roman(87) self.assertEqual(roman_number, "LXXXVII") def test_decimal_91_to_roman(self): roman_number = decimal_to_roman(91) self.assertEqual(roman_number, "XCI") def test_decimal_99_to_roman(self): roman_number = decimal_to_roman(99) self.assertEqual(roman_number, "XCIX") def test_decimal_149_to_roman(self): roman_number = decimal_to_roman(149) self.assertEqual(roman_number, "CXLIX") def test_decimal_478_to_roman(self): roman_number = decimal_to_roman(478) self.assertEqual(roman_number, "CDLXXVIII") def test_decimal_693_to_roman(self): roman_number = decimal_to_roman(693) self.assertEqual(roman_number, "DCXCIII") def test_decimal_954_to_roman(self): roman_number = decimal_to_roman(954) self.assertEqual(roman_number, "CMLIV") def test_decimal_999_to_roman(self): roman_number = decimal_to_roman(999) self.assertEqual(roman_number, "CMXCIX") if __name__ == '__main__': unittest.main()
51bea350d440603b53f13ae8f38ef5c07b445792
annaymj/LeetCode
/PerfectSubString.py
975
3.515625
4
``` # find the perfect substring that has each characater appear exactly k times s = '1102021222' k = 2 # return the number of perfect substring, expected return 6 # s[0:1] = 11 # s[0:5] = 110202 # s[2:5] = 0202 # s[1:6] = 102021 # s[7:8] = 22 # s[8:9] = 22 ``` def isPerfect(substring, k): s_dict = {} for char in substring: if char not in s_dict.keys(): s_dict[char] = 1 else: s_dict[char] += 1 for val in s_dict.values(): if val != k: return False return True def perfectSubstring(s,k): if k > len(s): return 0 res = 0 # loop through the list to get substring for i in range(len(s)- k + 1): for j in range(i+k, len(s)+1): substring = s[i:j] # check whether the substring is a perfect string, if yes, res += 1 if isPerfect(substring, k): res += 1 return res
c50f0dd256ac6d76f74a7e77b64b90f2b617bdb8
shaikhAbuzar/Diffie-Helman
/ShiftCipher.py
1,415
4.03125
4
# importing numpy library import numpy as np # function for shift cipher def shift(string, key): # list to store ascii values of characters ascii_list =[] for i in string: # converting the characters to 0-255 # using ord to get ascii values ascii_list.append(ord(i)) # -65) # add to the list we made # covert to np array and add key, the mod 256 # using numpy because it save you from manually coding ascii_list = (np.array(ascii_list) + key) % 256 char_list = [] # list for storing chars for i in ascii_list: # chr to get char from ascii value char_list.append(chr(i)) # logic from converting list to string cipher_text = '' for char in char_list: cipher_text += char # print(f'[RESULT OF SHIFT]: {cipher_text}') return cipher_text # Decryption function for shift cipher def shift_decrypt(ciphered_text, key): ascii_list = [] for i in ciphered_text: # converting the characters to 0-255 # using ord to get ascii values ascii_list.append(ord(i)) # add to the list we made # covert to np array and add 256, subtract key, then mod 256 ascii_list = (np.array(ascii_list) + 256 - key) % 256 # loop for converting the numeric values to their characters text = '' for char in ascii_list: text += chr(char) return text
813d14537199669b319549eecab8186c3a47dd74
princemathew1997/random-python
/Day 10/d10-11.py
122
3.96875
4
#multiplication table a = int(input("Enter a number:")) for i in range(1,11): m = a * i print(a,'*',i,'=',m)
555f6123d898cae15a6ec478ac2cf9bf8448ab7e
Portfolio-Projects42/UsefulResourceRepo2.0
/GIT-USERS/TOM2/cspt19long/comp.py
562
3.890625
4
class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f"Name: {self.name}, Age: {self.age}" def __repr__(self): return f"<Person: {self.name}, {self.age}>" dave = Person("Dave", 67) dave2 = { "name": "Dave", "age": 67 } ste = Person("Steve", 22) bob = Person("Bob", 102) people = [ dave, ste, bob ] # for person in people: # print(person.name) a = [person for person in people if person.name[0] == 'D'] for thing in a: print(thing) print(a)
9241564b470a8df518cbbaf650428c2a0a35e792
tagler/Maryland_Python_Programming
/chapter9_files7.py
467
3.71875
4
import sys import os if len(sys.argv) == 3: file1 = sys.argv[1] file1 = sys.argv[2] else: file1 = "text1.txt" file2 = "text2.txt" list_names1 = [] list_names2 = [] with open(file1,'r') as f1: for line in f1: list_names1.append(line.strip()) with open(file2,'r') as f2: for line in f2: list_names2.append(line.strip()) print( [each_name for each_name in list_names1 if each_name in list_names2] )
ae288ea2eb97c5f7bd77c30a096434fd649baadd
jjspetz/PyGames
/characters.py
2,792
3.65625
4
''' To Do: add lifes and final death when lifes up add leader board ''' import pygame, random class Sprite: def __init__(self, filename): self.img = pygame.image.load(filename) self.pos = random.choice([[50,50],[50,420],[420,420],[420,50]]) self.colorkey = [0, 0, 0] self.alpha = 255 self.speed = 1 def render(self, screen): try: self.img.set_colorkey(self.colorkey) self.img.set_alpha(self.alpha) screen.blit(self.img, self.pos) except: print('An error has occurred while the game was rendering the image.') exit(0) def move(self, count, screen, width, height): x = self.pos[0] y = self.pos[1] if count == 0 or count % 90 == 0: self.switch = random.randint(0,7) # script for monster's random movement if self.switch == 0: x += 4 * self.speed elif self.switch == 1: x += 3 * self.speed y += 3 * self.speed elif self.switch == 2: x += -3 * self.speed y += 3 * self.speed elif self.switch == 3: x += -4 * self.speed elif self.switch == 4: y += 4 * self.speed elif self.switch == 5: x += 3 * self.speed y += -3 * self.speed elif self.switch == 6: x += -3 * self.speed y += -3 * self.speed elif self.switch == 7: y += -4 * self.speed # resets monster when it moves off the edge of the screen if self.pos[0] > width: x = 10 elif self.pos[0] < 0: x = width- 10 elif self.pos[1] > height: y = 10 elif self.pos[1] < 0: y = height - 10 self.pos = [x, y] self.render(screen) class Goblin(Sprite): def __init__(self, filename, LEVEL): self.img = pygame.image.load(filename) self.pos = random.choice( [[random.randint(20,100), random.randint(20,100)], [random.randint(100,150), random.randint(100,150)], [random.randint(270,325), random.randint(270,325)], [random.randint(325,460), random.randint(325,460)]] ) self.colorkey = [0, 0, 0] self.alpha = 255 if LEVEL < 5: self.speed = 0.4 elif LEVEL <= 8: self.speed = 0.5 else: self.speed = random.choice([0.5, 0.7]) class Hero(Sprite): def __init__(self, filename): self.img = pygame.image.load(filename) self.pos = [200, 200] self.colorkey = [0, 0, 0] self.alpha = 255 def move(self, x, y, screen): self.pos = [x, y] self.render(screen)
838c6676073bb5bc04df39ac47a3260c2048e29e
abelidze/JentuBot
/archive/using_multiprocessing/settings.py
514
3.546875
4
def to_ascii(h): strs = "" for i in range(len(h)//2): strs += chr(int(h[(i*2):(i*2)+2], 16)) return strs def drink(message): message = to_ascii(message) for i, v in enumerate(message): message = message[:i] + chr(ord(v)+12) + message[i+1:] return message vodka = "..." #def to_hex(s): # strs = "" # for i in range(len(s)): # strs += "%x"%(ord(s[i])) # return strs #def rot(message): # for i, v in enumerate(message): # message = message[:i] + chr(ord(v)-12) + message[i+1:] # return to_hex(message)
a43e1ae5f4ea8488d955b7b7535d1d662687ff64
SusanaPavez/zoo-python
/clases/Ornitorrinco.py
1,010
3.78125
4
from clases.animal import Animal class Ornitorrinco(Animal): #por qué se me ocurrió un nombre tan largo? def __init__(self, nombre,edad,nivelsalud,felicidad): super().__init__(nombre,edad,nivelsalud,felicidad) super().alimentacion() self.alimentacion() self.nivelsalud = nivelsalud self.felicidad = felicidad #que actividad le produce felicidad al loro def grazna(self): self.felicidad =+50 print(f"El ornitorrinco {self.nombre} grazna,tiene un nivel de salud : {self.nivelsalud} y un nivel de felicidad {self.felicidad}") return self if __name__ == '__main__': try: ornitorrico1 = Ornitorrinco( "Perry", 22, 33, 44, 55 ) ornitorrico1.display_info() ornitorrico1.alimentacion() ornitorrico1.display_info() ornitorrico1.cacarear() ornitorrico1.display_info() except Exception as err: print("Error", err) print("Hay un error en la clase Ornitorrinco")
7d23919d6688962e3ef50c253f3c0b9ee067452f
ericdegan/Curso-em-Video
/ex062.py
524
3.765625
4
pt = int(input('Diga o primeiro termo: ')) rz = int(input('Diga a razao: ')) d = pt + (10 - 1) * rz pa = 0 c = 1 z = 1 while c < 11: f = pa + pt pa += rz print(f) c += 1 if c == 11: prox = int(input('Você gostaria de ver mais quantos termos: ')) if prox != 0: while z < prox +1: f = pa + pt pa += rz print(f) z += 1 else: print('Tudo bem, terminamos aqui.')
a5c49b3cfa43207f81b43808054c6bd34a279e79
sakthi5006/Problem-Solving-with-Algorithms-and-Data-Structures-using-Python-2
/Ch04. Recursion/towersOfHanoi.py
355
3.90625
4
def printMove(start, end): print("Moving from " + start + " to " + end) def towers(number, start, spare, end): if number == 1: printMove(start, end) else: towers(number - 1, start, end, spare) towers(1, start, spare, end) towers(number - 1, spare, start, end) towers(7, "start", "spare", "end")
5ed3082108fa5eb11b1219bc12aac204818c09fa
daniel-reich/turbo-robot
/8gE6FCdnWbECiR7ze_19.py
3,101
3.75
4
""" In numbers theory, a positive composite integer is a Smith number if its digital root is equal to the digital root of the sum of its prime factors, with factors being counted by multiplicity. Trivially, every prime is also a Smith number, having just one prime factor that is equal to itself. If two Smith numbers are consecutive in the integer series, then they are Smith brothers. Any other number will not be a Smith. Given a positive integer `number`, implement a function that returns: * `"Youngest Smith"` if the given number is the lower element of a couple of Smith brothers. * `"Oldest Smith"` if the given number is the higher element of a couple of Smith brothers. * `"Single Smith"` if the given number is a Smith number without another Smith number adjacent, lower or higher. * `"Trivial Smith"` if the given number is a prime. * `"Not a Smith"` if the given number is not a Smith number. ### Examples smith_type(22) ➞ "Single Smith" # Digital root of 22 = 2 + 2 = 4 # Sum of prime factors of 22 = 2 + 11 = 13 # Digital root of 13 = 1 + 3 = 4 # Is a Smith number without a brother smith_type(7) ➞ "Trivial Smith" # The given number is a prime smith_type(728) ➞ "Youngest Smith" # Digital root of 728 = 7 + 2 + 8 = 17 = 1 + 7 = 8 # Sum of prime factors of 728 = 2 + 2 + 2 + 7 + 13 = 26 # Digital root of 26 = 2 + 6 = 8 # The number 729 is a Smith number, so 728 is the youngest brother smith_type(6) ➞ "Not a Smith" # Digital root of 6 = 6 # Sum of prime factors of 6 = 2 + 3 = 5 # Digital root of 5 = 5 ### Notes * The prime factors are counted by multiplicity, they don't have to be unique (see example #3). * Two Smith numbers are brothers if they are adjacent and if they are **composite** , a Trivial Smith (a prime) can't be the brother of a Smith number! Look at example #1: 22 is a Single Smith, despite the next one, 23 (a prime), being a Trivial Smith. * The digital root is the reiterated sum of the digits of a number until a single digit is reached. You can find more info in the **Resources** tab. * All given integers will be greater than zero. """ def isPrime(n): if n < 2: return False else: for i in range(2, n): if n % i == 0: return False return True ​ def factors(n): return [i for i in range(2, n+1) if n % i == 0] def primeFactors(n): p_facts = [] while n != 1: for factor in factors(n)[::-1]: if isPrime(factor): p_facts.append(factor) n = int(n/factor) return p_facts def digitalRoot(n): dR = 0 while n != 0: dR += (n % 10) n //= 10 return dR def isSmith(n): sum = 0 for prime in primeFactors(n): sum += digitalRoot(prime) return sum == digitalRoot(n) and not isPrime(n) ​ def smith_type(n): if isPrime(n): return "Trivial Smith" elif isSmith(n) and isSmith(n-1): return "Oldest Smith" elif isSmith(n) and isSmith(n+1): return "Youngest Smith" elif isSmith(n): return "Single Smith" else: return "Not a Smith"
0101e6c4edbb24f6a519138a28146f670dae5ef4
mmkhaque/LeetCode_Practice
/125. Valid Palindrome.py
1,937
3.53125
4
class Solution: def isPalindrome(self, s: str) -> bool: if s == reversed(s): return True if len(s) == 1: return True left = 0 right = len(s) - 1 while left <= right: while not s[left].isalnum(): left +=1 # extra check to see if it has no alphanumeric ',.' if left >= len(s): return True while not s[right].isalnum(): right -=1 if s[left].lower() != s[right].lower(): return False left +=1 right -=1 return True ########################################################## class Solution: def isPalindrome(self, s: str) -> bool: s_new = [] for s_ in s: if s_.isalnum(): s_new.append(s_) s = ("").join(s_new) #print(s) if len(s) <= 1: return True i, j = 0, len(s)- 1 while i < j: if not s[i].isalnum(): i +=1 if not s[j].isalnum(): j -=1 if s[i].lower() == s[j].lower(): i +=1 j -=1 #print(i, j, s[i], s[j]) #if s[i].isalpha() and s[j].isalpha() and s[i].lower() != s[j].lower(): if s[i].lower() != s[j].lower(): #print('This got executed') return False if i > j: return True if i ==j: return True return True
dd919792838b2778fff7f1ea814ba331a5982e2f
ferisso/forloopython
/ex10.py
212
4.125
4
# Faça um programa que receba dois números inteiros e gere os números inteiros que estão no intervalo # compreendido por eles x = int(input('> ')) y = int(input('> ')) for x in range(x, y + 1): print(x)
c03b88fe247f1fa1dec0c5738df9e902117b1ab1
tk3/backlog-api-in-action-python
/05_print_date_from_unix_time.py
276
3.625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import time import datetime def print_date_from_unix_time(unix_time): date = datetime.datetime.fromtimestamp(unix_time) print(date) if __name__ == '__main__': now = time.time() print_date_from_unix_time(now)
31473171e6785d1133a6c7a900473c5fb28e1c16
blane612/lists
/primary.py
5,926
4.6875
5
# name: # author: # -------------------- Section 1 ------------------------- # # ------------------ List Creation ----------------------- # print('# -------------------- Section 1 ------------------------- #') print('Creating an Empty List' '\n') # 1. Creating an Empty List # -------------------------------------------------------- # Instructions # 1. Create empty lists using the following methods. # a. via List Displays # b. via the list() function. # 2. Print the lists. # # WRITE CODE BELOW list1 = [] list2 = list() print(list1) print(list2) print('\n' 'Creating a Pre-Populated List' '\n') # 2. Creating a Pre-Populated List # ------------------------------------------------------------ # Instructions # 1. Create the following pre-populated lists: # a. A list filled with 5 integers. # b. A list filled with 5 floats. # c. A list filled with 3 boolean values (True / False) # d. A list of three animals # e. A list with of 3 objects, that are all different data types. # f. Convert the string of the name of a star to a list via the list() function. # 2. Print the lists. # # 1.a has been done for you. # # WRITE CODE BELOW integers = [1, 15, -4, -26, 34] floats = [1.03, 67.8, -09.78, 22.3, 4.33] boolean_values = [True, False] animals = ['panda', 'unicorn', 'dinosaur'] objects = [7.09, 'fairy', 90] print() print(integers) print(floats) print(boolean_values) print(animals) print(objects) # -------------------- Section 2 ------------------------- # # ---------------- List Modification --------------------- # print('\n' '# -------------------- Section 2 ------------------------- #') print('Accessing and Modifying a List' '\n') # 1. Accessing and Modifying a List # ------------------------------------------------------------ # Instructions # 1. Modify the lists created in Section 1, Part 2: # a. Integers --> Replace the item at position 2 with a new number. # b. Floats --> Replace the item at position 4 with a new number. # c. Booleans --> Replace the item at position 0 with itself negated. (not) # d. Animals --> Replace one of the animals with a new animal. # e. Objects --> Replace one of the items within the list with a new one. # 2. Print the lists. # # 1.a has been done for you. # # WRITE CODE BELOW print() integers[2] = 44 floats[4] = 24.7 boolean_values[0] animals[2] = 'dragon' objects[1] = 'alligator' print(integers) print(floats) print(boolean_values) print(animals) print(objects) print() # Booleans --> Data Type (True, False) print('\n' 'Append, Insert, and Remove' '\n') # 2. Accessing and Modifying a List # ------------------------------------------------------------ # Instructions # 1. Modify the lists created in Section 1, Part 2: # a. Integers --> Append a new number to the list. # b. Floats --> Append a new float to the list. # c. Booleans --> Remove one of the items from the list # d. Animals --> Insert a new animal at the beginning of the list. # e. Objects --> Insert a new object at the middle of the list. # 2. Print the lists. # # 1.a has been done for you. # # WRITE CODE BELOW integers.append(25) floats.append(15.6) boolean_values.remove() animals.insert() objects.insert print('\n' 'List Concatenation' '\n') # 3. List Concatenation # ------------------------------------------------------------ # # Lists like Strings can Concatenate with other Lists using the + operator. They can also be duplicated by # multiplying the list. # # Instructions # 1. Modify the lists created in Section 1, Part 2: # a. Concatenate the lists holding the integers and floats together, and save the result to a new variable. # d. Duplicate the list holding animals 3 times, and save the result to a new variable. # 2. Print the new lists. # # Examples are below for reference # # WRITE CODE BELOW things1 = integers + floats things2 = animals * 5 print( '\n' f'things1 | {things1}' '\n' f'things2 | {things2}' '\n' ) # -------------------- Section 3 ------------------------- # # --------------------- Looping -------------------------- # print('\n' '# -------------------- Section 3 ------------------------- #') print('Looping' '\n') # 1. Looping # ------------------------------------------------------------ # Instructions # 1. Create a loop that prints out the contents of the two of the lists you have already created, using the # methods below. # a. via in range() # b. via direct access # # An example has been shown below: # # WRITE CODE BELOW for i in range(list1): print(list1) for i in range(list2): pass # -------------------- Section 4 ------------------------- # # ------------------ Comprehension ----------------------- # print('\n' '# -------------------- Section 3 ------------------------- #') print('Dice - Statistics' '\n') # 1. Dice - Statistics # ------------------------------------------------------------ # Preface # When we roll a dice, the side it lands on is random. However, since a dice has multiple sides that are equivalent # in chance of falling, then we say a side has a 1/6 chance of happening, or 16.7% chance. Lets test to see if # that's true! # # 1. Create multiple for loops to run 5, 10, 100, and 1000 times. # a. Within the loops, roll a dice and append the roll to a list that is keeping track of all the rolls. # 2. After the loop has finished rolling, print the number of times each face appeared, as well as the rate of # rate of appearance. # # The beginning of the loop running 5 times has been done for you. Be sure to finish it. # # WRITE CODE BELOW from random import randint size = 5 rolls = [] for i in range(size): pass # finish the loop print(f'rolls | {rolls}') print(f'1\t| total - {rolls.count(1)}\t\t| rate of appearance - {"{:.2%}".format(rolls.count(1) / size)}') # finish the rest!
f4709cd1d6f3f2f645a9dcf0743a0fefe073014e
jainish-jain/GeeksforGeeks
/Mathematics/Quadratic Equation Root.py
848
3.8125
4
#{ #Driver Code Starts #Initial Template for Python 3 import math # } Driver Code Ends #User function Template for python3 ##Complete this function from math import floor def quadraticRoots(a,b,c): #Your code here s=(b*b)-(4*a*c) r=abs(s)**0.5 if s>0: h=floor((-b+r)/(2*a)) l=floor((-b-r)/(2*a)) if h>l: print(h,l) else: print(l,h) elif s==0: j=floor(-b/(2*a)) print(j,j) else: print("Imaginary") #{ #Driver Code Starts. def main(): T=int(input()) while(T>0): abc=[int(x) for x in input().strip().split()] a=abc[0] b=abc[1] c=abc[2] quadraticRoots(a,b,c) T-=1 if __name__=="__main__": main() #} Driver Code Ends
a9f24539c18c537b96a808dabc01506f4733fa5f
handsomm/PythonLearn
/Chapter 4 (list & tuple)/02_list_slicing.py
114
3.671875
4
# List slicing friends = ["shibu", "soumya", "handsomm", "tom", "jerry"] print(friends[0:4]) print(friends[-4:])
fe4a95ff7a5b3e86216fa5dae08e2fe8b918f3d6
PA3EFR/Supermarket_superpy
/report_inventory.py
1,801
3.546875
4
import os import sys import fileinput import csv import math from os import system, name from print_tabel import print_tabel count = 0 sales_price = 0.0 purchase_price = 0.0 sold_counter = 0 expire_counter = 0 value_loss = 0.0 full_path = os.path.realpath(__file__) file_directory = os.path.dirname(full_path) directory_path = os.path.join(file_directory, "initial_files") inventory_file = os.path.join(directory_path, "inventory.csv") expire_file = os.path.join(directory_path, "expires_dates.csv") purchase_file = os.path.join(directory_path, "purchase.csv") sales_file = os.path.join(directory_path, "sales.csv") with fileinput.input(files=inventory_file, inplace=False, mode='r') as file: reader =csv.DictReader(file) # print("\t,".join(reader.fieldnames)) # print back the headers for row in reader: purchase_price = purchase_price + float(row["purchase_price"]) count+= 1 # row counter if row["sold_price"] != "0.0": if row["exit_status"] == "sold": sales_price = sales_price + float(row["sold_price"]) sold_counter += 1 if row["exit_status"] == "expired": expire_counter += 1 value_loss += float(row["purchase_price"]) print_tabel(inventory_file) # external routine print("\n\n\tnumber of inventory items:",count) print("\n\ttotal purchase costs:\t\t", round((purchase_price),2)) print(f"\ttotal of {sold_counter} sales:\t\t", round((sales_price), 2)) print("\tnumber of expired items today:\t", expire_counter) print("\tvalueloss due to expired items:\t", value_loss) print("\ttoday's profit on total stock:\t", (round((sales_price-purchase_price-value_loss),2)), "\n\n\n")
9b3a5d14d59414311b806c799394e04c01f2c5c6
tjperr/aoc2020
/q4/a.py
487
3.515625
4
import re with open("input.txt") as file: entries = file.read().split("\n\n") passports = [] for entry in entries: passport = {} data = re.split("\\n| ", entry) for field in data: if ":" in field: key, value = field.split(":") passport[key] = value passports.append(passport) def valid(passport): keys = list(passport.keys()) keys.append("cid") return len(set(keys)) == 8 print(sum([valid(p) for p in passports]))
2534c1942f57399c023f519ab67ea0cf4df8fc5a
sainihimanshu1999/Data-Structures
/July2021/BitManipulation/ConsistentStrings.py
259
3.8125
4
'''using basic set''' def consistent(allowed,words): allowed = set(allowed) count = 0 for word in words: for letter in word: if letter not in allowed: count+=1 break return len(words)-count
fde6021ada2e72d88d11c0ab4e99d4277b38b54d
heitorchang/learn-code
/levelup/2018_jun/cracking_the_coding_interview/data_structures/queues_tale_of_two_stacks.py
1,471
4.09375
4
description = """ A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed. A basic queue has the following operations: Enqueue: add a new element to the end of the queue. Dequeue: remove the element from the front of the queue and return it. In this challenge, you must first implement a queue using two stacks. Then process queries, where each query is one of the following types: 1 x: Enqueue element into the end of the queue. 2: Dequeue the element at the front of the queue. 3: Print the element at the front of the queue. For example, a series of requests might be as follows: """ class MyQueue(object): def __init__(self): self.stack = [] def peek(self): return self.stack[0] def pop(self): self.stack.pop(0) def put(self, value): self.stack.append(value) """ t = int(input()) for line in range(t): values = map(int, input().split()) values = list(values) if values[0] == 1: queue.put(values[1]) elif values[0] == 2: queue.pop() else: print(queue.peek()) """ def test(): q = MyQueue() q.put(1)
f42fb927e0cdcb26a004b0bca9eafeabc397bb6f
ptrcode/cloudauto
/vmware-automation/python/check_port.py
678
3.9375
4
#!/usr/bin/python # Basic python check to see if a port is open, can be used for many different applications. # Author: Mark Austin <ganthore@gmail.com> # Usage: # ./check_port.py <host/ip> <port> import socket; import sys; import errno; sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def check_host(remote_ip,remote_port): remote_ip = sys.argv[1] remote_port = int(sys.argv[2]) result = sock.connect_ex((remote_ip,remote_port)) if result == 0: print "[SUCCESS] Host %s has port %s open" % (remote_ip, remote_port) sys.exit(0) else: print "[ERROR] Host %s does not have port %s open" % (remote_ip, remote_port) sys.exit(1) check_host(sys.argv[1], sys.argv[2])
4420382055090bec7bfd23ce6ff93dcad1d12449
vivibruce/dailycodingproblem
/max_nonadj_sum/max_nonadj_sum.py
521
4
4
''' Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative. For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10, since we pick 5 and 5 ''' inplst = list(map(int, input().split())) included_sum, excluded_sum = inplst[0], 0 for i in range(1,len(inplst)): temp = max(included_sum, excluded_sum) included_sum = excluded_sum + inplst[i] excluded_sum = temp print(max(included_sum, excluded_sum))
42f42ae9d4b0465d37aed32afc0d689b38ed220d
umelly/gf-lesson
/byte-of-python/task_9x9.py
457
3.546875
4
# -*- coding:utf-8 -*- """ 列*行=列行 1*1=1 1*2=2 2*2=4 1*3=3 2*3=6 3*3=0 ... """ for i in range(1,10):#行 for j in range(1,10):#列 if i>=j: print '%s*%s=%s' % (j,i,i*j), print print "\n\n", "="*80 ,"\n" print "".join([ '%s*%s=%s%s' % ( j, i, i*j, "\n" if i==j else "\t" ) for i in range(1,10) for j in range(1,10) if i>=j ])
4be486c6d63217fb9715040826b75e8b26bbe105
GreatRaksin/TurtleGraphics
/ListsOfNumbers.py
262
3.796875
4
import turtle tina = turtle.Turtle() tina.shape('turtle') screen = turtle.Screen() tina.pensize(2) tina.speed(50) number_list = range(1, 50) tina.color("green") for number in number_list: tina.forward(number * 2) tina.left(60) screen.exitonclick()
9fb8fc13d38b50a44bfb745fc2236709b9a75b67
ayushmad/puzzles
/project_euler/prob64.py
909
3.609375
4
import os import math import sys # This is can be later changed to a library # Takes a number at removes all the square terms def square_term(num): terms = range(2, int(math.ceil(math.pow(num, 2)))); terms.reverse(); for i in terms: if num%(i*i) == 0: num = num/(i*i); return num; def get_period(num): mprev = 0; dprev = 1; aprev = int(math.floor(math.pow(num, 0.5))); a0 = aprev; period = 0; while True: period += 1; mnext = dprev*aprev - mprev; dnext = (num - (mnext*mnext))/dprev anext = int(math.floor((a0 + mnext)/dnext)) if anext == 2*a0: return period; (mprev, dprev, aprev) = (mnext, dnext, anext); odd_period = 0; for i in range(2, 10000): if math.pow(i, 0.5)%1 == 0: continue; if not get_period(i)%2 == 0: odd_period += 1; print odd_period
2f281a4abfcec8c0da69c19f7d80cadab9478f42
nengdaqin/Python
/Study/Python_Basic_Study/file/json_file/qnd_05_josn文件写入.py
323
3.71875
4
# 导入模块 import json # 定义一个字典 my_dict = {"name": "小明", "age": 23, "no": "007"} # 将字典转成json -> 进行编码 json_str = json.dumps(my_dict) # 打印json字符串 print(type(json_str)) # 把json数据写入到文件中 with open("hm.json", "w", encoding="utf-8") as f: f.write(json_str)
a8b2cdd9ab7bcd28eaf23ba397a0e15929c51b4b
robinyms78/My-Portfolio
/Exercises/Python/Learning Python_5th Edition/Chapter 5_Numeric Types/Examples/Bitwise Operations/Example2/Example2/Example2.py
193
3.984375
4
# Binary literals X = 0b0001 # Shift left print(X << 2) # Binary digits string print(bin (X << 2)) # Bitwise OR: either print(bin (X | 0b010)) # Bitwise AND: both print(bin (X & 0b1))
3627fb347bc2450d8d866fe797890347c4cbf03c
LucasPAndrade/_Learning
/_Python/Fundamentos-CursoEmVídeo/Desafio 102.py
706
3.765625
4
print('=' * 10) print('DESAFIO 102 - Fatorial v.3') print('=' * 10, '\n') def fatorial(n, show=False): """ Calcula o fatorial de um número. :param n: Número a ser calculado. :param show: (opcional) Mostrar ou não o cálculo. :return: Valor do fatorial de um número n. """ f = 1 for c in range(n, 0, -1): f *= c if show: print(c, end='') if c > 1: print(' x ', end='') else: print(' = ', end='') return f nf = int(input('Digite um valor: ')) r = str(input('Visualizar cálculo? [S/N]')) if r in 'sS': ver = True else: ver = False print(fatorial(nf, ver)) help(fatorial)
7ec6b92e961c3d382cad95a06531bae6276c81fa
YazzyYaz/codinginterviews
/recursive/sum.py
172
3.625
4
def sum(alist): if len(alist) == 0: return 0 else: return alist[0] + sum(alist[1:]) if __name__ == "__main__": print(sum([0, 1, 2, 3, 4, 5]))
a8e67cbd7935c21ecbac0e46a2598b84faa208fe
soundlake/projecteuler
/problem047/sol.py
1,226
3.53125
4
primes = [2, 3] def extendPrimesUpto(limit): if limit < primes[-1]: return primes def isPrime(n): if n in primes: return True for p in primes: if p > n**.5: return True if n % p == 0: return False return True o1 = (5 - primes[-1]) % 6 o2 = (9 - primes[-1]) % 6 if o1 > o2: o1, o2 = o2, o1 for c in range(primes[-1]+2, limit+1, 6): if c+o1<=limit and isPrime(c+o1): primes.append(c+o1) if c+o2<=limit and isPrime(c+o2): primes.append(c+o2) return primes def factorize(n): pfs = {} if n > primes[-1]: extendPrimesUpto(n*2) while n > 1: for p in primes: if n % p: continue n /= p if p in pfs: pfs[p] += 1 else: pfs[p] = 1 break return pfs def isConsecutive(t): return all(t[i]+1 == t[i+1] for i in range(len(t)-1)) def findConsecutiveNumbersWithSameNumberOfDistinctPrimeFactor(N): n = 1 a = [] while 1: if len(factorize(n)) == N: a.append(n) if len(a) > N: a = a[-N:] if len(a) == N and isConsecutive(a): return a n += 1 print findConsecutiveNumbersWithSameNumberOfDistinctPrimeFactor(4)
dbf4a05aa269427dc735ff81510aed60182b1d3c
RowiSinghPXL/IT-Essentials
/3_condities/oefening3.6.py
375
3.59375
4
basis_prijs = 5 huidig_jaar = 2018 jaar = int(input("Van welk jaar is de film: ")) rating = int(input("Welke rating heeft de film (1 - 5): ")) prijs = basis_prijs if huidig_jaar - jaar < 2: prijs += 1 if rating == 4 or rating == 5: prijs +=2 elif rating == 3 or rating == 2: prijs +=1 if prijs > 7: prijs = 7 print("De prijs voor de film is:", prijs)
0576b4505c8e0f08bb2470d81baf02264e632282
LizinczykKarolina/Python
/Regex/ex30.py
927
4.3125
4
#46. Write a Python program to find all adverbs and their positions in a given sentence. import re sample_text = """ Clearly, he has no excuse for such behavior. He was carefully disguised but captured quickly by police. """ pattern = r"\w+ly" for a in re.finditer(pattern, sample_text): print "{0}-{1}: {2}".format(a.start(), a.end(), a.group(0)) print "-------------------------------" #47. Write a Python program to split a string with multiple delimiters. text = 'The quick brown\nfox jumps*over the lazy dog.' print re.split(r"\n|\*|;|,", text) print "---------------------------------" #48. Write a Python program to check a decimal with a precision of 2. def is_decimal(num): import re pattern = re.match(r"\d+\.\d{2}$", num) if pattern: return True else: return False print(is_decimal('123.11')) print(is_decimal('123.1')) print(is_decimal('123')) print(is_decimal('0.21'))
85fac8915b3bf2c1e96a52f197aefdd55f885d87
mrmoore6/Module-4-Py-2
/Card_Game.py
803
3.53125
4
""" Name: Michael Moore Date: 2/11/2021 Program: Card_Game.py Description: This game randomizes a 6x6 array and manipulates for each players hand and sums the total \ for winner. """ import numpy as np my_array = np.arange(1, 37) np.random.shuffle(my_array) my_array = np.array(my_array) my_array.resize(6, 6) x = np.identity(6) my_new_array = my_array * x my_new_array = np.array(my_new_array) id_array = np.identity(6) c_array = np.arange(1, 37) c_array = np.array(c_array / c_array) c_array.resize(6, 6) c_array = id_array - c_array c_array = c_array * my_array my_array = my_new_array + c_array x = my_array.sum(axis=0) max_score = np.max(x) max_player = np.nanargmax(x) + 1 print(my_array) print('\n''Results {}'.format(x)) print('\n''Winner is player {} with a {}'.format(max_player, max_score))
6977fbc400c6f6f5af433c8f0b9a9278449eff95
Zenglinxiao/ReinforcementLearning
/session_2/agent.py
5,102
3.609375
4
import numpy as np from scipy.special import gamma np.random.seed() """ Contains the definition of the agent that will run in an environment. """ class RandomAgent: def __init__(self): """Init a new agent. """ def choose(self): """Acts given an observation of the environment. Takes as argument an observation of the current state, and returns the chosen action. """ return np.random.randint(0, 10) def update(self, action, reward): """Receive a reward for performing given action on given observation. This is where your agent can learn. """ pass class epsGreedyAgent: def __init__(self): self.A = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] self.mu = np.zeros(len(self.A)) self.optimal_mu = 0 self.draws = np.zeros(len(self.A)) self.epsilon = 0.0 def choose(self): self.optimal_mu = np.argmax(self.mu) random = np.random.randn() if random < self.epsilon: return np.random.randint(0, len(self.A)) else: return self.optimal_mu def update(self, action, reward): self.draws[action] += 1 self.mu[action] = ((self.draws[action]-1)*self.mu[action] + reward)/self.draws[action] class UCBAgent: # https://homes.di.unimi.it/~cesabian/Pubblicazioni/ml-02.pdf def __init__(self): self.A = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] self.mu = np.zeros(10) self.optimal_mu = 0 self.draws = np.zeros(10) def choose(self): # Compute bounds n = np.sum(self.draws) bounds = self.mu + np.sqrt(2*np.log(n)/self.draws) self.optimal_policy = np.argmax(bounds) return self.optimal_policy def update(self, action, reward): self.draws[action] += 1 self.mu[action] = ((self.draws[action]-1)*self.mu[action] + reward)/self.draws[action] class BesaAgent(epsGreedyAgent): # https://hal.archives-ouvertes.fr/hal-01025651v1/document def __init__(self): self.A = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] self.mu = np.zeros(10) self.draws_rewards = [[] for i in range(10)] def choose(self): # A changer: passer le calcul de mu_hat ici # D'abord, tirer tous les bras qu'on a encore jamais tire # Puis faire le calcul "classique" N_per_actions = [len(draws_per_action) for draws_per_action in self.draws_rewards] min_arm, min_arm_len = np.argmin(N_per_actions), np.min(N_per_actions) if min_arm_len == 0: # print('explore arm no', min_arm) return min_arm else: for temp_action in self.A: random_draw_per_action = np.random.choice(N_per_actions[temp_action], min_arm_len, replace=False) self.mu[temp_action] = np.mean(np.array(self.draws_rewards[temp_action\ ])[random_draw_per_action]) # print('compute mu: {}\n try arm: {}'.format(self.mu, np.argmax(self.mu))) return np.argmax(self.mu) def update(self, action, reward): # Add new observation in list associated to action self.draws_rewards[action].append(reward) class SoftmaxAgent: # https://www.cs.mcgill.ca/~vkules/bandits.pdf def __init__(self): self.A = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] self.tau = float(0.01) # hyperparameter self.mu = np.ones(len(self.A))/len(self.A) # initialized mu at uniform random self.draws = np.zeros(len(self.A)) # number of times each arm is drawn def choose(self): p = (np.exp(self.mu)/self.tau)/np.sum((np.exp(self.mu)/self.tau)) return np.argmax(p) def update(self, action, reward): # Update mu(action) with moving mean self.draws[action] += 1 self.mu[action] = ((self.draws[action]-1)*self.mu[action] + reward)/self.draws[action] class ThompsonAgent: # https://en.wikipedia.org/wiki/Thompson_sampling """ We will implement Bernouilli Thompson Agent (from ```A Tutorial on Thompson Sampling```, Daniel J. Russo)""" def __init__(self): self.A = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] self.alpha = np.ones(len(self.A))*1e-4 self.beta = np.ones(len(self.A))*1e-4 def choose(self): # Compute probability of theta with beta distribution p = np.random.beta(self.alpha, self.beta) return np.argmax(p) def update(self, action, reward): print(self.alpha, self.beta) # Update alpha, beta self.alpha[action] += reward self.beta[action] += (1 - reward) print(self.alpha, self.beta) class KLUCBAgent: # See: https://hal.archives-ouvertes.fr/hal-00738209v2 def __init__(self): self.A = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] def choose(self): raise NotImplemented def update(self, action, reward): raise NotImplemented # Choose which Agent is run for scoring Agent = BesaAgent
3adcc28caccac8e55a2be53e1fdcd20fc60e3be0
elizabethdaly/pands-project
/get-data.py
3,389
3.890625
4
# Elizabeth Daly # HDip Data Analytics 2019 pands-project # # get-data.py # Script to read in & analyse the iris data set. # # ########################################################### # Import Pandas data analysis library. import pandas as pd # Import matplotlib for 2D plotting. import matplotlib.pyplot as plt # Import Numpy import numpy as np # Read the iris.csv file from this directory. # The result is a DataFrame, the basic data format for Pandas. data = pd.read_csv('iris.csv') # ########################################################### # Look at various attributes of the data to get an idea of its structure. # General information about the data set. print(data.info()) # Print the first few lines. print(data.head()) # What are the data types of each column? print(data.dtypes) # What is the number of rows, columns in the data set? d_shape = data.shape print("n rows = ", d_shape[0], ", n_cols = ", d_shape[1] ) # What are the row labels of the DataFrame? print("Data index: ", data.index) # What are the column labels of the DataFrame? col_labels = data.columns print("Data column labels: ", col_labels) # List the unique values in data['Name'] column i.ie species. species = data.Name.unique() print("The three species are: ", species) # These are the column headings. print("col1: ", col_labels[0]) print("col2: ", col_labels[1]) print("col3: ", col_labels[2]) print("col4: ", col_labels[3]) print("col5: ", col_labels[4]) # ########################################################### # Try some plotting. I want each column as a line. # Keep track of axes so they can be used several times. ax = plt.gca() # Plot each column of the data set as a different colour. data[col_labels[0]].plot(kind='line', y= 'SepalLength', ax=ax) data[col_labels[1]].plot(kind='line', y= 'SepalWidth', color='green', ax=ax) data[col_labels[2]].plot(kind='line', y= 'PetalLength', color='red', ax=ax) data[col_labels[3]].plot(kind='line', y= 'PetalWidth', color='yellow', ax=ax) # Set x range. plt.xlim(0, 150) # Set the x tick marks. x = np.arange(0, 150, 25) plt.xticks(x) # Graph, x-axis, and y-axis titles. plt.title("Overview of the Iris Data Set", fontsize=18) plt.ylabel('cm', fontsize=16) plt.xlabel('sample', fontsize=16) # Graph legend and grid plt.legend(loc='best', fontsize=10) plt.grid() # Save the figure. plt.savefig('Overview.jpeg') plt.show() # ########################################################### # Use describe() to get some basic statistics about each column. # It would make more sense to get this information for each species, # but I'll start with this. # print(data[col_labels[0]].describe()) # print(data[col_labels[1]].describe()) # print(data[col_labels[2]].describe()) # print(data[col_labels[3]].describe()) # print(data[col_labels[4]].describe()) # Or do all the numeric columns together, the output is another dataframe. data_summary = data.describe() print(data_summary) # ########################################################### # Plot these summary statistics as a bar chart. # Omits count row by selecting all but first row of summary statistics dataframe. data_summary.iloc[1:8,0:4].plot.bar() # Set up graph properties. plt.title("Summary statistics: all species", fontsize=18) plt.ylabel('cm', fontsize=16) plt.legend(loc='best', fontsize=10) plt.grid() # Save the figure. plt.savefig('SummaryStats.jpeg') plt.show()
8f2100cb292fd30dd7c7caf712b82c12cc67d7d4
iayoung85/2ndsandbox
/postage3.py
201
3.640625
4
#figure 3 program def postage(weight): import math costfig3=49 if weight>1: costfig3=costfig3+22*math.ceil(weight-1) if weight>3.5: costfig3 +=49 return costfig3/100
78cfc50c70cc9c75ed3e413c4f499bbe26c56100
sarias12/AirBnB_clone
/console.py
6,923
3.515625
4
#!/usr/bin/python3 """ The command interpreter """ import cmd import sys import shlex import models from models.base_model import BaseModel from models.user import User from models.place import Place from models.state import State from models.city import City from models.amenity import Amenity from models.review import Review class HBNBCommand(cmd.Cmd): """ HBNBCommand """ classes = { 'BaseModel': BaseModel, 'Amenity': Amenity, 'State': State, 'Place': Place, 'Review': Review, 'User': User, 'City': City } prompt = '(hbnb) ' def do_EOF(self, line): """ Ctrl + D command to exit the program (End of File). """ return True def do_quit(self, args): """ Quit command to exit the program. """ return True def emptyline(self): """ This does nothing. An empty line + ENTER shouldn’t execute anything. """ pass def do_create(self, arg): """do_create Creates a new instance of class BaseModel. Arg: arg (class): name. Syntax: cretate <class_name> Example: $ create BaseModel """ args = shlex.split(arg) if len(args) == 0: print("** class name missing **") elif args[0] in self.classes: new_instance = self.classes[args[0]]() new_instance.save() print(new_instance.id) else: print("** class doesn't exist **") def do_show(self, arg): """do_show Prints the string representation of an instance based on the class name and id Args: arg (class): class's name (instance) and id. Syntax: show <class_name> <id> Example: $ show BaseModel 1234-1234-1234 """ args = shlex.split(arg) if len(args) == 0: print("** class name missing **") elif not args[0] in self.classes: print(args[0]) print("** class doesn't exist **") elif len(args) == 1: print("** instance id missing **") else: all_obj = models.storage.all() for key, value in all_obj.items(): id_current = key.split('.') if id_current[1] == args[1]: print(all_obj[key]) return print("** no instance found **") def do_destroy(self, arg): """do_destroy Deletes an instance based on the class name and id Args: arg (class): class's name (instance) and id. Syntax: destroy <class_name> <id> Example: $ destroy BaseModel 1234-1234-1234 """ args = shlex.split(arg) if len(args) == 0: print("** class name missing **") elif not args[0] in self.classes: print("** class doesn't exist **") elif len(args) == 1: print("** instance id missing **") else: idx = "{}.{}".format(args[0], args[1]) all_obj = models.storage.all() if idx in all_obj: all_obj.pop(idx) models.storage.save() else: print("** no instance found **") def do_all(self, arg): """do_all Prints all string representation of all instances based or not on the class name Args: arg (class): class's name (instance) or nothing. Syntax: all or all <class_name> Example: $ all (...) $ all BaseModel """ args = shlex.split(arg) all_obj = models.storage.all() new_list = [] for key, value in all_obj.items(): new_list.append(str(all_obj[key])) if len(args) == 0: print(new_list) elif args[0] in self.classes: new_list = [] for key, value in all_obj.items(): obj_current = key.split('.') if obj_current[0] == args[0]: new_list.append(str(all_obj[key])) print(new_list) else: print("** class doesn't exist **") def do_update(self, arg): """do_update Updates an instance based on the class name and id by adding or updating attribute Args: arg (class): class's name (instance), id, key and value. Syntax: update <class_name> <id> <key> <value> Example: $ all BaseModel 1234-1234-123 email "example@holbertonschool.com" """ args = shlex.split(arg) all_obj = models.storage.all() if len(args) == 0: print("** class name missing **") elif not args[0] in self.classes: print("** class doesn't exist **") elif len(args) == 1: print("** instance id missing **") elif len(args) == 2: print("** attribute name missing **") elif len(args) == 3: print("** value missing **") else: obj = "{}.{}".format(args[0], args[1]) if obj in all_obj: obj_new_attribute = all_obj[obj] try: tmp = eval(args[3]) if type(tmp) == int or type(tmp) == float: args[3] = tmp except: pass setattr(obj_new_attribute, args[2], args[3]) obj_new_attribute.save() else: print("** no instance found **") def default(self, arg): """default [summary] Args: arg ([type]): [description] Returns: [type]: [description] """ args = arg.split('.') if len(args) > 1: if args[1] == 'all()': return self.do_all(args[0]) elif args[1] == 'count()': count = 0 all_obj = models.storage.all() for key, value in all_obj.items(): tmp = key.split('.') if args[0] in tmp: count += 1 print(count) return else: try: tmp = args[1].split('show') tmp2 = eval(tmp[1]) self.do_show(args[0] + ' ' + tmp2) return except: pass try: tmp = args[1].split('destroy') tmp2 = eval(tmp[1]) self.do_destroy(args[0] + ' ' + tmp2) return except: pass print("*** Unknown syntax: {}".format(arg)) if __name__ == '__main__': HBNBCommand().cmdloop()
c2321344bbe7ee6e338a879bceb69a39bed73f1d
danielthorr18/forritun_git
/FUNCTIONS/7.1.functions.py
326
4.15625
4
def find_min(num1, num2): if num1 < num2: return(num1) else: return(num2) # find_min function definition goes here first = int(input("Enter first number: ")) second = int(input("Enter second number: ")) minimum = find_min(first, second) # Call the function here print("Minimum: ", minimum)
eb0212d3c2443b4266f51b9d7de4b4fba0daa6df
dwaq/advent-of-code-solutions
/2022/01/1-feed.py
442
3.625
4
txt = open("input.txt", "r").readlines() #print(txt) # store each elf's calories elf = [] count = 0 for line in txt: # when not a newline if (line != '\n'): # add that to the elf's count count += int(line) else: # put that elf's count into the list elf.append(count) # reset count count = 0 #print(elf) # the elf with the most calories print(max(elf)) #print(elf.index(max(elf)))
c06423f62784888a5ba0591ae6a1e3a41861beaf
ct61632n/CS3612017
/Python/Exercise7.py
484
4.1875
4
#prints list def List(): list = ['a','b','c','d','e'] for i in (list): print (i) List() print("\n") #prints list reversed def Listrev(): list = ['a','b','c','d','e'] for i in reversed(list): print(i,) Listrev() print("\n") #prints len of the list def Size(): list = ['a','b','c','d','e'] lenoflist = 0 for i in (list): lenoflist += 1 print(lenoflist) print("The size of the list is") Size()
706307c2d91b068ad301f3ebcba3cce0a443edcd
rajlath/rkl_codes
/Miscellaneous/Trie2.py
1,422
4.125
4
from collections import defaultdict class Trie(object): ''' implements Trie data structrue methods include Insert Search Prefix ''' def __init__(self): self.root = defaultdict() def insert(self, word): ''' @param {String} word @return void inserts a word into the trie ''' current = self.root for ch in word: current = current.setdefault(ch, {}) current.setdefault("_end") def search(self, word): ''' @param {string} word @return {boolean} searches trie for the word, return True if found else False ''' current = self.root for ch in word: if ch not in current: return False current = current[ch] if "_end" in current: return True return False def start_with(self, prefix): ''' @param {String} prefix @return {Boolean} searches for prefix in Trie, return True if found else False ''' current = self.root for ch in prefix: if ch not in current: return False else: current = current[ch] return True test = Trie() test.insert("Raj") test.insert("lath") test.insert("Padma") print(test.search("Lath")) print(test.search("lath")) print(test.start_with("la"))
3022f5cc163a8ff72cf17333a5a414eafff86c0f
JakubKazimierski/PythonPortfolio
/AlgoExpert_algorithms/Medium/Permutations/test_Permutations.py
1,004
3.703125
4
''' Unittests for Permutations.py February 2021 Jakub Kazimierski ''' import unittest from Permutations import getPermutations class test_Permutations(unittest.TestCase): ''' Class with unittests for Permutations.py ''' def SetUp(self): ''' Set Up input list. ''' self.input = [1, 2, 3] # due to list in list is not hashable type, use tuple for permutation self.output = [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)] return self.input, self.output # region Unittests def test_RemoveKthNodeFromEnd(self): ''' Checks if output is correct. ''' input_list, correct_output = self.SetUp() output = getPermutations(input_list) self.assertEqual(set(output), set(correct_output)) # endregion if __name__ == "__main__": ''' Main method for test cases. ''' unittest.main()
e09c72db774177b13819ffbcbdc494380d2ddd59
DT2004/Python2
/app.py
424
3.96875
4
character_name = "Murasame" # this is the first variable character_age = "8" # this is the second variable print("There once was a boat named "+ character_name + ", ") # vatiables are not enclosed by strings print("She was "+ character_age + " years old.") print(character_name + " really liked helping her friends,") print("But " + character_name + " only got to be " + character_age + " years old.") #now run the program
4871ef2ea79f5369e27673b1efd60a0fc76a85a4
jovemsabio/CPF-Calc
/main.py
299
3.53125
4
from validador import validaCPF if __name__ == '__main__': while True: cpf = input('Informe o CPF (apenas números), \'q\' para sair: ') if cpf == 'q': break if validaCPF(cpf): print('CPF válido') else: print("CPF Invalido")
cbc46e1c31476dd41006abe275a8f8bdc9280361
MasKong/Algorithms
/sort.py
6,851
4.0625
4
class Sort(): def __init__(self, l = None): if l is not None: assert type(l) == list,("please input a list") else: l = self._generate() self.l = l self.result = None def insert_sort(self): l = self.l #add new reference to self.l, change l would change self.l for i in range(1,len(l)): #use built-in methods to insert for j in range(i-1,-1,-1): if l[i] < l[j]: if j == 0: l.insert(j,l[i]) del(l[i+1]) elif l[i] >= l[j-1]: l.insert(j, l[i]) del (l[i + 1]) def insert_sort_v1(self): #much slower than using built-in method l = self.l #add new reference to self.l, change l would change self.l for i in range(1,len(l)): #switch position for j in range(i-1,-1,-1): if l[j+1] < l[j]: l[j], l[j+1] = l[j+1], l[j] def bubble_sort(self): l = self.l for i in range(0,len(l)-1): for j in range(0,len(l)-i-1): if l[j] > l[j+1]: l[j], l[j+1] = l[j+1], l[j] # def quick_sort(self): # '''extra space usage''' # '''divide the original into two parts such that elements in part a < that of part b''' # l1 = [] # l2 = [] # pivot = self.l[-1] # for i in self.l: # if i <= pivot: # l1.append(i) # else: # l2.append(i) # l1.append(pivot) def quick_sort(self, p=None, r=None): '''extra space usage''' '''divide the original into two parts such that elements in part a < that of part b''' if p is None or r is None: p = 0 r = len(self.l) # print("p ",p) # print("r ", r) if p<r-1: q = self._quick_sort_partition(p, r) # print("q ", q) self.quick_sort(p,q) self.quick_sort(q,r) # self._quick_sort_partition(p, q) # self._quick_sort_partition(q, r) # q = self._quick_sort_partition(p, r) # print(q) # while True: # if self._quick_sort_partition(p, q) == 0: # break # while True: # if self._quick_sort_partition(q, r) == r-1: # break # q = self._quick_sort_partition(0,len(self.l)) # self.quick_sort(p,q) # self.quick_sort(q,r) # else: # q = self._quick_sort_partition(p, r) # self.quick_sort(p, q - 1) # self.quick_sort(q, r) def _quick_sort_partition(self, p, r): # l = list(self.l) l = self.l i = p-1 pivot = l[r-1] for j in range(p,r-1): #in-place exchange without memory overhead if l[j] <= pivot: i += 1 l[i], l[j] = l[j], l[i] # print(i) # print(l) l[i+1], l[r-1] = l[r-1], l[i+1] # print(l) # print(self.l) # print("i ",i) return i+1 def merge_sort(self, p=None, r=None): l = self.l if p is None or r is None: p = 0 r = len(l) #not include r if p < r-1: q = int((p+r)/2) self.merge_sort(p,q) self.merge_sort(q, r) self.merge(p,q,r) def merge(self, p,q,r): l = self.l L = l[p:q] R = l[q:r] L.append(float('inf')) R.append(float('inf')) i,j = 0,0 for k in range(p,r): #r = len(list), not include r if L[i] < R[j]: l[k] = L[i] i+=1 else: l[k] = R[j] j += 1 def merge_two_lists(self,l1,l2): assert l1 is None or l2 is None,("empty list") l = [] i = 0 j = 0 while i<len(l1) and j<len(l2): if l1[i] < l2[j]: l.append(l1[i]) i+=1 else: l.append(l2[j]) j += 1 if i == len(l1): l.extend(l2[j:]) else: l.extend(l1[i:]) return l def heap_sort(self): l = self.l self.heap_size = len(l) self.build_heap() for i in range(len(l)-1,0,-1): #no need to include 0. change with itself is meaningless l[i], l[0] = l[0], l[i] self.heap_size -= 1 self.max_heaplify(0) def build_heap(self): #bottom up. the first level of the tree has no child, no need to maintain for i in range(int(self.heap_size/2),-1,-1): self.max_heaplify(i) def max_heaplify(self,i): l = self.l left = 2*i +1 right = 2*i +2 largest = i if left < self.heap_size and l[left] > l[i]: largest = left if right < self.heap_size and l[right] > l[largest]: largest = right if largest != i: '''if position changes, need to recursively run max_heaplify to guarantee the descendant are also max heap''' l[i], l[largest] = l[largest], l[i] self.max_heaplify(largest) def _evaluate(self): if self.result is None: self.result = self.l for i in range(1,len(self.result)): if self.result[i] < self.result[i-1]: return False return True def _generate(self,length = None): try: import random if length is None: length = random.randint(0, 1000) # length = random.randint(0,100000) l = [] for i in range(length): l.append(random.randint(-length,length)) return l except ImportError: print("no random module, please input a sequence") l = [4,6,1,0,5,-9,0,5,] # l = [4,6,10,23,-1,-6] # s = Sort(l) # print(s._quick_sort_partition(0,len(l))) # print(s.l) s = Sort() # s.quick_sort() print("length ",len(s.l)) s.heap_sort() # s.build_heap() # s.merge_sort() # s.insert_sort_v1() # s.insert_sort() print(s._evaluate()) # s._quick_sort_partition(0,len(l)) print(s.l) def compare_time(): import time print("**************compare time**************") s = Sort() l = s._generate(1000000) start_time = time.time() Sort(l).quick_sort() print("--- %s seconds ---" % (time.time() - start_time)) start_time = time.time() Sort(l).merge_sort() print('--- {} seconds ---'.format(time.time() - start_time)) start_time = time.time() Sort(l).heap_sort() print('--- {} seconds ---'.format(time.time() - start_time)) compare_time()
127712ac25c36d95dd83f0068133051413a4fe14
thedegar/thinkful-data-science-webscrape
/education.py
8,041
3.859375
4
##################################################### # Tyler Hedegard # 6/21/2016 # Thinkful Data Science # GDP + Education Web Scrape Project ##################################################### from bs4 import BeautifulSoup import requests import sqlite3 as lite import pandas as pd import matplotlib.pyplot as plt import csv import numpy as np import statsmodels.api as sm def sqlTodf(query): """creates a pandas dataframe from a sql query assumes sqlite3 connection = con and cur = con.cursor()""" with con: cur.execute(query) rows = cur.fetchall() cols = [desc[0] for desc in cur.description] return pd.DataFrame(rows, columns=cols) # Collect the UN Education data url = "http://web.archive.org/web/20110514112442/\ http://unstats.un.org/unsd/demographic/products/socind/education.htm" r = requests.get(url) soup = BeautifulSoup(r.content) myTable = soup('table')[6] my_tbody = myTable('tbody')[3] max_count = len(my_tbody('tr')) # Connect to the database con = lite.connect('UNdata.db') print("Connected to database: UNdata.db") with con: cur = con.cursor() # Create the countries table cur.execute("DROP TABLE IF EXISTS countries") cur.execute("DROP TABLE IF EXISTS gdp") cur.execute("CREATE TABLE countries (country text, male number, female number, year number)") cur.execute("CREATE TABLE gdp (country_name text, _1999 text, _2000 text, \ _2001 text, _2002 text, _2003 text, _2004 text, _2005 text, \ _2006 text, _2007 text, _2008 text, _2009 text, _2010 text)" ) for i in range(4,max_count): row = my_tbody('tr')[i] country = (row('td')[0].string) male = int(row('td')[7].string) female = int(row('td')[10].string) year = int(row('td')[1].string) data = (country,male,female,year) cur.execute("INSERT INTO countries VALUES(?,?,?,?)", data) df_edu = sqlTodf("select * from countries") # Show descriptive statistics for the education data list = ['male','female'] for each in list: col = df_edu[each] #plt.hist(col) print('Descriptive statistics for males: ') print(' Mean: {}'.format(col.mean())) print(' Median: {}'.format(col.median())) print(' Min: {}'.format(col.min())) print(' Max: {}'.format(col.max())) print(' Range: {}'.format(col.max()-col.min())) print(' Variance: {}'.format(col.var())) # Collect GDP Data with open('GDP.csv','r') as inputFile: next(inputFile) # skip the first two lines next(inputFile) next(inputFile) next(inputFile) header = next(inputFile) inputReader = csv.reader(inputFile) country_list = [] # handles duplicate rows for line in inputReader: if line[43] == '' or line[0] in country_list: pass else: country_list.append(line[0]) data = (line[0], line[43], line[44], line[45], line[46], line[47], line[48], line[49], line[50], line[51], line[52], line[53], line[54]) with con: cur.execute('INSERT INTO gdp (country_name, _1999, _2000, _2001, _2002, _2003, _2004, _2005, _2006, _2007, _2008, _2009, _2010) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)',data) df_gdp = sqlTodf("select * from gdp") df_join = sqlTodf("select c.*, g.* from countries c join gdp g on c.country = g.country_name") df_join['gdp'] = '' # Find the gdp for the year of the education data point for i in range(0,df_join.shape[0]): this = '_'+str(df_join['year'][i]) df_join['gdp'][i] = float(df_join[this][i]) # Final clean data set to test with df_test = df_join[['country','male','female','year','gdp']] male = df_test['male'] female = df_test['female'] gdp = df_test['gdp'] # The dependent variables are male and female y_male = male y_female = female # The independent variable is gdp # Converting GDP to log. As regular number the fit was even worse x = np.log(np.array(gdp, dtype=float)) X = sm.add_constant(x) male_model = sm.OLS(y_male, X) female_model = sm.OLS(y_female, X) f_male = male_model.fit() f_female = female_model.fit() # Null hypothesis is that the education level and gdp do not relate to each other f_male.summary() """ OLS Regression Results ============================================================================== Dep. Variable: male R-squared: 0.248 Model: OLS Adj. R-squared: 0.242 Method: Least Squares F-statistic: 46.72 Date: Fri, 24 Jun 2016 Prob (F-statistic): 2.23e-10 Time: 14:42:55 Log-Likelihood: -327.83 No. Observations: 144 AIC: 659.7 Df Residuals: 142 BIC: 665.6 Df Model: 1 ============================================================================== coef std err t P>|t| [95.0% Conf. Int.] ------------------------------------------------------------------------------ const -0.5170 1.909 -0.271 0.787 -4.290 3.256 x1 0.5437 0.080 6.835 0.000 0.386 0.701 ============================================================================== Omnibus: 1.467 Durbin-Watson: 2.184 Prob(Omnibus): 0.480 Jarque-Bera (JB): 1.077 Skew: -0.189 Prob(JB): 0.584 Kurtosis: 3.193 Cond. No. 232. ============================================================================== Conclusion: Reject the null hypothesis since p < 0.05. Male education levels are impacted by the GPD of the country. The fit of this model is not great though with R-squared = 0.248. f(x) = 0.5437(log(x)) - 0.5170 """ f_female.summary() """ OLS Regression Results ============================================================================== Dep. Variable: female R-squared: 0.216 Model: OLS Adj. R-squared: 0.210 Method: Least Squares F-statistic: 39.12 Date: Fri, 24 Jun 2016 Prob (F-statistic): 4.42e-09 Time: 14:42:56 Log-Likelihood: -373.74 No. Observations: 144 AIC: 751.5 Df Residuals: 142 BIC: 757.4 Df Model: 1 ============================================================================== coef std err t P>|t| [95.0% Conf. Int.] ------------------------------------------------------------------------------ const -3.7681 2.625 -1.435 0.153 -8.958 1.421 x1 0.6843 0.109 6.254 0.000 0.468 0.901 ============================================================================== Omnibus: 1.228 Durbin-Watson: 2.119 Prob(Omnibus): 0.541 Jarque-Bera (JB): 1.326 Skew: -0.197 Prob(JB): 0.515 Kurtosis: 2.742 Cond. No. 232. ============================================================================== Conclusion: Reject the null hypothesis since p < 0.05. Female education levels are impacted by the GPD of the country. The fit of this model is also not great though with R-squared = 0.216. f(x) = 0.6843(log(x)) - 3.7681 """
3a66367816e3083caa9befbdc5c4f6b0ecd891cb
ricvo/argo
/word_embeddings/test/nearest_words_from_analogy.py
5,107
3.578125
4
""" Testing of a word embedding, answers to queries a:b=c:d. It is possible to specify a, b and d; so to obtain the word embedding nearer to a-b+d, i.e. the best approximation for c. """ import argparse import numpy as np import os, sys from utils import * parser = argparse.ArgumentParser(description='Testing of a word embedding, answers to queries a:b=c:d. It is possible to specify a, b and d; so to obtain the word embedding nearer to a-b+d, i.e. the best approximation for c.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('inputfile', help='The file where to find the parameters of the GloVe model. Each line: word u_vec u_bias v_vec v_bias') parser.add_argument('--howmany', '-hm', type=int, help='Returns the nearest words in the word_embedding space. How many words to return with associated distances.', default=10) parser.add_argument('--amonghowmany', '-ahm', type=int, help='How many words of the dictionary to consider as candidates, i.e. among how many words to consider the possible "nearest words" to the analogy. -1 for all of them.', default=-1) parser.add_argument('--vecsize', '-v', required=True, type=int, help='Vector size of the word embedding.') parser.add_argument('--worda', '-a', help='The word a.', default='king') parser.add_argument('--wordb', '-b', help='The word b.', default='man') parser.add_argument('--wordd', '-d', help='The word d.', default='woman') parser.add_argument('--onlyu', action='store_true', help='If this flag is set, only the u vector is expected, thus only the distance in the euclidean space is possible.') parser.add_argument('--numthreads', '-nt', type=int, help='Number of threads to use.', default=20) parser.add_argument('--tolerance', action='store_true', help='This is the tolerance flag in the query. If true, the words of the query are removed from the possible answers. a:b=c:? can never return a, b or c.') args = parser.parse_args() vecsize = args.vecsize onlyu = args.onlyu tolerance=args.tolerance numthreads=args.numthreads os.environ['OMP_NUM_THREADS'] = str(numthreads) os.environ['NUMEXPR_NUM_THREADS'] = str(numthreads) dictionary_size, dictionary, reversed_dictionary, u_embeddings, \ u_biases, v_embeddings, v_biases = \ read_embeddings(args.inputfile, args.vecsize, onlyu) if (not onlyu) and (u_embeddings.shape != v_embeddings.shape): raise ValueError("The dimensions of the loaded u_embeddings (%d,%d) are not matching with the dimensions of the loaded v_embeddings (%d,%d). Quitting.."%(u_embeddings.shape[0], u_embeddings.shape[1],v_embeddings.shape[0],v_embeddings.shape[1])) if u_embeddings.shape[0] != len(dictionary): raise ValueError("The number of vectors present in the embeddings is %d while the lenght of the dictionary is %d. Quitting.."%(u_embeddings.shape[0], len(dictionary))) howmany=args.howmany amonghowmany=args.amonghowmany if amonghowmany==-1: amonghowmany=None # a:b=c:d wa=args.worda wb=args.wordb wd=args.wordd import time print(" Query result for %s - %s + %s = ?"%(wa,wb,wd)) print("\n u embedding in Euclidean space measures") start = time.time() distcalc=DistanceCalculatorMeasuresEuclidean(dictionary, reversed_dictionary, u_embeddings, v_embeddings, howmany, amonghowmany, tolerance=tolerance) iam = distcalc.analogy_query_c(wa, wb, wd) end = time.time() print_array([(reversed_dictionary[i], dist) for (i,dist) in iam]) print("time: %f"%(end - start)) print("\n") print("\n u embedding in Euclidean space target") start = time.time() distcalc=DistanceCalculatorTargetEuclidean(dictionary, reversed_dictionary, u_embeddings, v_embeddings, howmany, amonghowmany, tolerance=tolerance) iam = distcalc.analogy_query_c(wa, wb, wd) end = time.time() print_array([(reversed_dictionary[i], dist) for (i,dist) in iam]) print("time: %f"%(end - start)) print("\n") print("\n u embedding on the Sphere, comparison in 0") start = time.time() distcalc=DistanceCalculatorMeasuresSpherein0(dictionary, reversed_dictionary, u_embeddings, v_embeddings, howmany, amonghowmany, tolerance=tolerance) iam = distcalc.analogy_query_c(wa, wb, wd) end = time.time() print_array([(reversed_dictionary[i], dist) for (i,dist) in iam]) print("time: %f"%(end - start)) print("\n") print("\n u embedding on the Sphere, comparison in a") start = time.time() distcalc=DistanceCalculatorMeasuresSphereinA(dictionary, reversed_dictionary, u_embeddings, v_embeddings, howmany, amonghowmany, tolerance=tolerance) iam = distcalc.analogy_query_c(wa, wb, wd) end = time.time() print_array([(reversed_dictionary[i], dist) for (i,dist) in iam]) print("time: %f"%(end - start)) print("\n") print("\n u embedding on the Sphere, follow logmap and find closest") start = time.time() distcalc=DistanceCalculatorTargetSphere(dictionary, reversed_dictionary, u_embeddings, v_embeddings, howmany, amonghowmany, tolerance=tolerance) iam = distcalc.analogy_query_c(wa, wb, wd) end = time.time() print_array([(reversed_dictionary[i], dist) for (i,dist) in iam]) print("time: %f"%(end - start)) print("\n") # print("v embedding") # relationship_query(wa, wb, wd, v_embeddings)
06dcd0f4a45110a1787fe570577304e85c3eb0c9
k4t0mono/regex-to-code
/MinimizaAuto/class_auto.py
2,799
3.53125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import re class Auto: def __init__(self, arq): arquivo = open(arq, "r") linhas = arquivo.read().strip().splitlines() # Achar estados # O estados tem que conter pelo menos uma letra seguido por pelo menos um digito e = re.compile('\w+\d+') # Achando os estados no padrão do RegEx self.estados = e.findall(linhas[1]) a = linhas[2].strip()[1:][:-2] self.alfabeto = a.split(',') if 'λ' in self.alfabeto: self.alfabeto.remove('λ') # Achar os estados finais self.finais = e.findall(linhas[-2]) # Achar o estado inicial self.inicial = e.findall(linhas[-3])[0] # Achar as funções de transição d = re.compile('(\w+\d+),(.+)->(\w+\d+)') self.trans = [] for i in linhas: self.trans += (d.findall(i)) self.corrige_estados() def corrige_estados(self): m = '' for e in self.estados: if len(e) > len(m): m = e m = len(m)-1 n_estados = [] for e in self.estados: e_ = e[1:] if len(e_) < m: while len(e_) < m: e_ = '0{}'.format(e_) e_ = 'q{}'.format(e_) n_estados.append(e_) for i in range(len(self.trans)): if self.trans[i][0] == e: t_ = list(self.trans[i]) t_[0] = e_ self.trans[i] = tuple(t_) for i in range(len(self.trans)): if self.trans[i][2] == e: t_ = list(self.trans[i]) t_[2] = e_ self.trans[i] = tuple(t_) if self.inicial == e: self.inicial = e_ for i in range(len(self.finais)): if self.finais[i] == e: self.finais[i] = e_ else: n_estados.append(e) self.estados = n_estados def __str__(self): # Essa função faz mágica, não mexa s = "(\n" s += "\t{" for i in self.estados: s += "{},".format(i) s = s[:-1] s += "},\n" s += "\t{" for i in self.alfabeto: s += "{},".format(i) s = s[:-1] s += "},\n\t{\n" for i in self.trans: s += "\t\t({},{}->{}),\n".format(i[0], i[1], i[2]) s = s[:-2] s += "\n\t},\n" s += "\t{},\n".format(self.inicial) s += "\t{" for i in self.finais: s += "{},".format(i) s = s[:-1] s += "}\n)" return s
be8f6441dc947ec146d8f5573a5754d50f9a7b4b
xieh1987/MyLeetCodePy
/Sqrt(x).py
294
3.5625
4
class Solution: # @param x, an integer # @return an integer def sqrt(self, x): head, end = 0, x/2+1 while end>=head: mid=(head+end)/2 if mid**2>x: end=mid-1 else: head=mid+1 return int(end)
f0f9321e8400115c351327461f821a261e7eff93
Fuerfenf/Basic_things_of_the_Python_language
/data_type/collections/UserList.py
1,212
4.40625
4
# Python supports a List like a container called UserList present in the collections module. # This class acts as a wrapper class around the List objects. This class is useful when one wants to create a list # of their own with some modified functionality or with some new functionality. # It can be considered as a way of adding new behaviors for the list. # This class takes a list instance as an argument and simulates a list that is kept in a regular list. # The list is accessible by the data attribute of the this class. from collections import UserList L = [1, 2, 3, 4] # Creating a userlist userL = UserList(L) print(userL.data) # Creating empty userlist userL = UserList() print(userL.data) # Creating a List where # deletion is not allowed class MyList(UserList): # Function to stop deleltion # from List def remove(self, s=None): raise RuntimeError("Deletion not allowed") # Function to stop pop from # List def pop(self, s=None): raise RuntimeError("Deletion not allowed") # Driver's code L = MyList([1, 2, 3, 4]) print("Original List") # Inserting to List" L.append(5) print("After Insertion") print(L) # Deliting From List L.remove()