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 |
|---|---|---|---|---|---|---|
12c96ea6817d91f8d488f13c119752f747971c94 | caesarbonicillo/ITC110 | /Temperature.py | 496 | 4.125 | 4 | #convert Celsius to Fehrenheit
def main(): #this is a function
#input
celsius = eval (input ("Enter the temp in Celsius ")) #must convert to number call function EVAL
#processing
fahrenheit = round(9/5 * celsius + 32, 0)
#output
print (celsius, "The Fehrenheit temp is", fahrenheit)
main() # press f5 to run
def kiloMile():
kilo = eval (input("enter kilometers "))
miles = 1.6 * kilo
print ( kilo, "The conversion is", miles)
kiloMile()
|
27cf55f0f342a4cf7747f3ee7a13e56c5d91bfcc | loganwastlund/cs1410 | /frogger_assignment/froggerlib/frog.py | 675 | 3.546875 | 4 | from froggerlib.player_controllable import PlayerControllable
class Frog(PlayerControllable):
def __init__(self, x=0, y=0, w=0, h=0, dx=0, dy=0, s=0, hg=0, vg=0):
PlayerControllable.__init__(self, x, y, w, h, dx, dy, s, hg, vg)
return
def __str__(self):
s = "Frog<"+PlayerControllable.__str__(self)+">"
return s
def __repr__(self):
return str(self)
def test():
f = Frog()
f.setHorizontalGap(15)
f.setVerticalGap(15)
f.setSpeed(2)
print(f)
f.up()
print(f)
while not f.atDesiredLocation():
f.move()
print(f)
return
if __name__ == "__main__":
test()
|
a48246d152225d226d01bf5139ede5ec88149989 | loganwastlund/cs1410 | /frogger_assignment/froggerlib/truck.py | 551 | 3.71875 | 4 | from froggerlib.dodgeable import Dodgeable
import random
class Truck(Dodgeable):
def __init__(self, x=0, y=0, w=0, h=0, dx=0, dy=0, s=0):
Dodgeable.__init__(self, x, y, w, h, dx, dy, s)
return
def __str__(self):
s = "Truck<"+Dodgeable.__str__(self)+">"
return s
def __repr__(self):
return str(self)
def test():
r = Truck(5,5,10,10, -15, 10, 4)
print(r)
while not r.atDesiredLocation():
r.move()
print(r)
return
if __name__ == "__main__":
test()
|
ad3dcc55ba5993e6e902723f5b4170a259276530 | loganwastlund/cs1410 | /caloric_balance_assignment/caloric_balance/test_main_getUserFloat.py | 3,461 | 3.84375 | 4 | """
Do Not Edit this file. You may and are encouraged to look at it for reference.
"""
import sys
if sys.version_info.major != 3:
print('You must use Python 3.x version to run this unit test')
sys.exit(1)
import unittest
import main
class TestGetUserFloat(unittest.TestCase):
def input_replacement(self, prompt):
self.assertFalse(self.too_many_inputs)
self.input_given_prompt = prompt
r = self.input_response_list[self.input_response_index]
self.input_response_index += 1
if self.input_response_index >= len(self.input_response_list):
self.input_response_index = 0
self.too_many_inputs = True
return r
def print_replacement(self, *args, **kargs):
return
def setUp(self):
self.too_many_inputs = False
self.input_given_prompt = None
self.input_response_index = 0
self.input_response_list = [""]
main.input = self.input_replacement
main.print = self.print_replacement
return
def test001_getUserFloatExists(self):
self.assertTrue('getUserFloat' in dir(main),
'Function "getUserFloat" is not defined, check your spelling')
return
def test002_getUserFloatSendsCorrectPrompt(self):
from main import getUserFloat
expected_prompt = "HELLO"
expected_response = "1.7"
self.input_response_list = [expected_response]
actual_response = getUserFloat(expected_prompt)
self.assertEqual(expected_prompt, self.input_given_prompt)
return
def test003_getUserFloatGetsInput(self):
from main import getUserFloat
expected_prompt = "HELLO"
expected_response = "1"
self.input_response_list = [expected_response]
actual_response = getUserFloat(expected_prompt)
self.assertTrue(type(actual_response) is float)
self.assertEqual(1.0, actual_response)
return
def test004_getUserFloatStripsWhitespace(self):
from main import getUserFloat
expected_prompt = "HELLO"
expected_response = "1.7"
self.input_response_list = [" \t\n" + expected_response + " \t\n"]
actual_response = getUserFloat(expected_prompt)
self.assertTrue(type(actual_response) is float)
self.assertEqual(float(expected_response), actual_response)
return
def test005_getUserFloatBadInputCheck(self):
from main import getUserFloat
expected_prompt = "HELLO"
expected_response = "7.6"
self.input_response_list = ["zero", "-1.7", "0", "0.0", "-20.0", "", "sixteen", expected_response]
actual_response = getUserFloat(expected_prompt)
self.assertTrue(type(actual_response) is float)
self.assertEqual(float(expected_response), actual_response,
'Your repsonse (%s) did not equal the expected response (%s)' % (actual_response, expected_response))
return
def test006_getUserFloatIgnoresBlankLines(self):
from main import getUserFloat
expected_prompt = "HELLO"
expected_response = "10"
self.input_response_list = ["", "0.0", "hello", "-1.7", "\n", " \t\n" + expected_response + " \t\n"]
actual_response = getUserFloat(expected_prompt)
self.assertTrue(type(actual_response) is float)
self.assertEqual(10.0, actual_response)
return
if __name__ == '__main__':
unittest.main()
|
e72a2b169ddeb44b6c3ab9ee24d4818dbdc89e79 | loganwastlund/cs1410 | /isbn_assignment/isbnTests/test_findBook.py | 1,205 | 3.765625 | 4 | """
Do Not Edit this file. You may and are encouraged to look at it for reference.
"""
import unittest
from isbnTests import isbn_index
class test_findBook( unittest.TestCase ):
def setUp(self):
return
def tearDown(self):
return
def test001_findBookExists(self):
self.assertTrue('findBook' in dir(isbn_index),
'Function "findBook" is not defined, check your spelling')
return
def test002_findBookFindsExistingBook(self):
isbn = "0000-00000000"
title = "Book Title"
expected = title
index = isbn_index.createIndex()
isbn_index.recordBook(index, isbn, title)
self.assertEqual(isbn_index.findBook(index, isbn), expected)
return
def test003_findBookDoesNotFindMissingBook(self):
isbn1 = "0000-00000000"
isbn2 = "0000-12345678"
title = "Book Title"
expected = ""
index = isbn_index.createIndex()
isbn_index.recordBook(index, isbn1, title)
self.assertEqual(isbn_index.findBook(index, isbn2), expected)
return
if __name__ == '__main__':
unittest.main()
|
5f7d558e0dc80f651c1b1fbc79b3748f17451b2c | loganwastlund/cs1410 | /asteroids_assignment/test_all_asteroids_part1/test_005_rock_004_createRandomPolygon.py | 3,624 | 3.515625 | 4 | """
Do Not Edit this file. You may and are encouraged to look at it for reference.
"""
import unittest
import math
import rock
class TestRockCreatePolygon( unittest.TestCase ):
def setUp( self ):
self.expected_x = 100
self.expected_y = 200
self.expected_dx = 0.0
self.expected_dy = 0.0
self.expected_rotation = 0
self.expected_world_width = 600
self.expected_world_height = 400
self.constructed_obj = rock.Rock( self.expected_x, self.expected_y, self.expected_world_width, self.expected_world_height )
return
def tearDown( self ):
return
def test001_generatesCorrectNumberOfPoints( self ):
number_of_points = 5
radius = 1.0
random_polygon = self.constructed_obj.createRandomPolygon( radius, number_of_points )
self.assertEqual( len( random_polygon ), number_of_points )
return
def test002_generatesCorrectRadius( self ):
number_of_points = 5
radius = 1.0
min_radius = 0.7
max_radius = 1.3
random_polygon = self.constructed_obj.createRandomPolygon( radius, number_of_points )
for random_point in random_polygon:
( x, y ) = random_point
random_distance = math.sqrt( x * x + y * y )
self.assertGreaterEqual( random_distance, min_radius )
self.assertLessEqual( random_distance, max_radius )
return
def test003_generatesCorrectAngle72( self ):
number_of_points = 5
radius = 1.0
expected_angle = 72
random_polygon = self.constructed_obj.createRandomPolygon( radius, number_of_points )
previous_angle = None
for random_point in random_polygon:
( x, y ) = random_point
current_angle = math.degrees( math.atan2( y, x ) )
if previous_angle is not None:
actual_angle = ( current_angle - previous_angle ) % 360
self.assertAlmostEqual( actual_angle , expected_angle )
previous_angle = current_angle
return
def test004_generatesCorrectAngle60( self ):
number_of_points = 6
radius = 1.0
expected_angle = 60
random_polygon = self.constructed_obj.createRandomPolygon( radius, number_of_points )
previous_angle = None
for random_point in random_polygon:
( x, y ) = random_point
current_angle = math.degrees( math.atan2( y, x ) )
if previous_angle is not None:
actual_angle = ( current_angle - previous_angle ) % 360
self.assertAlmostEqual( actual_angle , expected_angle )
previous_angle = current_angle
return
def test005_generatesCorrectRadius100( self ):
number_of_points = 5
radius = 100.0
min_radius = 70.0
max_radius = 130.0
random_polygon = self.constructed_obj.createRandomPolygon( radius, number_of_points )
for random_point in random_polygon:
( x, y ) = random_point
random_distance = math.sqrt( x * x + y * y )
self.assertGreaterEqual( random_distance, min_radius )
self.assertLessEqual( random_distance, max_radius )
return
def suite( ):
return unittest.TestLoader( ).loadTestsFromTestCase( TestRockCreatePolygon )
if __name__ == '__main__':
runner = unittest.TextTestRunner( )
runner.run( suite( ) )
|
a99ebf6cc65ac45f0837c615de75e10ccc3cbc72 | loganwastlund/cs1410 | /caloric_balance_assignment/caloric_balance/test_main_eatFoodAction.py | 5,507 | 3.59375 | 4 | """
Do Not Edit this file. You may and are encouraged to look at it for reference.
"""
import sys
if sys.version_info.major != 3:
print('You must use Python 3.x version to run this unit test')
sys.exit(1)
import unittest
import re
import main
class TestEatFoodAction(unittest.TestCase):
def input_replacement(self, prompt):
self.assertFalse(self.too_many_inputs)
self.input_given_prompt = prompt
r = self.input_response_list[self.input_response_index]
self.input_response_index += 1
if self.input_response_index >= len(self.input_response_list):
self.input_response_index = 0
self.too_many_inputs = True
return r
def print_replacement(self, *text, **kwargs):
line = " ".join(text) + "\n"
self.printed_lines.append(line)
def setUp(self):
self.too_many_inputs = False
self.input_given_prompt = None
self.input_response_index = 0
self.input_response_list = [""]
main.input = self.input_replacement
self.printed_lines = []
main.print = self.print_replacement
def test001_eatFoodActionExists(self):
self.assertTrue('eatFoodAction' in dir(main),
'Function "eatFoodAction" is not defined, check your spelling')
def test002_eatFoodAction_updatesBalance(self):
from main import eatFoodAction
from caloric_balance import CaloricBalance
cb = CaloricBalance('f', 23.0, 65.0, 130.0)
expected = -1417.9
actual = cb.getBalance()
self.assertAlmostEqual(actual, expected, 2,
'Your result (%s) is not close enough to (%s)' % (actual, expected))
self.input_response_list = ["400"]
eatFoodAction(cb)
actual_response = self.input_response_list[self.input_response_index]
self.assertEqual("400", actual_response)
actual2 = cb.getBalance()
self.assertNotEqual(actual, actual2,
'Your eatFoodAction did not update the caloric balance.')
lines = " ".join(self.printed_lines)
expression = "caloric.*balance.*(-[0-9]+\.[0-9]+)"
matches = re.findall(expression, lines.lower())
self.assertTrue(
len(matches) >= 1,
'You did not print the updated caloric balance to the user?\n' +
'Your message should contain the words "caloric", "balance", and the updated balance.\n' +
'You printed:\n %s' % lines
)
def test003_eatFoodAction_updatesBalance(self):
from main import eatFoodAction
from caloric_balance import CaloricBalance
cb = CaloricBalance('f', 23.0, 65.0, 130.0)
expected = -1417.9
actual = cb.getBalance()
self.assertAlmostEqual(actual, expected, 2,
'Your result (%s) is not close enough to (%s)' % (actual, expected))
expected_response = "400"
self.input_response_list = ["0", "-1.7", "-20", "zero", "twleve", "", "\n", expected_response]
eatFoodAction(cb)
actual2 = cb.getBalance()
self.assertNotEqual(actual, actual2,
'Your eatFoodAction did not update the caloric balance.')
expected = actual + float(expected_response)
actual = actual2
self.assertAlmostEqual(expected, actual, 2,
'Your result (%s) is not close enough to (%s). Did you use getUserFloat?' % (actual, expected))
lines = " ".join(self.printed_lines)
expression = "caloric.*balance.*(-[0-9]+\.[0-9]+)"
matches = re.findall(expression, lines.lower())
self.assertTrue(
len(matches) >= 1,
'You did not print the updated caloric balance to the user?\n' +
'Your message should contain the words "caloric", "balance", and the updated balance.\n' +
'You printed:\n %s' % lines
)
def test004_eatFoodAction_updatesBalance(self):
from main import eatFoodAction
from caloric_balance import CaloricBalance
cb = CaloricBalance('f', 23.0, 65.0, 130.0)
expected = -1417.9
actual = cb.getBalance()
self.assertAlmostEqual(actual, expected, 2,
'Your result (%s) is not close enough to (%s)' % (actual, expected))
expected_response = "998"
self.input_response_list = ["0", "-1.7", "-20", "zero", "twleve", "", "\n", expected_response, "500", "600", "700"]
eatFoodAction(cb)
actual2 = cb.getBalance()
self.assertNotEqual(actual, actual2,
'Your eatFoodAction did not update the caloric balance.')
expected = actual + float(expected_response)
actual = actual2
self.assertAlmostEqual(expected, actual, 2,
'Your result (%s) is not close enough to (%s). Did you use getUserFloat?' % (actual, expected))
lines = " ".join(self.printed_lines)
expression = "caloric.*balance.*(-[0-9]+\.[0-9]+)"
matches = re.findall(expression, lines.lower())
self.assertTrue(
len(matches) >= 1,
'You did not print the updated caloric balance to the user?\n' +
'Your message should contain the words "caloric", "balance", and the updated balance.\n' +
'You printed:\n %s' % lines
)
if __name__ == '__main__':
unittest.main()
|
def3e215af2f9d8c874d14ecba1b4b07cc233b4e | loganwastlund/cs1410 | /gas_mileage_assignment/gas_mileage/test_listTripsAction.py | 2,919 | 3.5625 | 4 | """
Do Not Edit this file. You may and are encouraged to look at it for reference.
"""
import unittest
import gas_mileage
class TestListTripsAction(unittest.TestCase):
def input_replacement(self, prompt):
self.assertFalse(self.too_many_inputs)
self.input_given_prompt = prompt
r = self.input_response_list[self.input_response_index]
self.input_response_index += 1
if self.input_response_index >= len(self.input_response_list):
self.input_response_index = 0
self.too_many_inputs = True
return r
def print_replacement(self, *text, **kwargs):
line = " ".join(text) + "\n"
self.printed_lines.append(line)
return
def setUp(self):
self.too_many_inputs = False
self.input_given_prompt = None
self.input_response_index = 0
self.input_response_list = [""]
gas_mileage.input = self.input_replacement
self.printed_lines = []
gas_mileage.print = self.print_replacement
return
def test001_listTripsActionExists(self):
self.assertTrue('listTripsAction' in dir(gas_mileage),
'Function "listTripsAction" is not defined, check your spelling')
return
def test002_listTripsActionDoesNotUpdate(self):
from gas_mileage import listTripsAction
notebook = []
expected = []
self.input_response_list = ["???"]
listTripsAction(notebook)
self.assertListEqual(expected, notebook, "Your listTripsAction made changes to the notebook when it shouldn't")
self.assertGreaterEqual(len(self.printed_lines), 1, 'Make sure to print a message to the user about no trips being recorded')
def test003_listTripsActionPrintLines(self):
from gas_mileage import listTripsAction
notebook = [
{'date': "01/01/17", 'miles': 100.0, 'gallons': 5.0},
{'date': "01/02/17", 'miles': 300.0, 'gallons': 10.0}
]
expected = [
{'date': "01/01/17", 'miles': 100.0, 'gallons': 5.0},
{'date': "01/02/17", 'miles': 300.0, 'gallons': 10.0}
]
self.input_response_list = ["???"]
listTripsAction(notebook)
self.assertListEqual(expected, notebook, "Your listTripsAction made changes to the notebook when it shouldn't")
self.assertGreaterEqual(len(self.printed_lines), 2, 'You should print a line for each trip')
printed_text = "".join(self.printed_lines)
self.assertIn("01/01/17", printed_text)
self.assertIn("100.0", printed_text)
self.assertIn("5.0", printed_text)
self.assertIn("20.0", printed_text)
self.assertIn("01/02/17", printed_text)
self.assertIn("300.0", printed_text)
self.assertIn("10.0", printed_text)
self.assertIn("30.0", printed_text)
if __name__ == '__main__':
unittest.main()
|
5465a46981d4b4632a15d7003e2bf3b0c11aab1a | loganwastlund/cs1410 | /in_class/notes.py | 3,113 | 4.09375 | 4 | # dictionaries
d = {'key': 'value', 'name': 'Logan', 'id': 123, 'backpack': ['pencil', 'pen', 'pen', 'paper']}
d['name'] = 'John'
# how to update a key ^
d['dob'] = '01-17-18'
d['dob'] = '01-18-18'
# keys can be integers, strings, variables, but not lists. The value can be anything
print(d['backpack'][2])
# prints second pen ^
# if key in dictionary:
# how to check if key is in dictionary
# for key in dictionary:
# value = dictionary[key]
# if value == 'value':
# how to find a value in a dictionary
# del d['key']
# how to delete a key ^
# classes
# Classes:
# have abilities
# and traits
# a marker has:
# color
# erasable
# capacity
# tip size
# write
# use "class {name}:"
# Pascal Case
# StudlyCaps
class Marker:
def __init__(self):
self.color = (0, 0, 255)
self.erasable = True
self.capacity = 5
self.tipsize = 0.001
def write(self, length):
self.capacity -= self.tipsize * abs(length)
def show(self):
print(self.color, self.erasable, self.capacity, self.tipsize)
redexpo1 = Marker()
redexpo1.color = (255, 0, 0)
blueexpo1 = Marker()
blueexpo2 = Marker()
bluesharpie1 = Marker()
bluesharpie1.erasable = False
bluesharpie1.tipsize = 0.001/5
bluesharpie1.capacity = 5/2
print(redexpo1.color)
print(blueexpo1.color)
print(bluesharpie1.erasable)
print(blueexpo1.capacity)
blueexpo1.write(1000)
print(blueexpo1.capacity)
print(blueexpo2.capacity)
blueexpo2.write(75.8)
print(blueexpo2.capacity)
redexpo1.show()
blueexpo1.show()
blueexpo2.show()
bluesharpie1.write(1000)
bluesharpie1.show()
# copy
# import copy
# copy.copy()
# used to copy anything from objects to lists and dictionaries
# class Nothing:
#
# def __init__(self, something):
# self.something = something
# OR
# self.__something = something
# This makes it private so that you can't change it through self.__something = updated_value
# It would have to be through a function
# TODO: surprise Logan, remember this, it is cool!!!!!!!!!!!!!!!!!!!!!!!
TODO: surprise Logan, remember this, it is cool!!!!!!!!!!!!!!!!!!!!!!!
# just comment sentence out, as long as TODO: is at the start it will do this!
# collapse code -> Command + -
# operator overloading
# def __gt__(self): <-- Greater than (>)
# __ls__ <-- Less than (<)
# __eq__ <-- Equal to (==)
# __add__ <-- Add (+)
# __mul__ <-- Multiply(*)
# __iadd__ <-- Add (+=)
# unittest
import unittest
import sys
from unittest import TestCase, main
class Test(TestCase):
def setUp(self):
self.something = 'something'
self.othersomething = 'othersomething'
def test_a_test(self): # has to start with test
self.assertEqual(self.something + self.othersomething, 'somethingothersomething')
@unittest.skipIf(not sys.platform.startswith('darwin'), "This should be skipped") # only macs, mac = 'darwin'?
def test_b_test_mac(self):
self.fail('Just Because')
pass
if __name__ == "main":
main()
|
bef3086fbcdad462844ab8c80437366d2517b10c | loganwastlund/cs1410 | /caloric_balance_assignment/caloric_balance.py | 883 | 3.546875 | 4 |
class CaloricBalance:
def __init__(self, gender, age, height, weight):
self.weight = weight
bmr = self.getBMR(gender, age, height, weight)
self.balance = bmr - (bmr * 2)
def getBMR(self, gender, age, height, weight):
bmr = 0.0
if gender == 'm':
bmr = 66 + (12.7 * height) + (6.23 * weight) - (6.8 * age)
if gender == 'f':
bmr = 655 + (4.7 * height) + (4.35 * weight) - (4.7 * age)
return bmr
def getBalance(self):
return self.balance
def recordActivity(self, caloric_burn_per_pound_per_minute, minutes):
calories_burned_per_minute = caloric_burn_per_pound_per_minute * self.weight
calories_burned = float(calories_burned_per_minute) * float(minutes)
self.balance -= calories_burned
def eatFood(self, calories):
self.balance += calories
|
a7ea4875f924aceeb06f252fa4d38313c6042436 | loganwastlund/cs1410 | /gas_mileage_assignment/gas_mileage/test_recordTrip.py | 2,457 | 3.8125 | 4 | """
Do Not Edit this file. You may and are encouraged to look at it for reference.
"""
import unittest
import random
import gas_mileage
class TestRecordTrip(unittest.TestCase):
def test001_recordTripExists(self):
self.assertTrue('recordTrip' in dir(gas_mileage),
'Function "recordTrip" is not defined, check your spelling')
return
def test002_recordOneTrip(self):
# start with empty trip log
notebook = []
date = "01/01/2017"
miles = 300.0
gallons = 10.0
# record a trip
gas_mileage.recordTrip(notebook, date, miles, gallons)
# check total number of recorded trips
number_of_trips = len(notebook)
self.assertTrue(number_of_trips == 1, 'We recorded 1 trip, your notebook had %d' % number_of_trips)
# get the recorded trip dictionary and check its values
trip = notebook[0]
self.assertDictEqual({'date': date, 'miles': miles, 'gallons': gallons}, trip)
def test003_recordMultipleTrips(self):
# start with empty trip log
notebook = []
# choose number of trips to generate
total_trips = random.randint(10, 20)
# generate and verify trips
for i in range(total_trips):
trip_number = i + 1
date = 'day' + str(trip_number)
ratio = random.randint(13, 34)
miles = float(random.randint(50, 250))
gallons = float(miles / ratio)
# record the trip
gas_mileage.recordTrip(notebook, date, miles, gallons)
# count the number of trips recorded so far
number_of_trips = len(notebook)
self.assertTrue(number_of_trips == trip_number,
'We have recorded %d trips, your notebook had %d' % (trip_number, number_of_trips))
# get the last trip recorded and verify the values
trip = notebook[number_of_trips - 1]
self.assertDictEqual({'date':date, 'miles':miles, 'gallons':gallons}, trip)
# get the total number of trips and verify it is the correct number
number_of_trips = len(notebook)
self.assertTrue(number_of_trips == total_trips,
'We recorded %d trips, your notebook had %d' % (total_trips, number_of_trips))
if __name__ == '__main__':
unittest.main()
|
3e419aa050aed59a0a9a5941f69cba22375eacc5 | TobiAdeniyi/hacker-rank-problems | /Algorithms/Implementation/ClimbingTheLeaderboard.py | 848 | 4 | 4 | """
An arcade game player wants to climb to the top of the leaderboard and track their
ranking. The game uses Dense Ranking, so its leaderboard works like this:
• The player with the highest score is ranked number on the leaderboard.
• Players who have equal scores receive the same ranking number, and the
next player(s) receive the immediately following ranking number.
"""
def climbing_leaderboard(N: list, M: list) -> list:
X = list(set(N))
X.sort(reverse=True)
J = []
j = len(X)
for m in M:
while (j>0) and (m >= X[j-1]):
j -= 1
J.append(j+1)
return J
if __name__ == '__main__':
n = int(input())
N = [int(i) for i in input().split()]
m = int(input())
M = [int(i) for i in input().split()]
J = climbing_leaderboard(N, M)
for j in J:
print(j) |
d6c282c0e9b51b97f6aa30d44b96ecd2fd9e405f | TobiAdeniyi/hacker-rank-problems | /Algorithms/Implementation/DesignerPDFViewer.py | 795 | 4.0625 | 4 | import os
"""
Sample Input
------------
1 3 1 3 1 4 1 3 2 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5
abc
Sample Output
-------------
9
"""
def designer_viewer(h: list, word: str) -> int:
# 1) Convert word to lower case
word = word.lower()
# print(word)
# 2) Convert word to unicode representation - 97
coded = [ord(char) - 97 for char in word]
# print(coded)
# 3) For each chr in word find corresponding number in h
height_collection = [h[i] for i in coded]
# print(height_collection)
# 4) Return max number * length of word
return max(height_collection) * len(word)
if __name__ == '__main__':
# none return value
h = list(int(i) for i in input().rstrip().split())
word = input()
result = designer_viewer(h, word)
print(result)
|
fc16775fecae5b5b59885cdde7f6a5c4dcaf7ecf | BrandonIslas/Curso_Basico_Python | /ejemplo3CondicionalesCompuestas.py | 297 | 3.875 | 4 | sueldo1= int(input("Introduce un sueldo1: "))
sueldo2= int(input("Introduce un sueldo2: "))
if sueldo1 > sueldo2:
print("El sueldo1 "+ str(sueldo1)+ " es mayor que el sueldo2 ("+str(sueldo2) +")")
else:
print("El sueldo1 ("+ str(sueldo1)+ ") es menor que el sueldo2 ("+str(sueldo2) +")")
|
21385d2bce3d5ddfb79334cc1a274e108932d0f7 | BrandonIslas/Curso_Basico_Python | /Listas1.py | 993 | 3.984375 | 4 | lista=[] #DECLARACION DE LA LISTA
for k in range(10):
lista.append(input("Introduce el "+str(k)+" valor a la lista:"))
print("Los elementos de la lista son:"+str(lista))
valor=int(input("Introduce el valor a modificar de la lista por el indice"))
nuevo=input("Introduce el nuevo valor:")
lista[valor]=nuevo#MODIFICAR VALOR DE LA LISTA
print("Los elementos de la lista son:"+str(lista))
valor=int(input("Introduce el valor en el que se insertara el nuevo valor"))
nuevo=input("Introduce el nuevo valor:")
lista.insert(valor,nuevo)#INSERTAR VALOR A LA LISTA
print("Los elementos de la lista son:"+str(lista))
nuevo=input("Introduce el valor a eliminar")
lista.remove(nuevo) #ELIMINAR VALOR DE LA LISTA
print("Los elementos de la lista son:"+str(lista))
nuevo=input("Introduce el valor de la lista que se desea buscar:")
resultado=(nuevo in lista)
if (resultado):
print("Existe el elemento en la posicion: "+str(lista.index(nuevo)))
else:
print("El elemento no existe en la lista ")
|
db6decc20f095d23d6842efef66cc0de5fbb6893 | BrandonIslas/Curso_Basico_Python | /ProgramacionOrientadaaObjetos/FuncionalidadModuloAs.py | 212 | 4.03125 | 4 | from math import sqrt as raiz, pow as exponente
dato=int(input("Ingrese un valor entero: "))
raizcuadrada=raiz(dato)
cubo=exponente(dato,3)
print("La raiz cuadrada es: ",raizcuadrada)
print("El cubo es: ",cubo)
|
5b080ee8d026affda640ab1284aafe4464329621 | BrandonIslas/Curso_Basico_Python | /ejemplo6While2.py | 286 | 3.875 | 4 | #Ejercicio while 2
cantidad=0
x=1
n=int(input("Cuantas piezas cargara:"))
while x<=n:
largo=float(input("Ingrese la medida de la ( " +str(x) +" ) pieza"))
if largo>=1.2 and largo<=1.3:
cantidad=cantidad+1
x=x+1
print("La cantidad de piezas aptas son"+str(cantidad))
|
e2c69c7053081eb29da7875b1ae37122d8ad1f25 | yukiii-zhong/Leetcode | /Linked List/138. Copy List with Random Pointer.py | 1,444 | 4.09375 | 4 | # Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
# Step1: Totally copy a list: iter1--> copy1 --> iter2 --> copy2
# Do not consider random in this step
iter = head
while iter:
copy = RandomListNode(iter.label)
copy.next = iter.next
iter.next = copy
iter = copy.next
# Step2: From the head, give random pointer to the copies
# Don't change the linkage, because the pointer is in random
# You should consider random may be Null
iter = head
while iter:
if iter.random:
iter.next.random = iter.random.next
else:
iter.next.random = None
iter = iter.next.next
# Step3: After all the value has been set, make the copy a new list
# The original list should not be changed
pre = dummy = RandomListNode(-1)
iter = head
while iter:
pre.next = iter.next
pre = pre.next
iter.next = iter.next.next
iter = iter.next
return dummy.next
|
15069d7c114bbac94c1eba39fd0c67da4588b56d | yukiii-zhong/Leetcode | /Linked List/24. Swap Nodes in Pairs.py | 1,289 | 3.59375 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
ans = ""
curr = self
while curr:
ans += str(curr.val) + " -> "
curr = curr.next
return ans[:-4]
def newValue(self, inputList):
pre = self
for i in inputList:
pre.next = ListNode(i)
pre = pre.next
return self.next
class Solution:
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# if head and !head.next
pre = head
if head and head.next:
pre = head.next
head.next = self.swapPairs(pre.next)
pre.next = head
return pre
def swapPairs2_SLOW(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy = ListNode(-1)
curr = dummy
while head and head.next:
pre = head
curr.next = head.next
head = head.next.next
curr.next.next = pre
curr = curr.next.next
if head:
curr.next = head
else:
curr.next = None
return dummy.next |
906f40cc6ff0bd3eb51af097f84ae975e7ac3957 | yukiii-zhong/Leetcode | /Array/src/16. 3Sum Closest.py | 730 | 3.578125 | 4 | class Solution:
def threeSumClosest(self,nums,target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
closest = nums[0]+nums[1]+nums[2]
for a in range(len(nums)-2):
i=a+1
j=len(nums)-1
while j>i:
sum = nums[a] + nums[i] + nums[j]
if sum == target:
return sum
if abs(closest-target)>abs(sum-target):
closest = sum
if sum < target:
i +=1
else:
j -= 1
return closest
nums = [-3,-2,-5,3,-4]
print(Solution().threeSumClosest(nums,-1)) |
0ec7dd4c022d0d7e9db17817daca8bf7fc721e18 | yukiii-zhong/Leetcode | /Linked List/143. Reorder List.py | 1,545 | 3.65625 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
ans = ""
curr = self
while curr:
ans += str(curr.val) + " -> "
curr = curr.next
return ans[:-4]
def newValue(self, inputList):
pre = self
for i in inputList:
pre.next = ListNode(i)
pre = pre.next
return self.next
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
"""
pre = dummy = ListNode("#")
pre.next = head
slow = head
fast = head
while fast and fast.next:
pre = pre.next
slow = slow.next
fast = fast.next.next
pre.next = None
trav = self.traverse(slow)
while head and trav:
headTemp = head.next
head.next = trav
travTemp = trav.next
pre = trav
trav.next = headTemp
head = headTemp
trav = travTemp
if trav:
pre.next = trav
return dummy.next
def traverse(self,head):
pre = None
while head:
temp = head.next
head.next = pre
pre = head
head = temp
return pre
def __init__(self):
self. a = 1
L1 = ListNode(1)
#L1 = L1.newValue([1,2,3,4,5])
S1 = Solution()
print(S1.reorderList(L1)) |
0d3bb69003e43914bb44c4b3a228635aec14222e | yukiii-zhong/Leetcode | /problems/7. Reverse Integer.py | 487 | 3.5 | 4 | class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x < -(2 ** 31) or x > 2 ** 31 - 1:
return 0
if x == 0:
return x
elif x < 0:
return self.reverse(-x) * (-1)
# x>0
rev = 0
while x > 0:
x, rev = x // 10, x % 10 + rev * 10
if rev > 2 ** 31 - 1:
rev = 0
break
return rev
|
9b00ed3ea091453040f192c3e2018f7745970627 | yukiii-zhong/Leetcode | /Linked List/142. Linked List Cycle II.py | 1,191 | 3.875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def detectCycle2(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
node = head
visited = set()
while node:
if node in visited:
return node
else:
visited.add(node)
node = node.next
return None
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
ptr2 = self.meetPoint(head)
if ptr2 == None:
return None
ptr1 = head
while ptr1:
if ptr1 == ptr2:
return ptr1
else:
ptr1 = ptr1.next
ptr2 = ptr2.next
def meetPoint(self,head):
# Return the meet Point of slow and fast pointers
fast = head
slow = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if fast == slow:
return fast
return None |
eb4b875ea3f86babccc588f48ab8a27d95ce7934 | yukiii-zhong/Leetcode | /Linked List/ListNode.py | 596 | 3.59375 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
ans = ""
curr = self
while curr:
ans += str(curr.val) + " -> "
curr = curr.next
return ans[:-4]
def newValue(self, inputList):
pre = self
for i in inputList:
pre.next = ListNode(i)
pre = pre.next
return self.next
class Solution:
def __init__(self):
self. a = 1
L1 = ListNode(1)
L1 = L1.newValue([9,1,3])
S1 = Solution()
|
947af29568cc8fb642503115d2a4c7d582b1c274 | yukiii-zhong/Leetcode | /problems/9. Palindrome Number.py | 1,248 | 3.734375 | 4 | class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x <0:
return False
elif x == 0:
return True
# turn the int to an digit list
dig = []
while x > 0:
dig.append(x % 10)
x = x // 10
def palinDig(dig):
if len(dig) <=1:
return True
return dig[0] == dig[-1] and palinDig(dig[1:-1])
return palinDig(dig)
# In Python, you can directly tranfer the int to a String
def isPalindrome2(self, x):
if x < 0:
return False
elif x == 0:
return True
str_x = str(x)
i = 0
j = len(str_x)-1
while j>i:
if str_x[i] == str_x[j]:
i += 1
j -= 1
else:
return False
return True
# Without extra space
def isPalindrome3(self, x):
if x <0 or (x % 10 ==0 and x != 0):
return False
reverted = 0
while x > reverted:
x, rem = x // 10, x % 10
reverted = reverted *10 + rem
return x == reverted or x == reverted // 10 |
405cebe01e5875b953e07be442398b3e67275d88 | lockmachine/DeepLearningFromScratch | /ch04/gradient_descent.py | 2,233 | 3.515625 | 4 | #!/usr/bin/env python3
# coding: utf-8
import sys,os
sys.path.append(os.pardir)
import numpy as np
import matplotlib.pyplot as plt
from numerical_gradient import numerical_gradient
def gradient_descent(f, init_x, lr = 0.01, step_num=100):
x = init_x
grad_data = np.zeros(0)
for i in range(step_num):
grad = numerical_gradient(f, x)
x = x - lr * grad
# 途中の勾配を保存
if i == 0:
x_history = x.reshape(1, -1)
grad_data = grad.reshape(1, -1)
elif i % 10 == 0:
x_history = np.append(x_history, x.reshape(1, -1), axis=0)
grad_data = np.append(grad_data, grad.reshape(1, -1), axis=0)
return x, grad_data, x_history
def function_2(x):
if x.ndim == 1:
return np.sum(x**2)
else:
return np.sum(x**2, axis=1)
if __name__ == "__main__":
# f(x0, x1) = x0^2 + x1^2 の最小値を勾配法で求めよ
init_x = np.array([-3.0, 4.0])
# x = np.arange(-4.0, 4.0, 0.1) # (80, )
# y = np.arange(-4.0, 4.0, 0.1) # (80, )
# x_con = np.vstack((x, y)) # (2, 80)
# Z = function_2(x_con)
# X, Y = np.meshgrid(x, y) # メッシュグリッドの生成
# plt.contour(X, Y, Z)
# plt.gca().set_aspect('equal')
# plt.show()
# 学習率が大きすぎる例
x_large, grad_x_large, x_large_history = gradient_descent(function_2, init_x, lr = 10.0, step_num=100)
print("学習率が大きすぎる場合:" + str(x_large))
print(function_2(x_large))
# plt.plot(grad_x_large[:, 0], grad_x_large[:, 1], "o")
plt.plot(x_large_history[:, 0], x_large_history[:, 1], "o")
# 学習率が小さすぎる例
x_small, grad_x_small, x_small_history = gradient_descent(function_2, init_x, lr = 1e-10, step_num=100)
print("学習率が小さすぎる場合:" + str(x_small))
print(function_2(x_small))
# plt.plot(grad_x_small[:, 0], grad_x_small[:, 1], "x")
plt.plot(x_small_history[:, 0], x_small_history[:, 1], "x")
# デフォルトの学習率
x_default, grad_x_default, x_default_history = gradient_descent(function_2, init_x, lr = 0.01, step_num=100)
print("デフォルトの学習率:" + str(x_default))
print(function_2(x_default))
# plt.plot(grad_x_default[:, 0], grad_x_default[:, 1], ".")
plt.plot(x_default_history[:, 0], x_default_history[:, 1], ".")
plt.xlim(-5, 5)
plt.ylim(-5, 5)
plt.show()
|
2c8ddb9a521e97f69e56db1a3ef504c7503c55b1 | Tuffour-Akwasi/Day2 | /part3.py | 672 | 3.875 | 4 | some_var = 5
if some_var > 10:
print('some_var is smaller than 10')
elif some_var < 10:
print("some_var is less than 10")
else:
print("some_var is needed")
print("dog " is "a mammal")
print("cat" is "a mammal")
print("mouse " is "a mammal")
for animal in ["dog","cat","mouse"]:
print("{0} is a mammal".format(animal))
for i in range(4):
print(i)
for i in range(4,8):
print(i)
'''x = 0
while x < 4:
print(x)
x += 1
'''
def add(x,y):
print("x is {0} and y is {1}".format(x,y))
return x + y
add(5,6)
def keyword_args(**kwargs):
return kwargs
keyword_args(big="foot", loch="ness")
x = 5
def sex_x(num):
x = num
print(x)
|
b261cd770064d7e35b55d80821053c79efd62e22 | L111235/Python-code | /嵩天python3/两数之和(字典).py | 1,468 | 3.765625 | 4 | '''给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的
那两个整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
'''
def twoSum( nums, target) :
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
n = len(nums)
lookup = {} #建一个空字典
#(1,2,3)代表tuple元组数据类型,元组是一种不可变序列。
#['p', 'y', 't', 'h', 'o', 'n']代表list列表数据类型
#{'lili': 'girl', 'jon': 'boy'}代表dict字典数据类型,字典是由键对值组组成
for i in range(n):
tmp = target - nums[i] #tmp可以理解为nums[j]
if tmp in lookup: #判断nums[i]+nums[j]是否等于target
return [lookup[tmp], i]
lookup[nums[i]] = i #在字典lookup里增加键为nums[i]、值为i的数据
'''
把nums[i]为键、i为值添加到字典lookup中,然后用后续的target-nums[i]与字典中的
nums[i]值进行对比,就可以把执行一个循环的时间变为一个数值与字典中的值进行对比
的时间
#列表中的元素或者字典中的键值可以是int数值
#假如nums中有两个相同元素2,2,且target是4的话,第一个tmp会保存在字典中,第二个
#会直接输出
'''
|
3f365ba40640a9396a784cb3d597a91775bac3ef | L111235/Python-code | /嵩天python3/科赫雪花(递归迭代).py | 867 | 3.65625 | 4 | #科赫雪花
import turtle as t
def koch(size,n):
if n==0:
t.fd(size)
else:
for angle in [0,60,-120,60]:
t.left(angle)
koch(size/3,n-1)
#n-1阶科赫曲线相当于0阶,n阶相当于1阶
#用一阶图形替代0阶线段画二阶科赫曲线
#用n-1阶图形替代0阶线段画n阶科赫曲线
#将最小size的3倍长的线段替换为一阶科赫曲线
#只画了第n阶的科赫曲线
#每递归一次size都要除以3,初始n阶科赫曲线的size固定
def main():
t.setup(800,800,200,20)
t.width(2)
t.penup()
t.goto(-200,150)
t.pendown()
a=120
for i in range(360//a):#对商取整,range函数参数必须为int型,不能是float
koch(400,3)
t.right(a)
t.hideturtle()
t.done
main()
|
edba9fdc0690c73ee47c88f6d77ade4054c2a70d | L111235/Python-code | /力扣/11.盛最多的水-双指针法.py | 827 | 3.75 | 4 | '''
给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。
在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。
找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
'''
#双指针法
def maxArea(height):
#双指针法:短线段不变, 长线段向内收缩的话,无论之后的线段再长,
#也要以短线段长度为基准,但两条线段之间的距离却缩短了,
#所以不可能比之前装的水多
maxarea=0
i=0
j=len(height)-1
while i<j:
if height[i]<height[j]:
maxarea=max(maxarea,(j-i)*height[i])
i+=1
else:
maxarea=max(maxarea,(j-i)*height[j])
j-=1
return maxarea
height=[1,8,6,2,5,4,8,3,7]
print(maxArea(height)) |
dab7423796be87917bf76e78455eb0fc2853cb33 | L111235/Python-code | /嵩天python3/Hello World.py | 237 | 3.9375 | 4 | a=input('请输入一个整数:')
a=int(a)
if a==0:
print('Hello World 啊!')
elif a>0:
print('He\nll\no \nWo\nrl\nd 啊!')
elif a<0:
print('H\ne\nl\nl\no\n \nW\no\nr\nl\nd 啊!')
else:
print('输入格式有误') |
f88803a8d0b44c62fb19c0e90c5d9e8ad0f43878 | antoniovukovic/test7 | /test.py | 211 | 3.578125 | 4 | # -*- coding: utf-8 -*-
secretNum = 6
test = int(raw_input("Odaberi jedan broj, sigurno ćeš pogriješiti: "))
if test == secretNum:
print("Bravo, 6.")
else:
print("Nisi pogodio prijatelju") |
47f296fe941b489c59dd1952ad6ca111a8a86e8a | pandeesh/CodeFights | /Challenges/sum_of_odd_nos.py | 661 | 3.75 | 4 | #!/usr/bin/env python
"""
Example
For a = 3 and b = 5 the output should be 0.
For a = 3006 and b = 4090 the output should be 1923016.
Note
If you don't want to read the text below, maybe your code won't pass time and memory limits. ;)
[input] integer a
The first integer, -1 < a < 1e8.
[input] integer b
The second integer, 0 < b < 1e8 + 1.
[output] integer
Return the answer modulo 10000007
"""
__author__ = 'pandeesh'
import math
def sumofoddnumbers(a, b):
start_pos = math.ceil( a / 2 )
end_pos = math.floor( b / 2 )
return end_pos ** 2 - start_pos ** 2
#tests
x = sumofoddnumbers(3,5)
print(x)
x = sumofoddnumbers(30,4090)
print(x)
|
d8325a2d9e1214a72880b37b023d4af1a8d88469 | pandeesh/CodeFights | /Challenges/find_and_replace.py | 556 | 4.28125 | 4 | #!/usr/bin/env python
"""
ind all occurrences of the substring in the given string and replace them with another given string...
just for fun :)
Example:
findAndReplace("I love Codefights", "I", "We") = "We love Codefights"
[input] string originalString
The original string.
[input] string stringToFind
A string to find in the originalString.
[input] string stringToReplace
A string to replace with.
[output] string
The resulting string.
"""
def findAndReplace(o, s, r):
"""
o - original string
s - substitute
r - replace
"""
return re.sub(s,r,o)
|
5fa88d472f98e125a2dd79e2d6986630bbb28396 | pandeesh/CodeFights | /Challenges/palindromic_no.py | 393 | 4.125 | 4 | #!/usr/bin/env python
"""
You're given a digit N.
Your task is to return "1234...N...4321".
Example:
For N = 5, the output is "123454321".
For N = 8, the output is "123456787654321".
[input] integer N
0 < N < 10
[output] string
"""
def Palindromic_Number(N):
s = ''
for i in range(1,N):
s = s + str(i)
return s + str(N) + s[::-1]
#tests
print(Palindromic_Number(5))
|
2f8478b92851cbf82d84d06cae05bd4ab4f9d161 | donghyoya/swp1-test | /Hello175(숫자 맞추기).py | 542 | 3.515625 | 4 | import random
num_selected = int(input("AI의 범위를 정하세요:"))
ai_random = random.randrange(1,num_selected)
try_number = 1
while try_number < 10:
try_number += 1
num_player = int(input("AI가 생각하는 수를 추측해보세요:"))
if ai_random < num_player:
print("당신은 AI보다 높은수를 생각하고 있습니다.")
if ai_random > num_player:
print("당신은 AI보다 낮은수를 생각하고 있습니다.")
else:
break;
print("{}번 만에 찾으셧습니다!".format(try_number))
|
a69789bfada6cdab50325c5d2c9ff3edf887aebe | dhasl002/Algorithms-DataStructures | /stack.py | 1,562 | 4.3125 | 4 | class Stack:
def __init__(self):
self.elements = []
def pop(self):
if not self.is_empty():
top_element = self.elements[len(self.elements)-1]
self.elements.pop(len(self.elements)-1)
return top_element
else:
print("The stack is empty, you cannot pop")
def push(self, element):
self.elements.append(element)
def peek(self):
if not self.is_empty():
top_element = self.elements[len(self.elements)-1]
else:
print("The stack is empty, you cannot peek")
return top_element
def is_empty(self):
if len(self.elements) > 0:
return False
else:
return True
def access_element_n(self, n):
if n > len(self.elements)-1:
return None
tmp_stack = Stack()
for i in range(0, n-1):
tmp_stack.push(self.pop())
element_to_return = self.peek()
for i in range(0, n-1):
self.push(tmp_stack.pop())
return element_to_return
if __name__ == "__main__":
print("Creating a stack with values 0-4")
stack = Stack()
for i in range(0, 5):
stack.push(i)
print("Is the stack we built empty? {}".format(stack.is_empty()))
print("Peek the top of the stack: {}".format(stack.peek()))
print("Pop the top of the stack: {}".format(stack.pop()))
print("Peek to make sure the pop worked: {}".format(stack.peek()))
print("Access the 3rd element: {}".format(stack.access_element_n(2)))
|
d9910eb3deaa08b03c3d5ee6b1aac7ee2a8b5f49 | RuchikDama24/IUB_CSCI_B551_EAI | /Assignment 2/part2/SebastianAutoPlayer.py | 7,877 | 3.859375 | 4 | # Automatic Sebastian game player
# B551 Fall 2020
# PUT YOUR NAME AND USER ID HERE!
#
# Based on skeleton code by D. Crandall
#
#
# This is the file you should modify to create your new smart player.
# The main program calls this program three times for each turn.
# 1. First it calls first_roll, passing in a Dice object which records the
# result of the first roll (state of 5 dice) and current Scorecard.
# You should implement this method so that it returns a (0-based) list
# of dice indices that should be re-rolled.
#
# 2. It then re-rolls the specified dice, and calls second_roll, with
# the new state of the dice and scorecard. This method should also return
# a list of dice indices that should be re-rolled.
#
# 3. Finally it calls third_roll, with the final state of the dice.
# This function should return the name of a scorecard category that
# this roll should be recorded under. The names of the scorecard entries
# are given in Scorecard.Categories.
#
# this is one layer with comments
from SebastianState import Dice
from SebastianState import Scorecard
import random
class SebastianAutoPlayer:
def __init__(self):
pass
#Score Function: to calculate the scores for the dice roll with the parameters : dice_roll- dice combination, reroll_number: to check which function is calling the score function,
#scorecard=holds all the score values, score_dict= dictionary which holds the computed scores for the different dice combinations so it can be reused again
def score(self,dice_roll,reroll_number,scorecard,score_dict):
s=Scorecard()
score_card=scorecard.scorecard
d=Dice()
#if third rolls calls this score function, then the scoreboard is an object of type dice, else, if called from first or second reroll it is a list of dice rolls
if (reroll_number=="third"):
d.dice=dice_roll.dice
else:
d.dice=dice_roll
Categories = [ "primis", "secundus", "tertium", "quartus", "quintus", "sextus", "company", "prattle", "squadron", "triplex", "quadrupla", "quintuplicatam", "pandemonium" ]
#checking if the score card list exists, as, in the first call the score card is not yet created
if bool(score_card):
for i in score_card:
Categories.remove(i) #removing all those categories which have already been assigned in this game
#calculate the scores for each category in this dice combination
all_good=False # var:all_good lets us know if the scores for this combination has already been computed and if it is present in the dictionary of pre computed scores
if (reroll_number!="third") and d.dice in score_dict:
all_good=True
for category in Categories:
if category not in score_dict[d.dice]:
all_good=False
if all_good is True:
s.scorecard=score_dict[d.dice] #scores for the dice combination is already computed, hence retrieved from the dictionary
else:
for category in Categories: #call the record function of the class Scorecard to retrieve the scores of the dice combination
s.record(category,d)
if (reroll_number!="third"):
score_dict[d.dice]=s.scorecard #store the scoreboard values of the dice in the dictionary
max_category=max(s.scorecard,key=s.scorecard.get) #choose the category with the max score from the scores computed from the categories which are yet to be assinged
if (reroll_number=="third"): #if called from 3rd reroll return the category with the max score else return the max score itself
return max_category
return(s.scorecard[max_category],score_dict)
# Idea derived from expectation_of_reroll() function in program shown in the
# Discussion 8 Walkthrough of CSCI 551 - Spring 2021
# Function to calculate the expectation value
def expection_score_second_reroll(self,roll,reroll,scorecard,score_dict):
exp=0
roll_dice=roll.dice
reroll_score_dict=score_dict
#compute the scores for the dice combinations with the given rerolls
for outcome_a in ((roll_dice[0],) if not reroll[0] else range(1,7)):
for outcome_b in ((roll_dice[1],) if not reroll[1] else range(1,7)):
for outcome_c in ((roll_dice[2],) if not reroll[2] else range(1,7)):
for outcome_d in ((roll_dice[3],) if not reroll[3] else range(1,7)):
for outcome_e in ((roll_dice[4],) if not reroll[4] else range(1,7)):
exp_score=(self.score((outcome_a,outcome_b,outcome_c,outcome_d,outcome_e),"second",scorecard,reroll_score_dict))
reroll_score_dict=exp_score[1]
exp+=exp_score[0]
#calculate the expected value by multiplying the probabilty over all the rerolls and the sum of the scores of the dice rolls
expected_value=exp*1/(6**sum(reroll))
return(expected_value,reroll_score_dict)
#Function to find the best possible rerolls for the first dice roll
def first_roll(self, dice, scorecard):
score_dict={}
roll=dice
current_max=(0,0) #holds the indices and the max value
#compute all the possible rerolls or combinations possible for the dice roll
possible_rerolls=[(roll_a,roll_b,roll_c,roll_d,roll_e) for roll_a in (True,False) for roll_b in (True,False) for roll_c in (True,False) for roll_d in (True,False) for roll_e in (True,False) ]
for reroll in possible_rerolls:
exp_score=(self.expection_score_second_reroll(roll,reroll,scorecard,score_dict))
score_dict=exp_score[1]
if(exp_score[0]>current_max[0]): #compute the maximum of the scores
current_max=(exp_score[0],reroll)
#get the roll combination for which you got the maximum score (eg:-[1,2] means roll the 1st and 2nd die)
reroll_index=[ i for i,j in enumerate(current_max[1]) if j is True]
return reroll_index # return the indices to re roll
#Function to find the best possible rerolls for the second dice roll
def second_roll(self, dice, scorecard):
score_dict={}
roll=dice
current_max=(0,0) #tuple which holds the indices of the dice combination and the max value
#compute all the possible rerolls or combinations possible for the dice roll
possible_rerolls=[(roll_a,roll_b,roll_c,roll_d,roll_e) for roll_a in (True,False) for roll_b in (True,False) for roll_c in (True,False) for roll_d in (True,False) for roll_e in (True,False) ]
for reroll in possible_rerolls:
exp_score=(self.expection_score_second_reroll(roll,reroll,scorecard,score_dict))
score_dict=exp_score[1]
if(exp_score[0]>current_max[0]): #compute the maximum of the scores
current_max=(exp_score[0],reroll)
#get the roll combination for which you got the maximum score(eg:-[1,2] means roll the 1st and 2nd die)
reroll_index=[ i for i,j in enumerate(current_max[1]) if j is True]
return reroll_index# return the indices to re roll
#return the best category for which the 3 rolled dice belongs to out of all the categories by choosing the maximum category value
def third_roll(self, dice, scorecard):
score_dict={}
scorecard_category=self.score(dice,"third",scorecard,score_dict)
return scorecard_category
|
fcb556abbd51a184f6dce990399fac1049b2e5a7 | davidlyness/Advent-of-Code-2018 | /17/main.py | 2,660 | 3.65625 | 4 | # coding=utf-8
"""Advent of Code 2018, Day 17"""
import collections
def find_water_overflow(water_x, water_y, step):
"""Locate bucket overflow in a given direction."""
while True:
next_cell = grid[water_y + 1][water_x]
current_cell = grid[water_y][water_x]
if current_cell == "#":
water_x -= step
return water_x, False
elif next_cell == ".":
sources.append((water_x, water_y))
return water_x, True
elif current_cell == "|" and next_cell == "|":
return water_x, True
water_x += step
scans = []
for line in open("puzzle_input").read().split("\n"):
clay_start, clay_range = line.split(", ")
clay_start = int(clay_start.split("=")[1])
range1, range2 = map(int, clay_range[2:].split(".."))
scans.append((line[0], clay_start, range1, range2))
x_min, x_max = float("inf"), float("-inf")
y_min, y_max = float("inf"), float("-inf")
for range_type, point, range_start, range_end in scans:
if range_type == "x":
x_min, x_max = min(point, x_min), max(point, x_max)
y_min, y_max = min(range_start, y_min), max(range_end, y_max)
else:
x_min, x_max = min(range_start, x_min), max(range_end, x_max)
y_min, y_max = min(point, y_min), max(point, y_max)
x_min -= 1
x_max += 1
grid = [["." for _ in range(x_max - x_min)] for _ in range(y_max + 1)]
for range_type, point, range_start, range_end in scans:
for i in range(range_start, range_end + 1):
if range_type == "x":
x, y = point, i
else:
x, y = i, point
grid[y][x - x_min] = "#"
sources = [(500 - x_min, 0)]
while sources:
x_source, y_source = sources.pop()
y_source += 1
while y_source <= y_max:
cell = grid[y_source][x_source]
if cell == "|":
break
elif cell == ".":
grid[y_source][x_source] = "|"
y_source += 1
elif cell in("#", "~"):
y_source -= 1
left_amount, left_overflow = find_water_overflow(x_source, y_source, -1)
right_amount, right_overflow = find_water_overflow(x_source, y_source, 1)
for x in range(left_amount, right_amount + 1):
if left_overflow or right_overflow:
grid[y_source][x] = "|"
else:
grid[y_source][x] = "~"
symbol_counts = collections.Counter(cell for row in grid[y_min:] for cell in row)
def part_one():
"""Solution to Part 1"""
return symbol_counts["~"] + symbol_counts["|"]
def part_two():
"""Solution to Part 2"""
return symbol_counts["~"]
|
7358df3f9f86fda07fbd980364aa9d2877eed918 | davidlyness/Advent-of-Code-2018 | /09/main.py | 935 | 3.78125 | 4 | # coding=utf-8
"""Advent of Code 2018, Day 9"""
import collections
import re
with open("puzzle_input") as f:
match = re.search("(?P<players>\d+) players; last marble is worth (?P<points>\d+) points", f.read())
num_players = int(match.group("players"))
num_points = int(match.group("points"))
def run_marble_game(players, max_points):
"""Run marble game with specified number of players and points."""
marbles = collections.deque([0])
scores = collections.defaultdict(int)
for marble in range(1, max_points + 1):
if marble % 23 > 0:
marbles.rotate(-1)
marbles.append(marble)
else:
marbles.rotate(7)
scores[marble % players] += marble + marbles.pop()
marbles.rotate(-1)
return max(scores.values())
# Part One
print(run_marble_game(num_players, num_points))
# Part Two
print(run_marble_game(num_players, num_points * 100))
|
cb3f6144b597cb5dc22ce03d9ac54dd7abe3aee4 | Bitcents/exercism_tracks | /python/hangman/hangman.py | 1,425 | 3.6875 | 4 | # Game status categories
# Change the values as you see fit
STATUS_WIN = "win"
STATUS_LOSE = "lose"
STATUS_ONGOING = "ongoing"
class Hangman:
def __init__(self, word):
self.remaining_guesses = 9
self.status = STATUS_ONGOING
self.__word = word
self.remaining_characters = set()
self.guessed_characters = set()
for letter in word:
self.remaining_characters.add(letter)
def guess(self, char):
# Check if the game is still going on
if self.status != STATUS_ONGOING:
raise ValueError('game is over')
if char in self.remaining_characters:
self.remaining_characters.remove(char)
self.guessed_characters.add(char)
if len(self.remaining_characters) == 0:
self.status = STATUS_WIN
elif char in self.guessed_characters:
self.remaining_guesses -= 1
else:
self.remaining_guesses -= 1
# Check if there are any guesses left
if self.remaining_guesses < 0:
self.status = STATUS_LOSE
def get_masked_word(self):
masked_word = ""
for letter in self.__word:
if letter in self.remaining_characters:
masked_word += '_'
else:
masked_word += letter
return masked_word
def get_status(self):
return self.status
|
f4a3d3365a114ced431f2a84d6c2b7b631c97575 | Bitcents/exercism_tracks | /python/difference-of-squares/difference_of_squares.py | 240 | 3.9375 | 4 | def square_of_sum(number):
return (number*(number+1)//2)**2
def sum_of_squares(number):
return (number)*(2*number + 1)*(number + 1)//6
def difference_of_squares(number):
return square_of_sum(number) - sum_of_squares(number)
|
1ee723a5d3ac7ccd8883aa6b0e3b7129c90da52d | Bitcents/exercism_tracks | /python/pythagorean-triplet/pythagorean_triplet.py | 297 | 3.765625 | 4 | from math import sqrt
def triplets_with_sum(number):
results = []
for i in range(number//2, number//3, -1):
for j in range(i-1,i//2,-1):
k = sqrt(i*i - j*j)
if i + j + k == number and k < j:
results.append([int(k),j,i])
return results
|
a8934dd089aeb3763409d937502708680e59d765 | AnupritaPro/gittest | /list1.py | 845 | 3.78125 | 4 | #list
l1=[2011,2013,"anu","pratiksha"]
l2=[2021,22.22,2002,1111]
print "value of l1",l1
print ("value of ",l1[1])
print "value of ",l1[0:2]
print "length of list is:",len(l1)
print "minimum lenght",min(l2)
print "maximum length",max(l2)
l1.append("sarita")
print "add update",l1
l1.append(2011)
print l1
c=l1.count(2011)
print "count is",c
l1.extend(l2)
print l1
l2.insert(2,400)
print l2
#l1.pop(2)
print l1.pop()
print l1
l1.remove("anu")
print l1
l2.reverse()
print l2
l1.sort()
print l1
#directory
dict={'Name':'Anu','Age':50,'class':'bsc'};
print "dict['Name']:",dict['Name'];
print "dict['Age']:",dict['Age'];
dict['Age']=20
print "dict['Age']:",dict['Age'] #edit
dict['friend']="Sarita"
print "dict['friend']:",dict['friend'] #insert
#print dict
del dict['Name']
print "dict['Name']",dict['Name']
dict.clear();
print dict
#del dict
|
46193fb3b9db2783700ef0026a2e1d274eb43842 | ramesheerpina/AutomateBoringStuff | /AutomateBoringStuff.py | 517 | 4.09375 | 4 | print("I am thinking of a number between 1 and 20. \n")
import random
randomnum = random.randint(1,20)
for guesstaken in range(1,9):
print("Take Guess\n")
guess = int(input())
if guess < randomnum:
print("your guess is too low")
elif guess > randomnum:
print("your guess is too high")
else:
break
if guess == randomnum:
print("Good Job! You guessed my number in " + str(guesstaken) + " guesses")
else:
print("Nope. The number I was thinking of was "+str(randomnum)) |
33dbfd93f39cc11cca56d3099ac9310a3f488113 | javibolibic/SPSI | /kasiskiAttack.py | 5,683 | 3.640625 | 4 | #! /usr/bin/python
# -*- coding: utf-8 -*-
###################################################################
# _ _ _ _ _ _ _ _ #
# | | ____ _ ___(_)___| | _(_) / \ | |_| |_ __ _ ___| | __ #
# | |/ / _` / __| / __| |/ / | / _ \| __| __/ _` |/ __| |/ / #
# | < (_| \__ \ \__ \ <| |/ ___ \ |_| || (_| | (__| < #
# |_|\_\__,_|___/_|___/_|\_\_/_/ \_\__|\__\__,_|\___|_|\_\ #
# Creado por Antonio Miguel Pozo Cámara y Javier Bolívar Valverde #
# Universidad de Granada #
###################################################################
from fractions import gcd
import sys
import collections
# alphabet = "ABCDEFGHIJKLMNÑOPQRSTUVWXYZ"
alphabet = "ABCDEFGHIJKLMNNOPQRSTUVWXYZ"
spanish = 0.0775
min_subs_size = 4
"""
Desencripta el texto plano a cifrado vigenère
"""
def decrypt(cipher, key):
key_index = 0
plain = ''
for i in cipher:
plain += chr((ord(i)-ord(key[key_index])-2*65) %26 +65)
if key_index < len(key) - 1:
key_index += 1
else:
key_index = 0
return plain
"""
busca todas las subcadenas de longitud 'l' en 'text'
modifica la variable global lista_ocurrencias, añadiendo la distancia entre dichas repeticiones.
"""
def findsubs(text, l, lista_ocurrencias):
for i in range(len(text)-l):
subcadena = text[i:i+l]
found = text[i+l:].find(subcadena)
if found != -1:
f = found+i+l
if i>0 and text[i-1:i+l] == text[f-1:f+l]:
continue
if i+l < len(text) and text[i:i+l+1] == text[f:f+l+1]:
continue
print "%-10s %3d " % (subcadena, found+l)
a = found+l
lista_ocurrencias.append(a)
return lista_ocurrencias
"""
excluye caracteres de text que no estan en el alfabeto alphabet
"""
def filter(text):
ctext = ""
for c in text:
c = c.upper()
if c in alphabet:
ctext += c
sys.stdout.write("Sin caracteres raros:")
sys.stdout.write(ctext)
return ctext
"""
Imprime la cadena pasada como argumento.
"""
def imprime(cadena):
sys.stdout.write("***** ")
for i in range(len(cadena)):
sys.stdout.write(cadena[i])
sys.stdout.write(" *****")
print""
"""
Calcula el índice de coincidencia de una cadena “cadena” en la posición “i”
"""
def indexofCoincidence(cadena, i):
N = len(cadena[i])
freqs = collections.Counter( cadena[i] )
freqsum = 0.0
for letter in alphabet:
freqsum += freqs[ letter ] * ( freqs[ letter ] - 1 )
IC = freqsum / (N*(N-1))
return IC
def splitText(ctext, mcd):
cadena=[[] for x in range(mcd)]
for i in range(0, (len(ctext)/mcd)):
j=0
if i == 0:
for j in range(0,mcd):
cadena[j].append(ctext[j])
else:
for j in range(0,mcd):
if i*mcd+j<len(ctext):
cadena[j].append(ctext[i*mcd+j])
return cadena
def ktest(text):
lista_ocurrencias = []
ctext = filter(text)
"""
el tamaño máximo de una cadena que se puede repetir en el texto tiene
de tamaño como máximo la longitud del texto / 2. Empieza desde esa longitud hacia abajo.
"""
for l in range(len(text)/2,min_subs_size-1,-1):
findsubs (ctext, l, lista_ocurrencias)
if len(lista_ocurrencias)<=1:
# print "asasdfasdfasdf"
sys.exit("No se han encontrado cadenas repetidas o no se ha podido dictaminar una longitud de clave válida")
mcd = reduce(gcd,lista_ocurrencias) #cálculo del máximo común divisor
print "Posible longitud de la clave = " + str(mcd)
if mcd ==1:
print "El programa no es concluyente. De la distancia entre subcadenas repetidas no se puede extraer un tamaño de clave válido"
return
# sys.exit(0)
print ""
cadena = splitText(ctext, mcd)
"""
contar las letras que más se repiten en cada una de las cadenas
"""
ocurrencias=0
clave=[]
vocurrencias=[[] for x in range(mcd)] #ocurrencias de cada caracter c en cada subcadena
for i in range(0, mcd):
sys.stdout.write("cadena[" + str(i) + "]== ")
for j in range(len(cadena[i])):
sys.stdout.write(cadena[i][j])
print ""
for c in alphabet:
ocurrencias = cadena[i].count(c);
vocurrencias[i].append(ocurrencias)
max1=0
max2=0
max3=0
letra1=''
letra2=''
letra3=''
maxocurrencias1=0
maxocurrencias2=0
for k in range(0, len(alphabet)):
cantidad = vocurrencias[i][k%len(alphabet)]
cantidad +=vocurrencias[i][(k+4)%len(alphabet)]
cantidad +=vocurrencias[i][(k+15)%len(alphabet)]
if cantidad > max1:
max3=max2
max2=max1
max1=cantidad
letra3=letra2
letra2=letra1
letra1=alphabet[k]
elif cantidad > max2:
max3=max2
max2=cantidad
letra3=letra2
letra2=alphabet[k]
elif cantidad > max3:
max3=cantidad
letra3=alphabet[k]
print "Primera letra más probable: " + letra1
print "Segunda letra más probable: " + letra2
print "Tercera letra más probable: " + letra3
"""
Cálculo del íncide de coincidencia
"""
IC = indexofCoincidence(cadena, i)
print "Indice de coincidencia de cadena[" + str(i) + "] %.3f" % IC, "({})".format( IC )
if IC < spanish:
print "(NO FIABLE)\n"
else:
print"(FIABLE)\n"
clave.append(letra1)
"""
imprimir las claves
"""
sys.stdout.write("POSIBLE CLAVE\t")
imprime(clave)
clavestring = ''.join(clave)
plano = decrypt(ctext, clavestring)
print "Posible texto plano: " + str(plano)
if __name__ == "__main__":
def main():
while True:
text =raw_input ("Introducir el texto cifrado: \n")
if len(text) == 0:
break
ktest(text)
main()
# *************************************CADENA DE EJEMPLO AQUÍ*************************************
# PPQCAXQVEKGYBNKMAZUYBNGBALJONITSZMJYIMVRAGVOHTVRAUCTKSGDDWUOXITLAZUVAVVRAZCVKBQPIWPOU
# PPQCAXQV EKGYBNKM AZUYBNGB ALJONITS ZMJYIMVR AGVOHTVR AUCTKSGD DWUOXITL AZUVAVVR AZCVKBQP IWPOU
|
546936ded7cbd026dfd23c02cffda693e9840c01 | aliensmart/week2_day4 | /terminalTeller2/account.py | 1,483 | 3.65625 | 4 | import json
import os
class Account:
filepath = "data.json"
def __init__(self, username):
self.username = username
self.pin = None
self.balance = 0.0
self.data = {}
self.load()
def load(self):
try:
with open(self.filepath, 'r') as json_file:
self.data = json.load(json_file)
except FileNotFoundError:
pass
if self.username in self.data:
self.balance = self.data[self.username]['balance']
self.pin = self.data[self.username]['pin']
def save(self):
self.data[self.username] = {
"balance": self.balance,
"pin": self.pin
}
with open(self.filepath, 'w') as json_file:
json.dump(self.data, json_file, indent=3)
def withdraw(self, amount):
if amount < 0:
raise ValueError("amount must be positive")
if self.balance < amount:
raise ValueError("amount must not be greater than balance")
self.balance -= amount
def deposit(self, amount):
if amount < 0:
raise ValueError("amount must be positive")
self.balance += amount
@classmethod
def login(cls, username, pin):
# Account.login("Greg", "1234")
# should return an account object with my data
account = cls(username)
if pin != account.pin:
return None
return account
|
83a2fe0e985ffa4d33987b15e6b4ed8a6eb5703b | Nbouchek/python-tutorials | /0001_ifelse.py | 836 | 4.375 | 4 | #!/bin/python3
# Given an integer, , perform the following conditional actions:
#
# If is odd, print Weird
# If is even and in the inclusive range of 2 to 5, print Not Weird
# If is even and in the inclusive range of 6 to 20, print Weird
# If is even and greater than 20, print Not Weird
# Input Format
#
# A single line containing a positive integer, .
#
# Constraints
#
# Output Format
#
# Print Weird if the number is weird; otherwise, print Not Weird.
#
# Sample Input 0
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input("Enter a number >>> ").strip())
if n % 2 == 1:
print("Weird")
if n % 2 == 0 and 2 <= n <= 5:
print("Not Weird")
if n % 2 == 0 and 6 <= n <= 20:
print("Weird")
if n % 2 == 0 and n > 20:
print("Not Weird")
|
4e3be7e82c018e9309bf2d16135cd12af6302328 | ByketPoe/gmitPandS | /week02/lab2.3.2sub.py | 790 | 4.0625 | 4 | # sub.py
# The purpose of this program is to subtract one number from another.
# author: Emma Farrell
# The input fuctions ask the user to input two numbers.
# This numbers are input as strings
# They must be cast as an integer using the int() function before the program can perform mathematical operations on it
number1 = int(input("Enter the first number: "))
number2 = int(input("Enter the second number: "))
# The result of subtracting the second number from the first number is calculted
# The result is printed with the format() function used to insert the variables within the string
answer = number1 - number2
print("{} minus {} is {}".format(number1, number2, answer))
# Errors occur when the user tries to enter a float or a string.
# The program is able to calculate minus numbers |
a30b0e3f5120fc484cd712f932171bd322e757df | ByketPoe/gmitPandS | /week04-flow/lab4.1.3gradeMod2.py | 1,152 | 4.25 | 4 | # grade.py
# The purpose of this program is to provide a grade based on the input percentage.
# It allows for rounding up of grades if the student is 0.5% away from a higher grade bracket.
# author: Emma Farrell
# The percentage is requested from the user and converted to a float.
# Float is appropriate in this occasion as we do not want people to fail based on rounding to an integer.
percentage = float(input("Enter the percentage: "))
# In this modification of the program, the percentage inputted by the user is rounded.
# As we want to round up if the first decimal place is 0.5 or greater, we do not need to state number of decimal places.
percentageRounded = round(percentage)
# The if statements are executed as in the original program, but evaluating the new variable "percentageRounded" instead of "percentage"
if percentageRounded < 0 or percentageRounded > 100:
print("Please enter a number between 0 and 100")
elif percentageRounded < 40:
print("Fail")
elif percentageRounded < 50:
print("Pass")
elif percentageRounded < 60:
print("Merit 1")
elif percentageRounded < 70:
print("Merit 2")
else:
print("Distinction") |
0037856dbebe4ada7ce5edf268bb83f7563e1169 | ByketPoe/gmitPandS | /week02/addOne.py | 327 | 3.90625 | 4 | # addOne.py
# The purpose of this program is to add 1 to a number
# author: Emma Farrell
# Read in the number and cast to an integer
number = int(input("Enter a number: "))
# Add one to the number and assign the result to the variable addOne
addOne = number + 1
# Print the result
print('{} plus one is {}'.format(number, addOne)) |
0c64591006436bfdf1c666b79f4d2e90da5afcff | ByketPoe/gmitPandS | /week02/nameAndAge.py | 353 | 4.0625 | 4 | # nameAndAge.py
# The purpose of this program is to
# author: Emma Farrell
# Request the name and age of the user
name = input('What is your name? ')
age = input('What is your age? ')
# Output the name and age (using indexing)
print('Hello {0}, your age is {1}'.format(name, age))
# Modified version
print('Hello {0}, \tyour age is {1}'.format(name, age)) |
6f16bc65643470b2bca5401667c9537d88187656 | ByketPoe/gmitPandS | /week04-flow/lab4.1.1isEven.py | 742 | 4.5 | 4 | # isEven.py
# The purpose of this program is to use modulus and if statements to determine if a number is odd or even.
# author: Emma Farrell
# I prefer to use phrases like "text" or "whole number" instead of "string" and "integer" as I beleive they are more user friendly.
number = int(input("Enter a whole number: "))
# Modulus (%) is used to calculated the remainder of the input number divided by 2.
# The if statement evaluates if the remainder is equal to 0.
# If true, the number is even and a message to indicate this is printed.
# Otherwise, the number is odd and the message diplayed will state that it is odd.
if (number % 2) == 0:
print("{} is an even number".format(number))
else:
print("{} is an odd number".format(number)) |
0a13765ecbc3d4c6cae6e666e9ec67149eb7d1a0 | smiks/CodeWars | /ValidateSudoku/program.py | 3,002 | 3.59375 | 4 | __author__ = 'Sandi'
class Sudoku(object):
def __init__(self, sudo):
self.sudo = sudo
def check(self, row):
for v in row.values():
if v != 1:
return False
return True
def is_valid(self):
su = self.sudo # less typing in the future
""" check dimensions """
shouldBe = len(su)
for row in su:
if len(row) != shouldBe:
return False
""" assign allowed values """
allowedValues = {i for i in range(1,shouldBe+1)}
""" check rows """
nums = [{i:0 for i in range(1, shouldBe+1)}for _ in range(shouldBe)]
for e, row in enumerate(su):
for el in row:
if not isinstance(el, int) or el not in allowedValues:
return False
nums[e][el] += 1
if not self.check(nums[e]):
return False
""" check columns """
nums = [{i:0 for i in range(1, shouldBe+1)}for _ in range(shouldBe)]
for e, col in enumerate(zip(*su)):
for el in col:
if isinstance(el, bool) or not isinstance(el, int) or el not in allowedValues:
return False
nums[e][el] += 1
if not self.check(nums[e]):
return False
""" check quadrants """
qsize = int(shouldBe**0.5)
""" iterate through quadrants """
for i in range(qsize):
for j in range(qsize):
toCheck = {i:0 for i in range(1, shouldBe+1)}
""" iterate through single quadrant """
for row in range(i*qsize, (i+1)*qsize):
for col in range(j*qsize, (j+1)*qsize):
tmp = su[row][col]
toCheck[tmp] += 1
if not self.check(toCheck):
return False
return True
goodSudoku1 = Sudoku([
[7,8,4, 1,5,9, 3,2,6],
[5,3,9, 6,7,2, 8,4,1],
[6,1,2, 4,3,8, 7,5,9],
[9,2,8, 7,1,5, 4,6,3],
[3,5,7, 8,4,6, 1,9,2],
[4,6,1, 9,2,3, 5,8,7],
[8,7,6, 3,9,4, 2,1,5],
[2,4,3, 5,6,1, 9,7,8],
[1,9,5, 2,8,7, 6,3,4]
])
goodSudoku2 = Sudoku([
[1,4, 2,3],
[3,2, 4,1],
[4,1, 3,2],
[2,3, 1,4]
])
badSudoku2 = Sudoku([
[1,2,3,4,5],
[1,2,3,4],
[1,2,3,4],
[1]
])
badSudoku3 = Sudoku([[True]])
badSudoku4 = Sudoku([[1, 4, 4, 3, 'a'], [3, 2, 4, 1], [4, 1, 3, 3], [2, 0, 1, 4], ['', False, None, '4']])
badSudoku5 = Sudoku([[1, 2, 3, 4, 5, 6, 7, 8, 9], [2, 3, 1, 5, 6, 4, 8, 9, 7], [3, 1, 2, 6, 4, 5, 9, 7, 8], [4, 5, 6, 7, 8, 9, 1, 2, 3], [5, 6, 4, 8, 9, 7, 2, 3, 1], [6, 4, 5, 9, 7, 8, 3, 1, 2], [7, 8, 9, 1, 2, 3, 4, 5, 6], [8, 9, 7, 2, 3, 1, 5, 6, 4], [9, 7, 8, 3, 1, 2, 6, 4, 5]])
""" valid sudokus """
assert goodSudoku1.is_valid()
assert goodSudoku2.is_valid()
""" invalid sudokus """
assert not badSudoku2.is_valid()
assert not badSudoku3.is_valid()
assert not badSudoku4.is_valid()
assert not badSudoku5.is_valid() |
acb07871af074d9a4560ffca24697c2bcdda5403 | bhavyavj/python-challenges | /problem6.py | 950 | 4.09375 | 4 | #!/usr/bin/python3
options='''
press 1 to view the contents of a file
press 2 cat -n => to show line numbers
press 3 cat -e => to add $ sign at the end of the line
press 4 to view multiple files at once
'''
print(options)
opt=input("Enter your choice")
if (opt==1):
i=input("Enter your file name")
f=open(i,'r')
data=f.read()
print(data)
f.close()
if (opt==2):
i=input("Enter your file name")
f=open(i,'r')
data=f.read()
a=data.split('\n')
line_no=1
for i in a:
print(str(line_no)+" "+i)
line_no=line_no+1
if (opt==3):
i=input("Enter your file name")
f=open(i,'r')
data=f.read()
a=data.split('\n')
for i in a:
print(i+"$")
if (opt==4):
noOfFiles=int(input('Enter no. of files :'))
filenames=[]
print("Press enter after writing a file name")
print('Enter name of files :')
for i in range(noOfFiles):
name=input()
filenames.append(name)
for i in filenames:
f=open(i,'r')
print(f.read())
f.close()
|
4f70866e867bc46f9c609efece8a7338a3f5ad64 | kee007ney/scripts | /toy.py | 282 | 3.9375 | 4 | import csv
"""
This script will use xxx.csv as an input and output all the rows with the row number.
"""
with open("A.csv", 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',', quotechar='|')
for row in csvreader:
for j in xrange(0,len(row)):
print (j,row[j])
|
5a983b9c67438e27c89c5f973d9d09b05dc6ca79 | airje/codewars | /whatsthefloor.py | 123 | 3.546875 | 4 | def get_real_floor(n):
if n>13:
return n-2
elif n>0 and n<14:
return n-1
else:
return n |
7d38c44f7a46926dbf041ceb774a08284cdf8204 | airje/codewars | /findthenextperfectsquare.py | 213 | 3.921875 | 4 | import math as m
def find_next_square(n):
# Return the next square if sq is a square, -1 otherwise
result = (m.sqrt(n)+1)**2
if result-int(result) > 0:
return -1
else:
return result |
8b6646f5da8840e82476bb97f9e5c2668963a612 | Aeronyx/School | /conversations.py | 1,531 | 3.921875 | 4 | # File: conversations.py
# Name: George Trammell
# Date: 9/8/19
# Desc: Program has a discussion with the user.
# Sources: None
# OMH
from time import sleep
# Initial Greeting
print('Hello! What is your name?')
name = input('Name: ')
# Capitalize name if uncapitalized
name = name[0].upper() + name[1:]
print('Hello %s! \n' %(name))
sleep(1)
# First Question
print('%s, Do you have any pets?' %(name))
sleep(1)
# Response tree for amount of pets
pets = input('Type \'y\' for Yes and \'n\' for No: ')
# Nested if statement for appropriate response
if pets == 'y':
print('Wonderful. How many pets? \n')
sleep(.5)
petNumber = int(input('Number of pets (integer): '))
if petNumber > 2:
print('That\'s a lotta pets! You make me proud.')
elif petNumber == 2:
print('I hope you love your duo very much.')
elif petNumber == 1:
print('One loving companion is all you need.')
elif petNumber < 0:
print('You can\'t have negative pets!')
print('Thanks for playing!')
# No pets, ask about eye color instead
elif pets == 'n':
print('\nUnbelieveable. This program is terminated. \n')
sleep(1)
print('Kidding. Sorta. What color are your eyes?')
eyeColor = input('Eye color: ')
eyeColor = eyeColor[0].upper() + eyeColor[1:]
sleep(.5)
print('Processing...')
sleep(1.5)
print('%s\'s a beautiful color! You\'ve been redeemed.' %(eyeColor))
print('Thanks for playing!')
# Incorrect entry
else:
print('You didn\'t follow instructions! Try again.') |
38b6119f2584c44b97990c72d983b4e55275fc2e | akashchevli/Competitive-Programming | /FindBit.py | 1,349 | 4 | 4 | """
Write a program to find out the bits of the given number
Input
Enter number:7
How many bits want:4
Output
0111
Description
The original bits of number 7 is 111, but the user want 4 bits so you have added zeros in front of the bits
Input
Enter number:12
How many bits want:2
Output:
Actual bits is greater than the bits you want
Description
The original bits of number 12 is 1100, but the user enters 2 bits which is less than the length of the original bits
that's why it will be thrown an error
"""
result = ''
negative = False
def getBit(n):
global result, negative
if str(n)[0] == '-':
n = str(n)[1:]
negative = True
n = int(n)
if n == 0 or n == 1:
return str(n).zfill(bits)
next_n = n // 2
rem = n % 2
result += str(rem)
if next_n == 1:
result = str(next_n) + result[::-1]
size = len(result)
if bits < size:
return "Actual bits is greater than the bits you want"
if negative:
return '-' + result.zfill(bits)
return result.zfill(bits)
return getBit(next_n)
n = int(input("Enter number:"))
bits = int(input("How many bits want:"))
print(getBit(n)) |
dd256c28dcb505d183faf042d1ef88f8661435d9 | yaozeye/python | /learner/exercise/greatest_common_divisor.py | 635 | 3.984375 | 4 | # Python Greatest Common Divisor
# Code by Yaoze Ye
# https://yaozeye.github.io
# 09 April 2020
# under the MIT License https://github.com/yaozeye/python/raw/master/LICENSE
num1 = int(input('The first number: '))
num2 = int(input('The second number: '))
num3 = min(num1, num2)
for i in range(1, num3 + 1):
if num1 % i == 0 and num2 % i == 0:
greatest_common_divisor = i
print('The maximum common divisor of %d and %d is %d.' % (num1, num2, greatest_common_divisor))
least_common_multiple = (num1 * num2) / greatest_common_divisor
print('The minimum common multiple of %d and %d is %d.' % (num1, num2, least_common_multiple))
|
e836385db2c976c6b1c779e25f0717a0eb4f57f9 | yaozeye/python | /learner/exercise/rectangle_area.py | 264 | 3.625 | 4 | # Python Rectangle Area
# Code by Yaoze Ye
# https://yaozeye.github.io
# 19 March, 2020
# under the MIT License https://github.com/yaozeye/python/raw/master/LICENSE
length = float(input())
width = float(input())
area = length * width
print("{:.2f}".format(area))
|
a708feba667fb030f755e5564c9cd1772a127dbc | econocoffee/Econo-Maths | /fun.py | 247 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 3 18:19:07 2020
@author: gdolores
"""
def area_r():
print(" Radio : ")
Radio = float(input())
return(" El área es: " + str( ( Radio ** 2 ) * 3.1416 )) |
b8d30e11c617a20d87e105c74cdcb05f8b9147d3 | eralpkor/cs-module-project-iterative-sorting | /src/searching/searching.py | 900 | 4.0625 | 4 | def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1 # not found
# Write an iterative implementation of Binary Search
def binary_search(arr, target):
low = 0
high = len(arr) - 1
# While we haven't narrowed it down to one element ...
while low <= high:
# ... check the middle element
mid = (low + high) // 2
guess = arr[mid]
# Found the item.
if guess == target:
return mid
# The guess was too high.
if guess > target:
high = mid - 1
# The guess was too low.
else:
low = mid + 1
return -1 # not found
# list1 = ['eat', 'sleep', 'repeat']
# str2 = 'dude'
# obj1 = enumerate(list1)
# obj2 = enumerate(str2)
# print(list(enumerate(list1)))
# print(list(enumerate(str2)))
# print(list(obj1))
|
4bac91f95ecabfd99ddc83c288f667c743f00e9a | abtahi-tajwar/python-algo-implementation | /dfs.py | 705 | 4.03125 | 4 | # Calling dfs function will traverse and print using dfs method
def graphSort(graph):
newGraph = dict()
for key in graph:
lst = graph[key]
lst.sort()
newGraph[key] = lst
return newGraph
stack = []
def dfs(graphMap, currentNode):
graph = graphSort(graphMap)
dict_map = dict()
for node in graphMap:
dict_map[node] = False
traverse(graph, currentNode, dict_map)
def traverse(graph, currentNode, dict_map):
stack.append(currentNode)
for node in graph[currentNode]:
if node not in stack:
traverse(graph, node, dict_map)
if dict_map[stack[-1]] != True:
dict_map[stack[-1]] = True
print(stack.pop())
|
4dc6ecdfe3063f3015801cf13472f7f77d742f0a | Denton044/Machine-Learning | /PythonPractice/python-programming-beginner/Python Basics-1.py | 2,217 | 4.5625 | 5 | ## 1. Programming And Data Science ##
england = 135
india = 124
united_states = 134
china = 123
## 2. Display Values Using The Print Function ##
china = 123
india = 124
united_states = 134
print (china)
print (united_states)
print (india)
## 3. Data Types ##
china_name = "China"
china_rounded = 123
china_exact = 122.5
print(china_name, china_rounded, china_exact)
## 4. The Type Function ##
china_name = "China"
china_exact = 122.5
print (type(china_exact))
## 5. Converting Types ##
china_rounded = 123
int_to_str = str(china_rounded)
str_to_int = int(int_to_str)
## 6. Comments ##
#temperature in China
china = 123
#temperature in India
india = 124
#temperature in United__States
united_states = 134
## 7. Arithmetic Operators ##
china_plus_10 = china + 10
us_times_100 = united_states *100
print (china_plus_10, us_times_100)
## 8. Order Of Operations ##
china = 123
india = 124
united_states = 134
china_celsius = (china - 32) * 0.56
india_celsius = (india - 32) * 0.56
us_celsius = (united_states -32) *0.56
## 10. Using A List To Store Multiple Values ##
countries = []
temperatures = []
countries.append('China')
countries.append('India')
countries.append('United States')
temperatures.append(122.5)
temperatures.append(124.0)
temperatures.append(134.1)
print (countries, temperatures)
## 11. Creating Lists With Values ##
temps = ['China', 122.5, 'India', 124.0, 'United States', 134.1]
## 12. Accessing Elements In A List ##
countries = []
temperatures = []
countries.append("China")
countries.append("India")
countries.append("United States")
temperatures.append(122.5)
temperatures.append(124.0)
temperatures.append(134.1)
# Add your code here.
china = countries[0]
china_temperature = temperatures[0]
## 13. Retrieving The Length Of A List ##
countries = ["China", "India", "United States", "Indonesia", "Brazil", "Pakistan"]
temperatures = [122.5, 124.0, 134.1, 103.1, 112.5, 128.3]
two_sum = len(countries) + len(temperatures)
## 14. Slicing Lists ##
countries = ["China", "India", "United States", "Indonesia", "Brazil", "Pakistan"]
temperatures = [122.5, 124.0, 134.1, 103.1, 112.5, 128.3]
countries_slice = countries[1:4]
temperatures_slice = temperatures[-3:] |
342201ebee1eea4fcf8e381dfbdba93caae0af61 | Denton044/Machine-Learning | /PythonPractice/data-analysis-intermediate/Pandas Internals_ Series-145.py | 1,021 | 3.734375 | 4 | ## 1. Data Structures ##
import pandas as pd
fandango = pd.read_csv("fandango_score_comparison.csv")
fandango.head()
## 2. Integer Indexes ##
fandango = pd.read_csv('fandango_score_comparison.csv')
series_film = fandango['FILM']
print(series_film[0:5])
series_rt = fandango['RottenTomatoes']
print(series_rt[:5])
## 3. Custom Indexes ##
# Import the Series object from pandas
from pandas import Series
film_names = series_film.values
rt_scores = series_rt.values
series_custom = pandas.Series(data = rt_scores, index= film_names)
print(series_custom)
## 4. Integer Index Preservation ##
series_custom = Series(rt_scores , index=film_names)
series_custom[['Minions (2015)', 'Leviathan (2014)']]
fiveten = series_custom[5:11]
print(fiveten)
## 5. Reindexing ##
original_index = series_custom.index
sorted_index = sorted(original_index)
sorted_by_index = series_custom.reindex(sorted_index)
## 6. Sorting ##
sc2 = series_custom.sort_index()
sc3 = series_custom.sort_values()
print(sc2[0:10])
print(sc3[0:10]) |
572fe2d092fa65fb3beec45c1ed467e65529998b | ChandanShastri/PGPTP | /Tools/separateByYear.py | 660 | 3.5 | 4 | #!/usr/bin/env python
'''
Created on Oct 13, 2014
@author: waldo
'''
import sys
import os
import csv
def makeOutFile(outdict, term, fname, header):
outfile = csv.writer(open(term + '/' + fname, 'w'))
outdict[term] = outfile
outfile.writerow(header)
if __name__ == '__main__':
if len(sys.argv) < 1:
print 'Usage: separateByYear csvFile'
sys.exit(1)
fname = sys.argv[1]
fin = csv.reader(open(fname, 'rU'))
header = fin.next()
outdict = {}
for l in fin:
term = l[1]
if term not in outdict:
makeOutFile(outdict, term, fname, header)
outdict[term].writerow(l) |
6fa32bc3efeb0a908468e6f9cec210846cd69085 | yoli202/cursopython | /ejerciciosBasicos/main3.py | 396 | 4.40625 | 4 | '''
Escribir un programa que pregunte el nombre del usuario en la consola
y después de que el usuario lo introduzca muestre por pantalla <NOMBRE>
tiene <n> letras, donde <NOMBRE> es el nombre de usuario en mayúsculas y
<n> es el número de letras que tienen el nombre.
'''
name = input(" Introduce tu nombre: ")
print(name.upper() + " Tu nombre tiene " + str(len(name)) + (" letras")) |
0606fc6b61277a99f4c5146df4784e2ae5f70e50 | VadimSerov/Zarina2 | /Python и C++/Untitled-3.py | 269 | 3.65625 | 4 | import random
random.seed()
n=int(input("введите разменость массива "))
a=[]
for i in range(0,n) :
a.append(random.randint(0,100))
print(a)
k=int(input("введите целое число для проверки "))
aver=sum(a)
print(aver) |
0c729c03c7a3ed808fe246ae5df3494e6857ac5b | adelbast/Space-Conquest-3012 | /src/Tile/Map.py | 1,144 | 3.65625 | 4 | __author__ = "Arnaud Girardin &Alexandre Laplante-Turpin& Antoine Delbast"
import csv
class Map:
def __init__(self, path):
self.map = []
self.startingPoint =[]
self.numRow = 0
self.numCol = 0
self.generateMapFromFile(path)
def generateMapFromFile(self, path):
#Lecture de la map dans le fichier csv
with open(path, 'r') as f:
reader = csv.reader(f)
for row in reader:
self.numCol = len(row)
self.map.append(row)
self.numRow +=1
self.startingPoint.append((4,4))
self.startingPoint.append((self.numCol-4,self.numRow-4))
self.startingPoint.append((self.numCol-4,int((self.numRow/2)-4)))
self.startingPoint.append((self.numCol-4,4))
self.startingPoint.append((int((self.numCol/2)-5),self.numRow-4))
self.startingPoint.append((52,52))
self.startingPoint.append((int(self.numCol/2-4),4))
self.startingPoint.append((4,self.numRow-9))
self.startingPoint.append((15,int((self.numRow/2)+3)))
|
e34a8e5ccc558f833d4c50fdc538d1d1cec51616 | rhrhdhdh1/rhrhdhdh1 | /moving/이동하기.py | 959 | 3.59375 | 4 | import moveclass
lo = moveclass.Point2D(100, 100)
lo1 = moveclass.Point2D(0, 0)
atype = 2
btype = 3
Time = 0
T = 0
T2 = 0
unit0 = moveclass.Unit(lo, atype)
p = lo
unit2 = moveclass.Unit(lo1, btype)
p1 = lo1
lenge1 = moveclass.lenge1(lo, lo1)
while True:
Time += 1
print()
T += 1
T2 += 1
ctl = input('a. 0번유닛 조작 b. 1번유닛 조작 c. 둘다 조작 엔터는 통과 ')
if ctl == 'a' or ctl == 'c':
T = 0
x = int(input('x좌표'))
y = int(input('y좌표'))
p = moveclass.Point2D(x, y)
t = unit0.time(p)
if ctl == 'b' or ctl == 'c':
T2 = 0
x1= int(input('x좌표'))
y1 = int(input('y좌표'))
p1 = moveclass.Point2D(x1, y1)
t1 = unit2.time(p1)
print('0번 유닛 위치는')
unit0.move1(p, T)
print('2번유닛 위치는')
unit2.move1(p1, T2)
c = lenge1.lenge()
print(c)
|
abd16a8c5cd1d032134cdb3afd3a1cb9d8153da1 | rajat1994/LeetCode-PythonSolns | /Topics/Recursion/permutation_with_case_change.py | 324 | 3.8125 | 4 | def permutation_with_case_change (ip,op):
if ip == "":
print(op)
return
op1 = op
op2 = op
op1 = op1 + ip[0]
op2 = op2 + ip[0].upper()
ip = ip[1:]
permutation_with_case_change(ip,op1)
permutation_with_case_change(ip,op2)
permutation_with_case_change("ab", "")
|
c1fb5165232637d91f4ca68a696f9aaa850b87cd | rajat1994/LeetCode-PythonSolns | /Arrays/queue.py | 488 | 3.6875 | 4 | from collections import deque
class Queue:
def __init__ (self):
self.buffer = deque()
def enqueue(self,data):
return self.buffer.appendleft(data)
def dequeue(self):
return self.buffer.pop()
def isempty(self):
return len(self.buffer) == 0
def length(self):
return len(self.buffer)
Q = Queue()
Q.enqueue(2)
Q.enqueue(3)
Q.enqueue(4)
Q.enqueue(6)
print(Q.length())
print(Q.dequeue())
print(Q.length())
print(Q.isempty()) |
471050a9fce4fae1fde774b2be629d428499a8ae | lsieber/BestListData | /src/io/exportCSV.py | 349 | 3.5 | 4 | import csv
def exportCSV(table, filename):
with open(filename, mode='w', newline='', encoding='utf-8') as file:
test_writer = csv.writer(file, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for row in table:
#row.append(" ")
test_writer.writerow(row)
print("exported file" + filename) |
31a698480e214a38bf5954b16f0589f9516038c3 | annaprzybysz/projektFUW | /sprspr.py | 545 | 3.796875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.animation import FuncAnimation
# arr = []
# for i in range(100):
# c = np.random.rand(10, 10)
# arr.append(c)
# plt.imshow(arr[45])
# plt.show()
def data_gen():
while True:
yield np.random.rand(10)
fig, ax = plt.subplots()
line, = ax.plot(np.random.rand(10))
ax.set_ylim('1', '2', '3')
def update(data):
line.set_ydata(data)
return line,
ani = FuncAnimation(fig, update, data_gen, interval=100)
plt.show() |
5901b1fcabefe69b1ecc24f2e15ffe2d3daed18b | MaurizioAlt/ProgrammingLanguages | /Python/sample.py | 454 | 4.125 | 4 |
#input
name = input("What is your name? ")
age = input("What is your age? ")
city = input("What is your city ")
enjoy = input("What do you enjoy? ")
print("Hello " + name + ". Your age is " + age )
print("You live in " + city)
print("And you enjoy " + enjoy)
#string stuff
text = "Who dis? "
print(text*3)
#or for lists
listname.reverse
#reverse
print(text[::-1])
len(text)
#if condition:
# code...
#else if condition:
# code...
#else:
# code...
|
a3d36d9a9c98a858ed5b26cb03cb917c0e0889b3 | soni-aditya/pan-aadhar-ocr | /pan.py | 2,659 | 3.609375 | 4 | import re
import string
from processing import clean_text
def clean_gibbersh(arr):
'''
From an input array of OCR text, removes the gibberish and noise, such as,
symbols and empty strings
'''
arr = [x for x in arr if len(x) > 3]
t = 0
d = 0
for i in range(len(arr)):
if "india" in arr[i].lower():
d = i
if "income" in arr[i].lower() or "tax" in arr[i].lower():
t = i
del arr[:max([d, t])+1]
print("d= ", d, t)
print(arr)
for i in range(len(arr)):
arr[i] = arr[i].replace("!", "i")
arr[i] = clean_text(arr[i])
temp = list(arr[i])
for j in range(len(temp)):
#if not ((j >= "A" and j <= "Z") or j == " "):
# arr[i].replace(j, "")
if (temp[j] in string.punctuation) and (temp[j] not in ",/-" ):
#arr[i].replace(j, "")
temp[j] = ""
arr[i] = "".join(temp).strip()
return (arr)
def extract_pan(text_in):
'''
From the array of text, searches for the PAN number using regex
'''
try:
pan_regex = r"[A-Z]{5}[0-9]{4}[A-Z]{1}"
# pan = re.compile(pan_regex)
for i in text_in:
# print(i)
pan = re.findall(pan_regex, i)
if len(pan) > 0:
return (pan[0])
except:
print("Error in PAN Number Extraction")
def extract_dob(text_in):
'''
From the array of text, searches for the Data of Birth using regex
'''
try:
# pan = re.compile(pan_regex)
dob_regex = r"\d{1,2}\/\d{1,2}\/\d{4}"
for i in text_in:
# print(i)
dob = re.findall(dob_regex, i)
if len(dob) > 0:
return (dob[0])
except:
print("Error in DOB extraction")
def check_names(arr):
'''
From the array of text, searches for the person names using specific pattern
TODO: Improvements
'''
names = []
for i in arr:
flag = False
for j in i:
if not ((j >= "A" and j <= "Z") or j == " "):
flag = True
break
if not flag and i != "":
names.append(i)
return (names)
def get_labels_from_pan(text_in):
imp = {}
text_in = clean_gibbersh(text_in)
# print(text_in)
imp["PAN No"] = extract_pan(text_in)
imp["Date Of Birth"] = extract_dob(text_in)
names = check_names(text_in)
imp["Name"] = names[0]
try:
imp["Father's Name"] = names[1]
except:
pass
return(imp)
|
9881a1a5d57b81528b0607185ece6a930817c8ac | EastTown2000/ITGK | /Øvinger/Øving 6/lett_og_blandet.py | 352 | 3.78125 | 4 | def is_six_at_edge(liste):
return liste[0] == 6 or liste[-1] == 6
print(is_six_at_edge([1,2,3,4,5,6]))
print(is_six_at_edge([1,2,3,4,5,6,7]))
def average(liste):
return sum(liste) / len(liste)
print(average([1,3,5,7,9,11]))
def median(liste):
liste.sort()
indeks = int(len(liste) / 2)
return liste[indeks]
print(median([1,2,4,5,7,9,10])) |
e9880136681f934261cfbb6cf1ddb5bbfb541c8e | EastTown2000/ITGK | /Øvinger/Øving 6/generelt_om_lister.py | 227 | 3.59375 | 4 | my_first_list = [1, 2, 3, 4, 5, 6]
print(my_first_list)
print(len(my_first_list))
my_first_list[-2] = 'pluss'
print(my_first_list)
my_second_list = my_first_list[-3:]
print(my_second_list)
print(my_second_list, 'er lik 10') |
8ec16f85a9d50dd2e38f76ba3316d2191e8e8efd | EastTown2000/ITGK | /Øvinger/Øving 3/Alternerendesum_a.py | 328 | 3.53125 | 4 | def altnum(n):
"""
gir en liste(int) av funksjonen i oppgaven
"""
a = []
for i in range(1, n + 1):
if i%2 == 0:
s = - i**2
else:
s = i**2
a.append(s)
return a
a = int(input('Hvilket tall i tall-serien vil du ha summen av: '))
print(sum(altnum(a))) |
d0b440603d159f4791f9965325e71827b18e55da | ibarchakov/Stepik---Algorithms.-Methods | /heapq first try.py | 777 | 3.9375 | 4 | """The first line contains the number of operations 1≤n≤10**5.
Each of next n lines specifies the operations one of the next types:
Insert x, where 0≤x≤10**9 — integer;
ExtractMax.
The first operation adds x to a heap, the second — extracts the maximum number and outputs it.
Sample Input:
6
Insert 200
Insert 10
ExtractMax
Insert 5
Insert 500
ExtractMax
Sample Output:
200
500
"""
import heapq
h = []
max_elems = []
n = int(input())
for _ in range(n):
command = input()
if command.startswith('Insert'):
command = command.split(' ')
elem = int(command[1])
heapq.heappush(h, -elem)
else:
max_elems.append(-h[0])
heapq.heappop(h)
for _ in max_elems:
print(_) |
8ffb8acf399b2dc836c6b390072eece66c1e51c4 | MDRCS/pyregex | /re-basics.py | 2,048 | 3.921875 | 4 | import re
"""
Bytecode is an intermediary language. It's the output generated by languages,
which will be later interpreted by an interpreter. The Java bytecode that is interpreted by JVM
is probably the best known example.
"""
# RegexObject: It is also known as Pattern Object. It represents a compiled regular expression
RegexObject = re.compile(r'\bfoo\b')
MatchObject = RegexObject.match("foo bar")
print(MatchObject)
"""
You can always use re.purge to clear the cache but this is a tradeoff with performance.
Using compiled patterns allows you to have a fine-grained control of the memory consumption
because you can decide when to purge them.
"""
re.purge()
RegexObject = re.compile(r'\w+')
MatchObject = RegexObject.findall("hello world")
print(MatchObject)
RegexObject = re.compile(r'a*')
MatchObject = RegexObject.findall("aba") # match -> a // findall -> ['a', '', 'a', '']
print(MatchObject)
# The maxsplit parameter specifies how many splits can be done at maximum and returns the remaining part in the result:
RegexObject = re.compile(r"\W")
MatchObject = RegexObject.split("Beautiful is better than ugly", 3)
print(MatchObject)
# split
RegexObject = re.compile(r"(-)")
MatchObject = RegexObject.split("hello-world")
print(MatchObject)
# replace
RegexObject = re.compile(r"[0-9]+")
MatchObject = RegexObject.sub('-', "hello0-world13")
print(MatchObject)
# also
res = re.sub('00', "--", "hello00000")
print(res)
def normalize_orders(MatchObject):
print(MatchObject.group(1))
if MatchObject.group(1) == '-':
return "A"
else:
return "B"
"""
As mentioned previously, for each matched pattern the normalize_orders function is called.
So, if the first matched group is a –, then we return an A; in any other case, we return B.
"""
# matchobject -> '([-|A-Z])'
res = re.sub('([-|A-Z])', normalize_orders, '-1234⇢A193⇢ B123')
print(res)
# groups
pattern = re.compile("(\w+) (\w+)")
match = pattern.search("Hello⇢World")
print(match.groups())
|
a588eb9088de56096f90119b4193087ce7ee6a58 | setsunaNANA/pythonhomework | /__init__.py | 663 | 4.1875 | 4 | import turtle
def tree(n,degree):
# 设置出递归条件
if n<=1and degree<=10:
return
#首先让画笔向当前指向方向画n的距离
turtle.forward(n)
# 画笔向左转20度
turtle.right(degree)
#进入递归 把画n的距离缩短一半 同时再缩小转向角度
tree(n/2, degree/1.3)
# 出上层递归 转两倍角度把“头”转正
turtle.left(2*degree)
# 对左边做相同操作
tree(n / 2, degree / 1.3)
turtle.right(degree)
# 退出该层递归后画原来长度
turtle.backward(n)
if __name__ == '__main__':
# 先把画笔角度转正
turtle.left(90)
tree(100, 60) |
a91bad82a5c65180440b412be2b3d9e6b9c661e0 | kshm2483/ssafy_TIL | /Algori/AD/B/B6_marble1.py | 261 | 3.578125 | 4 | def DFS(n, k):
if n == k:
for i in range(N):
print(marble[i]*(i+1), end=' ')
print()
return
else:
marble[k] = 1
DFS(n, k+1)
marble[k] = 0
DFS(n, k+1)
N = 3
marble = [1, 2, 3]
DFS(3, 0) |
f01c35ee2dad4a6e1908364f0133a90d00c8182e | ashish-mj/Data_Science | /Pandas.py | 4,504 | 3.546875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 24 12:11:42 2021
@author: ashish
"""
import pandas as pd
########################################################Series
a=["a","B","c","D","e"]
print(pd.Series())
print(pd.Series(a))
x=pd.Series(a,index=[100,101,102,103,104])
print(x)
data={'a':200,'b':201,'c':202}
print(pd.Series(data))
print(pd.Series(data,index=["b","c","a"]))
print(pd.Series(5,index=[1,2,3,4,5]))
data={'a':200,'b':201,'c':202}
c = pd.Series(data)
print(c[0])
print(c["a"])
c['d']=203
print(c)
########################################################Dataframe
data=[1,2,3,4,5,6]
print(pd.DataFrame())
print(pd.DataFrame(data))
data = [[1,"Ashish",20,50000],[2,"Akshay",26,30000],[3,"Rajeev",50,150000]]
print(pd.DataFrame(data,columns=["ID","Name","Age","Salary"],dtype=float))
data={"Name":["Ashish","Girish","Pavan"],"Age":[21,24,28]}
print(pd.DataFrame(data,index=["rank1","rank2","rank3"]))
data = [[1,"Ashish",20,50000],[2,"Akshay",26,30000],[3,"Rajeev",50,150000]]
table = pd.DataFrame(data,columns=["ID","Name","Age","Salary"],dtype=float)
print(table)
print("Name : "+str(table["Name"]))
print(table.iloc[1,2])
print(table["Age"])
table["Dept"]=['IS','CS',"EC"]
print(table)
t1=table.append({"ID":4,"Name":"Pavan","Age":44,"Salary":20000,"Dept":"IS"},ignore_index = True)
temp = pd.Series([5,"Ajay",30,40000,"EE"],t1.columns)
t1=t1.append(temp,ignore_index = True)
print(t1)
t1.pop("Dept")
print(t1)
t1=t1.drop(t1.index[0:3])
print(t1)
df = pd.DataFrame([[1, 2], [3, 4]], columns = ['a','b'])
df2 = pd.DataFrame([[5, 6], [7, 8]], columns = ['a','b'])
df = df.append(df2,ignore_index=True)
print(df)
df = df.drop(0)
print(df)
############################################Practice Dataframes
data = [[1,"Ashish","MI"],[2,"Dhoni","CSK"],[3,"Virat","RCB"],[4,"Warner","SRH"],[5,"Rahul","KP"],[6,"Dinesh","KKR"],[7,"Iyer","DC"],[8,"Samson","RR"]]
data = pd.DataFrame(data,columns=["ID","Player_Name","Team"])
print(data)
data["Salary"]="$2000"
print(data)
titles ={"MI":5,"CSK":3,"KKR":2,"SRH":2,"RR":1,"RCB":0,"DC":0,"KP":0}
data["Titles"]=data["Team"].map(titles)
print(data)
net_worth=[]
for i in data["Titles"]:
if i==5:
net_worth.append("$1200000")
elif i==3:
net_worth.append("$900000")
elif i==2:
net_worth.append("$500000")
else:
net_worth.append("$350000")
data["Net_worth"]=net_worth
print(data)
data.loc[data["Titles"]>=3,"Salary"]="$4000"
print(data)
del data["ID"]
print(data)
print(data[:4])
print(data.loc[data["Player_Name"]!=""])
temp = pd.Series(["Smith","RPSG","$2000",0,"$35000"],data.columns)
data=data.append(temp,ignore_index=True)
print(data)
data=data.drop(8)
print(data)
data=data.drop([1,4])
############################################Basic Functionality
data = pd.Series([1,2,3,4,5,6,7,8,9])
data1 = [[1,"Ashish","MI"],[2,"Dhoni","CSK"],[3,"Virat","RCB"],[4,"Warner","SRH"],[5,"Rahul","KP"],[6,"Dinesh","KKR"],[7,"Iyer","DC"],[8,"Samson","RR"]]
data1 = pd.DataFrame(data1,columns=["ID","Player_Name","Team"])
print(data)
print(data1)
print(data.axes)
print(data1.axes)
print(data.dtype)
print(data1.dtypes) #dtypes for dataframes
print(data.empty)
print(data1.empty)
print(data.head(4))
print(data1.head(4))
print(data.tail(7))
print(data1.tail(7))
print(data.values)
print(data1.values)
print(data1.T)
############################################Statistics Functions
data = pd.Series([1,2,3,4,5,6,7,8,9])
data1 = [[1,"Ashish","MI",5],[2,"Dhoni","CSK",3],[3,"Virat","RCB",0],[4,"Warner","SRH",2],[5,"Rahul","KP",0],[6,"Dinesh","KKR",2],[7,"Iyer","DC",0],[8,"Samson","RR",1]]
data1 = pd.DataFrame(data1,columns=["ID","Player_Name","Team","Titles"])
print(data)
print(data1)
print(data.sum())
print(data1.sum(axis=1))
print(data.mean())
print(data1.mean())
print(data.describe())
print(data1.describe(include=["number"]))
print(data1.describe(include=["object"]))
print(data1.describe(include="all"))
############################################Additional operations
data = pd.Series([1,2,3,4,5,6,7,8,9])
data1 = [[1,"Ashish","MI",5],[2,"Dhoni","CSK",3],[3,"Virat","RCB",0],[4,"Warner","SRH",2],[5,"Rahul","KP",0],[6,"Dinesh","KKR",2],[7,"Iyer","DC",0],[8,"Samson","RR",1]]
data1 = pd.DataFrame(data1,columns=["ID","Player_Name","Team","Titles"])
for i in data1.values:
print("_______________")
print(i[1])
for key,value in data1.iteritems():
print(str(key)+" "+str(value))
print(data1.sort_values(by="Titles")) |
850c9b5747a330256c90c047f0ef1f601b14af8c | sjs521/BIS-397-497-SomanSebastian | /assignment 3/assignment 3 - exercise 5.15.py | 998 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 8 17:08:03 2020
@author: sebastian_soman
"""
from operator import itemgetter
invoice_tuples = [(83, 'Electric sander', 7, 57.98),
(24, 'Power saw', 18, 99.99),
(7, 'Sledge Hammer', 11, 21.50),
(77, 'Hammer', 76, 11.99),
(39, 'Jig saw', 3, 79.50)]
# part a:
print(sorted(invoice_tuples, key=itemgetter(1)))
# part b:
print(sorted(invoice_tuples, key=itemgetter(3)))
# part c:
c_tuple = ()
for item in invoice_tuples:
y = ((item[1]), item[2])
c_tuple = c_tuple + (y,)
print(sorted(c_tuple,key=itemgetter(1)))
# part d
d_tuple = ()
for item in invoice_tuples:
a = ((item[1]),item[2]*item[3])
d_tuple = d_tuple + (a,)
print(sorted(d_tuple,key=itemgetter(1)))
# part e
for item in d_tuple:
if item[1] >= 200 and item[1] <= 500:
print(item)
# part f
total = 0
for item in d_tuple:
total += item[1]
print(total)
|
0cec6e966c788756c9abdc7c6381bbc2fc22c475 | sjs521/BIS-397-497-SomanSebastian | /assignment 4/assignment 4 - exercise 7.3.py | 278 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 15 18:52:19 2020
@author: sebastian_soman
"""
import numpy as np
numbers = np.arange(2,19,2).reshape(3,3)
numbers
numbers2 = np.arange(9,0,-1).reshape(3,3)
numbers2
product = numbers * numbers2
product
|
b4cea7cbeda845b7df310f85ecc1fee04284404e | belledon/hdf5_dataset | /h5data/hdf5.py | 3,007 | 3.640625 | 4 | """ HDF5 Creator.
This script converts an arbitrary directory to an hdf5 file.
Classes:
Folder
File
"""
import os
import h5py
import argparse
import numpy as np
class Folder:
"""Group analog of hdf5 structure.
Represents a directory as a hdf5 group.
The source directory's name is the name of the group.
"""
def __init__(self, origin, handle):
""" Creates an instance of `Folder`
Parameters:
origin (str): The directory to search.
handle (h5py.File): The file object associate with the dataset.
"""
if not isinstance(handle, h5py.File):
raise TypeError('handle must be `h5py.File`')
root = os.path.basename(handle.filename)
root = os.path.splitext(root)[0]
bridge = origin.split(root)[-1]
contents = os.listdir(origin)
for element in contents:
path = os.path.join(origin, element)
if os.path.isfile(path):
try:
f_obj = File(path, handle)
except ValueError as e:
print("File {} could not be added because of:\n {}".format(
path, e))
elif os.path.isdir(path):
g_path = os.path.join(handle.name, bridge, element)
group = handle.create_group(g_path)
Folder(path, handle)
class File:
"""Dataset analog of hdf5 structure.
Consists of a dataset containing the source files contents as bytes.
The name of the source file is the name of the dataset.
"""
def __init__(self, source, handle):
""" Creates an instance of `File`
Parameters:
source (str): The file to load.
handle (h5py.File): The file object associate with the dataset.
"""
root = os.path.basename(handle.filename)
root = os.path.splitext(root)[0]
bridge = source.split(root)[-1]
path = os.path.join(handle.name, bridge)
with open(source, 'rb') as d:
raw = d.read()
data = np.void(raw)
handle.create_dataset(path, data=data)
def main():
parser = argparse.ArgumentParser(
description = "Converts directorty tree to hdf5"
)
parser.add_argument("root", type =str, help = "Root path")
parser.add_argument("--out", "-o", type = str, default = os.getcwd(),
help = "Path to save dataset. Default is CWD")
args = parser.parse_args()
if not os.path.isdir(args.root):
raise ValueError("{} is not a valid path".format(args.root))
out = os.path.join(args.out, os.path.basename(args.root) + '.hdf5')
if os.path.exists(out):
raise ValueError('{} already exists'.format(out))
print("Save destination: {}".format(out))
print("Beginning HDF5 conversion")
with h5py.File(out, "w") as f:
Folder(args.root, f)
print("HDF5 conversion complete")
if __name__ == '__main__':
main()
|
2250c751a45b78eff1e2807b30f681161bb5f245 | claudiama09/python_learning_note | /turtle/main.py | 945 | 3.953125 | 4 | from turtle import Turtle, Screen
my_turtle = Turtle()
screen = Screen()
# W = Forward
# S = Backward
# A = Counter-Clockwise
# D = Clockwise
# C = Clear Drawing
#---------------------------------------------------
# def move_forward():
# my_turtle.forward(10)
#
# def move_backward():
# my_turtle.backward(10)
#
# def turn_left():
# new_heading = my_turtle.heading() + 10
# my_turtle.setheading(new_heading)
#
# def turn_right():
# new_heading = my_turtle.heading() - 10
# my_turtle.setheading(new_heading)
#
# def clear_screen():
# my_turtle.clear()
# my_turtle.penup()
# my_turtle.home()
# my_turtle.pendown()
#
# screen.listen()
# screen.onkey(move_forward, "w")
# screen.onkey(move_backward, "s")
# screen.onkey(turn_left, "a")
# screen.onkey(turn_right, "d")
# screen.onkey(clear_screen, "c")
# screen.exitonclick()
#---------------------------------------------------
screen.setup(500, 400)
|
e91613869c1751c8bb3a0a0abaeb1dfb9cafa5c3 | MingCai06/leetcode | /7-ReverseInterger.py | 1,118 | 4.21875 | 4 | """
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
"""
class Solution:
def reverse(self, x: int) -> int:
r_x = ''
if x > -10 and x<10:
return x
elif x > pow(2,31)-1 or x < -pow(2,31):
return 0
else:
str_x =str(x)
if x>0:
r_x = r_x
elif x<0:
str_x = str_x[1:]
r_x += '-'
for i in reversed(range(len(str_x))):
if i== len(str_x)-1 and str_x[i]==0:
r_x = r_x
else:
r_x = r_x + str_x[i]
if int(r_x)> pow(2,31)-1 or int(r_x) < -pow(2,31):
return 0
else:
return int(r_x)
|
169aab304dfd600a169822c65e448b7e4a4abeb3 | simgroenewald/Variables | /Details.py | 341 | 4.21875 | 4 | # Compulsory Task 2
name = input("Enter your name:")
age = input ("Enter your age:")
house_number = input ("Enter the number of your house:")
street_name = input("Enter the name of the street:")
print("This is " + name + " he/she is " + age + " years old and lives at house number " + house_number + " on " + street_name +" street.")
|
56cd6db7536a1d79bed71596980631462d0c6c64 | destinyc/leet-code | /leetcode/数字在排序数组中出现次数.py | 1,509 | 3.671875 | 4 |
def findFristIndex(List, num): #这个函数用二分查找来找这个数的起始索引
if len(List) == 0:
return 0
begin, end = 0, len(List) - 1
while begin <= end:
mid = (end + begin) // 2
if List[mid] < num:
begin = mid + 1
elif List[mid] > num:
end = mid - 1
else:
if mid == 0 or List[mid] != List[mid - 1]: #这个判定条件是关键
return mid
else:
end = mid - 1
return -1 #没有找到这个数
def findLastIndex(List, num): #同样,这个函数找结尾索引
if len(List) == 0:
return 0
begin, end = 0, len(List) - 1
while begin <= end:
mid = (end + begin) // 2
if List[mid] < num:
begin = mid + 1
elif List[mid] > num:
end = mid - 1
else:
if mid == len(List) - 1 or List[mid] != List[mid + 1]: #注意判定条件
return mid
else:
begin = mid + 1
return -1 #并没有找到这个数
def count(List, num):
if len(List) == 0:
return 0
begin_index = findFristIndex(List, num)
end_index = findLastIndex(List, num)
if begin_index != -1 and end_index != -1:
return end_index - begin_index + 1
return 0 #没有找到这个数
if __name__ == '__main__':
List = [3,6,6,6,6,6,6,6,7,8,9]
num = 10
print(count(List, num))
|
9b0e0cd3ca37622fb85d312dd7e5e2efe12023de | destinyc/leet-code | /leetcode/螺旋矩阵.py | 1,368 | 3.828125 | 4 |
def _bianli(List, rows, columns, index): #这个函数根据index位置遍历这一圈
#正向先走第一行
output = []
for i in range(index, columns - index):
output.append(List[index][i])
#当前要遍历的一圈大于等于两行时才有向下的遍历
if rows - index - 1 > index:
for i in range(index + 1, rows - index):
output.append(List[i][columns - index - 1])
#同样当这一圈大于等于两列时才存在回去的行
if columns - index - 1 > index:
for i in range(columns - index - 2, index - 1, -1):
output.append(List[columns - index - 1][i])
#当这一圈大于等于 三行 时才存在向上的遍历
if rows - index - 2 > index:
for i in range(rows - index - 2, index, -1):
output.append(List[i][index])
return output
def bianli(List):
if List == []:
return []
rows, columns = len(List), len(List[0])
output = []
index = 0 #这个索引对应第几个左上角,我们从这个左上角开始走一圈
while index * 2 < rows and index * 2 < columns: #开始一圈一圈的遍历
output.extend(_bianli(List, rows, columns, index))
index += 1
return output
if __name__ == '__main__':
List = [[1,2,3], [4,5,6],[7,8,9]]
print(bianli(List)) |
ce72f53c88a6b57659b77c4cf2dee1bff7378c70 | destinyc/leet-code | /leetcode/最接近的三数之和.py | 902 | 3.828125 | 4 |
#列表中最接近target的三个数之和,跟三数之和一个意思
def threeSumClosest(nums, target):
nums.sort()
output = nums[0]+nums[1]+nums[2]
min_diff = abs(target - (nums[0] + nums[1] + nums[2]))
for i in range(len(nums)):
left, right = i + 1, len(nums) - 1
while left < right:
diff = abs(target - (nums[i] + nums[left] + nums[right]))
if diff < min_diff:
min_diff = diff
output = nums[i] + nums[left] + nums[right]
if target - (nums[i] + nums[left] + nums[right]) == 0:
return nums[i] + nums[left] + nums[right]
elif target - (nums[i] + nums[left] + nums[right]) > 0:
left += 1
else:
right -= 1
return output
if __name__ == '__main__':
List = [0,2,1,-3]
num = 1
print(threeSumClosest(List, num))
|
4b38ad8416a5cdf3fb3820065674c94ce6307970 | destinyc/leet-code | /leetcode/二叉树所有左叶节点之和.py | 355 | 3.640625 | 4 |
#看到二叉树就先思考一下递归
def _sum(root):
if root is None:
return 0
if root.left and root.left.left is None and root.left.right is None:
return root.left.val + _sum(root.right) #是左叶节点,就把它的值加上右子树的左叶节点
else:
return _sum(root.left) + _sum(root.right)
|
52723de95d7497fe45003144be92b5971c325fa9 | destinyc/leet-code | /leetcode/最长回文子串.py | 468 | 3.859375 | 4 |
#暴力查找法:容易超出时间限制
def search(S):
if S == S[::-1]:
return S
output = ''
for left in range(len(S)):
for right in range(left, len(S)):
if S[left : right + 1] == S[left : right + 1][::-1] and len(S[left : right + 1]) > len(output):
output = S[left : right + 1]
return output
#马拉车算法,专门用来做这道题的算法
def _search(S):
if S == S[::-1]:
return S |
46b52ac9272886aabbe1a85c239d0ae342e8c7f9 | destinyc/leet-code | /leetcode/第n个丑数.py | 1,799 | 3.890625 | 4 |
#先写一个简单的问题,判断一个数是否是丑数(只包含因子2,3,5)leetcode263
def isuglynum(num):
if num == 1:
return True
if num == 0:
return False
while num % 2 == 0:
num = num // 2
while num % 3 == 0:
num = num // 3
while num % 5 == 0:
num = num // 5
if num == 1:
return True
return False
#找第n个丑数 leetcode264
#基本思路,我们从小到大只找丑数
def UglyNum(n):
if n == 1:
return 1
current_num = [1] * n #因为有n个丑数,我们先初始化一个数组
next_index = 1 #这是我们下一个要找的丑数
Multiply2_index = 0
Multiply3_index = 0
Multiply5_index = 0 #我们时刻维护三个索引,这三个索引对应的是乘上相应因子后大于当前丑数的那个索引
while next_index < n:
current_num[next_index] = min(current_num[Multiply2_index] * 2, #这三个数都是刚好比上一个丑数打,但我们要最小的那个
current_num[Multiply3_index] * 3,
current_num[Multiply5_index] * 5)
#现在由于我们又找到了一个最新的最大丑数,所以相应的也要更新这三个索引的位置
while current_num[Multiply2_index] * 2 <= current_num[next_index]:
Multiply2_index += 1
while current_num[Multiply3_index] * 3 <= current_num[next_index]:
Multiply3_index += 1
while current_num[Multiply5_index] * 5 <= current_num[next_index]:
Multiply5_index += 1
next_index += 1
return current_num[-1]
if __name__ == '__main__':
num = 10
print(UglyNum(num))
|
8de43bac6026bbb9158f1066f2d201695b9ee3e4 | destinyc/leet-code | /leetcode/两数之和三数之和.py | 3,749 | 3.5 | 4 |
#两数之和,返回两个数的索引,使用字典做
def find(List, add):
if List == []:
return None
dic = {}
for index, num in enumerate(List):
diff = add - num
if diff in dic:
return [dic[diff], index]
dic[num] = index
#三数之和
def _find(List, add): #注意数组中可以存在重复元素
List.sort() #毫无疑问,先排序
if List == []:
return None
output = []
for i in range(len(List)): #先固定住一个数,然后找另外两个数
if i == 0 or List[i] > List[i - 1]: #可以跳过重复元素
left = i + 1
right = len(List) - 1 #维护另外两个数的指针
while left < right:
current_add = List[i] + List[left] + List[right]
if current_add == add:
output.append([List[i], List[left], List[right]])
left += 1
right -= 1 #因为答案不能重复,所以这两个数不能再用了,要移动
while left < right and List[right] == List[right + 1]: #跳过重复的答案
right -= 1
while left < right and List[left] == List[left - 1]:
left += 1
elif current_add > add :
right -= 1
while left < right and List[right] == List[right + 1]: #跳过重复的非答案
right -= 1
else:
left += 1
while left < right and List[left] == List[left - 1]:
left += 1
return output
#四数之和(之前想过先set来剔除重复,但是仔细想想不行,因为四个数中可能用到两个相等的数)
def _find_(List, add): #同样元素存在重复
if List == []:
return None
List.sort()
output = []
i = 0
while i < len(List): #第一个数的索引
j = i + 1
# while j < len(List) - 1 and List[j] == List[i]: #不能跳过
# j += 1 #举例 [0,0,0,0] add = 0跳过会出错
while j < len(List): #第二个数的索引
left, right = j + 1, len(List) - 1 #维护剩下两个数的指针
while left < right:
current_add = List[i] + List[j] + List[left] + List[right]
if current_add == add:
output.append([List[i], List[j], List[left], List[right]])
left += 1
right -= 1
while left < right and List[right] == List[right + 1]: #跳过重复答案
right -= 1
while left < right and List[left] == List[left - 1]:
left += 1
elif current_add > add:
right -= 1
while left < right and List[right] == List[right + 1]: #跳过重复的错误答案
right -= 1
else:
left += 1
while left < right and List[left] == List[left - 1]:
left += 1
j += 1 #跳过第二个数的重复
while j < len(List) and List[j] == List[j - 1]:
j += 1
i += 1
while i < len(List) and List[i] == List[i - 1]:
i += 1
return output
if __name__ == '__main__':
List = [-3,-2,-1,0,0,1,2,3]
add = 0
print(_find_(List, add)) |
41569ee202a6d5a68ce4d2f217a76e762a9c821b | spd94/Marvellous_Infosystem_Python_ML_Assignments | /Marvellous_Infosystem_Assignment_1/Assingment1_2.py | 157 | 3.84375 | 4 | def ChkNum(n):
if(n%2==0):print("Output : Even number",end=" ")
else:print("Output : Odd number",end=" ")
print("Input:",end=" ")
x=int(input())
ChkNum(x) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.