blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
1468451a6aba8cc88f561ec31892b71c8da4395c | sonilakar/SNA-Learning-Class-Stuff | /ShortestPaths.py | 1,755 | 3.96875 | 4 |
print()
import networkx
from networkx import algorithms
import matplotlib
# create a weighted graph
G = networkx.Graph()
nA, nB, nC, nD, nE = 'A', 'B', 'C', 'D', 'E'
G.add_nodes_from([nA, nB, nC, nD, nE])
G.add_weighted_edges_from([(nA,nB,2),(nB,nC,3),(nC,nD,4)])
G.add_weighted_edges_from([(nA,nE,9),(nE,nD,10)])
# Graph Distance:
# Unweighted distance - number of edges between two nodes
# Weighted distance - sum of weights between two nodes.
# so shortest path is least combined weight, not necessarily the fewest nodes
# Dijkstra's Algorithm:
# For a given vertex it finds the lowest cost path to all other vertices,
# where “cost” is determined by summing edge weights. In graphs where edge
# weights correspond to distance (in unweighted graphs the weights are
# assumed to be one) the found path is the shortest.
# The algorithm can also determine the lowest cost path between two given
# vertices.
print ("Shortest Path from node A to node D:")
print (algorithms.shortest_path(G,nA,nD))
print ()
print ("Dijkstra Shortest Path from node A to node D:")
print (algorithms.dijkstra_path(G,nA,nD))
# plot the weighted graph
pos=networkx.spring_layout(G)
matplotlib.pyplot.figure(figsize=(10,10))
networkx.draw_networkx_nodes(G,pos,node_size=1500)
networkx.draw_networkx_labels(G,pos,font_size=20)
edgewidth = [ d['weight'] for (u,v,d) in G.edges(data=True)]
networkx.draw_networkx_edges(G,pos,edge_color=edgewidth,width=edgewidth)
edgelabel = networkx.get_edge_attributes(G,'weight')
networkx.draw_networkx_edge_labels(G,pos,edge_labels=edgelabel,font_size=20)
matplotlib.pyplot.axis('off')
#matplotlib.pyplot.savefig("graph.png")
matplotlib.pyplot.show() |
55895597212b89446247b11f01530c29776a2822 | VPP-CT/Backend-Flask | /hotel_parser.py | 3,108 | 3.578125 | 4 | """Module for hotel searching and parsing.
This module would process hotel related data, and return filtered result to the
server.
"""
from __future__ import print_function
import requests
import json
returnedNum = 200 # only return top 50 hotel data
def search_hotels(hotel_data):
# type: (str) -> object
"""Send query to Expedia to get hotel information in given area.
This function will utilize the Expedia API to query hotel information. It
would send a GET request to the API, and catch the result as JSON text.
Args:
location: string, the city or location to search.
Returns:
A JSON object which contains hotel information.
"""
param = {'sortOrder': 'price',
'pageIndex': 0,
'enableSponsoredListings': 'false',
'room1': 1,
'filterUnavailable': 'true',
'checkInDate': hotel_data.checkin_date,
'checkOutDate': hotel_data.checkout_date,
'latitude': hotel_data.latitude,
'longitude': hotel_data.longitude,
'resultsPerPage': returnedNum
}
raw_response = requests.get("https://www.expedia.com/m/api/hotel/search/v3",
params=param)
return parse_hotel(json.loads(raw_response.text))
def parse_hotel(raw_data):
# type: (object, str) -> object
"""Parser for hotel data JSON object.
This function would extract important information from the raw data, and
parse it.
Args:
raw_data: dict, data from API call.
location: string, the city or location to search.
Returns:
"""
return_data = dict()
# return_data['availableHotelCount'] = raw_data['availableHotelCount']
# return_data['numberOfRoomsRequested'] = raw_data['numberOfRoomsRequested']
for x in range(len(raw_data['hotelList'])):
hotel = dict()
hotel['city'] = raw_data['hotelList'][x]['city']
hotel['name'] = raw_data['hotelList'][x]['localizedName']
hotel['hotelId'] = raw_data['hotelList'][x]['hotelId']
hotel['address'] = raw_data['hotelList'][x]['address']
hotel['description'] = raw_data['hotelList'][x]['shortDescription']
hotel['availability'] = raw_data['hotelList'][x]['isHotelAvailable']
hotel['roomsLeft'] = raw_data['hotelList'][x]['roomsLeftAtThisRate']
hotel['totalReviews'] = raw_data['hotelList'][x]['totalReviews']
hotel['guestRating'] = raw_data['hotelList'][x]['hotelGuestRating']
hotel['starRating'] = raw_data['hotelList'][x]['hotelStarRating']
hotel['rateWithTax'] = raw_data['hotelList'][x]['lowRateInfo']['formattedTotalPriceWithMandatoryFees']
hotel['distanceFromCenter'] = raw_data['hotelList'][x]['proximityDistanceInMiles']
return_data['hotel_%d' % x] = hotel
""" For debug only
formated_return_data = json.dumps(
return_data, sort_keys=True, indent=4, separators=(',', ': '))
print(formated_return_data, file=open('top_query_hotels.log', 'w+'))
logging.warning(raw_data)"""
return return_data
|
c0b98e16909c75d0e9be772bfe8f6c91400f2329 | sarahwang93/leetcode_summary | /src/searchTree.py | 578 | 3.84375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class searchTree:
def searchBST(self, root: TreeNode, val: int) -> TreeNode:
#corner case
res = []
if root == None:
return res
node = root
while node!=None:
if val<node.val:
node = node.left
elif val>node.val:
node = node.right
else:
return node |
d1b7d84d24419fecf78c4929ec1e02d74c7d33e0 | vkmrishad/string-find | /string_find.py | 1,728 | 4 | 4 | from typing import List
def find(data: List[str], query: str):
"""
Function that will find all exact words from list of words.
"""
# List for storing result.
result = list()
# Check if data is a list.
if type(data) == list:
# Check if data and query is not None.
if data and query:
# Sort query string
query_str_sorted = "".join(sorted(query))
# Loop all item in list.
for item in data:
# Check for length to skip sorting operation.
if len(query) == len(query):
# If length matches, straight comparison. Using case insensitive comparison.
if str(query).lower() == str(item).lower():
# Push to result list
result.append(item)
# Else, sort item and compare. Using case insensitive comparison.
else:
item_str = "".join(sorted(item))
if str(query_str_sorted).lower() == str(item_str).lower():
# Push to result list
result.append(item)
# Return list of result items.
return result
else:
# If data and query not found
if not data and not query:
return "data and query not found!"
# Elif data not found
elif not data:
return "data not found!"
# Elif query not found
elif not query:
return "query not found!"
else:
return "some other error"
else:
return "data should be a list type"
|
0e345182eac194768d04998afe39423f7515958e | danilevy1212/Exercism | /python/armstrong-numbers/armstrong_numbers.py | 160 | 3.671875 | 4 | def is_armstrong_number(number):
num2str = str(number)
length = len(num2str)
return sum(int(num2str[i])**length for i in range(length)) == number
|
1af54799ccb47425656ae37daf665f02a09dcace | bcastor/A.I.---Sudoku | /backtrack.py | 3,478 | 3.765625 | 4 | '''
COURSE: CS-550 Artificial Intelligence
SECTION: 01-MW 4:00-5:15pm
DATE: 15 April 2020
ASSIGNMENT: 05
@author Mariano Hernandez & Brandon Castor
DESCRIPTION:
Backtrack
'''
from csp_lib.backtrack_util import (first_unassigned_variable,
unordered_domain_values,
no_inference)
def backtracking_search(csp,
select_unassigned_variable=first_unassigned_variable,
order_domain_values=unordered_domain_values,
inference=no_inference):
""""BACKTRACKING_SEARCH(
CSP, SELECT_UNASSIGNED_VARIABLE, ORDER_DOMAIN_VALUES, INFERENCE)
Solves particular CSP using backtrack search
Arguments:
csp -- a constraint satisfaction problem
select_unassigned_variable -- function handle for selecting variables
order_domain_values -- function handle for selecting elements of a domain
inference -- set of inferences
"""
# Title: function BACKTRACK(assignment,csp)
# Author: Russell, Stuart and Peter Norvig
# Date: 2010
# Code Version: N/A Pseudocode
# Availability: Artificial Intelligence: A Modern Approach, 3rd ed.,
# Chapter 6, Figure 6.5
def backtrack(assignment):
"""BACKTRACK(ASSIGNMENT)
# function BACKTRACK(assignment,csp) returns a solution, or failure
Attempt to backtrack search with current assignment
Returns None if there is no solution. Otherwise, the
csp should be in a goal state.
Arguments:
assignment -- current assignment
"""
# if assignment is complete then return assignment
if len(assignment) == len(csp.variables): return assignment # TODO understand what this does
# var ← SELECT-UNASSIGNED-VARIABLE(csp)
var = select_unassigned_variable(assignment, csp)
# for each value in ORDER-DOMAIN-VALUES(var,assignment,csp) do
for value in order_domain_values(var, assignment, csp):
# if value is consistent with assignment then
if csp.nconflicts(var, value, assignment) == 0:
# add {var = value} to assignment
csp.assign(var, value, assignment)
# inferences ←INFERENCE(csp,var,value)
removals = csp.suppose(var, value) # TODO understand what suppose does
inferences = inference(csp, var, value, assignment, removals)
# if inferences != failure then # TODO understand what inferences are
if inferences:
# add inferences to assignment
# result ← BACKTRACK(assignment, csp)
result = backtrack(assignment)
# if result != failure then
if result is not None:
# return result
return result
# remove {var = value} and inferences from assignment
csp.restore(removals)
csp.unassign(var, assignment)
# return failure
return None
# Call with empty assignments, variables accessed
# through dynamic scoping (variables in outer
# scope can be accessed in Python)
result = backtrack({})
assert result is None or csp.goal_test(result)
return result
|
c27205377f4de9ef50f141c30b502a795c6dc118 | wmjpillow/Algorithm-Collection | /how to code a linked list.py | 2,356 | 4.21875 | 4 | #https://www.freecodecamp.org/news/python-interview-question-guide-how-to-code-a-linked-list-fd77cbbd367d/
#Nodes
#1 value- anything strings, integers, objects
#2 the next node
class linkedListNode:
def __init__(self,value,nextNode=None):
self.value= value
self.nextNode= nextNode
def insertNode(head, valuetoInsert):
currentNode= head
while currentNode is not None:
if currentNode.nextNode is None:
currentNode.nextNode= linkedListNode(valuetoInsert)
return head
currentNode= currentNode.nextNode
#Delete node function
def deleteNode(head, valueToDelete):
currentNode= head
previousNode= None
while currentNode is not None:
if currentNode.value == valueToDelete:
if previousNode is None:
newHead = currentNode.nextNode
currentNode.nextNode = None
return newHead
previousNode.nextNode = currentNode.nextNode
return head
previousNode = currentNode
currentNode = currentNode.nextNode
return head # Value to delete was not found.
# "3" -> "7" -> "10"
node1 = linkedListNode("3") # "3"
node2 = linkedListNode("7") # "7"
node3 = linkedListNode("10") # "10"
node1.nextNode = node2 # node1 -> node2 , "3" -> "7"
node2.nextNode = node3 # node2 -> node3 , "7" -> "10"
# node1 -> node2 -> node3
head = node1
print "*********************************"
print "Traversing the regular linkedList"
print "*********************************"
# Regular Traversal
currentNode = head
while currentNode is not None:
print currentNode.value,
currentNode = currentNode.nextNode
print ''
print "*********************************"
print "deleting the node '7'"
newHead = deleteNode(head, "10")
print "*********************************"
print "traversing the new linkedList with the node 7 removed"
print "*********************************"
currentNode = newHead
while currentNode is not None:
print currentNode.value,
currentNode = currentNode.nextNode
print ''
print "*********************************"
print "Inserting the node '99'"
newHead = insertNode(newHead, "99")
print "*********************************"
print "traversing the new linkedList with the node 99 added"
print "*********************************"
currentNode = newHead
while currentNode is not None:
print currentNode.value,
currentNode = currentNode.nextNode |
ca845b51f55cef583bfc6b9ff05741d56f474fec | mbravofuentes/Codingpractice | /python/IfStatement.py | 625 | 4.21875 | 4 | import datetime
DOB = input("Enter your DOB: ")
CurrentYear = datetime.datetime.now().year
Age = CurrentYear-int(DOB) #This will change the string into an integer
if(Age>=18):
print("Your age is {} and you are an adult".format(Age))
if(Age<=18):
print("Your age is {} and you are a Kid".format(Age))
#In Python, if statements are included in "Blocks" which is just where the code is going to be running
#in that case, blocks run by spaces/indents
#If and Else Statements
num = input("Put in a number: ")
if (int(num) >= 0):
print("This is a positive number")
else:
print("This number is negative")
|
cde66f08f3e8ccd4e52c94d824e314ea6056f9c2 | mbravofuentes/Codingpractice | /python/FindAge.py | 199 | 4.0625 | 4 | import datetime
DOB = input("Enter your DOB: ")
CurrentYear = datetime.datetime.now().year
Age = CurrentYear-int(DOB) #This will change the string into an integer
print("Your age is {}".format(Age))
|
a437e6ff2a34a1c63914332265ec25fba5f5aac8 | eranilkrsharma/PythonCourse | /BasicCourse/Hello.py | 360 | 3.796875 | 4 | """This is the first Python file
Comments added
"""
print("Hello World Again test Git")
#Format examples
name = "Python"
machine = "MyMac"
print "Nice to meet you {0}. I am {1}".format(name,machine)
# below can be used in Python 3
# f"Nice to meet you {name}. I am {machine}"
#Booelan flag starts with Caps few examples below
python_course = True
|
ae5354fd80a8cc13740a768d48d1226ff3d2964d | rayvonne828/Project-1 | /ex47/ex47/lexicon.py | 917 | 3.8125 | 4 | class Lexicon(object):
def __init__(self):
self.directions = ['north', 'south', 'east', 'west', 'down', 'up', 'left', 'right', 'back']
self.verbs = ['go', 'stop', 'kill', 'eat']
self.stop_words = ['the', 'in', 'of', 'from', 'at', 'it']
self.nouns = ['door', 'bear', 'princess', 'cabinet']
self.numbers = [x for x in range(10)]
def scan(self, sentence):
words = sentence.split()
sentence_list = []
for word in words:
try:
sentence_list.append(('number', int(word)))
except ValueError:
if word in self.directions:
sentence_list.append(('direction', word))
elif word in self.verbs:
sentence_list.append(('verb', word))
elif word in self.stop_words:
sentence_list.append(('stop', word))
elif word in self.nouns:
sentence_list.append(('noun', word))
else:
sentence_list.append(('error', word))
return sentence_list
lexicon = Lexicon() |
2394253e7f9bb0c905b9917ee7a1501087bc1af0 | williamsalas/EasyHours | /my_cal.py | 960 | 4.03125 | 4 | from tkinter import *
from tkcalendar import *
from datetime import datetime
"""
William Salas
9/6/20
Purpose: Designing a program to input and track hours worked, etc.
"""
# basic tkinter starter code
root = Tk()
root.title('EasyHours')
root.geometry('600x400')
file = open("text.txt", "a+")
# date data type, todays date in YYYY-MM-DD format
todayIs = datetime.date(datetime.now())
# calendar opens to the current date
cal = Calendar(root, selectmode='day', year=todayIs.year, month=todayIs.month, day=todayIs.day)
cal.pack(pady=20, fill='both', expand=True)
# to be used with a button to write to text file
def add_date():
my_label.config(text='Selected date is: ' + cal.get_date())
file.write(cal.get_date() + "\n")
# button when pressed grabs date of selected date in calendar
my_button = Button(root, text='Get Date', command=add_date)
my_button.pack(pady=20)
my_label = Label(root, text='')
my_label.pack(pady=20)
root.mainloop()
file.close()
|
d36ac222c28deed0fdbfb9d06c2143fee26f28e3 | StanislavHorod/LV-431-PythonCore | /3(3 task)_HW.py | 218 | 3.984375 | 4 | number = int(input("Write the number: "))
start_number = str(number)
cash = 1
while number>1:
cash *=number
number-=1
final_number = str(cash)
print("The factorial of the "+start_number+ " is: '"+ final_number) |
4ad51b29bc544a7061347b6808da4fa6896e2a6b | StanislavHorod/LV-431-PythonCore | /Home work 2/2(3 task)_HW.py | 401 | 4.15625 | 4 | try:
first_word = str(input("Write 1 word/numb: "))
second_word = str(input("Write 2 word/numb: "))
first_word, second_word = second_word, first_word
print("The first word now: " + first_word +
"\nThe second word now: " + second_word)
if first_word == " " or second_word == " ":
raise Exception("There is an empty lines")
except Exception as exi:
print(exi) |
e8f91a9e3091299e48c986243efd63120147f730 | StanislavHorod/LV-431-PythonCore | /lec 8.12/CW-4.py | 329 | 3.578125 | 4 | try:
login = input("Press login: ")
while True:
if login == "First":
print("Gracios, you are connected")
break
elif login == " ":
raise Exception("Write login!")
else:
login = input("Try again\nPress login: ")
except Exception as exi:
print(exi) |
78bc2aebff4c8b27e3d10136e949a08f2032aabc | StanislavHorod/LV-431-PythonCore | /Class work 5/CW-4.py | 1,398 | 3.84375 | 4 | class CustomExaption(Exception):
def __init__(self, data):
self.data = data
def __str__(self):
return repr(self.data)
days = {
1: "focus: Mondey",
2: "focus: Tuesday",
3: "focus: Wednesday",
4: "focus: Thursday",
5: "focus: Friday",
6: "focus: Saturday",
7: "focus: Sunday"
}
while True:
try:
chooser = int(input("Write the number for focus (1-7): "))
# if chooser==1:
# print("focus: Mondey")
# break
# elif chooser==2:
# print("focus: Tuesday")
# break
# elif chooser==3:
# print("focus: Wednesday")
# break
# elif chooser==4:
# print("focus: Thursday")
# break
# elif chooser==5:
# print("focus: Friday")
# break
# elif chooser==6:
# print("focus: Saturday")
# break
# elif chooser==7:
# print("Sunday")
# break
# elif chooser>7 or chooser<1:
# raise CustomExaption("Ooops, you write the wrong number {}!".format(chooser))
# except ValueError:
# print("Wrong input")
# except CustomExaption as exi:
# print(exi.data)
except ValueError:
print("Ooops, you write not number ")
else:
print(days.get(chooser, "There is no such day!"))
|
ca77d5aa0a60f834e16bfc43be30d4f32d2e7f00 | StanislavHorod/LV-431-PythonCore | /Home work 1/1(2 task)_HW.py | 191 | 4 | 4 | name = input("What is your name? \n")
age = input("How old are ypu? \n")
adress = input("Where do you live? \n")
print("Hello, "+ name +". Your age is " + age+
". You live in " + adress) |
aad8fee13302cfa94e8d4533976a20f3cc908b2e | StanislavHorod/LV-431-PythonCore | /CW 5/CW - 2.py | 1,028 | 3.96875 | 4 | class Figure():
def __init__(self, color=None, type_figure=None):
self.color = color
self.type_figure = type_figure
def get_color(self):
return self.color
def info(self):
print(f'Фігура - {self.type_figure}, колір - {self.color}')
class Rectangle(Figure):
def __init__(self, side=0, height=0):
self.side = side
self.height = height
super().__init__('red', 'rectangle')
def square(self):
return self.side * self.height * 0.5
class Square(Figure):
def __init__(self, wight=0, height=0):
self.wight = wight
self.height = height
super().__init__('green', 'square')
def square(self):
return self.wight * self.height
sqr = Square(15, 25)
# sqr.color = 'red'
# sqr.type_figure = 'square'
sqr.info()
print(f'Square {sqr.type_figure} - {sqr.square()}')
rec = Rectangle(15, 25)
# rec.color = 'green'
# rec.type_figure = 'rectangle'
rec.info()
print(f'Square {rec.type_figure} - {rec.square()}') |
420837ef3802a6236b606bade8425f960acf7f4b | kidconan/demo | /neuralNetworks/classifiers/classifier.py | 1,313 | 3.84375 | 4 | '''@file classifier.py
The abstract class for a neural network classifier'''
from abc import ABCMeta, abstractmethod
class Classifier(object, metaclass=ABCMeta):
'''This an abstract class defining a neural net classifier'''
def __init__(self, output_dim):
'''classifier constructor'''
self.output_dim = output_dim
@abstractmethod
def __call__(self, inputs, seq_length, is_training=False, reuse=False,
scope=None):
'''
Add the neural net variables and operations to the graph
Args:
inputs: the inputs to the neural network, this is a list containing
a [batch_size, input_dim] tensor for each time step
seq_length: The sequence lengths of the input utterances
is_training: whether or not the network is in training mode
reuse: wheter or not the variables in the network should be reused
scope: the name scope
Returns:
A triple containing:
- output logits
- the output logits sequence lengths as a vector
- a saver object
- a dictionary of control operations (may be empty)
'''
raise NotImplementedError("Abstract method")
|
c2f09af2908cbb047746d1758162e273953d46e9 | FarabiAkash/Pyhton | /EverydayCode/Odd_Numbers.py | 150 | 3.90625 | 4 | numbers= range(21)
odd_numbers =""
for i in numbers :
if i % 2 != 0:
odd_numbers =odd_numbers + str(i) + " "
print(odd_numbers)
|
df4bc513bb24346c05f07469ab49b7955a361bdc | mhrones/statistical-computing | /problem-sets/ps3-monte_carlo_player/ps3b.py | 762 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author:
"""
import random
import ps2
import ps3a
word_list = ps2.load_words()
def test_mc_player(hand, N=100, seed=1):
"""
play a hand 3 times, make sure produced same scores.
"""
hand_score = ps3a.play_mc_hand(hand)
if hand_score != ps3a.play_mc_hand(hand):
return False
return True
if __name__ == "__main__":
# Set the MC seed
seed = 100
test_hands = ['helloworld', 'UMasswins', 'statisticscomputing']
for handword in test_hands:
hand = ps2.get_frequency_dict(handword)
if not test_mc_player(hand, seed=seed):
print('Reproducibility problem for %s' % handword)
else:
print("No Issues for ", handword)
|
2caf204be9de0b2ae802f1b96b71423a2e8da936 | Laxiflora/fintech_final | /server/src/random_code.py | 799 | 3.515625 | 4 | from random import Random
str = ''
chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
length = len(chars) - 1
random = Random()
#生成16字的英數亂碼
for i in range(16):
str+=chars[random.randint(0,length)]
print(str)
'''
import random, string
def GenPassword(length):
#隨機出數字的個數
numOfNum = random.randint(1,length-1)
numOfLetter = length - numOfNum
#選中numOfNum個數字
slcNum = [random.choice(string.digits) for i in range(numOfNum)]
#選中numOfLetter個字母
slcLetter = [random.choice(string.ascii_letters) for i in range(numOfLetter)]
#打亂這個組合
slcChar = slcNum + slcLetter
random.shuffle(slcChar)
#生成密碼
genPwd = ''.join([i for i in slcChar])
return genPwd
if __name__ == '__main__':
print GenPassword(6)
''' |
314f2a90c0c6fee4316d4e372799d425d31fe435 | 6871/matrix-display | /src/matrix_display/displays/display.py | 1,259 | 3.8125 | 4 | #!/usr/bin/env python3
"""Module defining base MatrixDisplay class."""
class Display:
"""Base class for display-specific classes to extend."""
row_count = 0
col_count = 0
def __init__(self, row_count, col_count):
"""Initialise a display object.
Parameters
----------
row_count : int
The number of rows in the corresponding physical display
col_count : int
The number of columns in the corresponding physical display
"""
self.row_count = row_count
self.col_count = col_count
def set_pixel(self, x, y, r, g, b):
"""Set a display pixel's RGB value (use draw method to display).
Parameters
----------
x : int
The x coordinate of the pixel to be updated
y : int
The y coordinate of the pixel to be updated
r : int
The red component of the pixel to be updated; 0-255
g : int
The green component of the pixel to be updated; 0-255
b : int
The blue component of the pixel to be updated; 0-255
"""
pass
def draw(self):
"""Show current pixel colours (set with set_pixel) on the display."""
pass
|
61c48bb6251a1b866e9326ef1e931f760373f867 | m3ddle/live-coding2 | /main.py | 930 | 3.921875 | 4 | example = "vfdsjsfaffffffffreitirrrrrert"
def longest_substring(string):
substring_tracker = {}
substring_length = 0
index = 0
subs_track = 0
curent_char = ''
while index < len(string):
if index < len(string) - 1:
if string[index + 1] == string[index]:
current_char = string[index]
subs_track += 1
while current_char == string[index]:
substring_length += 1
index += 1
substring_tracker[subs_track] = substring_length
else:
index += 1
substring_length = 0
else:
index += 1
indie = 0
print(substring_tracker)
for key in substring_tracker.values():
if key > indie:
indie = key
return indie
if __name__ == "__main__":
print(longest_substring(example))
|
3ea848cb1bbd54154386e8b066d0799a0d428248 | sanjaykumardbdev/pythonProject_2 | /111_test.py | 975 | 3.609375 | 4 | from tkinter import *
import datetime
root = Tk()
date = str(datetime.datetime.now().date())
print(date)
# need two frames: topFrame bottomFrame
topFrame = Frame(root, height=150, bg='white')
topFrame.pack(fill=X)
bottomFrame = Frame(root, height=350, bg='#7fe3a7')
bottomFrame.pack(fill=X)
heading = Label(topFrame, text='TEST****', bg='white', fg='blue', font='arial 15 bold')
heading.place(x=200, y=50)
date_lbl = Label(topFrame, text="Today's Date:" + date, font='arial 12 bold', fg='#7fe3a7', bg='white')
date_lbl.place(x=300, y=110)
scroll = Scrollbar(bottomFrame, orient=VERTICAL)
listbox = Listbox(bottomFrame, width=40, height=27)
listbox.grid(row=0, column=0)
listbox.config(yscrollcommand=scroll.set)
scroll.config(command=listbox.yview())
scroll.grid(row=0, column=1,sticky=N+S)
for i in range(200):
listbox.insert(END,'listitem: ' + str(i))
root.geometry('500x500+150+100')
root.title('My People')
root.resizable(False, False)
root.mainloop() |
3166ede4834ff94bcac3474b8e6c8be46ec282f8 | sanjaykumardbdev/pythonProject_2 | /53_Types_of_Methods.py | 1,299 | 3.890625 | 4 | # instance method
# class method variable
# static method variable
# in case of var, class n static var are same but difnt in case of method
class Student:
#static or class var : outside var
school = "Telusko"
def __init__(self, m1, m2, m3):
self.m1 = m1
self.m2 = m2
self.m3 = m3
# instance method
def agv(self):
return (self.m1 + self.m2 + self.m3)/3
# instance itself have to type of method: accessor, mutators
# accessor : fetch value , mutators: set the value
def get_m1(self):
return self.m1
def set_m1(self,value):
self.m1 = value
#classmethod use decorator to access class var
@classmethod
def getSchool(cls):
return cls.school
# static method: in case if you don't want to relate with any class or obj.
# this method nothing to do with instance or class variable
@staticmethod
def info():
print("this is student class.. in abc ")
s1 = Student(34, 47, 32)
s2 = Student(89, 32, 12)
print('using get ', s1.get_m1())
s1.set_m1(100)
print('using get ', s1.get_m1())
# avg is instance method becoz it called with object
print(s1.agv())
print(s2.agv())
print("-----------------------")
print(s1.getSchool())
print(Student.getSchool())
Student.info();
|
6e07857a742c76f44fef1489df67d00f8b118cf6 | sanjaykumardbdev/pythonProject_2 | /59_Operator_overloading.py | 1,272 | 4.46875 | 4 | #59 Python Tutorial for Beginners | Operator Overloading | Polymorphism
a = 5
b = 6
print(a+b)
print(int.__add__(a, b))
a = '5'
b = '6'
print(a+b)
print(str.__add__(a, b))
print(a.__str__()) # when u r calling print(a) behind it is calling like this : print(a.__str__())
print('-----------------------------')
class Student:
def __init__(self, m1, m2):
self.mk1 = m1
self.mk2 = m2
def __add__(self, other):
m1 = self.mk1 + other.mk1
m2 = self.mk2 + other.mk2
s3 = Student(m1, m2)
return s3
def __gt__(self, other):
#s1 = self.mk1 + other.mk1
#s2 = self.mk2 + other.mk2
s1 = self.mk1 + self.mk2
s2 = other.mk1 + other.mk2
if s1 > s2:
return True
else:
return False
def __str__(self):
#print(self.mk1, self.mk2)
return( '{} {}'.format(self.mk1, self.mk2))
s1 = Student(30, 3)
s2 = Student(3, 3)
print("Str overloading----------------------------------")
print()
print(s1.__str__())
print(s2.__str__())
print()
print("Done----------------------------------")
# Student.__add__(s1,s2)
s3 = s1 + s2
print(s3.mk1)
s4 = s1 + s2
print(s4.mk2)
if s1 > s2:
print('s1 Wins')
else:
print('s2 wins')
|
9bb1168da52c3bdbb7015f7a61f515b10dc69267 | ubercareerprep2019/Uber_Career_Prep_Homework | /Assignment-2/src/Part2_NumberOfIslands.py | 2,348 | 4.28125 | 4 | from typing import List, Tuple, Set
def number_of_islands(island_map: List[List[bool]]) -> int:
"""
[Graphs - Ex5] Exercise: Number of islands
We are given a 2d grid map of '1's (land) and '0's (water). We define an island as a body of land surrounded by
water and is formed by connecting adjacent lands horizontally or vertically. We may assume all four edges of the
grid are all surrounded by water. We need to write a method to find the number of islands in such a map.
Write a method number_of_islands(bool[][] island_map) that returns the number of islands in a 2dmap. For this
exercise you can think of a true in the island_map representing a '1' (land) and a false in the island_map
representing a '0' (water).
"""
counter: int = 0
visited: Set[Tuple[int, int]] = set()
for x in range(len(island_map)):
for y in range(len(island_map[x])):
if island_map[x][y] and (x, y) not in visited:
counter += 1
stack: List[Tuple[int, int]] = [(x, y)]
while stack:
node = stack.pop() # dfs
if node in visited:
continue
visited.add(node)
stack.extend(get_outward_edges(island_map, node))
return counter
def get_outward_edges(island_map: List[List[bool]], vertex: Tuple[int, int]) -> List[Tuple[int, int]]:
x, y = vertex
output: List[Tuple[int, int]] = []
for x1, y1 in [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]:
if x1 < 0 or y1 < 0:
continue
if x1 >= len(island_map) or y1 >= len(island_map[x1]):
continue
if island_map[x1][y1]:
output.append((x1, y1))
return output
def main():
island_map1 = [[True, True, True, True, False],
[True, True, False, True, False],
[True, True, False, False, False],
[False, False, False, False, False]]
assert number_of_islands(island_map1) == 1
island_map2 = [[True, True, False, False, False],
[True, True, False, False, False],
[False, False, True, False, False],
[False, False, False, True, True]]
assert number_of_islands(island_map2) == 3
if __name__ == "__main__":
main() |
dfc122137c813e45c1e45d22313e87022aee87d7 | ubercareerprep2019/Uber_Career_Prep_Homework | /Assignment-2/tests/Part1_PhoneBook_Test.py | 1,680 | 3.609375 | 4 | from unittest import TestCase
from Part1_PhoneBook import ListPhoneBook, BinarySearchTreePhoneBook
class Part1_PhoneBook_Test(TestCase):
def test_size(self):
phone_book = ListPhoneBook()
assert phone_book.size() == 0
phone_book.insert("ABC", 1111111111)
assert phone_book.size() == 1
phone_book.insert("XYZ", 9999999999)
assert phone_book.size() == 2
phone_book.insert("DEF", 2222222222)
assert phone_book.size() == 3
def test_find(self):
phone_book = ListPhoneBook()
phone_book.insert("ABC", 1111111111)
phone_book.insert("XYZ", 9999999999)
phone_book.insert("DEF", 2222222222)
assert phone_book.find("ABC") == 1111111111
assert phone_book.find("DEF") == 2222222222
assert phone_book.find("XYZ") == 9999999999
assert phone_book.find("PQR") == -1
def test_binary_size(self):
phone_book = BinarySearchTreePhoneBook()
assert phone_book.size() == 0
phone_book.insert("ABC", 1111111111)
assert phone_book.size() == 1
phone_book.insert("XYZ", 9999999999)
assert phone_book.size() == 2
phone_book.insert("DEF", 2222222222)
assert phone_book.size() == 3
def test_binary_find(self):
phone_book = BinarySearchTreePhoneBook()
phone_book.insert("ABC", 1111111111)
phone_book.insert("XYZ", 9999999999)
phone_book.insert("DEF", 2222222222)
assert phone_book.find("ABC") == 1111111111
assert phone_book.find("DEF") == 2222222222
assert phone_book.find("XYZ") == 9999999999
assert phone_book.find("PQR") == -1
|
bb9f315828e67a214030776d6bd28595e8592cf9 | Desty-3000/ISN | /421 Python.py | 1,392 | 3.875 | 4 | from random import*
#on veut lancer 3 dés , qui doivent au final former une suite 4,2,1. Si un des
#dés vaut 4,2,1 le dé n'est pas relancé . Au bout de 3 lancés sans la suite 421
#le joueur a perdu
#lancementDes lance n dés aléatoires entre 1 et 6 et stocke les résultats dans r1
def lancementDes(n):
r1 = []
for i in range(n):
random = randint(1,6)
r1.append(random)
return r1
#Fonction principale du Script
def jeu():
tour = 0
#Dés valides
listeFinale = []
#On simule les 3 tours
while tour!=3:
#On lance (3-taille de listeFinale) dés
lancementI = lancementDes(3-len(listeFinale))
print("Lancement de ",3-len(listeFinale)," dés ... ",lancementI)
#Si i est dans lancementI et pas dans listeFinale on ajoute i a listeFinale
for i in range(5):
if i!=3 and i not in listeFinale:
if i in lancementI:
listeFinale.append(i)
listeFinale.sort()
print(i," ajouté")
print(listeFinale," au tour ",tour+1)
print(" ")
tour+=1
#On vérifie à la fin des lancés si listeFinale est complète ou non
if tour==3 and listeFinale == [1,2,4]:
return "Le joueur a gagné!"
else:
return "Le joueur a perdu!"
|
b06d16f089b4fe4b73dcf8c7b04cd7dd0c9517c3 | adocto/python3 | /tutorial/mystuff/ex8.py | 454 | 3.640625 | 4 | formatter = "%r %r %r %r"
#Prints numbers
print(formatter % (1, 2, 3, 4))
#prints strings
print(formatter %("one","two","test","okay"))
#prints true/false
print(formatter %(True, False, True, False))
#prints formatter string as literal string.
print(formatter %(formatter,formatter, formatter, formatter))
#prints several sentence strings.
print(formatter %(
"testing string",
"testing2nd line",
"testing 3rd line",
"testing 4th line"
))
|
bbc9094b3949deb22766f21501d8f580d0750b09 | adocto/python3 | /hackerRankOlder/insertion_sort.py | 381 | 3.9375 | 4 | def insertion_sort(arr):
i = 0
# if arr==[]:
# return arr
for i in range(len(arr)):
if i == 0:
arr[i] = arr[i]
else:
j = i
for j in range(j, 0, -1):
if arr[j] < arr[j - 1]:
arr[j], arr[j - 1] = arr[j - 1], arr[j]
else:
break
return arr |
936da4fb6c7628cab7919507ca3fb8baaad97e8c | seancrawford-engineer/python_bootcamp | /coding_challanges/17_decorators/02_acess_control_decorator.py | 2,116 | 3.703125 | 4 | """
Implement a @access_control decorator that can be used like this:
@access_control(access_level)
def delete_some_file(filename):
# perform the deletion operation
print('{} is deleted!'.format(filename))
Your decorator should meet the following requirements:
- It takes in an argument `access_level` and would compare the current user's role with the access level.
- You can get the current user's role, represented by an integer, by calling the `get_current_user_role()` function.
You don't need to implement this function, we will take care of it for you.
- You may assume smaller access level value would have higher privilege. For example, 0 - admin, 1 - user, 2 - guest.
So you can check if the user has proper access level like this:
if get_current_user_role() <= access_level:
# do something
else:
# forbid
- If the user has the proper access level, we allow the user to call the function (that has this decorator).
- If the user does not have a proper access level, we raise a `PermissionError` with the message:
'You do not have the proper access level.'
- The decorator should be generic, which means it can be applied to any function that has any amount of
arguments (or key word arguments).
- Your decorator should keep the original function's `__name__` and `__doc__` strings.
"""
# DO NOT CHANGE
from functools import wraps
def get_current_user_role() -> int:
# return the current user's role, represented by an int
# for example, 0 - admin, 1 - user, 2 - guest
# You don't need to change this function, we will replace it with a real function that returns the user's role
return 0
def access_control(access_level: int):
# You code starts here:
def outer_wrapper(func):
@wraps(func)
def inner_wrapper(*args, **kwargs):
if get_current_user_role() <= access_level:
return func(*args,**kwargs)
else:
raise PermissionError('You do not have the proper access level.')
return inner_wrapper
return outer_wrapper
|
38a000d461e55ea657957c5ddf512e5ada182c54 | aisaack/data-structure_practical-usage | /hash_table.py | 2,353 | 3.734375 | 4 | class Node:
def __init__(self, data=None, pointer=None):
self.data = data
self.pointer = pointer
class Data:
def __init__(self, key, value):
self.key = key
self.value = value
class HashTable:
def __init__(self, table_size):
self.table_size = table_size
self.hash_table = [None] * table_size
def custum_hash(self, key):
hash_value = 0
for i in key:
hash_value += ord(i)
hash_value = (hash_value * ord(i)) % self.table_size
return hash_value
def add_key_value(self, key, value):
hashed_key = self.custom_hash(key)
if self.hash_table[hashed_key] is None:
self.hash_table[hashed_key] = Node(Data(key, value), None)
else:
node = self.hash_table[hashed_key]
while node.pointer:
node = node.pointer
node.pointer = Node(Data(key, value), None)
def get_value(self, key):
hashed_key = self.custom_hash(key)
if self.hash_table[hashed_key] is not None:
node = self.hash_talble[hashed_key]
if node.pointer is None:
return node.data
while node.pointer:
if key == node.data.key:
return node.data.value
node = node.pointer
if key == node.data.key:
return node.data.value
return None
if self.hash_table[hash_key] is None:
self.hash_talbe[hashed_key] = Node
def print_table(self):
print("{")
for idx, val in enumerate(self.hash_table):
if val is not None:
out = ""
node = val
if node.next_node:
while node.next_node:
out += (
str(node.data.key) + " : " + str(node.data.value) + " --> "
)
node = node.next_node
out += (
str(node.data.key) + " : " + str(node.data.value) + " --> None"
)
print(f" [{idx}] {out}")
else:
print(f" [{idx}] {val.data.key} : {val.data.value}")
else:
print(f" [{idx}] {val}")
print("}")
|
3b93a7884308035fc7779e86d861cfaa48a58433 | uttams237/GPython | /n-Derivative.py | 1,335 | 3.890625 | 4 | '''import sympy as sp
x = sp.Symbol('x')
a =(sp.diff(3*x**2,x))
print(type(a))
print(a)'''
from scipy.misc import derivative
import numpy as np
from scipy import integrate
import matplotlib.pyplot as plt
from numpy import *
from math import *
X = np.arange(-10,10,1)
s=input("Enter function : ")
num = int(input("Enter derivative number : "))
temp = s
s = s.replace('x','(x)')
f = lambda x:eval(s)
x,y = X,[]
ctr = -10
'''while ctr <=10:
x.append(ctr)
try:
y.append(derivative(f,ctr))
except:
y.append(None)
ctr+=0.01'''
def F(x):
res = np.zeros_like(x)
for i,val in enumerate(x):
try:
y= derivative(f,val,dx = 1,n = num,order = 3)
res[i]=y
except:
res[i] = None
return res
plt.figure(num ='GPYTHON')
plt.plot(x,F(x),label = temp,color = 'black')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.title("Derivative "+ str(num)+ ' of '+temp)
#plt.style.use('ggplot')
ax = plt.gca()
plt.grid()
plt.legend(bbox_to_anchor=(1.1, 1.05))
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
plt.show()
plt.close()
|
1968a6c4b52571a860648d474b65f89e3c1a3708 | shivahegonde/python_programs | /ass4.py | 160 | 3.703125 | 4 | if __name__=="__main__":
base=int(input("Enter Base :: "))
height=int(input("Enter Height :: "))
AoT=1/2*(base*height)
print ("Area of Triangle :: ",AoT)
|
6009d5c19d7d11bb847371c721d3f13e0fdefd49 | lihararora/snippets | /python/general/prime.py | 378 | 3.9375 | 4 | #!/usr/bin/python
'''
@author: Rahil Arora
@contact: rahil@jhu.edu
'''
def is_prime(num):
for j in range(2,num):
if (num % j) == 0:
return False
return True
if __name__ == "__main__":
low = int(input("Enter the lower bound: "))
high = int(input("Enter the upper bound: "))
for i in range(low,high):
if is_prime(i):
print(i)
|
a532b5e88316b3bee910035772a35293f62b8fee | stefanv/dpt | /dpt.py | 8,466 | 3.671875 | 4 | """ File dpt.py
Discrete Pulse Transform
Dirk Laurie, July 2009
"""
from sys import maxint
from collections import deque
from math import sqrt
""" Since we are importing deque anyway, it is simplest to define
queue as a specialization of deque."""
class queue(deque):
get = deque.popleft
put = deque.append
""" Coding style: I don't use 'self' for the object itself, but
a lower-case version of the class name.
"""
""" Node is a specialization of set. There is no "neighbors" entry:
node.add is used instead of node.neighbors.add, etc.
"if node:" is a test whether the node is empty.
The members of a node are indices into a list. Therefore algorithms
involving neighbours of nodes must be able to see the list of nodes.
They are implemented as methods of class GraphFunction, below.
node.tag is the index of the node itself into that list.
NB: it is not possible to have a set of nodes, since sets and therefore
nodes too are unhashable.
"""
class Node(set):
def __init__(node,tag,value,size=1):
node.parent = node
node.tag = tag
node.value = value
node.size = size
def active(node,size):
return node.parent is node and node.size == size
def __repr__(node):
return "%s_%r(%r)=>%s;%s" % (node.tag,
node.size,node.value,node.parent.tag,list(node))
""" Add the arc between a and b. This procedure does not require
access to the list of nodes. """
def arc(a,b): a.add(b.tag); b.add(a.tag)
""" Programming convention: the 'self' parameter is called either
'graph' or 'tree'. Functions that should be called only before "dpt"
is done, use "graph" for self; functions that should be called only
afterwards, use "tree". """
class GraphFunction:
def __init__(graph,values,arcs):
"""
Initialize a graph function from a list of values and a list of arcs,
where each arc is a tuple of two integers. """
n = len(values)
graph.schedule = Schedule(cutoff=int(sqrt(n)))
graph.nodes = tuple([Node(a,values[a]) for a in xrange(n)])
for (a,b) in arcs: arc(graph.nodes[a],graph.nodes[b])
# The following parameters are only academic.
graph.nnodes = n
graph.narcs = sum([len(node) for node in graph.nodes])/2
graph.count = graph.border = 0
def shrink(graph,node):
""" Read the description in the paper. """
agenda = queue([node])
sign = [0,0]
while agenda:
item = agenda.get()
for c in list(item):
graph.count += 1
child = graph.nodes[c]
child.remove(item.tag)
if child.parent is not node:
if node.value == child.value:
agenda.put(child)
child.parent = node
child.value = 0
node.discard(child.tag)
node.size += child.size
else:
arc(node,child)
sign[node.value>child.value] = 1
feature = sign[1]-sign[0]
graph.border += len(node)
if not node:
graph.root = node
elif feature:
graph.schedule.push(node,node.size,feature)
def nearest(graph,node):
neg = -maxint
pos = maxint
for i in node:
diff = node.value - graph.nodes[i].value
if diff>0 and diff<pos:
pos = diff
nearest = i
elif diff<=0 and diff>neg:
neg = diff
nearest = i
return graph.nodes[nearest]
def dpt(graph,thispolicy=None):
""" Transform graph function to DPT tree. Read the description
in the paper. """
global policy
policy = thispolicy or ceilingDPT
schedule = graph.schedule
for node in graph.nodes:
if node.parent is node:
graph.shrink(node)
graph.border1 = graph.border
graph.border=0
while True:
node = schedule.pop()
if node is None: break
survivor = graph.nearest(node)
height = node.value - survivor.value
node.value = survivor.value
graph.shrink(survivor)
node.value = height
for node in graph.nodes:
node.clear()
for child in graph.nodes:
if child is not graph.root:
child.parent.add(child.tag)
def revalue(tree):
for child in tree.traverse():
child.value += child.parent.value
def traverse(tree,root=None,include_root=False):
"""
tree.traverse(node) returns a breadth-first iterator for the subtree
starting at but not including node. Default: node is tree.root.
tree.traverse(node,include_root=True) does include node.
"""
if root is None:
root = tree.root
if include_root:
yield root
agenda = queue([root])
while agenda:
node = agenda.get()
for c in node:
child = tree.nodes[c]
yield child
agenda.put(child)
def __repr__(graph):
return str(graph.nodes)
class Schedule:
def __init__(schedule,cutoff=100):
schedule.cutoff = cutoff
schedule.boxes = [deque() for k in range(cutoff)]
schedule.start = schedule.stop = 0
# start is the bumber of the box from which the next item will be popped.
# stop-1 is the number of the last box that has actually been used.
schedule.tiebreak = policy(1)
schedule.store = {}
def __getitem__(schedule,i):
""" Return the deque that holds items of width i+1. """
if i<schedule.cutoff: return schedule.boxes[i]
if not schedule.store.has_key(i):
schedule.store[i] = deque()
return schedule.store[i]
def current(schedule):
""" Find the deque off which the next item will be popped. """
box = None
while schedule.start<schedule.stop:
if schedule.start<schedule.cutoff:
box = schedule.boxes[schedule.start]
elif schedule.store.has_key(schedule.start):
box = schedule.store[schedule.start]
if box:
return box
schedule.start += 1
schedule.tiebreak = policy(schedule.start+1)
return None
def pop(schedule):
while True:
pulse = None
box = schedule.current()
if not box:
break
if schedule.tiebreak:
pulse = box.pop()
else:
pulse = box.popleft()
if pulse is None: break
if pulse.active(schedule.start+1):
break
return pulse
def push(schedule,node,size,sign):
schedule.stop = max(schedule.stop,size)
box = schedule[size-1]
if sign>0: box.append(node)
else: box.appendleft(node)
def debug(schedule):
print('-------- start = %i ---- stop = %i --------')%(
schedule.start,schedule.stop)
for k in range(schedule.cutoff):
if schedule.boxes[k]:
print 'size %i' % (k+1), schedule.boxes[k]
if schedule.store: print 'store', schedule.store
ceilingDPT = lambda(size): False
floorDPT = lambda(size): True
policy = ceilingDPT
def ABC(k):
return 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[k]
def label(node):
return ''.join([ABC(j) for j in sorted(node)])
if __name__ == '__main__':
print " Small example from paper: size, neighbors, value, parent"
d = GraphFunction((9,7,6,0,8,13,6,7,7,0,13,13,8),
[(12,4),(4,6),(4,8),(6,2),(0,2),(8,7),(8,1),(0,1),(0,3),
(2,3),(2,5),(2,10),(11,10),(7,1),(1,3),(3,5),(5,10),(3,9)])
for node in d.nodes:
print "%s_%i(%s) = %i -> %s" % ( ABC(node.tag),node.size,
label(node),node.value,ABC(node.parent.tag))
d.dpt()
print ' After DPT'
for node in d.traverse(include_root=True):
print "%s_%i(%s) = %i -> %s" % ( ABC(node.tag),node.size,
label(node),node.value,ABC(node.parent.tag))
d.revalue()
print ' Node values recomputed from DPT'
for node in d.traverse(include_root=True):
print "%s = %i" % (ABC(node.tag),node.value)
|
45de73534623a904402c42fb38e1d0694350ca69 | samsalgado/Applied-Python | /Generators.py | 873 | 3.765625 | 4 | #functions that return an object that can be iterated over
import sys
def thegenerator():
yield 1
yield 2
yield 3
g = thegenerator()
print(sum(g))
sorted(g)
def countdown(num):
print('Starting')
while num > 0:
yield num
num -= 1
cd = countdown(9)
value = next(cd)
print(value)
value = next(cd)
print(next(cd))
def firstn(n):
nums = []
num = 0
while nums < n:
nums.append(num)
num += 1
return nums
def firstn_generator(n):
num = 0
while num < n:
yield num
num += 1
print(sys.getsizeof(firstn(1000000)))
print(sys.getsizeof(firstn_generator(1000000)))
def fibonacci(limit):
a,b = 0,1
while a < limit:
yield a
a,b = a+b
fib = fibonacci(30)
for i in fib:
print(i)
generator = (i for i in range(10) if i % 2 == 0)
for i in generator:
print(i)
|
bd829c3ee9c8593b97d74d5a1820c050013581f0 | lepy/phuzzy | /docs/examples/doe/scatter.py | 924 | 4.15625 | 4 |
'''
==============
3D scatterplot
==============
Demonstration of a basic scatterplot in 3D.
'''
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
def randrange(n, vmin, vmax):
'''
Helper function to make an array of random numbers having shape (n, )
with each number distributed Uniform(vmin, vmax).
'''
return (vmax - vmin)*np.random.rand(n) + vmin
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
n = 100
# For each set of style and range settings, plot n random points in the box
# defined by x in [23, 32], y in [0, 100], z in [zlow, zhigh].
for c, m, zlow, zhigh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]:
xs = randrange(n, 23, 32)
ys = randrange(n, 0, 100)
zs = randrange(n, zlow, zhigh)
ax.scatter(xs, ys, zs, c=c, marker=m)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()
|
f844aa1f3acbfd7c75631a5f184945b3ebb8f9ac | skarthikeyan85/learn | /python/pramp_smallest_substring.py | 1,423 | 3.890625 | 4 | #pass # your code goes here
'''
build a map for the arr
eliminate chars from the str and decrement the str map
such that i can still be valid with the arr map
'''
def get_shortest_unique_substring(arr, str):
arr_counts={}
for elem in arr:
arr_counts[elem] = 0
ans = ''
uc = 0
h = 0
i = 0
while i < len(str):
if str[i] not in arr_counts:
i += 1
continue
tc = arr_counts[str[i]]
if (tc == 0):
uc += 1
arr_counts[str[i]] = tc + 1
while (uc == len(arr)):
temp_len = i - h + 1
if ans == "" or temp_len < len(ans):
ans = str[h:i+1]
if (str[h] in arr_counts):
hc = arr_counts[str[h]] - 1
if (hc == 0):
uc -= 1
arr_counts[str[h]] = hc
h += 1
i += 1
return ans
'''
def all_present(arr_counts, string):
#if string == "zyx":
# print "here"
for key in arr_counts:
if key not in string:
return False
return True
def get_shortest_unique_substring(arr, input_string):
length = len(input_string)
ans = ''
two=''.join(arr)
arr_counts = collections.Counter(two)
for i in xrange(length):
for j in xrange(i,length):
curr = (input_string[i:j + 1])
if all_present(arr_counts, curr):
if ans is '' or len(curr) < len(ans):
ans = curr
return ans
'''
print get_shortest_unique_substring(['x','y','z'], 'xyyzyzyx')
|
b251cdbaa7ec08e7eb13683e5e62640c298882f6 | dianaalbarracin/Data-Science-Project-1 | /project1.py | 3,856 | 3.859375 | 4 | #import open source python library to perform data manipulation
import pandas as pd
#import json
import json
#Read CSV file from path in my computer
#in my case C:\Users\Diana Albarracin\Desktop\CO2Emission_LifeExp.csv
df = pd.read_csv (r'C:\Users\Diana Albarracin\Desktop\CO2Emission_LifeExp.csv') #change to the path where you saved the file
#Check if the data set is empty and show error if this is the case
if (df.empty):
print("Error: Data set is empty")
#CHECKPOINT 5
#Summarize data before modification: Number of rows per column and number of columns of datafile
#store number of rows in num_rows
num_rows = len(df)
#store number of rows per column in num_rows_col
num_rows_col = df.count()
#Store number of columns in num_col
#Getting shape of df
shape = df.shape
num_col = shape[1]
#source of code for shape [1]
# Printing number of rows and number of columns of datafile
print('\033[92m' + '\033[1m'+ '\033[4m'+'Summary of data set before modification:' + '\033[0m')
print('\033[1m'+'Number of columns in data file:'+'\033[0m', num_col)
print('\033[1m'+'Number of rows in data file:'+'\033[0m', num_rows)
# Source to format the print to bold and different color [2]
#Print name of column and number of rows in that column
print('\033[1m'+'Number of rows in each category: '+'\033[0m', num_rows_col, sep='\n')
#source of code for separating the print statement [3]
#CHECKPOINT 3
#Modify the data file
#Delete the YearlyChange column in the data file
df.pop('YearlyChange')
#Store number of columns in modified data file new_num_col
#Getting shape of df
shape_mod = df.shape
new_num_col = shape_mod[1]
#check that the column was deleted and if not print an error
if (num_col-new_num_col!=1):
print("Error: Modification of data file was not succesful")
#CHECKPOINT 5
#Summarize data after modification: Number of rows per column and number of columns of datafile
#store number of rows in new_num_rows
new_num_rows = len(df)
#store number of rows per column in new_num_rows_col
new_num_rows_col = df.count()
# Printing number of rows and number of columns of datafile
print('\033[92m' + '\033[1m'+ '\033[4m'+'Summary of data set after modification:' + '\033[0m')
print('\033[1m'+'Number of columns in data file:'+'\033[0m', new_num_col)
print('\033[1m'+'Number of rows in data file:'+'\033[0m', new_num_rows)
#Print name of column and number of rows in that column
print('\033[1m'+'Number of rows in each category: '+'\033[0m', new_num_rows_col, sep='\n')
#CHECKPOINT 2
#convert CSV file to JSON
df2 = df.to_json("CO2Emission_LifeExp.json")
#source of code for converting CSV to JSON [4]
#Save it onto your desktop
df.to_json(r'C:\Users\Diana Albarracin\Desktop\CO2Emission_LifeExp.json') #change to your path
#Check that the file was converted to JSON if not throw an error
with open('CO2Emission_LifeExp.json', 'r') as openfile:
try:
json_object = json.load(openfile)
except ValueError:
print ("Error: unable to convert to Json")
#source of code to validate if the file is a JSON file [5]
#Sources:
#[1] https://www.geeksforgeeks.org/count-number-of-columns-of-a-pandas-dataframe/#:~:text=Shape%20property%20returns%20the%20tuple%20representing%20the%20shape,get%20the%20number%20of%20columns%20in%20the%20df.
#[2] https://www.delftstack.com/howto/python/python-bold-text/#:~:text=To%20print%20the%20bold%20text%2C%20we%20use%20the,print%20statement%20will%20keep%20print%20the%20bold%20text.
#[3] https://realpython.com/python-print/
#[4] https://datatofish.com/csv-to-json-string-python/#:~:text=You%20may%20use%20the%20following%20template%20in%20order,steps%20to%20apply%20the%20above%20template%20in%20practice.
#[5] http://www.pythonpandas.com/reading-and-writing-json-to-a-file-in-python/#:~:text=Writing%20JSON%20to%20a%20file%20in%20python%20,%20%20numbers%20%203%20more%20rows%20
|
a4568bbce0e3753e1223512bf3cc51abb478b99d | shahhena95/competitive-programming | /advent-of-code/2015/2015_01.py | 565 | 3.609375 | 4 | from collections import deque
with open('./inputs/day_01.txt') as f:
instructions = f.readlines()
def count_floors(stack=deque()):
[stack.appendleft(1) if char == '(' else stack.appendleft(-1) for char in instructions[0]]
return sum(stack)
def find_basement(instructions, stack=deque()):
for i in range(len(instructions)):
if instructions[i] == '(':
stack.appendleft(1)
elif len(stack) == 0:
return i+1
else:
stack.popleft()
print count_floors()
print find_basement(instructions[0])
|
97d14cefc1fe8ede2d0552a3172c2763c857571f | RanulaGihara/Pharmago_App | /python_files/plotting.py | 566 | 3.53125 | 4 | from math import sqrt
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.metrics import mean_squared_error
df = pd.read_csv('paracetamol.csv', index_col='Date', parse_dates=True)
print(df)
xyz = df['sale'].values
test = df.iloc[160:]
print(xyz)
arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[10, 20], [30, 40]])
#arr2 = np.array(xyz)
# no axis provided, array elements will be flattened
arr_flat = np.append(arr1, arr2)
print(arr_flat)
rmse = sqrt(mean_squared_error(arr1,arr2))
print(rmse)
plt.plot(arr_flat)
plt.show()
|
40fe26bc966069a1fe4e2f3120fd4284db8c1e3f | sharlq/oldpythonprojects | /GUIP/check button and radion button.py | 645 | 3.84375 | 4 | import tkinter
from tkinter import * # its important if it says Tk is not defined
win =Tk()
var=IntVar()
c1 = IntVar() # we need variable to safe the value of the button and we declare it this way
ch = Checkbutton(win, text= "musicl", offvalue = 0, onvalue=1 , height=5, width=10 , variable=c1)
r= Radiobutton(win, text = "option 1" ,variable = var, value = 1) # it has one value and just one var can be checked in
r2= Radiobutton(win, text = "option 2" ,variable = var, value = 2) # it has one value
r3= Radiobutton(win, text = "option 3" ,variable = var, value = 3) # it has one value
ch.pack()
r.pack()
r2.pack()
r3.pack()
win.mainloop() |
7a57ab12d477ea81624b1b95ab56ad8e6bda20f0 | ninjaflesh/vsu_programming | /2_homework/7.py | 325 | 3.640625 | 4 | from random import randint
rand = randint(0, 100)
s = int(input("Vvod: "))
while s != rand:
if s > rand:
print("Загаданное число меньше!")
else:
print("Загаданное число больше!")
s = int(input("Vvod: "))
print("Вы угадали число!")
|
56a4825f2be045fba3c8f40d7ec6747da61ade99 | ninjaflesh/vsu_programming | /1_homework/7.py | 167 | 3.625 | 4 | x = input('Vvod x: ')
y = input('Vvod x: ')
x = int(x)
y = int(y)
counter = 0
for x in range(x, y + 1):
if not x % 5:
counter += x
print(counter)
|
ba4da6e5828ff691027f8351128a08f628fa71a1 | ninjaflesh/vsu_programming | /1_homework/5.py | 302 | 3.84375 | 4 | x = input('Vvod x: ')
y = input('Vvod x: ')
x = float(x)
y = float(y)
if x > 0 and y > 0:
print('1 4etvert')
elif x < 0 and y > 0:
print('2 4etvert')
elif x < 0 and y < 0:
print('3 4etvet')
elif x > 0 and y < 0:
print('4 4etvert')
elif not x or not y:
print('na osi')
|
2a234e6d11a892afd3fb47bbc3899f7631932ca8 | CromixPT/PythonLearning | /hello.py | 249 | 3.796875 | 4 | import sys
x = 1
print("Hello ")
x = 5
y = 10
print(x)
print(y)
y += x
if y > 2:
print("bad")
print(y)
test = "teste"
print("Hello")
print("teste")
def greet(who_to_meet):
greeting = "Hello, {}".format(who_to_meet)
return greeting
|
529738259a0398c322cda396cfc79a6b3f5b38d3 | nancydyc/algorithms | /backtracking/distributeCandies.py | 909 | 4.21875 | 4 | def distributeCandies(candies, num_people):
"""
- loop through the arr and add 1 more candy each time
- at the last distribution n, one gets n/remaining candies
- until the remaining of the candies is 0
- if no candy remains return the arr of last distribution
>>> distributeCandies(7, 4)
[1, 2, 3, 1]
>>> distributeCandies(10, 3)
[5, 2, 3]
"""
arr = [0] * num_people
candy = 0
while candies > 0:
for i in range(len(arr)):
candy += 1
candies -= candy
if candies >= 0:
arr[i] += candy
else:
candies += candy
arr[i] += candies
return arr
return arr
#################################################
if __name__ == "__main__":
import doctest
if doctest.testmod().failed == 0:
print('Suceeded!')
|
110d2e7f3b77de72d9815c9e8a739571854f519d | asliturkcalli/Python_How-to-program_Exercises | /function/perfect number.py | 935 | 3.75 | 4 |
""" perfect number is a number whose sum of its exclusive divisors is equal to itself
forexample=6 exclusive divisors of 6=(1,2,3)
and sum of=1+2+3=6 """
def perfect_number(number):
num=0
for i in range(1,number):
if number%i==0:
num=num+i
else:
continue
if num==number:
return True
else:
return False
while True:
number=input("enter a number")
if number=="q":
break
else:
number=int(number)
if perfect_number(number):
print(number,"is a perfect number")
else:
print(number,"is a not perfect number")
"""
def mukemmel(sayı):
toplam = 0
for i in range(1,sayı):
if (sayı % i == 0):
toplam += i
return toplam == sayı
for i in range(1,1001):
if (mukemmel(i)):
print("Mükemmel Sayı:",i)
"""
|
e1dd7fe02716ecce724bf257cf3dfa3d15e374ca | asliturkcalli/Python_How-to-program_Exercises | /loop/multiplication with loop.py | 141 | 3.703125 | 4 | for i in range(1,10):
for a in range(1,10):
result=i*a
print(f"{i}*{a}={result}")
print("","",sep="\n")
|
ec872a3fbe9b00611cf04c35e30e6a923409bd64 | Diegovsk/Aprendizado | /pythonTeste/ex78.py | 438 | 4.0625 | 4 | lista = [int(input("Digite um valor: ")), int(input("Digite um valor: ")), int(input("Digite um valor: ")),
int(input("Digite um valor: ")), int(input("Digite um valor: "))]
print(f'Você digitou: {lista}')
print(f'O valor minimo digitado está na posição {lista.index(min(lista))} e seu valor é {min(lista)}')
print(f'O valor máximo digitado está na posição {lista.index(max(lista))} e seu valor é {max(lista)}')
|
9089b92bcc94161174a21d9e7fa45b17857b13bb | Diegovsk/Aprendizado | /pythonTeste/projetinhos/exaleatorio.py | 3,092 | 3.78125 | 4 | import random
#declarando variáveis
ope = str('Pedra')
opa = str('Papel')
opt = str('Tesoura')
lista_opcoes = [ope, opa, opt]
aleatorio = random.choice(lista_opcoes)
opcao_selecionada = str(input('Vamos fazer um jogo?\nDuvido você ganhar de mim no pedra, papel ou tesoura. '
'\nA primeira letra há de ser maiúscula e as seguintes minúsculas. \nDigite Pedra ou Papel ou Tesoura para selecionar: '))
opcao_selecionada.capitalize()
if opcao_selecionada == aleatorio:
print('Oops, tirei o mesmo que você, empatamos. :| ')
#Pedra
elif opcao_selecionada == ope and aleatorio == opa:
print('Tirei {}, hehe, você perdeu! xD '.format(opa))
elif opcao_selecionada == ope and aleatorio == opt:
print('Tirei {}, parabéns, você ganhou! :) '.format(opt))
#Papel
elif opcao_selecionada == opa and aleatorio == ope:
print('Tirei {}, parabéns, você ganhou! :) '.format(ope))
elif opcao_selecionada == opa and aleatorio == opt:
print('Tirei {}, hehe, você perdeu! xD '.format(opt))
#Tesoura
elif opcao_selecionada == opt and aleatorio == opa:
print('Tirei {}, parabéns, você ganhou! :) '.format(opa))
elif opcao_selecionada == opt and aleatorio == ope:
print('Tirei {}, hehe, você perdeu! xD '.format(ope))
else:
print('Operação inválida, insira <Pedra>, <Papel> ou <Tesoura>, excluindo os <>')
continuar = str(input('Quer continuar a tentar? (s/n)\n'))
while continuar == 's':
ope = str('Pedra')
opa = str('Papel')
opt = str('Tesoura')
lista_opcoes = [ope, opa, opt]
aleatorio = random.choice(lista_opcoes)
opcao_selecionada = str(input('Vamos fazer um jogo?\nDuvido você ganhar de mim no pedra, papel ou tesoura. '
'\nA primeira letra há de ser maiúscula e as seguintes minúsculas. \nDigite Pedra ou Papel ou Tesoura para selecionar: '))
opcao_selecionada.capitalize()
if opcao_selecionada == aleatorio:
print('Oops, tirei o mesmo que você, empatamos. :| ')
# Pedra
elif opcao_selecionada == ope and aleatorio == opa:
print('Tirei {}, hehe, você perdeu! xD '.format(opa))
elif opcao_selecionada == ope and aleatorio == opt:
print('Tirei {}, parabéns, você ganhou! :) '.format(opt))
# Papel
elif opcao_selecionada == opa and aleatorio == ope:
print('Tirei {}, parabéns, você ganhou! :) '.format(ope))
elif opcao_selecionada == opa and aleatorio == opt:
print('Tirei {}, hehe, você perdeu! xD '.format(opt))
# Tesoura
elif opcao_selecionada == opt and aleatorio == opa:
print('Tirei {}, parabéns, você ganhou! :) '.format(opa))
elif opcao_selecionada == opt and aleatorio == ope:
print('Tirei {}, hehe, você perdeu! xD '.format(ope))
else:
print('Operação inválida, insira <Pedra>, <Papel> ou <Tesoura>, excluindo os <>')
continuar = str(input('Quer continuar a tentar? (s/n)\n'))
else:
print('Ok, parando a execução.')
|
f0fa4b9c13b33806a80c6582e15bda397fafe5b9 | JonRivera/cs-guided-project-time-and-space-complexity | /src/demonstration_1.py | 1,053 | 4.3125 | 4 | """
Given a sorted array `nums`, remove the duplicates from the array.
Example 1:
Given nums = [0, 1, 2, 3, 3, 3, 4]
Your function should return [0, 1, 2, 3, 4]
Example 2:
Given nums = [0, 1, 1, 2, 2, 2, 3, 4, 4, 5]
Your function should return [0, 1, 2, 3, 4, 5].
*Note: For your first-pass, an out-of-place solution is okay. However, after
solving out-of-place, try an in-place solution with a space complexity of O(1).
For that solution, you will need to return the length of the modified `nums`.
The length will tell the user where the end of the array is after removing all
of the duplicates.*
"""
# Track Time for Code to Execute:
t0 = time.time()
# CODE BLOCK
t1 = time.time()
time1 = t1 - t0
import time
# Understand
# Remove Duplicates for given list
# Plan
# Need a way of tracking repeated elements
# If we have a repeated element then remove it from list.pop based on index
# Option#2:Can simply convert given list to set and then reconvert it back to a list
def remove_duplicates(nums):
nums = list(set(nums))
return nums
|
1abe6f6352b042a7656f2f11f92f49b437ad1077 | yunabe/codelab | /swig/python/time_type.py | 410 | 3.6875 | 4 | class Time(object):
def __init__(self, hour, minute, second):
self.__second = hour * 3600 + minute * 60 + second
@property
def hour(self):
return self.__second / (60 * 60)
@property
def minute(self):
return (self.__second / 60) % 60
@property
def second(self):
return self.__second % 60
def __str__(self):
return '%02d:%02d:%02d' % (self.hour, self.minute, self.second)
|
c59eca98c3e4aa9ef73f03fbd4e222792aace43e | auserj/nand2tetris | /06/Python/hasmParser.py | 5,701 | 3.625 | 4 | # Copyright (C) 2011 Mark Armbrust. Permission granted for educational use.
"""
hasmParser.py -- Parser class for Hack computer assembler
See "The Elements of Computing Systems", by Noam Nisan and Shimon Schocken
This parser is slightly different than the parser design in
the book.
Because it is very difficult for HasMoreCommands() to deal with
trailing blank lines and comment only lines, CommandType() returns
NO_COMMAND for any lines that contains no command.
Use LineNo() to retrieve the current input line number and Line()
to retrieve the text. These can be used to add context to error
messages.
"""
from hasmError import *
NO_COMMAND = 0
A_COMMAND = 1
C_COMMAND = 2
L_COMMAND = 3
class Parser(object):
def __init__(self, source):
"""
Costructor Parser(source)
Open 'source' and get ready to parse it.
'source' may be a file name or a string list
"""
try:
self.file = open(source, 'r');
except:
FatalError('Could not open source file "'+source+'"')
self.lineNumber = 0
self.rawline = ''
self.line = ''
def HasMoreCommands(self):
"""
Returns True if there are more commands to process, False at end of file.
"""
return self.file is not None
def Advance(self):
"""
Reads the next command from the input and makes it the current
command. Should be called only if HasMoreCommands() is True.
Initially there is no current command.
"""
self.rawline = self.file.readline()
if len(self.rawline) == 0:
self.file.close()
self.file = None
self.commandType = NO_COMMAND
return
self.rawline = self.rawline.rstrip()
self.lineNumber += 1
self.line = self.rawline
i = self.line.find('//')
if i != -1:
self.line = self.line[:i]
self.line = self.line.strip()
self.line = self.line.replace('\t', ' ')
self._Parse()
return True
def CommandType(self):
"""
Returns the type of the current command:
A_COMMAND for @Xxx where Xxx is either a symbol or a decimal number
C_COMMAND for dest=comp;jump
L_COMMAND (actually, pseudocommand) for (Xxx) where Xxx is a symbol
NO_COMMAND a blank line or comment
"""
return self.commandType
def Symbol(self):
"""
Returns the symbol or decimal Xxx of the current command @Xxx or (Xxx).
Should be called only when commandType() is A_COMMAND or L_COMMAND.
"""
return self.symbol
def Dest(self):
"""
Returns the dest mnemonic in the current C-command (8 possibilities).
Should be called only when commandType() is C_COMMAND.
dest is optional; returns empty string if not present.
"""
return self.dest
def Comp(self):
"""
Returns the comp mnemonic in the current C-command (28 possibilities).
Should be called only when commandType() is C_COMMAND.
"""
return self.comp
def Jump(self):
"""
Returns the jump mnemonic in the current C-command (8 possibilities).
Should be called only when commandType() is C_COMMAND.
jump is optional; returns empty string if not present.
"""
return self.jump
def Line(self):
"""
Returns the input line that has been parsed.
May be used to implement list file output.
"""
return self.rawline
def LineNo(self):
"""
Returns the line number for the line that has been parsed.
May be used to implement list file output.
"""
return self.lineNumber
def _Parse(self):
self.commandType = None
self.symbol = None
self.dest = None
self.comp = None
self.jump = None
self.keywordId = None
self._ParseCommandType()
if self.commandType == A_COMMAND:
self._ParseSymbol()
elif self.commandType == L_COMMAND:
self._ParseSymbol()
elif self.commandType == C_COMMAND:
self._ParseDest()
self._ParseComp()
self._ParseJump()
def _ParseCommandType(self):
if len(self.line) == 0:
self.commandType = NO_COMMAND
elif self.line[0] == '@':
self.commandType = A_COMMAND
elif self.line[0] == '(':
self.commandType = L_COMMAND
else:
self.commandType = C_COMMAND
def _ParseSymbol(self):
if self.CommandType() == L_COMMAND:
if self.line[-1] == ')':
self.line = self.line[:-1]
self.symbol = self.line[1:].strip()
def _ParseDest(self):
i = self.line.find('=')
if i == -1:
self.dest = ''
else:
self.dest = self.line[:i].replace(' ', '')
def _ParseComp(self):
comp = self.line
i = comp.find('=')
if i != -1:
comp = comp[i+1:]
i = comp.find(';')
if i != -1:
comp = comp[:i]
self.comp = comp.replace(' ', '')
def _ParseJump(self):
i = self.line.find(';')
if i == -1:
self.jump = ''
else:
self.jump = self.line[i+1:].strip()
|
87ef151ab872b332a49826059af74669cf67ecc8 | ccydouglas/thePythonBible | /pig.py | 535 | 3.84375 | 4 | original=input("Please enter a sentence: ").strip().lower()
words= original.split()
new_words=[]
for o in words:
if o[0] in "aeiou":
new_word=o+"yay"
new_words.append(new_word)
else:
vowel_pos=0
for letter in o:
if letter not in "aeiou":
vowel_pos= vowel_pos+1
else:
break
cons=o[:vowel_pos]
the_rest=o[vowel_pos:]
new_world=the_rest+cons+"ay"
new_words.append(new_world)
output=" ".join(new_words)
print(output)
|
1dadfb8d032853879a5a45c7533676ee9f2be513 | chenke17/python_learn | /learn_process_xls.py | 1,408 | 3.546875 | 4 | # -*- coding: utf-8 -*-
import xlrd
import sys
# https://www.cnblogs.com/tynam/p/11204895.html
# usage: python learn_process_xls.py ${filename}
if __name__ == "__main__":
filename = sys.argv[1]
# 打开文件
data = xlrd.open_workbook(filename)
# 查看工作表
sheets = data.sheet_names()
print("sheets: ", sheets )
print( type( sheets ) )
# 通过文件名获得工作表,获取工作表1
table = data.sheet_by_name( sheets[0] )
# 打印data.sheet_names()可发现,返回的值为一个列表,通过对列表索引操作获得工作表1
# table = data.sheet_by_index(0)
# 获取行数和列数
# 行数:table.nrows
# 列数:table.ncols
print("总行数:" + str(table.nrows))
print("总列数:" + str(table.ncols))
print( type(table.row_values) )
print( table.row_values )
# 获取整行的值 和整列的值,返回的结果为数组
# 整行值:table.row_values(colx, start_rowx=0, end_rowx=None)
# 整列值:table.col_values(......)
# 参数 start 为从第几个开始打印,
# end为打印到那个位置结束,默认为none
print("整行值:" + str(table.row_values(0)))
print("整列值:" + str(table.col_values(1)))
print( table.row_values(1) )
print( type( table.row_values(0) ) )
# 获取某个单元格的值,例如获取B3单元格值
cel_B3 = table.cell(1,9).value
print("第三行第二列的值:" , cel_B3)
|
452f5cc48114e0b5451af11f18066a0af3125663 | kjans123/heart_rate_databases_starter_introduction | /validate_date_time.py | 3,870 | 4.53125 | 5 | def validate_date_time(date_time):
""""function that validates user input datetime.
Checks to ensure input is of list type. Checks to
ensure all elements are int. Check and forces list to
be 7 elements longs (puts 0's in for hour, minute
second and microsecond if none entered). Checks to
ensure every entered number is within proper range
(e.g., month is between 1 and 12).
:param date_time: takes as input the date in list format
[y, m, d, hr, min, sec, microsecond]
:raises TypeError: raises type error if input is not list.
raises type error if element is not int
raises type error if list is too short
or long
:raises ValueError: raises value error if year is not 4 digits long
raises value error if month is not in proper
range
raises value error if day is not in proper range
raises value error if hour is not in proper range
raises value error if second is not in
proper range
raises value error if microsecond is not
in proper range
"""
type_date = type(date_time)
if type_date is list:
type_date_check = True
else:
raise TypeError("input date is not of list type")
for i in range(len(date_time)):
if isinstance(date_time[i], int) is False:
raise TypeError("list element is not int")
len_date = len(date_time)
if len_date == 3:
date_time.append(0)
date_time.append(0)
date_time.append(0)
date_time.append(0)
elif len_date == 4:
date_time.append(0)
date_time.append(0)
date_time.append(0)
elif len_date == 5:
date_time.append(0)
date_time.append(0)
elif len_date == 6:
date_time.append(0)
elif len_date == 7:
pass
else:
raise TypeError("Not enough arguments in date list")
if len(str(date_time[0])) != 4:
raise ValueError("year is not 4 digits long")
else:
check_len_year = True
for i in list(range(1, 13)):
if date_time[1] == i:
check_month = True
break
else:
check_month = False
for i in list(range(1, 32)):
if date_time[2] == i:
check_day = True
break
else:
check_day = False
for i in list(range(0, 25)):
if date_time[3] == i:
check_hour = True
break
else:
check_hour = False
for i in list(range(0, 60)):
if date_time[4] == i:
check_min = True
break
else:
check_min = False
for i in list(range(0, 60)):
if date_time[5] == i:
check_sec = True
break
else:
check_sec = False
for i in list(range(0, 1000000)):
if date_time[6] == i:
check_micro = True
break
else:
check_micro = False
if check_month is not True:
raise ValueError("month is not in range 1-12")
if check_day is not True:
raise ValueError("day is not in range 1-31")
if check_hour is not True:
raise ValueError("hour is not in range 0-24")
if check_min is not True:
raise ValueError("minute is not in range 0-60")
if check_sec is not True:
raise ValueError("second is not in range 0-60")
if check_micro is not True:
raise ValueError("microsecond is not in range of 0-1000000")
|
2565020d17a45f8fee20ad3a36513da3d6ed029c | sushimon/CodingBat-Exercises | /Python/Logic-2/close_far.py | 625 | 3.796875 | 4 | # Given three ints, a b c, return True if one of b or c is "close" (differing from a by at most 1), while the other is "far", differing from both other values by 2 or more. Note: abs(num) computes the absolute value of a number.
# close_far(1, 2, 10) → True
# close_far(1, 2, 3) → False
# close_far(4, 1, 3) → True
def close_far(a, b, c):
close, far = None, None
if abs(b - a) <= 1:
close, far = b, c
elif abs(c - a) <= 1:
close, far = c, b
if close is None and far is None:
return False
else:
if abs(far - close) >= 2 and abs(far - a) >= 2:
return True
return False |
249d6c41bcc2e11d3888642aaa0424d68b39082e | tuscanos/pyDaily | /L2/L2Q10.py | 626 | 4.09375 | 4 | # Question:
# Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically.
# Suppose the following input is supplied to the program:
# hello world and practice makes perfect and hello world again
# Then, the output should be:
# again and hello makes perfect practice world
words = input("Enter words: ").split(' ')
# wordst = set(words)
# words = list(set(words)).sort()
words = sorted(list(set(words)))
# words.sort()
print(' ' .join(words))
# sorted = sorted(list(set(words)))
# print(sorted(list(set(words)))) |
e2dd799dc8af72c0411b6f551d97ef84f46b0997 | tuscanos/pyDaily | /L2/L2Q15.py | 323 | 4.03125 | 4 | # Question:
# Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a.
# Suppose the following input is supplied to the program:
# 9
# Then, the output should be:
# 11106
d = input("Enter number: ")
addCount = 0
for i in range(1, 5):
addCount += int(str(d) * i)
print(addCount) |
265f3997aab05ef4e4b1b265326e6a5492eef2a0 | corenel/auto-traffic-camera-calib | /misc/utils.py | 899 | 3.671875 | 4 | import cv2
def image_resize(image, width=None, height=None, inter=cv2.INTER_AREA):
# initialize the dimensions of the image to be resized and
# grab the image size
dim = None
(h, w) = image.shape[:2]
# if both the width and height are None, then return the
# original image
if width is None and height is None:
return image
# check to see if the width is None
if width is None:
# calculate the ratio of the height and construct the
# dimensions
r = height / float(h)
dim = (int(w * r), height)
# otherwise, the height is None
else:
# calculate the ratio of the width and construct the
# dimensions
r = width / float(w)
dim = (width, int(h * r))
# resize the image
resized = cv2.resize(image, dim, interpolation=inter)
# return the resized image
return resized
|
ba3d48ae6b982897ef620ce2f38103497d013de6 | ajacks14/MockPractical2 | /q3.py | 694 | 3.96875 | 4 | import random
def randomguess():
randomno=random.randint(0,99)
print(randomno)
guesses=0
correct=False
guess = int(input("Guess a number between 0 and 99: "))
guesses += 1
while not correct:
while guess <0 or guess >99:
guess=("you have guessed below 0 or above 99 guess again ")
guess+=1
if guess < randomno:
guess=int(input("Too low. Guess again: "))
guesses+=1
elif guess > randomno:
guess=int(input("Too high. Guess again: "))
guesses+=1
else:
print("Correct. It took you {} guesses".format(guesses))
correct=True
randomguess()
|
2997a5c9992bebe0d45ff62acd00b81cfab19897 | rrodriguez2018/Ver_Hawksbill_Range_Test | /RPi_AutomationHat_API.py | 2,178 | 3.671875 | 4 | import RPiHAT_mod as Pihat
def print_commands():
print("""Please enter a command:
(1) drain for x seconds long
(2) add DI water for x seconds long
(3) open test loop valve & measure ADC1 uS
(4) check Level to see if max water level detected
(5) fill vessel up to maximum level
(6) check Emergency switch status
(7) Stop flow
(8) Start flow
(9) Drain water, refill, and leave ready to restart
(10) open test loop valve & measure ADC2 uS
(q) Quit the API""")
while True:
print_commands()
selection = input()
if selection == '1':
tdrain = input("how many seconds?: ")
print("Draining water now...")
Pihat.drain(int(tdrain))
elif selection == '2':
tadd = input("How many seconds?: ")
if Pihat.checkLevel == False:
print("Adding DI water now...")
Pihat.add_DI(int(tadd))
else:
print("Sorry, level is already maximum!")
elif selection == '3':
print("running flow now...")
Pihat.runFlowTilHiCond_9900()
elif selection == '4':
print("checking level...")
overfill = Pihat.checkLevel()
if overfill == False:
print("Water level is below maximum.")
else:
print("Water level has reached maximum!!")
elif selection == '5':
print("filling vessel up ...")
Pihat.fillToLevel()
elif selection == '6':
switch = Pihat.is_Emergency()
if switch == True:
print("Emergency Switch is Activated!")
else:
print("Emergency Switch is not activated")
elif selection == '7':
print("Stopping flow now.")
Pihat.stopFlow()
elif selection == '8':
print("Flow starting now...")
Pihat.startFlow()
elif selection == '9':
decreasing_vol = input("How much to lower?: ")
print("lowering Conductivity accordingly")
Pihat.decrease_Cond(int(decreasing_vol))
elif selection == '10':
print("running flow now...")
Pihat.runFlowTilHiCond_8860()
elif selection == 'q':
break
else:
continue |
876962cd05e9f901392d9cc6262bb9c39936d31e | LeaneTEXIER/Licence_2 | /S3/Codage/TP5/tp2.py | 9,996 | 4.0625 | 4 | ##TEXIER Léane
##Groupe 1
import struct
#Question 5:
def integer_to_digit(n):
"""
Retourne le chiffre hexadécimal correspondant à n sous forme de caractère
:param n: Entier décimal
:type n: int
:return: Chiffre n en hexadécimal
:rtype: str
:CU: n est un entier compris entre 0 et 15 inclus
:Exemple:
>>> integer_to_digit(15)
'F'
>>> integer_to_digit(0)
'0'
"""
assert (type(n)==int), "Le paramètre entré n'est pas un entier"
assert (0<=n<=15), "L'entier entré n'est pas compris entre 0 et 15"
if n<=9:
return str(n)
else:
return chr(ord('7')+n)
#Question 6:
def integer_to_string(n,b):
"""
Retourne l'écriture de l'entier n en base b
:param n: Entier à convertir
:type n: int
:param b: Base dans laquelle convertir l'entier n
:type n: int
:return: L'entier n en base b
:rtype: str
:CU: Les deux paramètres sont des entiers, b est compris entre 0 et 36 et n est positif ou nul
:Exemple:
>>> integer_to_string(2000,16)
'7D0'
>>> integer_to_string(15,21)
'F'
"""
assert (type(n)==int), "Le nombre à convertir n'est pas un entier"
assert (type(b)==int), "La base entrée n'est pas un entier"
assert (0<=n), "Le nombre à convertir n'est pas positif ou nul"
assert (0<=b<=36), "La base entrée n'est pas compris entre 0 et 36"
if b>=10:
if n<=9:
return str(n)
elif n<b:
return chr(ord('7')+n)
else:
return (integer_to_string(n//b,b)+integer_to_string(n%b,b))
else:
if n<b:
return str(n)
else:
return (integer_to_string(n//b,b)+integer_to_string(n%b,b))
#Question 10:
def deux_puissances(n):
"""
Retourne la valeur de 2**n (à l'aide d'un opérateur logique)
:param n: Puissance
:type n: int
:return: 2**n
:rtype: int
:CU: n est un entier positif ou nul
:Exemple:
>>> deux_puissances(12)
4096
>>> deux_puissances(9)
512
"""
assert (type(n)==int), "Le paramètre entré n'est pas un entier"
assert (n>=0), "L'entier entré n'est pas positif ou nul"
return 1<<n
#Question 12:
def integer_to_binary_str(n):
"""
Retourne l'écriture binaire de l'entier n sous forme de chaîne de caractères
:param n: Entier à convertir
:type n: int
:return: L'entier n en binaire
:rtype: str
:CU: n est un entier positif ou nul
:Exemple:
>>>integer_to_binary_str(132)
'10000100'
>>> integer_to_binary_str(21)
'10101'
"""
assert (type(n)==int), "Le paramètre entré n'est pas un entier"
assert (n>=0), "L'entier entré n'est pas positif ou nul"
b=''
if n==0:
b='0'
else:
while n>=1:
b=str(n&1)+b
n=n>>1
return b
#Question 13:
def binary_str_to_integer(b):
"""
Retourne l'entier correpondant au nombre binaire b
:param b: Nombre binaire à convertir
:type b: str
:return: L'entier b en décimal
:rtype: int
:CU: b doit etre un nombre binaire
:Exemple:
>>> binary_str_to_integer('110100')
52
>>> binary_str_to_integer('11010110101')
1717
"""
assert (type(b)==str), "Le paramètre entré n'est pas une chaîne de caractères"
assert ((i=='0' or i=='1') for i in b), "Le nombre entré n'est pas un chiffre binaire"
n=0
for i in range(len(b)):
if b[i]=='0':
n=n<<1
else:
n=(n<<1) | 1
return n
#Question 14:
def byte_to_binary(o):
"""
Retourne la valeur binaire sur 8 bits de l'octet entré en paramètre
:param o: Octet à convertir
:type o: str
:return: L'octet o en binaire
:rtype: str
:CU: o doit être un octet
:Exemple:
>>> byte_to_binary(10)
'00001010'
>>> byte_to_binary(126)
'01111110'
"""
assert (type(o)==int), "Le paramètre entré n'est pas un entier (octet)"
assert (0<=o<256), "Le paramètre entré n'est pas un octet (valeur comprise entre 0 et 255 inclus)"
b=integer_to_binary_str(o)
while len(b)!=8:
b='0'+b
return b
#Question 15:
def float_to_bin (n):
"""
Retourne la chaine binaire correspondant au réel n
:param n: Réel
:type n: int or float
:return: Chaine binaire du réel n
:rtype: str
:CU: n est un réel
:Exemple:
>>> float_to_bin(3.5)
'01000000011000000000000000000000'
>>> float_to_bin(1)
'00111111100000000000000000000000'
"""
assert (type(n)==float or type(n)==int), "Le paramètre entré n'est pas un réel"
b=''
bytes_stored = struct.pack('>f', n)
for i in bytes_stored:
b=b+byte_to_binary(i)
return b
#Question 16:
def change_a_bit(b,p):
"""
Retourne la chaine binaire b entré en remplacant le bit à la position p par son bit inverse
:param b: Chaine binaire
:type b: str
:param p: Position du bit à inverser
:type p: int
:CU: b doit etre une chaine binaire et p un entier (compris entre 0 et len(b)-1)
:Exemple:
>>> change_a_bit('01011',2)
'01111'
>>> change_a_bit('010101011',1)
'000101011'
"""
assert (type(b)==str), "Le paramètre b entré n'est pas une chaîne de caractères"
assert (type(p)==int), "Le paramètre p entré n'est pas un entier"
assert (0<=p<len(b)), "Le paramètre p entré doit être compris entre 0 et la longueur de la chaine b-1"
return b[:p]+str(int(b[p])^1)+b[p+1:]
#Question 17:
def binary_to_bytes(b):
"""
Retourne la chaine binaire b en une liste d'entiers correspondants à chaque groupe de 8 bits contenus dans b
:param b: Chaine binaire
:type b: str
:return: Liste d'entiers
:rtype: list
:CU: b est une chaine binaire ayant une taille d'un multiple de 8
:Exemple:
>>> binary_to_bytes('0101101001010010')
[90, 82]
>>> binary_to_bytes('110101101101011111011000')
[214, 215, 216]
"""
assert (type(b)==str), "Le paramètre b entré n'est pas une chaîne de caractères"
assert (len(b)%8==0), "La longueur de la chaine b doit être un multiple de 8"
l=[]
while len(b)>0:
bi=b[:8]
l.append(binary_str_to_integer(bi))
b=b[8:]
return l
#Question 18:
def change_a_bit_in_float(n,p):
"""
Retourne la valeur du réel modifié (=prend la représentation binaire de n et change son bit se trouvant à la position p)
:param n: Réel à modifier
:type n: int or float
:param p: Position du bit à inverser
:type p: int
:return: Valeur du réel n modifié (inversion du bit à la position b dans la représentation binaire de n)
:rtype: float
:CU: n est un réel et p est un réel positif inférieur strictement à 32 (4 octets)
:Exemple:
>>> change_a_bit_in_float(3.5,10)
3.0
>>> change_a_bit_in_float(3.5,14)
3.53125
"""
assert (type(n)==float or type(n)==int), "Le paramètre entré n'est pas un réel"
assert (type(p)==int), "Le paramètre p entré n'est pas un entier"
assert (0<=p<32), "p doit être un réel positif inférieur strictement à 32"
b=change_a_bit(float_to_bin(n),p)
l=binary_to_bytes(b)
return (struct.unpack('>f', bytes(l))[0])
#Question 29:
def isolatin_to_utf8(stream):
"""
Lit un caractère ISO-8859-1 du flux 'stream' et retourne un tuple d'un ou deux octet(s) correspondant(s) au caractère UTF-8.
Si on est à la fin du fichier, retourne None
:param stream: flux
:return: Tuple d'un ou deux octet(s) correspondant(s) au caractère UTF-8 (ou None si fin du fichier)
:rtype: tuple
:CU: None
"""
try:
byte = stream.read(1)[0]
if byte<160:
return (byte,)
else:
return (((byte>>6)|192),((byte | 192) & 191))
except IndexError:
stream.close()
return None
#Question 30:
def convert_file(source, dest, conversion):
'''
Convert `source` file using the `conversion` function and writes the
output in the `dest` file.
:param source: The name of the source file
:type source: str
:param dest: The name of the destination file
:type dest: str
:param conversion: A function which takes in parameter a stream (opened\
in read and binary modes) and which returns a tuple of bytes.
:type conversion: function
'''
entree = open(source, 'rb')
sortie = open(dest, 'wb')
octets_sortie = conversion(entree)
while octets_sortie != None:
sortie.write(bytes(octets_sortie))
octets_sortie = conversion(entree)
sortie.close()
def convert_file_isolatin_utf8(source, dest):
'''
Converts `source` file from ISO-8859-1 encoding to UTF-8.
The output is written in the `dest` file.
'''
convert_file(source, dest, isolatin_to_utf8)
#convert_file_isolatin_utf8('cigale-ISO-8859-1.txt','cigale30-UTF-8.txt')
#Question 31:
def utf8_to_isolatin(stream):
"""
Lit un caractère UTF-8 du flux 'stream' et retourne un tuple d'un octet correspondant au caractère ISO-8859-1
Si on est à la fin du fichier, retourne None
:param stream: flux
:return: Tuple d'un octet correspondant au caractère ISO-8859-1 (ou None si fin du fichier)
:rtype: tuple
:CU: None
"""
try:
byte = stream.read(1)[0]
if (byte==194):
byte2=stream.read(1)[0]
return (byte2,)
elif (byte==195):
byte2=stream.read(1)[0]
return ((byte2+64),)
else:
return (byte,)
except IndexError:
stream.close()
return None
#Question 32:
def conversion_file_utf8_isolatin(source, dest):
'''
Converts `source` file from UTF-8 encoding to ISO-8859-1.
The output is written in the `dest` file.
'''
convert_file(source, dest, utf8_to_isolatin)
#conversion_file_utf8_isolatin('cigale-UTF-8.txt','cigale32-ISO-8859-1.txt')
|
0e9bb8e8d914754431f545af8cf6358012c52ca1 | MikeyABedneyJr/python_exercises | /challenge7.py | 677 | 4.1875 | 4 | '''
Write one line of Python that takes a given list and makes a new list that has only the even elements of this list in it. http://www.practicepython.org/exercise/2014/03/19/07-list-comprehensions.html
'''
import random
from random import randint
given_list = random.sample(xrange(101),randint(1, 101))
# even_numbers = [number % 2 == 0 for number in given_list]
# This only prints [false, true, false,...] and not actual values
even_numbers = [number for number in given_list if number % 2 == 0]
# This says even_numbers = [number] and "number" is determined by all the logic that follows it (i.e the for loop and if statement)
print given_list, "\n\n", even_numbers |
aecf0cd25de38821b669b51a5b48267379626e67 | DanielSank/aes-victor | /encrypt_main.py | 1,676 | 3.875 | 4 | """
This is the main routine for performing AES-256 encryption. It reads a key from
key.txt and performs key expansion. Then it reads plain text data from
plaintex.txt', and encrypts that data using the key. It then writes the
encrypted data to CTData.txt.
"""
from constants import Nr
from encrypt_functions import get_key, get_pt_data, out_ct_data, print_hex
from encrypt_functions import key_expansion, add_round_key, sub_bytes, shift_rows, mix_columns
key = get_key()
w = key_expansion(key) # Perform KeyExpansion input key(8), output w(60) = expanded key
state = get_pt_data()
print(' Main: Finished GetPTData state = ')
print_hex(state)
rround = 0
print('Main: round = ', rround)
add_round_key(state, w, rround) # First call to AddRoundKey uses first 4 words of w[], w[0] to w[3].
# The next 13 calls to AddRoundKey are with w(4 to 7) to w(52 to 55). round 14 uses w[56] to w[59].
for rround in range(1, Nr): # 1 to 13 for loop quits at Nr-1
print(' Main: round = ', rround)
sub_bytes(state) # SubBytes callss box, a byte oriented 16x16 array
shift_rows(state) # shifts Rows of state left r bytes, r = row number
mix_columns(state) # polynomial multiply of state modulo x^4 + 1)
add_round_key(state, w, rround) # Adds w, the RouncKey to columns of state
rround = 14 # round 14, (15th round) there is no MixColumns
print(' Main: round = ', rround)
sub_bytes(state)
shift_rows(state)
add_round_key(state, w, rround) # last calls to AddRoundKey is with w[56 to 59]
out_ct_data(state) # print to text file CTData.txt
print('Encrypted Data written to CTData.txt)')
|
537be385e6a599b2e3495753b8afa0e5c132c233 | miths-git/Testing | /task4.py | 5,134 | 4.34375 | 4 | """
TRADITIONAL FUNCTIONS,ANONYMOUS FUNCTIONS &
HIGHER ORDER FUNCTIONS
1. Write a program to reverse a string.
Sample input: “1234abcd”
Expected output: “dcba4321”
def reverse(s):
str = " "
for i in s:
str = i + str
return str
s = "Today is a wonderful day!"
print("The original string is : ", end="")
print(s)
print("The reversed string(using loops) is : ", end="")
print(reverse(s))
2. Write a function that accepts a string and prints the number of uppercase letters and lowercase
letters.
Sample input: “abcSdefPghijQkl”
Expected Output: No. of Uppercase characters : 3 No. of Lower case Characters : 12
def upper_lower(s):
up_case = sum(1 for i in s if i.isupper())
low_case = sum(1 for i in s if i.islower())
print( "Number of uppercase characters : %s\nNumber of lower case characters : %s" % (up_case,low_case))
upper_lower("asdWDJKKsasf")
3.Create a function that takes a list and returns a new list with unique elements of the first list.
def unique(list):
x = []
for s in list:
if s not in x:
x.append(s)
return x
print(unique([1,2,2,2,2,4,9,6,7,8,3,3,3,3,4,5]))
4. Write a program that accepts a hyphen-separated sequence of words as input and prints the words
in a hyphen-separated sequence after sorting them alphabetically.
print("Enter a hyphen separated sequence of words:\n")
l=[n for n in input().split('-')]
l.sort()
print("After sorting alphabetically:")
print('-'.join(l))
5. Write a program that accepts a sequence of lines as input and prints the lines after making all
characters in the sentence capitalized.
Sample input: Hello world Practice makes man perfect
Expected output: HELLO WORLD PRACTICE MAKES MAN PERFECT
lines = []
print("Sequence of lines: ")
while True:
line = input("> ")
if not line:
break
lines.append(line.upper())
print(lines)
6. Define a function that can receive two integral numbers in string form and compute their sum and print it in
the console.
def numbers(s1,s2):
print(int(s1) + int(s2))
print("The sum of the numbers:")
numbers("10","20")
7. Define a function that can accept two strings as input and print the string with the maximum length
in the console. If two strings have the same length, then the function should print both the strings line
by line.
def two_numbers(l1,l2):
len1 = len(l1)
len2 = len(l2)
if len1 > len2:
print(l1)
elif len2 > len1:
print(l2)
else:
print(l1)
print(l2)
two_numbers("one","one")
8. Define a function which can generate and print a tuple where the values are square of numbers
between 1 and 20 (both 1 and 20 included).
def values():
l = list()
for i in range(1, 21):
l.append(i ** 2)
print(tuple(l))
values()
9. Write a function called showNumbers that takes a parameter called limit. It should print all the
numbers between 0 and limit with a label to identify the even and odd numbers.
Sample input: show Numbers(3) (where limit=3)
Expected output:
0 EVEN
1 ODD
2 EVEN
3 ODD
def showNumbers(limit):
for i in range(0, limit + 1):
if i % 2 == 0:
print(i,'EVEN')
else:
print(i,'ODD')
showNumbers(4)
10.Write a program which uses filter() to make a list whose elements are even numbers between 1
and 20 (both included)
def even_numbers(x):
return x%2==0
even = filter(even_numbers,range(1,21))
print(list(even))
11. Write a program which uses map() and filter() to make a list whose elements are squares of even
numbers in [1,2,3,4,5,6,7,8,9,10].
Hints: Use filter() to filter even elements of the given listUse map() to generate a list of squares of the
numbers in the filtered list. Use lambda() to define anonymous functions.
def even_numbers(x):
return x % 2 == 0
def squares(x):
return x * x
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
l = map(squares , filter(even_numbers, l))
print(list(l))
12. Write a function to compute 5/0 and use try/except to catch the exceptions
def value():
return 5/0
try:
value()
except ZeroDivisionError as ze:
print("Any integer number divided by digit zero is a ZERO!")
except:
print("Any other exception")
13. Flatten the list [1,2,3,4,5,6,7] into 1234567 using reduce().
import functools
import operator
original_list = [1,2,3,4,5,6,7] #List to be flattened
flatten_list = functools.reduce(operator.iconcat, original_list,[])
print("Original List:", original_list)
print("Flattened List:", flatten_list)
15. Write a program in Python to multiply the elements of a list by itself using a traditional function
and pass the function to map() to complete the operation.
16. What is the output of the following codes:
(i)
def foo():
try:
return 1
finally:
return 2
k = foo()
print(k)
(ii)
def a():
try:
f(x, 4)
finally:
print('after f')
print('after f?')
a()
""" |
17b8708b811972931ee04b1295ce8a272cb410cf | Everett1914/CS325HW1 | /mergesort.py | 2,101 | 3.953125 | 4 | #Everett Williams
#30JUN17 as of 02JUL17
#HW1 Problem 4
#Merge sort program
#sort array using merge sort algorithm
def mergeSort(alist):
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf) #returns sorted left half which is sorted with the below while statements
mergeSort(righthalf) #returns sorted right half which is sorted with the below while statements
merge(lefthalf, righthalf, alist)
return alist
#helper function to merge sub arrays
def merge(lefthalf, righthalf, blist):
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf): #while both arrays lt length compare values
if lefthalf[i] < righthalf[j]:
blist[k]=lefthalf[i]
i=i+1
else:
blist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf): #when rt array has nothing left to check append remaining left elements
blist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf): ##when lt array has nothing left to check append remaining right elements
blist[k]=righthalf[j]
j=j+1
k=k+1
#read data from data.txt and store data as integers into the list dataArray and
#return unsorted array
def readArray():
with open('data.txt') as data:
for line in data:
dataArray = []
line = line.split() # to deal with blank
if line: # lines (ie skip them)
for value in line:
num = int(value)
dataArray.append(num)
del dataArray[0]
sortedArray = mergeSort(dataArray)
outPutArray(sortedArray)
return dataArray
#write sorted array to merge.out
def outPutArray(array):
with open('merge.out', 'a') as outPutFile:
for val in array:
num = str(val)
outPutFile.write(num + " ")
outPutFile.write("\n")
#Main program
readArray()
|
4d147ba2a66e2b63740cda46fabdad69a47925d9 | mbarakaja/codility-lessons | /lesson1/binary_gap.py | 1,757 | 3.828125 | 4 | """
Binary Gap
~~~~~~~~~~
A binary gap within a positive integer N is any maximal sequence of consecutive
zeros that is surrounded by ones at both ends in the binary representation of N.
For example, number 9 has binary representation 1001 and contains a binary gap
of length 2. The number 529 has binary representation 1000010001 and contains
two binary gaps: one of length 4 and one of length 3. The number 20 has binary
representation 10100 and contains one binary gap of length 1. The number 15 has
binary representation 1111 and has no binary gaps. The number 32 has binary
representation 100000 and has no binary gaps.
Write a function:
def solution(N):
that, given a positive integer N, returns the length of its longest binary gap.
The function should return 0 if N doesn't contain a binary gap.
For example, given N = 1041 the function should return 5, because N has binary
representation 10000010001 and so its longest binary gap is of length 5. Given
N = 32 the function should return 0, because N has binary representation '100000'
and thus no binary gaps.
Assume that:
N is an integer within the range [1..2,147,483,647].
Complexity:
expected worst-case time complexity is O(log(N));
expected worst-case space complexity is O(1).
"""
def solution(N):
# Binary representation as string
bstring = "{0:b}".format(N)
head = None
tail = None
gap = 0
for index, value in enumerate(bstring, 1):
if not head and value == "1":
head = index
continue
if head and not tail and value == "1":
tail = index
_gap = tail - (head + 1)
if _gap > gap:
gap = _gap
head = tail
tail = None
return gap
|
4728ec496ae1d032e36d65dd2ce88c2ddc52b831 | mbarakaja/codility-lessons | /challenges/digital_gold.py | 2,250 | 4.0625 | 4 | """
Dividing The Kingdom
~~~~~~~~~~~~~~~~~~~~
An old king wants to divide his kingdom between his two sons. He is well
known for his justness and wisdom, and he plans to make a good use of both
of these attributes while dividing his kingdom.
The kingdom is administratively split into square boroughs that form an
N × M grid. Some of the boroughs contain gold mines. The king knows that
his sons do not care as much about the land as they do about gold, so he
wants both parts of the kingdom to contain exactly the same number of
mines. Moreover, he wants to split the kingdom with either a horizontal or
a vertical line that goes along the borders of the boroughs (splitting no
borough into two parts).
The goal is to count how many ways he can split the kingdom.
Write a function::
def solution(N, M, X, Y)
that, given two arrays of K integers X and Y, denoting coordinates of
boroughs containing the gold mines, will compute the number of fair
divisions of the kingdom.
For example, given N = 5, M = 5, X = [0, 4, 2, 0] and Y = [0, 0, 1, 4], the
function should return 3. The king can divide his land in three different
ways shown on the picture below.
Permanent link of Codility award:
https://app.codility.com/cert/view/certDZ47JT-JXZZMUDEBFR8U85F/
"""
from collections import OrderedDict
def sum_lines(size, lines, max_gold):
"""Sum how many golds are over an axis."""
divisions = 0 # divisions
golds = 0 # Golds
for i in range(size):
golds += lines.get(i, 0)
if golds > max_gold:
break
if golds == max_gold:
divisions += 1
return divisions
def solution(N, M, X, Y):
NG = len(X) # number of golds
if NG % 2 != 0:
return 0
max_gold = int(NG / 2)
x_lines = OrderedDict()
y_lines = OrderedDict()
for c in range(NG):
cx = X[c]
cy = Y[c]
try:
x_lines[cx] += 1
except KeyError:
x_lines[cx] = 1
try:
y_lines[cy] += 1
except KeyError:
y_lines[cy] = 1
return sum_lines(M, y_lines, max_gold) + sum_lines(N, x_lines, max_gold)
|
18fa852cc95b13b76ef6f9c2effed76e9ca34e45 | naturalis/sdmdl-pollinators | /Data Preprocessing/crop_predictions.py | 2,318 | 3.90625 | 4 | def crop(netherlands_locations, world_locations, xmin, xmax, ymin, ymax):
""" Reads world_locations_to_predict.csv, and scans for coordinates that are
withing the range of the Netherlands. These coordinates are written to a
new file.
:param netherlands_locations: A csv-file, to where the cropped
coordinates extent is written
:param world_locations: A csv-file from SDMDL, containing the prediction
coordinates of the world
:param xmin: A float containing the minimum x coordinate of the Netherlands
:param xmax: A float containing the maximum x coordinate of the Netherlands
:param ymin: A float containing the minimum y coordinate of the Netherlands
:param ymax: A float containing the maximum y coordinate of the Netherlands
:return: -
"""
tag = 0
for lines in world_locations.readlines():
line = lines.rstrip('\n').split(',')
try:
if "decimal_longitude" not in line:
if float(line[1]) < xmax and float(line[1]) > xmin and\
float(line[2]) < ymax and float(line[2]) > ymin:
line = str(tag) + "," + str(line[1]) + "," + str(line[2])\
+ "\n"
netherlands_locations.write(line)
tag += 1
else:
print(line)
netherlands_locations.write(lines)
except ValueError:
netherlands_locations.write(',decimal_longitude,decimal_latitude\n')
def main():
""" Defines border coordinates of the Netherlands. Asks user to enter
pathway to world_locations_to_predict.csv, and a destination for the newly
cropped coordinate file. Initiates the cropping.
:return: -
"""
xmin = 3.245713
xmax = 7.256333
ymin = 50.72637
ymax = 53.53395
world_file = input("Enter the pathway to the world_locations_to_"
"predict file:\n")
netherlands_file = input("Enter desired pathway location to write"
"the cropped file:\n")
world_locations = open(world_file, "r")
netherlands_locations = open(netherlands_file, "w")
crop(netherlands_locations, world_locations, xmin, xmax, ymin, ymax)
main()
|
064514000707be0c1204f6e57d8ec3f02adb025d | Suraj-Mohite/Pattern_Practice | /pattern25.py | 1,133 | 3.9375 | 4 | """
input:4
1
2*2
3*3*3
4*4*4*4
4*4*4*4
3*3*3
2*2
1
"""
def Pattern(no):
try:
no=str(no)
no=int(no)
if no<=0:
print("ERROR: 0 and Negative numbers are not allowed")
return
for i in range(1,2*no+1):
if i==1 or i==2*no:
print("1")
elif i<=no:
print(f"{i}*"*(i-1)+str(i))
elif i==no+1:
print(f"{i-1}*"*(i-2)+str(i-1))
elif i>no+1:
print(f"{2*no-i+1}*"*(2*no-i)+str(2*no-i+1))
except Exception as e:
print("ERROR: Invalid Input")
if __name__ == "__main__":
inp=input("Enter the Number.\n")
Pattern(inp)
print()
#TestCases
#Different Datatype And Different Value Has been passed as an input to test the function
Pattern(6) #test with positive integer as input
print()
Pattern(-8) #test with negative integer as input
print()
Pattern(0) #test with 0 as input
print()
Pattern(1.3) #test with float as input
print()
Pattern("string") #test with string as input
print() |
9bc8c8becf15454c52961ba5c0321281ce702603 | Suraj-Mohite/Pattern_Practice | /pattern2.py | 419 | 3.6875 | 4 | #accept row and column from user and disply
'''
* * * *
$ $ $ $
* * * *
$ $ $ $
'''
def Pattern2(iRow,iCol):
for x in range(1,iRow+1):
for y in range(1,iCol+1):
if(x%2==0):
print("$",end=" ")
else:
print("*",end=" ")
print()
iRow=int(input("Enter the number of rows.\n"))
iCol=int(input("Enter the number of columns.\n"))
Pattern2(iRow,iCol) |
9e6faf0e5896657070cf9d1ac6ccc70026385083 | bbbarron/euler | /15euler.py | 1,077 | 3.890625 | 4 | """
Lattice paths
Problem 15
Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20×20 grid?
"""
import math
def test():
n = 20
paths = math.factorial(2 * n) / (math.factorial(n) * math.factorial(n))
print (int(paths))
test()
# Non-programming solution:
# This is an alternate way to solve it:
# Let each movement in the horizontal direction be a zero.
# Let each movement in the vertical direction be a one.
# 1st binary# in the series of possible solutions:
# 0000000000000000000011111111111111111111
# and the last:
# 1111111111111111111100000000000000000000
# For the combinations (or solutions) in between, the amount of
# zeros (20) should be the same as ones (20). In other
# words, the ones and zeros have to be rearranged in all possible ways.
# This then is the same as the possible number of arranging 40 things
# in sets of 20.
# The total is: 40!/(20!)(20!)
# Just use a calculator.
# 137846528820
|
d099937613e33925b2cd29456e066bfc30edcd43 | CrossLangNV/python-for-java-devs | /joris/printer.py | 1,459 | 3.828125 | 4 | # Python 3.6+ example
class Printer:
def print(self):
pass
class YamlPrinter(Printer):
def __init__(self, items=None):
# assume this is a dict
self._items = items
def print(self):
print('--- # YAML printer')
for item in self._items:
print(f'- {item}: {self._items[item]}')
@property
def items(self):
print("getter of items called")
return self._items
@items.setter
def items(self, value):
print("setter of items called")
self._items = value
def __repr__(self):
return "YamlPrinter items=%s" % self._items
class CSVPrinter(Printer):
def __init__(self, items={}):
# assume this is a dict
self._items = items
def print(self):
for item in self._items:
print(f'{item}, {self._items[item]}')
@property
def items(self):
print("getter of items called")
return self._items
@items.setter
def items(self, value):
print("setter of items called")
self._items = value
def __repr__(self):
return "CSVPrinter items=%s" % self._items
if __name__ == '__main__':
items = {
'color': 'red',
'amount': 5
}
y = YamlPrinter(items)
c = CSVPrinter(items)
y.print()
c.print()
y.items = {'color':'blue', 'amount':3, 'enabled':True} # setter called
items = y.items # getter called
print(y)
|
187897f5d5727394535438e09ae1a64db3fb1a32 | SeongwonChung/CodingTest | /dongbinbook/Graph/disjoint_set_cycle_detect.py | 1,209 | 3.578125 | 4 | """
서로소 집합으로 무뱡향 그래프에서 사이클을 판별할 때 사용할 수 있다.
union연산은 간선으로 표현된다.
간선을 하나씩 확인하면서 두 노드가 포함되어 있는 집합을 합치는 과정을 반복하는 것 만으로 사이클을 판별할 수 있다.
그래프에 포함되어 있는 간선의 개수가 E일때, 모든 간선을 하나씩 확인하며, 매 간선에 대해 union, find를 호출하는 방식.
무향그래프에만 적용 가능
"""
def find_parent(parent, x):
if parent[x] != x:
parent[x] = find_parent(parent, parent[x])
return parent[x]
def union_parent(parent, a, b):
a = find_parent(parent, a)
b = find_parent(parent, b)
if a < b:
parent[b] = a
else:
parent[a] = b
v, e = map(int, input().split())
parent = [0] * (v + 1)
for i in range(1, v + 1):
parent[i] = i
cycle = False
for i in range(e):
a, b = map(int, input().split())
# 사이클 발생시 종료
if find_parent(parent, a) == find_parent(parent, b):
cycle = True
break
else:
union_parent(parent, a, b)
if cycle:
print("cycle exists")
else:
print("no cycle")
|
4065c357fb3ff737db7c38321791081143203dee | SeongwonChung/CodingTest | /dongbinbook/BinarySearch/기출/28-고정점찾기.py | 441 | 3.578125 | 4 | n = int(input())
numbers = list(map(int, input().split()))
def bin_search(numbers, start, end):
if start > end:
return -1
mid = (start + end) // 2
if numbers[mid] == mid:
return mid
left = bin_search(numbers, start, mid - 1)
if left != -1:
return left
right = bin_search(numbers, mid + 1, end)
if right != -1:
return right
return -1
print(bin_search(numbers, 0, n - 1))
|
c760c3d8328fea177e2c7dee166b003a61297258 | SeongwonChung/CodingTest | /dongbinbook/Sort/sort_method.py | 429 | 4.03125 | 4 | """
sorted - O(NlogN)
정렬해서 리스트로 반환
"""
array = [1,6,3,6,8,8,6,2,67,9,0]
result = sorted(array)
print('sorted', result)
"""
.sort() => list 의 method
return 없이 list가 바로 sort됨
"""
array.sort()
print('.sort', array)
pairs = [('성원', 25), ('다운', 23), ('재원', 26), ('범수', 30)]
key_sort = sorted(pairs, key=lambda x: x[1]) # key에 함수를 통해 정렬.
print('keysort', key_sort)
|
18b1131cb6622c0d0a52b1b3cb8d57beba12a252 | SeongwonChung/CodingTest | /dongbinbook/Implement/기출/10-자물쇠와열쇠.py | 1,201 | 3.53125 | 4 | def rotate(matrix):
row = len(matrix)
column = len(matrix[0])
rotated = [[0 for _ in range(row)] for _ in range(column)]
for i in range(row):
for j in range(column):
rotated[j][row - i - 1] = matrix[i][j]
return rotated
def check(new_lock):
size = len(new_lock) // 3
for i in range(size, size * 2):
for j in range(size, size * 2):
if new_lock[i][j] != 1:
return False
return True
def solution(key, lock):
n = len(lock)
m = len(key)
lock_expanded = [[0 for _ in range(n * 3)] for _ in range(n * 3)]
for i in range(n):
for j in range(n):
lock_expanded[i + n][j + n] = lock[i][j]
for x in range(n * 2):
for y in range(n * 2):
for d in range(4):
key = rotate(key)
for i in range(m):
for j in range(m):
lock_expanded[i + x][j + y] += key[i][j]
if check(lock_expanded):
return True
for i in range(m):
for j in range(m):
lock_expanded[i + x][j + y] -= key[i][j]
return False
|
f8919c74bdc5226401bfebd62281888447bb9e39 | SeongwonChung/CodingTest | /Programmers/Graph/가장먼노드.py | 825 | 3.5625 | 4 | """
우선순위큐 다익스트라로 풀이.
"""
import heapq
def solution(n, edge):
answer = 0
INF = int(1e9)
distance = [INF for _ in range(n + 1)]
graph = [[] for _ in range(n + 1)]
for a, b in edge:
graph[a].append(b)
graph[b].append(a)
def dijkstra(s):
distance[s] = 0
q = []
heapq.heappush(q, (0, s))
while q:
dist, now = heapq.heappop(q)
if distance[now] < dist:
continue
for v in graph[now]:
cost = dist + 1
if cost < distance[v]:
distance[v] = cost
heapq.heappush(q, (cost, v))
dijkstra(1)
distance = list(filter(lambda x: x < INF, distance))
answer = distance.count(max(distance))
return answer |
8a392c0f82d807276beb43190b225601ae4380f9 | Oldgong1/Python_Project | /Python Final Project/flat.py | 3,091 | 3.5625 | 4 | #%%
print("WELCOME COME TO MOMO")
restart = ('y')
reload = 3
balance = 500
while reload >=0:
pin = int(input('Enter your password to continue''\n'))
if pin == (1234):
print('Your been has been verified, continue: ')
while restart not in ('n', 'NO', 'no', 'N'):
print("*******************************************")
print("===== MOBILE MONEY TANSACTION SYSTEM ====")
print("*******************************************")
print("======== 1. Check balance ========")
print("======== 2. Deposit Cash ========")
print("======== 3. Withdraw Cash ========")
print("======== 4. Transfer money ========")
print("======== 5. Quit ========")
print("*******************************************")
option = int(input('select an option to continue''\n'))
if option == 1:
number = int(input('enter phone number' '\n'))
print('Your account balance is Ghc', balance, '\n')
restart = input('Would you like to go back?' '\n')
if restart in ('n', 'NO', 'no', 'N'):
print('You are welcome')
break
elif option == 2:
print('Deposit')
number = int(input('enter phone number' '\n'))
deposit = float(input('How much are you depositing' '\n'))
balance = balance + deposit
print('\n Deposit sucessful, your balance is now Ghc ', balance)
restart = input('Would you like to go back?''\n')
if restart in ('n', 'NO', 'no', 'N'):
print('Thank you')
break
elif option == 3:
withdrawal = float(input('How much would you like to withdraw?''\n'))
number = int(input('enter phone number' '\n'))
number1 = int(input('repeat phone number' '\n'))
balance = balance - withdrawal
print('Withdrawal successful, balance is now Ghc', balance, '\n')
restart = input('Would you like to go back? ')
if restart in ('n', 'NO', 'no', 'N'):
break
elif option == 4:
transfer = float(input('Enter amount to transfer''\n'))
number = int(input('enter phone number' '\n'))
number1 = int(input('repeat phone number' '\n'))
balance = balance - transfer
print('Amount sent successfuly'), print('your balance is now Ghc', balance, '\n')
restart = input('Would you like to go back? ')
if restart in ('n', 'NO', 'no', 'N'):
break
elif option == 5:
if input("are you sure you want to quit? (y/n)" '\n') != "y":
exit()
print('thanks for your time')
break
# ============== end of momo account =============
# %%
|
e6a688b5a85a54fedd45925b8d263ed5f79a5b41 | shardul1999/Competitive-Programming | /Sieve_of_Eratosthenes/Sieve_of_Eratosthenes.py | 1,018 | 4.25 | 4 | # implementing the function of Sieve of Eratosthenes
def Sieve_of_Eratosthenes(n):
# Creating a boolean array and
# keeping all the entries as true.
# entry will become false later on in case
# the number turns out to be prime.
prime_list = [True for i in range(n+1)]
for number in range(2,n):
# It is a prime if prime_list[number] doesn't change.
if (prime_list[number] == True):
# Updating the multiples of the "number" greater
# than or equal to the square of this number.
# all the numbers which are multiple of "number" and
# are less than number2 have already been marked.
for i in range(number * number, n+1, number):
prime_list[i] = False
# To print all the prime numbers
for i in range(2, n+1):
if prime_list[i]:
print(i)
# Driver Function
if __name__=='__main__':
n = 40
print("The prime numbers less than or equal to ",end="")
print(n," are as follows: - ")
Sieve_of_Eratosthenes(n)
|
5a4091fcc02ab8625120f33dbc74a18f6d9a39e7 | shardul1999/Competitive-Programming | /CODEFORCES/Beautiful_Year_800.py | 195 | 3.71875 | 4 | year=int(input())
year+=1
s=str(year)
while True:
if s[0]!=s[1] and s[0]!=s[2] and s[0]!=s[3] and s[1]!=s[2] and s[1]!=s[3] and s[2]!=s[3]:
break
year+=1
s=str(year)
print(year)
|
30aad0e938f726ba882dddb5f6b66cb3f9140011 | javad-torkzadeh/courses | /python_course/ch5_exercise3.py | 553 | 4.21875 | 4 | '''
Author: Javad Torkzadehmahani
Student ID: 982164624
Instructor: Prof. Ghafouri
Course: Advanced Programming (Python)
Goal: working with function
'''
def get_students_name ():
names = []
for _ in range (0 , 6):
X = input("Enter your name: ")
names.append(X)
return names
def include_odd_indexes (names):
odd_names = []
for odd_index in range (1, 6, 2):
odd_names.append(names[odd_index])
return odd_names
names = get_students_name()
odd_names = include_odd_indexes(names)
print("your odd indexes are: ",odd_names ) |
548e5b007a816be6cbbc83d3675a03a97fd65758 | javad-torkzadeh/courses | /python_course/ch6_exercise2.py | 817 | 4.1875 | 4 | '''
Author: Javad Torkzadehmahani
Student ID: 982164624
Instructor: Prof. Ghafouri
Course: Advanced Programming (Python)
Goal: working with collection
'''
my_matrix = []
for i in range (0 , 3):
row = []
for j in range(0 , 2):
X = float(input("Enter (%d , %d): " %(i , j)))
row.append(X)
my_matrix.append(row)
print("The matrix is: ", my_matrix)
for row_counter in range(0,len(my_matrix)):
row_average = sum(my_matrix[row_counter]) / len(my_matrix[0])
print("row %d average is: %f" %(row_counter , row_average))
for column_counter in range (0, len(my_matrix[0])):
column_sum = 0
for row_counter in range(0, len(my_matrix)):
column_sum = column_sum + my_matrix[row_counter][column_counter]
print("Column %d average is: %f" % (column_counter, column_sum / len(my_matrix))) |
4a47b563eec43fc7639baa9429835819a456c1da | gopeshkh1/ml_assignment1 | /perceptron discriminant/2.py | 2,200 | 3.515625 | 4 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
class Perceptron():
''' perceptron algorithm '''
def __init__(self):
self.w = np.random.rand(3 , 1)
print("initial w: {}".format(self.w))
# reads data-set and transform w over each iteration
def transform(self, df):
n_epoch = 50
for epoch in range(n_epoch):
flag=self.modify_w(df)
self.plotting(df, epoch)
if flag == 0:
print("Epoch :{}".format(epoch+1))
break
print("final w: {}".format(self.w))
# modify w by calculating error over each data
def modify_w(self, df):
l_rate = 0.01
flag = 0
for fline in df:
pred_val = self.w[0] + self.w[1] * fline[1] + self.w[2] * fline[2]
act_res = int(fline[3])
if pred_val >= 0:
pred_res = 1
else:
pred_res = 0
if act_res != pred_res:
flag = 1
e = act_res - pred_res
self.w[0] = self.w[0] + l_rate * e
self.w[1] = self.w[1] + l_rate * e * fline[1]
self.w[2] = self.w[2] + l_rate * e * fline[2]
return flag
# plots the figure and saves it
def plotting(self, df, epoch):
clss = df[:, -1]
C0 = df[clss == 0]
C1 = df[clss == 1]
xc1 = -4
yc1 = (-self.w[0] - self.w[1] * xc1) / self.w[2]
xc2 = 4
yc2 = (-self.w[0] - self.w[1] * xc2) / self.w[2]
xcord = []
ycord = []
xcord.append(xc1)
xcord.append(xc2)
ycord.append(yc1)
ycord.append(yc2)
plt.scatter(C0[:, 1], C0[:, 2], label='Class - 0', c='r')
plt.scatter(C1[:, 1], C1[:, 2], label='Class - 1', c='b')
plt.xticks([])
plt.yticks([])
plt.xlabel('x')
plt.ylabel('y')
plt.title('Scatter Plot')
plt.legend()
plt.plot(xcord, ycord, c='green')
plt.savefig('plot' + str(epoch) + '.png')
plt.close()
classifier = Perceptron()
df = pd.read_csv("dataset_3.csv")
df = df.values
classifier.transform(df)
|
bb8cb835b829d3d25ed0546c702f38bb840e1157 | Vansh-Arora/Python | /fibonacci.py | 202 | 4.21875 | 4 | # Return the nth term of fibonacci sequence.
def fibonacci(n):
if n==1:
return 1
elif n==0:
return 0
return fibonacci(n-1)+fibonacci(n-2)
print(fibonacci(int(input()))) |
03432128d834f955eb2a3eddff9780616993ad98 | inwk6312fall2019/wordplay-ChandanaPagolu | /uses_only.py | 134 | 3.8125 | 4 | def uses_only(word, letter):
for character in word:
if character not in letter:
return False
return True
|
d9c60c605ef1668ba20ae377e6a56158e8d85b02 | MichaelDeutschCoding/Advent-of-Code-2016 | /day1_2016.py | 2,292 | 3.90625 | 4 |
def move(starting, instructions, visited):
x, y, heading = starting
turn, d = instructions[0], int(instructions[1:])
if turn == 'R':
heading = (heading + 1) % 4
elif turn == 'L':
heading = (heading + 3) % 4
else:
print("Heading Error.")
return
if heading == 0: #going north
for i in range(1, d+1):
visited.append((x, y+i))
elif heading == 1: #going east
for i in range(1, d+1):
visited.append((x+i, y))
elif heading == 2: #going south
for i in range(1, d+1):
visited.append((x, y-i))
else: #going west
for i in range(1, d+1):
visited.append((x-i, y))
return (visited[-1][0], visited[-1][1], heading)
def follow(l):
tele = (0, 0, 0)
visited = [(0, 0)]
for step in l:
tele = move(tele, step, visited)
for i in range(len(visited)):
if visited[i] in visited[:i]:
print(f"found a double: {visited[i]} which appears at index {visited.index(visited[i])} and index {i}")
break
else:
print("no doubles found")
print(f"Total (taxicab) distance of destination {visited[-1]} from origin (0, 0) is: {abs(visited[-1][0]) + abs(visited[-1][1])}")
sample = ['L2', 'R3', 'L5', 'L2', 'R6', 'L3', 'L7', 'L8']
#follow(sample)
sample2 = ['R5', 'L5', 'R5', 'R3']
#follow(sample2)
sample3 = ['R2', 'R2', 'R2']
#follow(sample3)
puzzle_data = "R4, R4, L1, R3, L5, R2, R5, R1, L4, R3, L5, R2, L3, L4, L3, R1, R5, R1, L3, L1, R3, L1, R2, R2, L2, R5, L3, L4, R4, R4, R2, L4, L1, R5, L1, L4, R4, L1, R1, L2, R5, L2, L3, R2, R1, L194, R2, L4, R49, R1, R3, L5, L4, L1, R4, R2, R1, L5, R3, L5, L4, R4, R4, L2, L3, R78, L5, R4, R191, R4, R3, R1, L2, R1, R3, L1, R3, R4, R2, L2, R1, R4, L5, R2, L2, L4, L2, R1, R2, L3, R5, R2, L3, L3, R3, L1, L1, R5, L4, L4, L2, R5, R1, R4, L3, L5, L4, R5, L4, R5, R4, L3, L2, L5, R4, R3, L3, R1, L5, R5, R1, L3, R2, L5, R5, L3, R1, R4, L5, R4, R2, R3, L4, L5, R3, R4, L5, L5, R4, L4, L4, R1, R5, R3, L1, L4, L3, L4, R1, L5, L1, R2, R2, R4, R4, L5, R4, R1, L1, L1, L3, L5, L2, R4, L3, L5, L4, L1, R3"
real_list = [x.strip() for x in puzzle_data.split(',')]
print('real list:')
follow(real_list)
|
116b7525e97b31490462f2cb9f6a8e82fbcaa1fb | KomalaB/pythontest | /Assignement -20201112 v2.py | 641 | 4.03125 | 4 | Id_num []
Stu_Name []
count=int(input("enter the number of IDs you will like to register :"))
ct=count
while count >0:
for i in range(0,count):
num=input("Enter the unique ID : ")
if num in Id_list:
print(" Id is Duplicate")
name=input("Enter Student Name : ")
Id_num.append(num)
Stu_Name.append(name)
count=count-1
##
##while ct >0:
## print(Id_num : Stu_Name)
##
##print("end of list, thank you")
##
#2.create a function changedata(mylist), which take a list as argument and changes the values in mylist. Display the contents of the list
|
c7aa13b7daabb4febc7a5dbd48b6051ae8ceffea | adesh777/Show_the_data_structure_project_2_udacity | /problem_2.py | 963 | 3.65625 | 4 | import os
def find_files(suffix, path):
if not os.path.isdir(path):
print("Add a valid directory path")
return []
if not suffix or len(suffix) == 0 or suffix.isnumeric():
print("This is not a valid suffix", str(suffix))
return []
files_found = []
for f in os.listdir(path):
if os.path.isfile(path + f):
if f.endswith(suffix):
files_found.append(path + f)
else:
files_found += find_files(suffix, path + f + '/')
return files_found
if __name__ == '__main__':
path = ' C:/Users/PC/Downloads/'
print(find_files('.c',path +'testdir/')) # return all files with .c extension in testdir/
print(find_files('.h',path + 'testdir/')) # return all files with .h extension in testdir/
print(find_files('.h', path + 'te')) # te is not a valid dir
print(find_files('',path + 'testdir/')) # '' suffix is not valid
|
c1850078b1122160830013a02b55749215c7c51f | nikmuhammadnaim/python_projects | /pomodoro/pomo_engine.py | 726 | 3.6875 | 4 | import time
# Function for printing dictionary contents
def print_dict(my_dict):
ready_list = ''
for key, value in my_dict.items():
ready_list += "\n{}) {}".format(key, value)
return ready_list
# Countdown function
def pomodoro_timer(t_minutes):
'''
Countdown clock function.
This function will display the time on the console.
'''
t_seconds = t_minutes * 60
while t_seconds:
minutes, seconds = divmod(t_seconds, 60)
# format integer to a field of minimum width 2 with 0 left paddings
t_display = '{:02d}:{:02d}'.format(minutes, seconds)
print(t_display, end='\r')
time.sleep(1)
t_seconds -= 1
print('Pomodoro set completed!')
|
abd7c1d0295c72c50a1fcfc8f426ec9459b9c43a | yunusordek/DetectionOfAndroidMalware | /data _cleaning_and_data_integration/Combining.py | 649 | 3.53125 | 4 | import glob
import os
import pandas as pd
# the path to your csv file directory
mycsvdir = ''
# get all the csv files in that directory (assuming they have the extension .csv)
csvfiles = glob.glob(os.path.join(mycsvdir, '*.csv'))
# loop through the files and read them in with pandas
dataframes = [] # a list to hold all the individual pandas DataFrames
for csvfile in csvfiles:
df = pd.read_csv(csvfile)
df = df.iloc[:,0:-1]
#df.insert(83, 'class', "1")
dataframes.append(df)
# concatenate them all together
result = pd.concat(dataframes, ignore_index=True)
# print out to a new csv file
result.to_csv('all.csv', index=False)
|
12d71d2d83766b1548bc7e9b26a511c815dbe6a1 | kyubeom21c/kosta_iot_study | /pythonPro/test04while.py | 221 | 3.84375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
print('while')
i=0
while True:
i +=1
if i==5 : continue
if i==10 : break
name = raw_input("input name:")
print("while" ,i)
print("Hello {} ".format(name))
|
02e061272cca7eefdab81d926634fa00c0c22a91 | david-ruggles/Bashfuscator | /bashfuscator/lib/misc_obfuscators.py | 4,422 | 3.921875 | 4 | from bashfuscator.common.random import RandomGen
def obfuscateInt(num, smallExpr):
"""
Obfuscate an integer by replacing the int
with an arithmetic expression. Returns a string that
when evaluated mathematically, is equal to the int entered.
@capnspacehook
"""
randGen = RandomGen()
exprStr, baseExprPieces = genSimpleExpr(num, smallExpr)
if smallExpr:
numExpr = exprStr % (baseExprPieces[0], baseExprPieces[1], baseExprPieces[2])
else:
subExprs = []
for piece in baseExprPieces:
expr, pieces = genSimpleExpr(piece, smallExpr)
subExprs.append(expr % (pieces[0], pieces[1], pieces[2]))
numExpr = exprStr % (subExprs[0], subExprs[1], subExprs[2])
# Randomly replace '+' with '--'. Same thing, more confusing
match = re.search(r"\+\d+", numExpr)
beginingExprLen = 0
while match is not None:
match = list(match.span())
match[0] += beginingExprLen
match[1] += beginingExprLen
choice = randGen.randChoice(2)
if choice:
numExpr = numExpr[:match[0]] + "-(-" + numExpr[match[0] + 1:match[1]] + ")" + numExpr[match[1]:]
beginingExprLen = len(numExpr[:match[1]])
match = re.search(r"\+\d+", numExpr[match[1]:])
# Properly separate any double '-' signs. Some langs complain
match = re.search(r"--\d+", numExpr)
beginingExprLen = 0
while match is not None:
match = list(match.span())
match[0] += beginingExprLen
match[1] += beginingExprLen
numExpr = numExpr[:match[0]] + "-(" + numExpr[match[0] + 1:match[1]] + ")" + numExpr[match[1]:]
beginingExprLen = len(numExpr[:match[1]])
match = re.search(r"--\d+", numExpr[match[1]:])
# Bash requires mathematical expressions to be in $((expression)) syntax
numExpr = "$((" + numExpr + "))"
return numExpr
def genSimpleExpr(n, smallExpr):
"""
Generates a simple mathematical expression of 3 terms
that equal the number passed. Returns a template
expression string, and a tuple of the values of the
terms in the generated expression.
@capnspacehook
"""
randGen = RandomGen()
if type(n) == str:
n = int(eval(n))
if n == 0:
N = 0
while N == 0:
N = randGen.randGenNum(-99999, 99999)
else:
N = n
choice = randGen.randGenNum(0, 2)
left = 0
if choice == 0:
if N < 0:
left = randGen.randGenNum(N * 2, -N + 1)
right = randGen.randGenNum(N - 1, -N * 2)
else:
left = randGen.randGenNum(-N * 2, N - 1)
right = randGen.randGenNum(-N + 1, N * 2)
if left + right < n:
offset = n - (left + right)
expr = "((%s+%s)+%s)"
else:
offset = (left + right) - n
expr = "(-(-(%s+%s)+%s))"
elif choice == 1:
if N < 0:
left = randGen.randGenNum(N - 1, -N * 2)
right = randGen.randGenNum(N * 2, N - 1)
else:
left = randGen.randGenNum(-N + 1, N * 2)
right = randGen.randGenNum(-N * 2, N + 1)
if left - right < n:
offset = n - (left - right)
expr = "((%s-%s)+%s)"
else:
offset = (left - right) - n
expr = "(-(-(%s-%s)+%s))"
elif choice == 2:
if N < 0:
left = randGen.randGenNum(int(N / 2), -int(N / 2) - 2)
right = randGen.randGenNum(int(N / 3), -int(N / 3))
else:
left = randGen.randGenNum(-int(n / 2), int(n / 2) + 2)
right = randGen.randGenNum(-int(n / 3), int(n / 3))
if left * right < n:
offset = n - (left * right)
expr = "((%s*%s)+%s)"
else:
offset = (left * right) - n
expr = "(-(-(%s*%s)+%s))"
# Replace all zeros with an expression. Zeros make arithmetic easy
if not smallExpr:
if left == 0:
zeroExpr, terms = genSimpleExpr(0, smallExpr)
left = zeroExpr % (terms[0], terms[1], terms[2])
if right == 0:
zeroExpr, terms = genSimpleExpr(0, smallExpr)
right = zeroExpr % (terms[0], terms[1], terms[2])
if offset == 0:
zeroExpr, terms = genSimpleExpr(0, smallExpr)
offset = zeroExpr % (terms[0], terms[1], terms[2])
return (expr, (left, right, offset))
|
07beb28d57f6ba9264a5ce7e3708f5423d63bd35 | Riaeuk/W3School | /Data_types1.py | 116 | 3.984375 | 4 | #The following code example would print the data type of x, what data type would that be?
x = 5
print(type(x))
#int |
6394034c37fae31c04181a9da315dc73f58529b4 | william-james-pj/LogicaProgramacao | /URI/1 - INICIANTE/Python/1150 - UltrapassandoZ.py | 219 | 3.515625 | 4 | x = int(input())
y = 0
cont = 1
while y == 0:
z = int(input())
if(z > x):
y = 1
y = 0
w = x
while y == 0:
if(x > z):
y = 1
else:
x += w
w += 1
cont +=1
print(cont) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.