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
baed6319f4390e3d1a5f91a531f4ecba47f87832
chrysmur/Python-DS-and-Algorithms
/reversing_strings.py
132
4.21875
4
def reverseString(string): '''Returns a string in reverse order''' print(string[::-1]) #O(n) reverseString('hi i am chrys')
8c958cc6fc0a70f123a73a919f313a7615801d1b
yothebob/file-counter
/count-files/count_files.py
1,316
3.6875
4
import os from os import path ''' A small utility to count all the files in a given master folder (main_dir) - folders donot get added to count to use (in terminal locally) - 1. go to count_files folder (cd ~/path/to/count_files) 2. type python3 -c "from count_files import main;main('/home/user/path/to/disired_file')" ''' def main(main_dir=os.getcwd()): os.chdir(main_dir) final_count = 0 def recursive_count_files(_dir): total_files=0 os.chdir(_dir) for file in os.listdir(): if path.isdir(file): total_files += recursive_count_files(_dir + '/' + file) else: total_files += 1 return total_files for file in os.listdir(): if path.isdir(file): #final_count += count_files(main_dir +'/'+ file) final_count += recursive_count_files(main_dir + '/' + file) os.chdir(main_dir) else: final_count += 1 print("Total files in folder: ",final_count) '''obsolete function that only counts one folder deep''' #def count_files(_dir): #os.chdir(_dir) #total_files = 0 #for file in os.listdir(): #total_files+= 1 #return total_files
a914d165c1439bcfe25e45971e3568c4d3705a1e
brijeshsahu/hello
/test.py
533
3.625
4
#loopstr = "return List.of(new rList("Brijesh1"), new rList("Brijesh2"), new rList("Brijesh3"), new rList("Brijesh4"));" # loopstr = "return List.of(new rList("Brijesh1"), new rList("Brijesh2") # appendstr = ", new rList(" + '"' + "Brijesh" + i +'")' def stringapp (): mainstring = "return List.of(" for i in range (1,601): i = str(i) appendstr = ", new rList(" + '"' + "Brijesh" + i + '")' mainstring = mainstring+appendstr # print (mainstring) return mainstring h=stringapp() print(h)
211505c790b228d865de8893cae1ef83a341ba6f
MechatronixX/TrailerReverse
/helperfunctions/constant_rotation_code.py
1,533
3.953125
4
#!/usr/bin/env python # coding: utf-8 ############################################################################################################################# # constant_rotation(constant,angle) # # # # This method is used to rotate a two dimensional vector with constant x value and no y value around its origin by an angle # # Inputs: constant x value of the rotated vector # # angle angle, value in degrees # # Outputs: vector rotated two dimensional vector # ############################################################################################################################# __author__ = "Pär-Love Palm, Felix Steimle, Jakob Wadman, Veit Wörner" __credits__ = ["Pär-Love Palm", "Felix Steimle", "Jakob Wadman", "Veit Wörner"] __license__ = "GPL" __version__ = "0.9b" __maintainer__ = "Veit Wörner" __email__ = "veit@student.chalmers.se" __status__ = "Production" import numpy as np from numpy import array def constant_rotation(constant,angle): rotation_vector = array([np.cos(np.deg2rad(angle)), np.sin(np.deg2rad(angle))]) vector = rotation_vector*constant return vector
fbc098c8a118510d4ca09b7fd628de6b5d69ad2e
4nnina/Python_Project
/stellaQuad.py
817
3.578125
4
import turtle def spezzataQuad(t, lato, livello): if livello == 0: t.forward(lato) else: spezzataQuad(t, lato / 3, livello - 1) t.right(90) spezzataQuad(t, lato / 3, livello - 1) t.left(90) spezzataQuad(t, lato / 3, livello - 1) t.left(90) spezzataQuad(t, lato / 3, livello - 1) t.right(90) spezzataQuad(t, lato / 3, livello - 1) return def stellaQuadParam(t, lato, livello, n_lati): for i in range(0,n_lati): spezzataQuad(t, lato, livello) t.left(2*180/n_lati) return if __name__ == "__main__": window = turtle.Screen() t = turtle.Pen() t.hideturtle() t.speed(100) #stellaQuad(t, 200, 2) stellaQuadParam(t, 50, 2, 5) window.exitonclick()
28e9426e7001c6e96c86121aff5b28315bfce24f
tcsfremont/curriculum
/python/pygame/maze/03_maze.py
2,899
3.515625
4
from pygame.locals import * import pygame, sys import maze_generator WIDTH = 800 HEIGHT = 800 BLACK = (0, 0, 0) RED = (255, 20, 0) YELLOW = (255, 255, 0) GRAY = (100, 100, 100) GREEN = (0, 200, 0) speed = 3 px = 100 py = 100 status = "new_game" direction = "" tile_x = 0 tile_y = 0 pygame.init() screen = pygame.display.set_mode((WIDTH,HEIGHT)) # Let's read the maze file maze_file = maze_generator.maze row_count = len(maze_file) tile_width = round(WIDTH / row_count) tile_height = round(HEIGHT / row_count) player_radius = round(min(tile_width, tile_height) * 0.8 /2) player_size = player_radius * 2 target_size = player_radius walls = [] for row in maze_file: tile_x = 0 columns = row # list(row.strip()) # Convert to list and remove newline chars for column in columns: if column == 0: new_wall = pygame.Rect(tile_x, tile_y, tile_width, tile_height) walls.append(new_wall) if column == "S": px = tile_x py = tile_y if column == "E": tx = tile_x ty = tile_y tile_x = tile_x + tile_width tile_y = tile_y + tile_height player = pygame.Rect(px, py, player_size, player_size) target = pygame.Rect(tx, ty, target_size, target_size) clock = pygame.time.Clock() while True: clock.tick(60) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() pressed = pygame.key.get_pressed() # Note that we are only allowing one direction at a time # hence using if / elif if (pressed[K_RIGHT]): player.x = player.x + speed direction = "RIGHT" elif (pressed[K_LEFT]): player.x = player.x - speed direction = "LEFT" elif (pressed[K_UP]): player.y = player.y - speed direction = "UP" elif (pressed[K_DOWN]): player.y = player.y + speed direction = "DOWN" # Check if the player is about to leave the screen # and correct if player.right > WIDTH: player.right = WIDTH if player.left < 0: player.left = 0 if player.bottom > HEIGHT: player.bottom = HEIGHT if player.top < 0: player.top = 0 screen.fill(BLACK) # Draw the maze walls for wall in walls: color = RED if player.colliderect(wall): color = GRAY if direction == "RIGHT": player.right = wall.left if direction == "LEFT": player.left = wall.right if direction == "UP": player.top = wall.bottom if direction == "DOWN": player.bottom = wall.top pygame.draw.rect(screen, color, wall) pygame.draw.circle(screen, YELLOW, player.center, player_radius) pygame.draw.circle(screen, GREEN, target.center, target_size) pygame.display.flip()
d146d5541c713488ed3e3cc0497baea68cf368ff
tcsfremont/curriculum
/python/pygame/breaking_blocks/02_move_ball.py
1,464
4.15625
4
""" Base window for breakout game using pygame.""" import pygame WHITE = (255, 255, 255) BALL_RADIUS = 8 BALL_DIAMETER = BALL_RADIUS * 2 # Add velocity component as a list with X and Y values ball_velocity = [5, -5] def move_ball(ball): """Change the location of the ball using velocity and direction.""" ball.left = ball.left + ball_velocity[0] ball.top = ball.top + ball_velocity[1] return ball def game(): """Main function for the game.""" WIDTH = 800 HEIGHT = 600 # Define the ball as a square box the size of the ball # We can use this to check collision later ball = pygame.Rect(300, HEIGHT - BALL_DIAMETER,BALL_DIAMETER,BALL_DIAMETER) # Initialize pygame pygame.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Breaking Blocks") clock = pygame.time.Clock() # Game Loop while True: # Set max frames per second clock.tick(30 # Fill the screen on every update screen.fill(BLACK) # Event Handler for event in pygame.event.get(): if event.type == pygame.QUIT: return # Move ball ball = move_ball(ball) # Draw ball pygame.draw.circle(screen, WHITE, (ball.left + BALL_RADIUS, ball.top + BALL_RADIUS), BALL_RADIUS) # Paint and refresh the screen pygame.display.flip() if __name__ == "__main__": game()
52dca49503204649407f1e5a6068ff4ff2876dd2
tcsfremont/curriculum
/python/tkinter/example-game/main.py
4,036
3.578125
4
""" JumpyGuy: An Example Tkinter Canvas Game Requirements: Keyboard input Game loop Gravity Splash Screen, play button Score Save data to text file """ import tkinter as tk import GameObjects from Vector import Vector from random import randint class Game(tk.Canvas): def __init__(self, master, **kwargs): tk.Canvas.__init__(self, master, width=600, height=800, bg="#a3c6ff", **kwargs) self.master = master self.width = int(self.cget("width")) self.height = int(self.cget("height")) self.mode = "splash" self.player = GameObjects.Player(self.width / 2, self.height / 2, 74, 100, "assets/player.gif") self.player.velocity.y = -20 self.platforms = [] self.keys_down = set() self.master.bind("<KeyPress>", self.handle_key_press) self.master.bind("<KeyRelease>", self.handle_key_release) self.game_loop() def handle_key_press(self, event): self.keys_down.add(event.keysym) if self.mode == "splash": self.start_game() def handle_key_release(self, event): try: self.keys_down.remove(event.keysym) except KeyError: pass def key_is_down(self, keysym): return keysym in self.keys_down def splash_screen(self): # Title self.create_text((self.width / 2, 100), text="JumpyGuy!", font=("Comic Sans MS", 32, "bold")) self.create_text((self.width / 2, 200), text="Press any key to continue.", font=("Comic Sans MS", 16, "bold")) # TODO: High scores def start_game(self): # Runs once at beginning of game for i in range(10): new_platform = GameObjects.get_new_platform(self) self.platforms.append(new_platform) self.mode = "game" def play_game(self): # The primary loop for gameplay self.player.update() self.player.position.y = self.height / 2 self.create_rectangle((0, 0, 20, 20), fill="red") for platform in self.platforms: if platform.position.y > self.height + platform.height / 2: self.platforms.remove(platform) self.add_platforms() else: platform.velocity.y = -1 * self.player.velocity.y platform.update() platform.draw(self) self.player.draw(self) if self.key_is_down("Left"): self.player.velocity.x = -20 elif self.key_is_down("Right"): self.player.velocity.x = 20 else: self.player.velocity.x = 0 # Gravity gravity_vector = Vector(0, 1.5) self.player.velocity.add(gravity_vector) # Collision (only if player is falling down) if self.player.velocity.y > 0: for platform in self.platforms: if self.player.check_collide(platform): # BOUNCE self.player.velocity.y = -35 def add_platforms(self): new_platforms = [] num_new_platforms = randint(1, 1) print(num_new_platforms) while len(new_platforms) < num_new_platforms: platform = GameObjects.get_new_platform(self) platform.position.y -= self.width collides = False for p in self.platforms: if platform.check_collide(p): collides = True if not collides: new_platforms.append(platform) self.platforms += new_platforms def game_over(self): # The game over loop print("GAME OVER") def game_loop(self): # The loop to run them all, and in the darkness bind them self.delete("all") if self.mode == "splash": self.splash_screen() elif self.mode == "game": self.play_game() self.after(40, self.game_loop) # 25 FPS root = tk.Tk() root.title("JumpyGuy") game = Game(root) game.pack() root.mainloop()
7190d1fc0e3277184a8b5852bb46d6d572305d3c
hazinudin/hacktiv8_043_HA
/pertemuan_2/exercise_1.py
213
3.828125
4
a = input("Masukkan angkan: ") #a = int(a) print (type(a)) print("Nilai a: {0}".format(a)) remainder = a%2 if remainder > 0: print("Nilai a adalah bilangan ganjil") else: print("Nilai a adalah bilangan genap")
56cb3dc1b9ef863246aa518d8a83b90b3f0c2d9d
trcooke/57-exercises-python
/src/exercises/Ex07_area_of_a_rectangular_room/rectangular_room.py
830
4.125
4
class RectangularRoom: SQUARE_FEET_TO_SQUARE_METER_CONVERSION = 0.09290304 lengthFeet = 0.0 widthFeet = 0.0 def __init__(self, length, width): self.lengthFeet = length self.widthFeet = width def areaFeet(self): return self.lengthFeet * self.widthFeet def areaMeters(self): return round(self.areaFeet() * self.SQUARE_FEET_TO_SQUARE_METER_CONVERSION, 3) if __name__ == "__main__": length = input("What is the length of the room in feet? ") width = input("What is the width of the room in feet? ") print("You entered dimensions of " + length + " feet by " + width + " feet.") print("The area is") room = RectangularRoom(float(length), float(width)) print(str(room.areaFeet()) + " square feet") print(str(room.areaMeters()) + " square meters.")
935e8136b2da504ce9d9695a2c6cc9228b43951f
gchh/python
/code/8-4.py
2,514
3.671875
4
class Student(object): def __init__(self,name): self.name=name def __str__(self): return 'Student object (name: %s)'%self.name __repr__=__str__ print(Student('Michael')) s=Student('Michael') print(s) class Fib(object): def __init__(self): self.a,self.b=0,1 def __iter__(self): return self def __next__(self): self.a,self.b=self.b,self.a+self.b if self.a>1000: raise StopIteration() return self.a def __getitem__(self,y): m,n=1,1 for x in range(y): m,n=n,m+n return m for n in Fib(): print(n) print(Fib()[2]) class Fib2(object): def __getitem__(self, n): if isinstance(n,int): a, b = 1, 1 for x in range(n): a, b = b, a + b return a if isinstance(n,slice): start=n.start stop=n.stop if start is None: start=0 a,b=1,1 L=[] for x in range(stop): if x>=start: L.append(a) a,b=b,a+b return L print(Fib2()[2:10]) class Fib3(object): def __getitem__(self, n): a, b = 1, 1 L=[] if isinstance(n,int): start=0 stop=n if isinstance(n,slice): start=n.start stop=n.stop if start is None: start=0 for x in range(stop): if x>=start: L.append(a) a, b = b, a + b if isinstance(n,int): return a if isinstance(n,slice): return L print(Fib3()[:10]) class Student(object): def __init__(self): self.name = 'Michael' def __getattr__(self,attr): if attr=='score': return 99 if attr=='age': return lambda:25 return AttributeError('\'Student\' object has no attribute \'%s\''%attr) class Chain(object): def __init__(self, path=''): self._path = path def __getattr__(self, path): return Chain('%s/%s' % (self._path, path)) def __str__(self): return self._path __repr__ = __str__ print(Chain().status.user.timeline.list) class Student(object): def __init__(self,name): self.name=name def __call__(self): print('My name is %s.'%self.name) s=Student('Michael') s.__call__() s() print(callable(s))
750f8c4d04bdd56ed851412e6b4b478ff9b4a0c3
gchh/python
/code/7-5.py
1,295
4.1875
4
class Student(object): def __init__(self,name): self.name=name s=Student('Bob') s.score=90 print(s.__dict__) del s.score print(s.__dict__) class Student1(object): name ='Student' p=Student1() print(p.name) #打印name属性,因为实例并没有name属性,所以会继续查找class的name属性 print(Student1.name) #打印类的name属性 p.name='Micheal'#给实例绑定name属性 print(p.name) print(Student1.name) del p.name#删除实例的name属性 print(p.name)#再次调用p.name,由于实例的name属性没有找到,类的name属性就显示出来了 p.score=89 print(p.score) del p.score #print(p.score) # 学生 class Student(object): # 用于记录已经注册学生数 student_number = 0 def __init__(self, name): self.name = name # 注册一个学生:注册必填项名字,选填项利用关键字参数传递。注册完成,学生数+1 def register(name, **kw): a = Student(name) for k, v in kw.items(): setattr(a, k, v) Student.student_number += 1 return a bob = register('Bob', score=90) ah = register('Ah', age=8) ht = register('ht', age=8, score=90, city='Beijing') print(getattr(bob, 'score')) print(getattr(ah, 'age')) print(ht.city) print(ht.__dict__) print(Student.student_number)
76c075036bdd0b243d4a563537a5f3b8082bdc3d
Davidprogramming1986/TicTacToe-Python
/test.py
386
3.875
4
board = [0, 1, 'O', 3, 'X', 5, 6, 7, 'X'] free_spaces = list(filter(lambda x: x != 'X' and x != 'O', board)) free_spaces = list(filter(lambda x: x != 'X' and x != 'O', board)) while True: print(free_spaces) player_choice = input('Select your square > ') player_choice = int(player_choice) print(type(player_choice)) if player_choice in free_spaces: break
9709138c05b3249535afa63d5ef56ef62efa3bb1
letstinker/microstat
/tempreader.py
1,878
3.515625
4
import time import dht from machine import Pin class Temperature(): current_temp = 0 # Store in Celsius system = 'celsius' def __init__(self, system='celsius'): self.system = system def temp(self): if self.system == 'fahrenheit': return self.fahrenheit() return self.celsius() def fahrenheit(self, f=None): if f: self.current_temp = (f - 32) * (5/9) return (self.current_temp * (9/5)) + 32 def symbol(self): if self.system == 'fahrenheit': return 'F' return 'C' def celsius(self, c=None): if c: self.current_temp = c return self.current_temp class TempReader(): current_temp = None sensor = None last_measure = 0 system = 'celsius' measure_interval = 10 def __init__(self, system='celsius', pin=27): self.sensor = dht.DHT11(Pin(pin)) self.system = system self.current_temp = Temperature(system=system) def symbol(self): return self.current_temp.symbol() def measure(self): if (time.time() - self.last_measure) > self.measure_interval: self.last_measure = time.time() self.sensor.measure() def temperture(self): t = self.sensor.temperature() self.current_temp.celsius(t) return self.current_temp.temp() def humidity(self): return self.sensor.humidity() # # This is only ran when the script is ran directly and is for testing purposes. # if __name__ == "__main__": tr = TempReader(system='celsius') while True: print('Measuring...') tr.measure() temp = tr.temperture() symbol = tr.symbol() hum = tr.humidity() print('Temperature: {}{}'.format(round(temp), symbol)) print('Humidity: {}%'.format(hum)) time.sleep(.2)
d25f3b137fd5ca0bbd8b0d9dcffbaa864400e2c6
pinkrespect/HappyHappyAlgorithm
/MergeSort.py
248
3.578125
4
def split(List): index_no = len(List) half = int(index_no/2) print(half) left_List = List[0:half] right_List = List[half:index_no] return left_List, right_List split(split([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]))
83d9d49419a87e961abf560f8a64aa0f9b32f5eb
pinkrespect/HappyHappyAlgorithm
/complete/1914.py
271
3.9375
4
#Hanoi tower def hanoi(n, from_pos, to_pos, aux_pos): if n == 1: print(from_pos, "->", to_pos) return hanoi(n - 1, from_pos, aux_pos, to_pos) print(from_pos, "->", to_pos) hanoi(n - 1, aux_pos, to_pos, from_pos) hanoi(3, 'A', 'B', 'C')
2cd0617ee9947584a86478f998eb1fcd81aeef71
pinkrespect/HappyHappyAlgorithm
/quickSort_NoCheatSheet.py
862
3.984375
4
# swap, partitioning, quickSort(recursion) # low index, high index, store index, pivot value, pivot index from random import randint def swap(array, i, j): _ = array[i] array[i] = array[j] array[j] = _ def partitioning(array, low, high): pivotIndex = randint(low, high) pivotValue = array[pivotIndex] swap(array, pivotIndex, high) storeIndex = low for i in range(low, high): if array[i] < pivotValue: swap(array, i, storeIndex) storeIndex = storeIndex +1 swap(array, storeIndex, high) return storeIndex def quicksort(array, low, high): if low < high: partition = partitioning(array, low, high) quicksort(array, low, partition-1) quicksort(array, partition+1, high) A = [randint(0, 100) for _ in range(15)] print(A) quicksort(A, 0, len(A)-1) print(A)
6289134ecc6f923b1e656dedb627a4f0ce45095d
kqyang0000/python3-fishc
/012/array.py
286
3.703125
4
list1 = [123, 456] list2 = [124, 789] print(list1 > list2) print(list1 + list2) list1 *= 5 print(list1) print(123 in list1) dir(list1) print(list1.count(123)) print(list1.index(123)) print(list1.reverse()) print(list1) list1.sort() print(list1) list1.sort(reverse=True) print(list1)
93b625394363477e1ce6f8c86ac8955f9b6f08a3
aviv86/RavenDB-Python-Client
/pyravendb/tools/pkcs7.py
891
3.71875
4
class PKCS7Encoder(object): """ Technique for padding a string as defined in RFC 2315, section 10.3, note #2 """ class InvalidBlockSizeError(Exception): """Raised for invalid block sizes""" pass def __init__(self, block_size=16): if block_size < 2 or block_size > 255: raise PKCS7Encoder.InvalidBlockSizeError('The block size must be ' \ 'between 2 and 255, inclusive') self.block_size = block_size def encode(self, text): text_length = len(text) amount_to_pad = self.block_size - (text_length % self.block_size) if amount_to_pad == 0: amount_to_pad = self.block_size pad = chr(amount_to_pad) return text + pad * amount_to_pad def decode(self, text): pad = ord(text[-1]) return text[:-pad]
10be402e437bc70ed369d54b6eb555aeb9dea225
CassandraTalbot32/round-up-using-classes
/TM112_18D_TMA02_Q5_ZY659778.py.py
1,695
3.953125
4
# TM112 18D TMA02 Question 5 def float_rounded_up(float): """Round up a float to the nearest integer""" integer = int(float) if int(float) != float: integer = int(float + 1) return integer # Add your code here class floor(): width = 100 length = 100 height = 10 #width = float(input('floor width:')) #length = float(input('floor length:')) #height = float(input('floor height:')) floor_to_cover = (width*length*height) class lorry(): width = 20 length = 50 height = 10 #width = float(input('lorry width:')) #length = float(input('lorry length:')) #height = float(input('lorry height:')) lorry_capacity = (width*length*height) class cylinder(): radius = 5 length = 10 #radius = float(input('cylinder radius:')) #length = float(input('cylinder length:')) capacity = radius*2*length def cylinders_per_lorry(lorry,cyinder): cylinder_in_row = float_rounded_up(lorry.width/(cylinder.radius*2)) cylinder_columns = float_rounded_up(lorry.length/cylinder.length) return(cylinders_in_row*cylinder_columns) def cylinders_required(cylinder,floor): return float_rounded_up(floor.floor_to_cover/cylinder.capacity) lorries_required = (cylinders_required(cylinder,floor)/cylinders_per_lorry(lorry,cylinder)) def open(): returnString = """To cover a floor with the below dimensions: each lorry can carry %d cylinders you will needa total of %d cylinders, in %d lorries """%(cylinders_per_lorry(lorry,cylinder),cylinders_required(cylinder,floor),lorries_required) return(returnString) print(open())
82f10b38d8681d1de310295eb301af18b137d631
federicorenda/ctr-design-and-path-plan
/ctrdapp/optimize/optimizer.py
607
3.5
4
from abc import ABC, abstractmethod class Optimizer(ABC): def __init__(self, heuristic_factory, collision_checker, initial_guess, configuration): self.tube_num = configuration.get("tube_number") self.precision = configuration.get("optimizer_precision") self.configuration = configuration self.heuristic_factory = heuristic_factory self.collision_checker = collision_checker self.initial_guess = initial_guess @abstractmethod def find_min(self): # should return q* for min cost and path (or maybe the best solver object) pass
3f639c6809001fef89b2d54722bd24f1ee0edc20
Jovanez/flask
/testeBanco.py
256
3.53125
4
from banco import Cinema,Filme, Programacao,db db.connect() cine = Cinema.select(Cinema).where((Programacao.filme == 3)& (Programacao.cinema == Cinema.codigo)).join(Programacao).join(Filme).group_by(Cinema.codigo) for c in cine: print(c.nome +" \n")
71400d34dacc010d4351186485e9266fda5e7513
kosvicz/swaroop
/user_input.py
338
4.15625
4
#!/usr/bin/env python3 #--*-- conding: utf-8 --*-- def reverse(text): return text[::-1] def is_palindrome(text): return text == reverse(text) something = input('Введите текск: ') if(is_palindrome(something)): print('Да, это палиндром') else: print('Нет, это не палиндром')
aac5371cae30991aa57698c725d2f9dbd07658aa
mccabedarren/python321
/p5.p5.py
943
3.875
4
Location = input('Enter your Location:') if Location== 'Dublin': print ('You entered Dublin. Dublin is in Leinster') elif Location == 'Belfast': print ('You entered Belfast. Belfast is in Ulster') elif Location == 'Cork': print ('You entered Cork. Cork is in Munster') elif Location == 'Limerick': print ('You entered Limerick. Limerick is in Munster') elif Location == 'Derry': print ('You entered Derry. Derry is in Ulster') elif Location == 'Galway': print ('You entered Galway. Galway is in Connaught') elif Location == 'Lisburn': print ('You entered Lisburn. Lisburn is in Ulster') elif Location == 'Kilkenny': print ('You entered Kilkenny. Kilkenny is in Leinster') elif Location == 'Waterford': print ('You entered Waterford. Waterford is in Leinster') elif Location == 'Sligo': print ('You entered Sligo. Sligo is in Connaught') else: print ('Sorry, I did not recognise that name.')
9ba7fb40eacf3ebca5c5fb9a5ac9e823f1ef9df0
mccabedarren/python321
/p12.p3.py
1,098
4.46875
4
#Define function "sqroot" (Function to find the square root of input float) #"Sqroot" calculates the square root using a while loop #"Sqroot" gives the number of guesses taken to calculate square root #The program takes input of a float #if positive the program calls the function "sqroot" #if negative the program prints the error message: "Error: Number must be greater than 0" def sqroot(number): epsilon = 0.01 step = epsilon**2 numguesses=0 root = 0.0 while abs(number-root **2) >=epsilon and root <=number: root += step numguesses +=1 if numguesses % 100000 == 0: print('Still running. Number of guesses:',numguesses) print ('Number of guesses:',numguesses) if abs (number-root**2) < epsilon: return ('The approximate square root of',number,'is',root) else: return('Failed to find the square root of',number) number = float(input('Enter the number for which you wish to calculate the square root:')) if number > 0: print (sqroot(number)) else: print("Error: Number must be greater than 0")
dc5b545562df84e36ce8696cdaa33e0239a37001
mccabedarren/python321
/p13.p2.py
431
4.46875
4
#Program to print out the largest of two user-entered numbers #Uses function "max" in a print statement def max(a,b): if a>b: return a else: return b #prompt the user for two floating-point numbers: number_1 = float(input("Enter a number: ")) number_2 = float(input("Enter another number: ")) print ("The largest of", number_1,"and", number_2, "is", max(number_1, number_2)) print("Finished!")
58755bd3db06ed522fc54b552b87fa769719e0d1
mccabedarren/python321
/p6.p1.py
232
4.0625
4
#prompt user for two separate ints (x,y) # if x +y > 100 , print "that is a big number!" #Exit program x = int(input('input an int:')) y = int(input('input another int:')) if x + y > 100: print('That is a big number!') exit()
31a449aab5fcf84187fc5cb62e5b26ba65e030a0
Prometeo/python-code-snippets
/palindrome.py
171
4.15625
4
def palindrome(a): """ This method checks whether a given string is a palindrome """ return a == a[::-1] if __name__ == '__main__': print(palindrome('mom'))
f427be78dd85ca42496722c2ba110c1db6a5158e
Prometeo/python-code-snippets
/most_common.py
249
4.0625
4
def most_commmon(lst): """ This method returns the most frequent element that appears in a list """ return max(set(lst), key=lst.count) if __name__ == '__main__': numbers = [1, 2, 1, 2, 3, 2, 1, 4, 2] print(most_commmon(numbers))
92a3125c830392873920de61ef52c78d048d1290
xiaocuizi/python3
/py_learn/com/gemini/pic/createpic.py
782
3.5
4
from PIL import Image, ImageDraw, ImageFont import random as random # 生成随机的字母 def rndChar(): return chr(random.randint(65, 90)) # print(rndChar()) # 随机颜色 def rndColor1(): return (random.randint(64, 256), random.randint(64, 256), random.randint(64, 256)) def rndColor2(): return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127)) # w = 240 h = 60 # 画板 img = Image.new("RGB", (w, h), (255, 255, 255)) # 创建字体对象 font = ImageFont.truetype("arial.ttf", 36) draw = ImageDraw.Draw(img) for x in range(w): for y in range(h): draw.point((x, y), fill=rndColor1()) for i in range(4): draw.text(((60 * i + 10), 10), rndChar(), font=font, fill=rndColor2()) #img.show() img.save("aa", "jepg")
653a43a7ccdb8ee230cc46c107b4ac2d21b040d0
xiaocuizi/python3
/py_learn/com/gemini/object/person.py
473
3.5625
4
class person: def cry(self): print("大哭") def __init__(self): ## 构造方法(专有方法) 当实例化对象的时候,就会调用 self.cry() p1 = person() class person2: def __init__(self, sex, name): self.sex = sex ## 给person实例对象顶一个实例变量sex,然后赋值为sex self.name = name def speck(self): print(self.name,self.sex) p2 = person2(sex="女",name="张三妹") p2.speck()
2008c87c3adaffbfa0467a86a44b41a5b09c0031
xiaocuizi/python3
/py_learn/com/gemini/scope/__init__.py
381
3.796875
4
def fun(): a = 3 ## 闭包外的函数变量 print(a) def inside(): b = 4 ## 局部变量 x = int(10) ## 内置作用域,通过系统函数创建的数据集、、 y = 2 ## 全局变量 a=4 def fun(): global a ### 声明加权限 ,就可以修改,否则引用函数外的变量是只读的,不得修改 a=5 print(a) fun() print(a)
579a158f6690c0ef213558d27d74cd77263b37ee
xiaocuizi/python3
/py_learn/com/gemini/list.py
369
3.796875
4
print("---------------------") ls=[5,True,"34343"] print(ls) ls.append("找") print(ls) ls2=[1,2,3] ls.extend(ls2) print(ls) ls.insert(3,"张龙") print(ls) del ls[1] print(ls) ls.pop() print(ls) ls.pop(4) print(ls) ls.remove("张龙") print("---------------------") ls2 = [1,25,7,4] ls2.sort(); print(ls2) ls2.reverse() print(ls2) print(sorted(ls2)) print(len(ls))
deebb2a59355871d9ea00a7502336c1c7e2dbe6f
jasonglassbrook/code-challenges
/leetcode/valid_palindrome.py
4,005
3.953125
4
#!python3 ############################################################ class Solution: def isPalindrome(self, s: str) -> bool: return self.isPalindrome__pointers(s) def isPalindrome__reverse_slice(self, s: str) -> bool: # Handle trivial cases. if len(s) < 2: return True # Strip non-alphanumeric characters and ignore case. s = "".join(c.lower() for c in s if c.isalnum()) # Compare with reversed version. result = (s == s[::-1]) return result def isPalindrome__reversed(self, s: str) -> bool: # Handle trivial cases. if len(s) < 2: return True # Strip non-alphanumeric characters and ignore case. s = "".join(c.lower() for c in s if c.isalnum()) # Compare with reversed version. result = (s == "".join(reversed(s))) return result def isPalindrome__pointers(self, s: str) -> bool: # Handle trivial cases. if len(s) < 2: return True # Strip non-alphanumeric characters and ignore case. s = "".join(c.lower() for c in s if c.isalnum()) # Iterate from outside to middle with left and right pointers. # - If the length is even, then when we reach the middle, # then we've made it to the base/trivial case of a string of length 0. # - If the length is odd, then when we reach the middle, # then we've made it to the base/trivial case of a string of length 1. for i in range(0, len(s) // 2): left = i # (LEFTMOST + i) where LEFTMOST = 0 right = (-1 - i) # (RIGHTMOST - i) where RIGHTMOST = len(s) - 1 if s[left] != s[right]: return False return True def isPalindrome__recursive(self, s: str) -> bool: """ Because why not? """ # Handle trivial cases. if len(s) < 2: return True # Strip non-alphanumeric characters and ignore case. s = "".join(c.lower() for c in s if c.isalnum()) # Iterate from outside to middle with left and right pointers. # - If the length is even, then when we reach the middle, # then we've made it to the base/trivial case of a string of length 0. # - If the length is odd, then when we reach the middle, # then we've made it to the base/trivial case of a string of length 1. middle = len(s) // 2 def compare_outside_to_inside(i: int) -> bool: # Handle trivial cases. if i >= middle: return True # Compare left and right. elif s[i] != s[-1 - i]: return False # Continue. else: return compare_outside_to_inside(i + 1) return compare_outside_to_inside(0) ############################################################ ############################################################ import unittest # noqa: E402 import random # noqa: E402 import string # noqa: E402 from tools import testing # noqa: E402 #----------------------------------------------------------- class TestSolution(testing.TestSolution): SOLUTION_CLASS = Solution SOLUTION_FUNCTION = "isPalindrome" def test_length_0(self): return self.run_test( args=[""], answer=True, ) def test_length_1(self): return self.run_test( args=[random.choice(string.printable)], answer=True, ) def test_example_1(self): return self.run_test( args=["A man, a plan, a canal: Panama"], answer=True, ) def test_example_2(self): return self.run_test( args=["race a car"], answer=False, ) ############################################################ if __name__ == "__main__": unittest.main(verbosity=2)
bc4fe0b9663c18a0147f33c0399d9cb16a380d7f
jasonglassbrook/code-challenges
/leetcode/invert_binary_tree.py
6,132
4.21875
4
#!python3 ############################################################ from typing import Union from leetcode.tools.binary_tree import TreeNode #----------------------------------------------------------- class Solution: MAIN = "invertTree" def invertTree(self, root: TreeNode) -> TreeNode: return self.invertTree__iterative__breadth_first(root) def invertTree__recursive(self, root: TreeNode) -> TreeNode: """ Solution to "invert binary tree" that... - Uses recursion. """ # I personally like using local functions instead of `self.<function>`. def invert_tree(node: Union[TreeNode, None]) -> Union[TreeNode, None]: if node: # Swap the left and right branches. # We must perform a simultaneous swap or else overwrite a branch. # [Otherwise, we could use a temporary variable.] ( node.left, node.right, ) = ( invert_tree(node.right), invert_tree(node.left), ) return node # Use our local function. return invert_tree(root) def invertTree__iterative__depth_first(self, root: TreeNode) -> TreeNode: """ Solution to "invert binary tree" that... - Uses iteration. - Visits nodes in a depth-first order by using a stack. """ from collections import deque as Deck # If `root` is falsy, we can skip everything. if not root: return root stack = Deck([root]) while stack: # Pop! node = stack.pop() # Swap the left and right branches. # We must perform a simultaneous swap or else overwrite a branch. # [Otherwise, we could use a temporary variable.] (node.left, node.right) = (node.right, node.left) # Put branches in stack, but only if they're truthy... if node.left: stack.append(node.left) if node.right: stack.append(node.right) return root def invertTree__iterative__breadth_first(self, root: TreeNode) -> TreeNode: """ Solution to "invert binary tree" that... - Uses iteration. - Visits nodes in a breadth-first order by using a queue. """ from collections import deque as Deck # If `root` is falsy, we can skip everything. if not root: return root queue = Deck([root]) while queue: # Pop! node = queue.popleft() # Swap the left and right branches. # We must perform a simultaneous swap or else overwrite a branch. # [Otherwise, we could use a temporary variable.] (node.left, node.right) = (node.right, node.left) # Put branches in queue, but only if they're truthy... if node.left: queue.append(node.left) if node.right: queue.append(node.right) return root ############################################################ import unittest # noqa: E402 from tools import testing # noqa: E402 from leetcode.tools.binary_tree import tree_from_data # noqa: E402 from .same_tree import Solution as SameTreeSolution # noqa: E402 #----------------------------------------------------------- class TestSolution(testing.TestSolution): SOLUTION_CLASS = Solution SOLUTION_FUNCTION = Solution.MAIN is_same_tree = testing.getattr_of_instance(SameTreeSolution, SameTreeSolution.MAIN) def run_test__is_same_tree( self, p: Union[TreeNode, None], q: Union[TreeNode, None], answer: bool = True, ): return self.run_test( args=[p], transform_result=self.is_same_tree, transform_result__rest=[q], answer=answer, ) def test_example_1(self): return self.run_test__is_same_tree( tree_from_data([ 4, [2, 1, 3], [7, 6, 9], ]), tree_from_data([ 4, [7, 9, 6], [2, 3, 1], ]), ) def test_empty_tree(self): return self.run_test__is_same_tree( tree_from_data([]), tree_from_data([]), ) def test_tree_of_depth_1(self): return self.run_test__is_same_tree( tree_from_data(["A", None, None]), tree_from_data(["A", None, None]), ) def test_tree_of_depth_2(self): return self.run_test__is_same_tree( tree_from_data(["A", "B", "C"]), tree_from_data(["A", "C", "B"]), ) def test_tree_of_depth_3(self): return self.run_test__is_same_tree( tree_from_data([ "A", ["B", "D", "E"], ["C", "F", "G"], ]), tree_from_data([ "A", ["C", "G", "F"], ["B", "E", "D"], ]), ) def test_tree_of_depth_4(self): return self.run_test__is_same_tree( tree_from_data([ "A", [ "B", ["D", "H", "I"], ["E", "J", "K"], ], [ "C", ["F", "L", "M"], ["G", "N", "O"], ], ]), tree_from_data([ "A", [ "C", ["G", "O", "N"], ["F", "M", "L"], ], [ "B", ["E", "K", "J"], ["D", "I", "H"], ], ]), ) ############################################################ if __name__ == "__main__": unittest.main(verbosity=2)
6685ea3f7aa0d211ee99961d7f16cb291ba723ef
jasonglassbrook/code-challenges
/leetcode/best_time_to_buy_and_sell_stock.py
3,599
4
4
#!python3 ############################################################ from typing import List #----------------------------------------------------------- class Solution: MAIN = "maxProfit" def maxProfit(self, prices: List[int]) -> int: return self.maxProfit__tracking_buy_price(prices) def maxProfit__brute_force(self, prices: List[int]) -> int: max_profit = 0 n = len(prices) # We need at least 2 prices to make a sale. if n < 2: return max_profit # Iterate through all combinations. for left in range(0, n - 1): for right in range(left + 1, n): # Choose the best profit so far. max_profit = max( prices[right] - prices[left], max_profit, ) return max_profit def maxProfit__tracking_buy_price(self, prices: List[int]) -> int: max_profit = 0 n = len(prices) # We need at least 2 prices to make a sale. if n < 2: return max_profit # Track the best buy price. buy_price = prices[0] # Iterate through combinations involving tracked `buy_price`. for this_price in prices[1 ::]: # If we find a lower price than `buy_price`, then... # - Replace `buy_price`. # - We can't make a *profit* here, so skip to next price. if this_price < buy_price: buy_price = this_price continue # Choose the best profit so far. max_profit = max( this_price - buy_price, max_profit, ) return max_profit ############################################################ import unittest # noqa: E402 import random # noqa: E402 from tools import testing # noqa: E402 #----------------------------------------------------------- class TestSolution(testing.TestSolution): SOLUTION_CLASS = Solution SOLUTION_FUNCTION = Solution.MAIN _MIN_VALUE = 0 _MAX_VALUE = 1000 _LENGTH = 1000 def test_example_1(self): return self.run_test( args=[[7, 1, 5, 3, 6, 4]], answer=5, ) def test_example_2(self): return self.run_test( args=[[7, 6, 4, 3, 1]], answer=0, ) def test_no_prices(self): return self.run_test( args=[[]], answer=0, ) def test_only_one_price(self): series = [random.randint(self._MIN_VALUE, self._MAX_VALUE)] answer = 0 return self.run_test( args=[series], answer=answer, ) def test_flat_series(self): series = [random.randint(self._MIN_VALUE, self._MAX_VALUE)] * self._LENGTH answer = 0 return self.run_test( args=[series], answer=answer, ) def test_all_ascending_series(self): series = list(range(self._MIN_VALUE, self._MAX_VALUE + 1, +1)) answer = max(0, series[-1] - series[0]) return self.run_test( args=[series], answer=answer, ) def test_all_descending_series(self): series = list(range(self._MAX_VALUE, self._MIN_VALUE - 1, -1)) answer = max(0, series[-1] - series[0]) return self.run_test( args=[series], answer=answer, ) ############################################################ if __name__ == "__main__": unittest.main(verbosity=2)
cd94720d183e0d8490662531dd369727db345c1a
jasonglassbrook/code-challenges
/leetcode/longest_palindromic_substring.py
1,942
4.03125
4
#!python3 class Solution: def longestPalindrome(self, string: str) -> str: result = "" for i in range(len(string)): # print("center:", i) odd_palindrome = self.find_odd_palindrome_from_center(string, i) # print("odd palindrome:", odd_palindrome) if len(odd_palindrome) > len(result): result = odd_palindrome # print("new result:", result) even_palindrome = self.find_even_palindrome_from_center(string, i) # print("even palindrome:", even_palindrome) if len(even_palindrome) > len(result): result = even_palindrome # print("new result:", result) return result def find_palindrome_from_center( self, string: str, center: int, left_offset: int, right_offset: int, ) -> str: left_stop = 0 right_stop = len(string) - 1 left = center + left_offset right = center + right_offset if center < left_stop or center > right_stop: raise IndexError("center outside of string's bounds") if left >= left_stop and right <= right_stop and string[left] == string[right]: while left - 1 >= left_stop and right + 1 <= right_stop: if string[left - 1] == string[right + 1]: left -= 1 right += 1 else: break else: left = right = center return string[left : right + 1] # Use need `right + 1` because we're slicing. def find_odd_palindrome_from_center(self, string: str, center: int) -> str: return self.find_palindrome_from_center(string, center, 0, 0) def find_even_palindrome_from_center(self, string: str, center: int) -> str: return self.find_palindrome_from_center(string, center, 0, 1)
e0fc45ba2b2da28b629f3c6bf7ce6c85d4334ca4
elizabethadventurer/Treasure-Seeker
/Mini Project 4 part 1.py
1,575
4.28125
4
# Treasure-Seeker #Introduction name = input("Before we get started, what's your name?") print("Are you ready for an adventure", name, "?") print("Let's jump right in then, shall we?") answer = input("Where do you thnk we should start? The old bookstore, the deserted pool, or the abandoned farm?") if answer == "the deserted pool" or "deserted pool" or "Pool" or "The deserted pool" or "pool" or "the pool" or "Deserted pool" or "deserted pool" or "the pool": print("Oooh, a spooky pool? Sure, why not? Lets see if there's even any water left...maybe a drowned spirit?!") if answer == "the old bookstore" or "the bookstore" or "bookstore" or "The old bookstore" or "Bookstore": print("The bookstore huh? Sounds like the lesser of three evils.") if answer == "the abandoned farm" or "the farm" or "The farm" or "Farm" or "The abandoned farm" or "farm": print("Hmm...sounds dangerous..but since you picked it...I guess I must join you. Whatever happens....happens.") name2 = input("Honestly...there seems to be more to this than meets the eye. Do you trust me ?") if name2 == "Yes" or name2 =="yes": print("Thanks for the confidence boost!") answer2 = input("We should move forward...right? *Answer in yes/no") if answer2 == "Yes" or answer2 == "yes": print("Okay...) if answer2 == "No" or answer2 == "no": print("Whew, bye bye.") exit(3) if name == "No" or name == "no": print("Ouch, okay. Good luck getting through this without any hints...in fact I suggest you restart the game...cuz you ain’t going nowhere no more.") exit()
c9b8122e000cb0a4fa6c65088b67d082ea0a9c32
nimit3/python-basics
/array.py
3,278
4.0625
4
no = [1, 2, 3, 4, 5] # # [from:to] this sytanx will work here tooo # print(no[0:3]) # print(no[2:]) # this will print everyting from 2nd index # 2d arrays matrix # matrix = [ # [1, 2, 3], # [4, 5, 6] # ] # # we can store mutliple types of elements in list. same like JS # arr=['fwqfq',12,122,1331,'fwqfwqf', False] # for i in arr: # print(type(i)) # # how to give some range of numbers to list directly # nos = list(range(1,9)) # print(nos) # # prinintg 2d array # for row in matrix: # for item in row: # print(item) # # we can use in operator in array too # print(4 in no) # will return true # no2 = no # no.insert(2, 22) # print(no2) # # how to remove duplicate items from arr # org = [1, 22, 22, 33, 444, 444, 33, 6, 8, 9] # dup = [] # for i in org: # if(i not in dup): # dup.append(i) # print(dup) # list methods: # 1) insert at last - append # arr = [1,2,3] # arr.append(4) #it only takes 1 argument. can't pass mutliple args # print(arr) # # 2) extend - adding multiple eleemnts at the end # arr.extend([55,66, 444]) # print(arr) # # 3) insert - adding element at specific location # arr.insert(1,11) # print(arr) # # ----------------------removing elements from list common methods # # # 1) clear - removed everything from list # # print(arr.clear()) #will print None # # removing last element only - pop # arr.pop() # print(arr) # # however we can even use pop(index_no_element) that we want to remove. NOT available in JS # arr.pop(0) #will remove 0th index element # print(arr) # # remove - will remove some specific element that you will pass in args. # arr2=list(range(11,19)) # arr2.remove(11) # print(arr2) # -----------------------------------some more advanced methods # 1) index - will find element's index in the lsit # arr = [1,2,2,3,1,5,3,1,6,5,2] # print(arr.index(5,6,10)) #syntax index(ele's index that you want, from to look, till look(will count this ele too)) # # 2) count - will count that how many times element is in the list # print(arr.count(2)) # # 3) reverse the list # arr.reverse() # print(arr) # will mutate the orignal list too # # 4) sort - will mututate the orignal list too # arr.sort() # print(arr) # 5) join - will convert list into the string # # ---------------------------------------IMPORTANT # # join doesn't work like it owrks in JS. it's weired here # # here join usually joins some string into the array # coding = ['coding', 'is', 'fun'] # print(' '.join(coding)) #JS version - coding conding.join('')=no space, coding.join(' ')=joined with space, coding.join('---')=joined with --- # print('-----'.join(coding)) # 6) slice --- syntax list_name[from_index: to_index(dosnt include this one. like rangefn): step] - won't mutuate the orignal list color = ['red', 'yellow', 'orange', 'silver', 'purple', 'green'] print(color[0:4]) print(color[-5:]) # will print till yellow(from reverse direction). # to print(color[:3]) # will print first 3 index ele(0-2) print(color[1:-3]) # will print yello and orange # step - almost like increment by +2, +3 etc. like range(0,10,2) print(color[::2]) # will print even index color from 0 # left out negative step thing. lil bit coplex # updating any list with slice nos = [1, 2, 3, 4, 5] nos[1:3] = ['a', 'b', 'c'] print(nos)
0006ed639bdc78c81f70363c4148a9a69fa212f7
civic/generic-anova
/check.py
364
3.53125
4
import sys def calc(prev, current, target): Kp = 20 Ki = 0.5 p = (target -current) * Kp i = ((target-current) + (target-prev))*10/2*Ki print("{:.3f}\tp={:.2f} i={:.2f} power={:d}".format(current, p, i, int(p+i))) prev = float(sys.argv[1]) current = float(sys.argv[2]) target = float(sys.argv[3]) calc(prev, current, target)
bbaf4883efe9a4a34487a6d9b1316cd1f54156ab
Bhanditz/ISBN-13-checksum-generator
/ISBN13.py
548
4.03125
4
code = input('Please enter the ISBN-13 number with or with \'-\'s: ') codex = '' for each in code: if each is '-': pass else: codex = codex + each code = codex code = code[::-1] code_even = code[1::2] code_odd = code[::2] total = 0 for x in code_odd: y = int(x) total = total + (y * 3) for z in code_even: z = int(z) total = total + z check = abs((total % 10) - 10) print('Checksum is equal to ' + str(check)) print('The ISBN-13 total before adding the checksum is equal to ' + str(total)) input('')
37fdff5b7a156971e0a016814b93fd2dc6770095
kompiangg/math-operation-in-python
/modulus.py
400
3.796875
4
print("Perhatikan bentuk berikut") print("-" * 19) print("| a mod b = hasil |") print("-" * 19) a = int(input("Masukkan a : ")) b = int(input("Masukkan b : ")) if (a > 0 and b > 0) or (a < 0 and b < 0): hasil = a - int(a/b) * b elif (a == 0 and b >= 0): hasil = 0 elif a > 0 and b == 0: hasil = a elif a < 0 and b > 0: hasil = ((int(a/b - 1)) * -b) + a print("hasilnya : ", hasil)
2f96931fad2b0596415a6308e5d479367245a56a
AfinFirnas/Muhammad-Firnas-Balisca-Putra_I0320063_Abyan_Tugas5
/I0320063_soal2_tugas5.py
845
3.84375
4
# Program Grading Nilai Nama = str(input('Masukkan Nama Anda : ')) Nilai = int(input('Masukkan Nilai Anda : ')) if Nilai < 60 : print('Halo,', Nama ,'!', 'Nilai Anda setelah dikonversi adalah E') elif 60 <= Nilai <= 64 : print('Halo,', Nama ,'!', 'Nilai Anda setelah dikonversi adalah C') elif 65 <= Nilai <= 69 : print('Halo,', Nama, '!', 'Nilai Anda setelah dikonversi adalah C+') elif 70 <= Nilai <= 74 : print('Halo,', Nama, '!', 'Nilai Anda setelah dikonversi adalah B') elif 75 <= Nilai <= 79 : print('Halo,', Nama, '!', 'Nilai Anda setelah dikonversi adalah B+') elif 80 <= Nilai <= 84 : print('Halo,', Nama, '!', 'Nilai Anda setelah dikonversi adalah A-') elif 85 <= Nilai <= 100 : print('Halo,', Nama, '!', 'Nilai Anda setelah dikonversi adalah A') else: print('Nilai Tidak Valid!')
4987d647d883befa0e2787bc7006c0db4a49decd
vicentecm/URI_respostas
/1008.py
216
3.5
4
# URI 1008 numero_do_func = int(input()) numero_horas = int(input()) valor_hora = float(input()) horas_x_valor = numero_horas*valor_hora print(f"NUMBER = {numero_do_func}") print(f"SALARY = U$ {horas_x_valor:.2f}")
a38d89434004dd34144ec1352c813dc335354db5
HohlovIlya/math_modeling
/lab_1_pr_4.py
138
3.71875
4
a = [1, 5, 'Good', 'Bad'] b = [9, 'Blue', 'Red', 11] print(a[1]+b[3]) print(a[2]+b[2]) print(a[0]*b[0]) print(a[1]**b[3]) print(a+b)
c7dfc4469d6c380e96e010197bfc86ec473c3c48
graememorgan/adventofcode
/day16.py
637
3.734375
4
from re import findall match = {"children": 3, "cats": 7, "samoyeds": 2, "pomeranians": 3, "akitas": 0, "vizslas": 0, "goldfish": 5, "trees": 3, "cars": 2, "perfumes": 1} sues = [{k: int(v) for k, v in findall("([a-z]+): ([0-9]+)", line)} for line in open("day16-input").read().splitlines()] print [ reduce( lambda x, y: x and y, [ # for part 1, just match[k] == v match[k] < v if k in ("cats", "trees") else (match[k] > v if k in ("pomeranians", "goldfish") else match[k] == v) for k, v in sue.iteritems() ], True) for sue in sues ].index(True) + 1
7f661c828e0b1dff2eba26b0f14832f5c8f27267
Gereaume/L2
/math/TP2/Exercice1/Exercice1.py
486
3.6875
4
#!/usr/bin/python3 # coding: utf-8 # from __future__ import division from random import * import matplotlib.pyplot as plt import numpy as np N=int(input("Saisir le nombre de tirage : ")) l=np.array([0]*20) for i in range(N): S=0 for d in range(3): S=S+randint(1,6) l[S]=l[S]+1 print ("---") for i in range(len(l)): print(l[i]) z = len(l) x = range(z) plt.bar(x,l) plt.title('Duc de Toscane') plt.ylabel('ordonnées') plt.xlabel('abscisses') plt.grid(True) plt.show()
55ca7df15d0ec947e09b3c0390030ea750143a6c
zingpython/webinarPytho_101
/five.py
233
4.25
4
def even_or_odd(): number = int(input("Enter number:")) if number % 2 == 1: print("{} is odd".format(number)) elif number % 2 == 0: print("{} is even".format(number)) even_or_odd() # "Dear Mr.{} {}".format("John","Murphy")
ee27e088d0490f70ed7b5b4b00b8b19edd2aa762
M-Faheem-Khan/Matrix-Encryption
/decrypt.py
1,196
3.734375
4
class create(object): # convert to original array def original_key(self, key, msg): temp = [] for i in range(len(msg)): temp.append(msg[i]/key[i]) return temp # converts ascii values to string class convert_from(object): def string_to_int(self, array): converted_array = [] array = array.split(", ") for i in range(len(array)): converted_array.append(int(array[i])) return converted_array def ascii_to_string(self, msg1, msg2): converted_string = "" for i in msg1: converted_string+= str(chr(int(i))) for i in msg2: converted_string+= str(chr(int(i))) return converted_string def main(): # seed = int(input("Seed:")) key = input("Key: ") msg1 = input("Message: ") msg2 = input("Message: ") key = convert_from().string_to_int(key) msg1 = convert_from().string_to_int(msg1) msg2 = convert_from().string_to_int(msg2) # c = create() msg1 = create().original_key(key, msg1) msg2 = create().original_key(key, msg2) m = convert_from() print(m.ascii_to_string(msg1,msg2)) main()
86ae639c1bcee8f1ef6274c4878fcd9aa3f41f99
HolyCash/SelfP
/ex_5.py
172
3.78125
4
x = input("Put your number here please:") def func1(x): try: return float(x) except (ValueError): print("Enter the number please.") print(func1(x))
e535489eb731ee8c8f0b95fcfe70aeb271d97a30
Robvanzoelen/Bingo
/Bingo card.py
5,353
3.734375
4
# Part 3 of assignment LCP: create a bingo card and mark the terms # Team: Evert Schonewille & Rob van Zoelen with open("bingo_terms.txt", "r") as input_file: # Use the file 'bingo_terms' as input inp = str(input_file.readlines()) # Make string of the input from file terms = [] # Create an empty list and append the input input_split = inp.split() for i in input_split: terms.append(i) del terms[0] del terms[len(terms) - 1] def new_card(list_with_terms): # Shuffle the list and make it a bingo card import random random.shuffle(terms) bingocard = [] row1 = terms[0:5] row2 = terms[5:10] row3 = terms[10:15] row4 = terms[15:20] row5 = terms[20:25] bingocard.append(row1) bingocard.append(row2) bingocard.append(row3) bingocard.append(row4) bingocard.append(row5) print("---------------------------------------------------") for i in bingocard: print(i) return bingocard def mark_term(row,column,bingocard): # Function to mark the terms that are drawn by draw terms by entering the coordinates bingocard[row-1][column-1] = "-----" print("---------------------------------------------------") for i in bingocard: print(i) return bingocard bingocard = new_card(terms) # Create a new card and set variables to start values marked = "-----" bingo_counter = 0 row_bingo = 0 column_bingo = 0 diagonal_bingo = 0 total_bingo = 0 while True: # Continue playing bingo until deciding to quit print("---------------------------------------------------") next_round = input("Press any button to continue, press '1' to quit") # Every round there is the possibility to quit, otherwise: play new round if next_round != "1": row = int(input("Tell us the row of the term you want to mark (1-5)")) # Possibility to enter coordinates of the given term column = int(input("Tell us the column of the term you want to mark (1-5)")) bingocard = mark_term(row, column, bingocard) total_bingo_start = total_bingo # Every round, amount of bingo's is counted, if this amount is increased compared to previous round, a sign is given that there is a new bingo row_bingo = 0 # Different types of bingo's are just counted for fun to give statistics at the end of the game column_bingo = 0 diagonal_bingo = 0 total_bingo = 0 for i in bingocard: # Check horizontal bingo's for j in i: if j == marked: bingo_counter += 1 continue else: bingo_counter = 0 break if bingo_counter >= 5: bingo_counter = 0 row_bingo += 1 for k in range(5): # Check vertical bingo's for h in range(5): if bingocard[h][k] == marked: bingo_counter += 1 continue else: bingo_counter = 0 break if bingo_counter >= 5: bingo_counter = 0 column_bingo += 1 for n in range(5): # Check diagonal bingo (left top to right bottom) if bingocard[n][n] == marked: bingo_counter += 1 continue else: bingo_counter = 0 break if bingo_counter >= 5: bingo_counter = 0 diagonal_bingo += 1 for m in range(5): # Check diagonal bingo (left bottom to right top) if bingocard[4 - m][m] == marked: bingo_counter += 1 continue else: bingo_counter = 0 break if bingo_counter >= 5: bingo_counter = 0 diagonal_bingo += 1 total_bingo = row_bingo+column_bingo+diagonal_bingo if total_bingo > total_bingo_start: # If amount of bingo's is bigger than previous round, show bingo sign that many times as new bingo's new_bingos = total_bingo-total_bingo_start print("---------------------------------------------------") for _ in range(new_bingos): print("!!!!!!!!!!BINGO!!!!!!!!!!") else: break print("------------------End of the game---------------------") # When decided to end the game, show end sign with the results print("Your score was: ") print(row_bingo, " horizontal bingo('s)") print(column_bingo, " vertical bingo('s)") print(diagonal_bingo, " diagonal bingo('s)") print("Which is a total of ", row_bingo + column_bingo + diagonal_bingo, " bingo's")
81188e106fd95f879224e4e352050f8c5118a304
another-computer/hanabi-py
/Hanabi/Deck.py
1,144
3.859375
4
from Card import Card from Card import colors from Card import numbers from random import shuffle class Deck(object): def __init__(self, difficulty): self.cards = [] self.frequencies = [3, 2, 2, 2, 1] self.excluded_colors = ["Unknown"] if difficulty == "Normal": self.excluded_colors.append("Rainbow") elif difficulty == "Difficult": self.frequencies = [1, 1, 1, 1, 1] for color in colors.keys(): if color not in self.excluded_colors: for number in numbers: for x in range(self.frequencies[int(number) - 1]): self.cards.append(Card(color, number)) shuffle(self.cards) self.cards_remaining = len(self.cards) def draw(self): drawn_card = self.cards.pop() self.cards_remaining = len(self.cards) return drawn_card test = Deck("Normal") for card in test.cards: print(card) print(test.cards_remaining) print('') print(test.cards[-1]) card = test.draw() print(card) print(test.cards_remaining)
7390058675a8e0347be9f57ed1545b41fa9e8f12
SalmaHazem310/MidtermImageSegmentation
/shallow_neural_network_image.py
3,175
3.5625
4
import numpy as np import cv2 import matplotlib.pyplot as plt class NeuralNetwork(): def __init__(self): self.weights = np.random.uniform(-1, 1, size = 1) def segmoid(self, x): return 1 / (1+ np.exp(-x)) def segmoid_derivative(self, x): return x * (1 - x) def train(self, training_inputs, training_outputs, training_iterations): for i in range(training_iterations): output = self.predict(training_inputs) error = training_outputs.T[0] - output updates = np.dot(training_inputs.T, error* self.segmoid_derivative(output)) self.weights += updates def predict(self, inputs): output = self.segmoid(np.dot(inputs, self.weights)) return output def get_results(test_image, nn): # Reading the three objects object_1_image = cv2.imread('object_1.bmp') object_2_image = cv2.imread('object_2.bmp') object_3_image = cv2.imread('object_3.bmp') # Getting sizes of object images H1 = object_1_image.shape[0] H2 = object_2_image.shape[0] H3 = object_3_image.shape[0] W1 = object_1_image.shape[1] W2 = object_2_image.shape[1] W3 = object_3_image.shape[1] # Get new image sizes height = max(H1, H2, H3) width = max(W1, W2, W3) dsize = (width, height) # Resize all images with the new size object_1_image = cv2.resize(object_1_image, dsize) object_2_image = cv2.resize(object_2_image, dsize) object_3_image = cv2.resize(object_3_image, dsize) # Getting each channel mean in all objects r_channel_mean_1 = np.mean(object_1_image[:, :, 2]) g_channel_mean_1 = np.mean(object_1_image[:, :, 1]) b_channel_mean_1 = np.mean(object_1_image[:, :, 0]) r_channel_mean_2 = np.mean(object_2_image[:, :, 2]) g_channel_mean_2 = np.mean(object_2_image[:, :, 1]) b_channel_mean_2 = np.mean(object_2_image[:, :, 0]) r_channel_mean_3 = np.mean(object_3_image[:, :, 2]) g_channel_mean_3 = np.mean(object_3_image[:, :, 1]) b_channel_mean_3 = np.mean(object_3_image[:, :, 0]) final_image = np.zeros((test_image.shape[0], test_image.shape[1], test_image.shape[2])) for i in range(test_image.shape[0]): for j in range(test_image.shape[1]): current_pixel_mean = np.mean([test_image[i][j][2], test_image[i][j][1], test_image[i][j][0]]) predicted_label = nn.predict([current_pixel_mean]) if int(predicted_label) == 0: final_image[i][j][0] = b_channel_mean_1/255 final_image[i][j][1] = g_channel_mean_1/255 final_image[i][j][2] = r_channel_mean_1/255 elif predicted_label == 0.5: final_image[i][j][0] = b_channel_mean_2/255 final_image[i][j][1] = g_channel_mean_2/255 final_image[i][j][2] = r_channel_mean_2/255 elif int(predicted_label) == 1: final_image[i][j][0] = b_channel_mean_3/255 final_image[i][j][1] = g_channel_mean_3/255 final_image[i][j][2] = r_channel_mean_3/255 return final_image
6e6545bf2e9b4a7ff360d8151e6418168f777ff8
sagarujjwal/DataStructures
/Stack/StackBalancedParens.py
986
4.15625
4
# W.A.P to find the given parenthesis in string format is balanced or not. # balanced: {([])}, [()] # non balanced: {{, (() from stack import Stack def is_match(p1, p2): if p1 == '[' and p2 == ']': return True elif p1 == '{' and p2 == '}': return True elif p1 == '(' and p2 == ')': return True else: return False def is_paren_balanced(paren_string): s=Stack() is_balanced=True index=0 while index < len(paren_string) and is_balanced: paren=paren_string[index] if paren in '[{(': s.push(paren) else: if s.is_empty(): is_balanced = False else: top=s.pop() if not is_match(top,paren): is_balanced = False index+=1 if s.is_empty() and is_balanced: return True else: return False #print(is_paren_balanced('([{(){}()}])')) print(is_paren_balanced('[{(){}{}]'))
06b3257978638ef255f9a457522402e79948fbc2
sagarujjwal/DataStructures
/List&Array/min&max_of_array.py
394
3.921875
4
#Find the maximum and minimum element in an array def minmaxArray(list): x = list[0] y = list[1] if x>y: max=x min=y else: max=y min=x for i in range(2,len(list)): if max < list[i]: max= list[i] elif min > list[i]: min=list[i] return min,max A = [-1,9,0,1, 2, 3, 4, 5, 6,-99] print(minmaxArray(A))
30815e5dc345089512ec5d8aefaeb252e38da2bf
McCoyAle/100-days-of-code
/python-hardway/ex5/ex5.py
580
3.5
4
my_name = 'Alexandra McCoy' my_age = 31 my_height = 66 # inches my_weight = 161 # lbs my_eyes = 'Brown' my_teeth = 'White' my_hair = 'Black' print "Let's talk about %s." % my_name print "She's %d inches tall." % my_height print "She's %d pounds heavy." % my_weight print "Actually, that's not too heavy." print "He's got %s eyes and %s hair." % (my_eyes, my_hair) print "His teeth are usually %s depending on the coffee." % my_teeth # This line is tricky. Try to get it correct. print "If I add %d, %d, and %d I get %d." % (my_age, my_height, my_weight, my_age + my_height + my_weight)
380769147add0ecf5e071fa3eb5859ee2eded6da
alexmeigz/code-excerpts
/trie.py
1,185
4.40625
4
# Trie Class Definition # '*' indicates end of string class Trie: def __init__(self): self.root = dict() def insert(self, s: str): traverse = self.root for char in s: if not traverse.get(char): traverse[char] = dict() traverse = traverse.get(char) traverse['*'] = '*' def find(self, s: str) -> bool: traverse = self.root for char in s: if not traverse.get(char): return False traverse = traverse.get(char) return traverse.get('*', '') == '*' def delete(self, s: str) -> bool: traverse = self.root for char in s: if not traverse.get(char): return False traverse = traverse.get(char) if not traverse.get('*'): return False traverse.pop("*") return True ''' # Sample Usage if __name__ == "__main__": t = Trie() t.insert("hello") print(t.find("he")) t.insert("he") print(t.find("he")) t.delete("he") print(t.find("he")) print(t.root) '''
93e3864e7fb2eef442177f2b6fab3b1f922a4b19
LozovskiAlexey/Computational-Algorithms
/lab_05/main.py
2,690
3.625
4
from math import pow CONST = 0 # константа Pнач/Tнач # класс функции T(z) чтоб по всем функциям не таскать много перменнных class T_function(object): def __init__(self, t0, tw, m): self.T0 = t0 self.Tw = tw self.m = m def count(self, z): return self.T0 + (self.Tw - self.T0) * pow(z, self.m) # функция N(T(z), P) def N(T, P): return 7243 * P / T # интеграл функции N(T(z), P)*z def integrate(a, b, n, T, P): # a, b - границы интегрирования # n - число разбиений # T, P параметры функции N(T(z), P) h = float(b-a) / n # высота трапеций res = 0 # результат куда суммируются площади z = a pr = N(T.count(z), P)*z z += h while z <= b: tmp = N(T.count(z), P)*z res += (pr + tmp)*h*0.5 pr = tmp z += h return res # считает уравнение def count_eq(T, P): global CONST n = 10 # число разбиений для метода трапеций return 7243*CONST - 2*integrate(0, 1, n, T, P) # находит корень уравнения методом дихотомии(половинного деления) def get_p(T, int_p): eps = 1e-12 st = int_p[0] end = int_p[-1] # TODO если корня на промежутке нет - программа зациклится while True: # выбираем среднее значение интервала и решаем уравнение P = 0.5*(st + end) res = count_eq(T, P) # обработка получившегося значения if abs(res) <= eps: break elif res < 0: # если полученное значение меньше нуля end = P # берем интервал [:p] elif res > 0: # иначе st = P # интервал [p:] return P def main(): global CONST # ввод параметров p_st = float(input("Введите Pнач: ")) t_st = float(input("Введите Tнач: ")) CONST = p_st / t_st t0 = float(input("Введите T0: ")) tw = float(input("Введите Tw: ")) m = float(input("Введите m: ")) int_p = [0, 20] T = T_function(t0, tw, m) # сохраняем параметры для высчитывания T(z) p = get_p(T, int_p) print("Результат вычислений: {:.4f}".format(p)) if __name__ == "__main__": main()
d5ac9b9c4c0ff99cfadd0bf6f48824d994f8582d
GT-ARC/gradoptbenchmark
/util/database.py
3,423
3.921875
4
# -*- coding: utf-8 -*- """ Created on 28.03.2019 @author: christian.geissler@gt-arc.com """ ''' A small, simple dirty dictionary database class, that can be used to simply store, save and load data to/from .json. The data is stored in a tree of dictionaries that are automatically created when referenced by a "store" method call. You can use any amount of arguments to encode the path. The last argument is assumed to be the value to be saved. # Usage: Create a database instance with db = Database() # store a value: db.store("a", "hierarchical", "path", 5) db.store("a", "nother", "path", 2) # save to file: db.saveToJson("myDbFile.json") # load from json: db2 = Database() db2.loadFromJson("myDbFile.json") # check, if a certain value exist: t = db2.exists("a", "hierarchical", "path") print(t) #should output "true" #retrieve values: v = db2.get("a", "hierarchical", "path") print(v) #should output "2" #retrieve the whole dictionary at "a" "hierarchical": d = db2.get("a", "hierarchical") ''' #system imports import logging import json #for tmp data storage class Database: def __init__(self, *args, **kw): self.core = dict() ''' Store a value in the database Input a couple of strings, followed by a value to be stored in the db. example: store("firstLayerId", "secondLayerId", 15) ''' def store(self, *args): subStore = self.core for arg in args[:-2]: if not (arg in subStore): subStore[arg] = dict() subStore = subStore[arg] subStore[args[-2]] = args[-1] ''' Check, if a certain layer or value exists Input a couple of strings. Output boolean ''' def exists(self, *args): subStore = self.core for arg in args: if not (arg in subStore): return False subStore = subStore[arg] return True ''' Retrieve a value from the database Input a couple of strings. example: get("firstLayerId", "secondLayerId") Output: Value or None, if that value doesn't exist ''' def get(self, *args): subStore = self.core for arg in args: if not (arg in subStore): return None subStore = subStore[arg] return subStore ''' load the metafeatures to a json file. You can load them with "loadFromJson". Input file[String] - path to the location + filename. Example: 'tmp/metastore.json' ''' def saveToJson(self, file): with open(file, 'w') as outfile: json.dump(self.core, outfile) ''' load the metafeatures from a json file. Warning: Overrides the current saved metafeatures of this instance. Input file[String] - path to the location + filename. Example: 'tmp/metastore.json' ''' def loadFromJson(self, file): try: with open(file, 'r') as infile: self.core = json.load(infile) except FileNotFoundError: logging.warning('could not find json file to load from: '+str(file)) pass
68fc3b5b321975420962fbbd42783034c20fec99
vishnu13579/principles-of-computing
/#5 - Word Wrangler.py
4,634
4
4
""" Student code for Word Wrangler game """ import urllib2 import codeskulptor import poc_wrangler_provided as provided import math WORDFILE = "assets_scrabble_words3.txt" # Functions to manipulate ordered word lists def remove_duplicates(list1): """ Eliminate duplicates in a sorted list. Returns a new sorted list with the same elements in list1, but with no duplicates. This function can be iterative. """ result = [] prev_word = "" for idx in range(len(list1)): curr_word = list1[idx] if curr_word != prev_word: result.append(curr_word) elif curr_word == prev_word: pass prev_word = curr_word return result def intersect(list1, list2): """ Compute the intersection of two sorted lists. Returns a new sorted list containing only elements that are in both list1 and list2. This function can be iterative. """ result = [] list1 = remove_duplicates(list1) list2 = remove_duplicates(list2) result = [val for val in list1 if val in list2] return result # Functions to perform merge sort def merge(list1, list2): """ Merge two sorted lists. Returns a new sorted list containing all of the elements that are in both list1 and list2. This function can be iterative. """ result = [] list1_copy = [] list2_copy = [] for idx in range(len(list1)): list1_copy.append(list1[idx]) for idy in range(len(list2)): list2_copy.append(list2[idy]) while list1_copy and list2_copy: if list1_copy[0] < list2_copy[0]: result.append(list1_copy.pop(0)) else: result.append(list2_copy.pop(0)) return result + list1_copy + list2_copy def merge_sort(list1): """ Sort the elements of list1. Return a new sorted list with the same elements as list1. This function should be recursive. """ if (len(list1) == 1 or len(list1) == 0): return list1 length = len(list1) mid = int(math.floor(length/2)) first = [] second = [] for idx in range(mid): first.append(list1[idx]) for idy in range(mid, length): second.append(list1[idy]) sorted_first = merge_sort(first) sorted_second = merge_sort(second) result = merge(sorted_first, sorted_second) return result # Function to generate all strings for the word wrangler game def gen_all_strings(word): """ Generate all strings that can be composed from the letters in word in any order. Returns a list of all strings that can be formed from the letters in word. This function should be recursive. """ result = [] if word == "": return [word] first = word[0] rest_word = word[1:] rest_strings = [] rest_strings = gen_all_strings(rest_word) for string in rest_strings: if string == "": new_string = first result.append(new_string) else: for idx in range(len(string)+1): front = string[0:idx] #print "front", front back = string[idx:] #print "back", back new_string = front + first + back #print "new string", new_string result.append(new_string) return result + rest_strings # Function to load words from a file def load_words(filename): """ Load word list from the file named filename. Returns a list of strings. """ url = codeskulptor.file2url(filename) netfile = urllib2.urlopen(url) data = [] for line in netfile.readlines(): word = line.strip() data.append(word) return data def run(): """ Run game. """ #list1 = ["aye", "bye", "bye", "hi", "hi", "oh"] #list1 = ["aye"] #list2 = ["cya", "bye", "aye"] #sortedlist = merge_sort(list2) #print "merge_sorted", sortedlist #list3 = ["bye", "oh", "hi", "hi"] #list2 = remove_duplicates(list1) #inter = intersect(list1, list3) #merged = merge(list1, list2) #print "merged", merged #print "remove_dupes", list2 #all_strings = gen_all_strings("bar") #print "all strings", all_strings words = load_words(WORDFILE) wrangler = provided.WordWrangler(words, remove_duplicates, intersect, merge_sort, gen_all_strings) provided.run_game(wrangler) # Uncomment when you are ready to try the game run()
9553ae83e83d03cf7ee73eaf32d153b5eea8a6ef
cartland/algorithms
/python/sort.py
6,130
3.734375
4
# Copyright 2017 Chris Cartland. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import random import sys import unittest from heap import Heap class Sorter(object): def sort(self, data): raise NotImplementedError() def is_sorted(self, data): l = len(data) if l == 0: return True val = data[0] for i in xrange(1, len(data)): next_val = data[i] if val > next_val: return False val = next_val return True class BubbleSorter(Sorter): def sort(self, data_input): data = list(data_input) # Copy list done = False while not done: done = True for i in xrange(len(data) - 1): if data[i] > data[i+1]: temp = data[i] data[i] = data[i+1] data[i+1] = temp done = False return data class HeapSorter(Sorter): def sort(self, data_input): data = list(data_input) # Copy list heap = Heap() for d in data: heap.insert(d) for i in xrange(len(data)): data[i] = heap.pop() return data class InsertionSorter(Sorter): def sort(self, data_input): data = list(data_input) # Copy list for i in xrange(1, len(data)): for j in xrange(i, 0, -1): if data[j] < data[j-1]: temp = data[j-1] data[j-1] = data[j] data[j] = temp return data class MergeSorter(Sorter): def sort(self, data_input): data = list(data_input) # Copy list self.merge_sort(data, 0, len(data_input) - 1) return data def merge_sort(self, data, left, right): if left < right: center = (left + right) / 2 self.merge_sort(data, left, center) self.merge_sort(data, center+1, right) self.merge(data, left, center+1, right) def merge(self, data, left, right, right_end): left_end = right - 1 temp = [] li = left ri = right while li <= left_end and ri <= right_end: if data[li] < data[ri]: temp.append(data[li]) li += 1 else: temp.append(data[ri]) ri+= 1 while li <= left_end: temp.append(data[li]) li += 1 while ri <= right_end: temp.append(data[ri]) ri += 1 for i in xrange(len(temp)): data[left + i] = temp[i] class SelectionSorter(Sorter): def sort(self, data_input): data = list(data_input) # Copy list for i in xrange(len(data)): best_index = i best_val = data[i] for j in xrange(i, len(data)): val = data[j] if val < best_val: best_index = j best_val = val temp = data[i] data[i] = data[best_index] data[best_index] = temp return data class QuickSorter(Sorter): def sort(self, data_input): data = list(data_input) # Copy list self.quick_sort(data, 0, len(data) - 1) return data def quick_sort(self, data, lo, hi): if lo >= hi: return pivot = random.randint(lo, hi) pivot_val = data[pivot] data[pivot] = data[lo] data[lo] = pivot_val pivot = lo for i in xrange(lo, hi + 1): if data[i] < pivot_val: data[pivot] = data[i] # New value moves to pivot location data[i] = data[pivot + 1] # pivot+1 goes to new value's location data[pivot + 1] = pivot_val # pivot goes to pivot+1 pivot += 1 self.quick_sort(data, lo, pivot - 1) self.quick_sort(data, pivot + 1, hi) class TestBubbleSorter(unittest.TestCase): """Test cases for sorters.""" def setUp(self): self.data = test_data() def test_empty(self): sorter = BubbleSorter() data = [] result = sorter.sort(data) self.assertIsNotNone(result) self.assertEqual(len(result), len(data)) self.assertTrue(sorter.is_sorted(result)) def test_bubble_sort(self): sorter = BubbleSorter() data = self.data result = sorter.sort(data) print 'Bubble Sort' print result self.assertIsNotNone(result) self.assertEqual(len(result), len(data)) self.assertTrue(sorter.is_sorted(result)) def test_merge_sort(self): sorter = MergeSorter() data = self.data result = sorter.sort(data) print 'Merge Sort' print result self.assertIsNotNone(result) self.assertEqual(len(result), len(data)) self.assertTrue(sorter.is_sorted(result)) def test_heap_sort(self): sorter = HeapSorter() data = self.data result = sorter.sort(data) print 'Heap Sort' print result self.assertIsNotNone(result) self.assertEqual(len(result), len(data)) self.assertTrue(sorter.is_sorted(result)) def test_insertion_sort(self): sorter = InsertionSorter() data = self.data result = sorter.sort(data) print 'Insertion Sort' print result self.assertIsNotNone(result) self.assertEqual(len(result), len(data)) self.assertTrue(sorter.is_sorted(result)) def test_quick_sort(self): sorter = QuickSorter() data = self.data result = sorter.sort(data) print 'Quick Sort' print result self.assertIsNotNone(result) self.assertEqual(len(result), len(data)) self.assertTrue(sorter.is_sorted(result)) def test_selection_sort(self): sorter = SelectionSorter() data = self.data result = sorter.sort(data) print 'Selection Sort' print result self.assertIsNotNone(result) self.assertEqual(len(result), len(data)) self.assertTrue(sorter.is_sorted(result)) DATA = None def test_data(): global DATA if DATA is None: max_int = 100 # sys.maxint DATA = tuple(random.randint(0, max_int) for _ in xrange(30)) return DATA if __name__ == '__main__': unittest.main()
c8e35a091a3e57b0ff80252f2179702f514bc21b
ezgoca/cursoEmVideo
/Exercicio28.py
459
3.78125
4
from random import randint from time import sleep # lista = [1,2,3,4,5] lista = randint(0,5) num_user = int(input('Em que numero estou pensando entre 0 a 5?\n')) # num_programa = random.choice(lista) # if num_user == num_programa: print('-=-'*20) print("Processandor....") sleep(3) print('-=-'*20) if num_user == lista: print('Parabens, pensei neste numero {} mesmo!'.format(lista)) else: print('Você errou! o numero escolhido foi {}!'.format(lista))
e80ea3211da7da949dfc61c325f7bdf3a2de6de4
ezgoca/cursoEmVideo
/exercicio5.py
132
3.953125
4
n=int (input('Digite um numero: ')) a= n-1 s= n+1 print('Analisando o valor {}, seu antercesor é {} e o sussesor {}'.format(n,a,s))
2efc13f292147b1f4f74ccb4dad7e3d113e6818b
ezgoca/cursoEmVideo
/Exercicio29.py
219
3.78125
4
vel = float(input('Digite a velocidade do carro: \n')) if vel >= 80: multa = (vel - 80) * 7 print('Você foi multado com o valor total R${}'.format(multa)) else: print('Tenha um bom dia e uma otima viagem')
2d830b044ad4b57d053424d2c432e13ad5d7aa1a
EgorBedokurov/-2-03.11.2020
/Lesson_2.3.py
553
3.84375
4
#v=int(input('с какой скоростью едет Василий? - ')) #t=int(input('где будет Василий через - ')) #x=v*t #print=('Вася будет на отметке ' + str(x)) print('с какой скоростью едет Василий? - ') v=int(input()) print('сколько времени Василий проехал? - ') t=int(input()) dis=v*t if dis <=100: print('Вася будет на отметке - ' + str(dis) + ' км') else: print('Вася, ты далеко уехал')
b49e031ff5b347ccc0eaad9ce0243d4f56d71768
Ibarra11/TicTacToe
/tic_tac_toe.py
4,055
3.921875
4
def game(): markers = [[],[]] player = 0 board = [['','',''] , ['','',''], ['','','']] remainingPositions = 9 hasWon = False def init(): markers[0] = input('Player 1 choose your marker: ').upper() markers[1] = input('Player 2 choose your marker: ').upper() def placeInputOnBoard(position): if position <= 3: if board[0][position-1] == '': board[0][position - 1] = markers[player] else: print('The position is already occupied on the board. Please try again!') position = getUserMarkerLocation() placeInputOnBoard(position) elif position <= 6: if board[1][position-4] == '': board[1][position-4] = markers[player] else: print("That space on the board is already occupied") position = getUserMarkerLocation() placeInputOnBoard(position) elif position <= 9: if board[2][position-7] == '': board[2][position-7] = markers[player] else: print("That space on the board is already occupied") position = getUserMarkerLocation() placeInputOnBoard(position) else: print("Sorry that position is out of range of the board. Please try again") position = getUserMarkerLocation() placeInputOnBoard(position) def checkGame(): wonGame = False if board[0][0] == markers[player] and board[0][1] == markers[player] and board[0][2] == markers[player]: wonGame = True elif board[0][0] == markers[player] and board[1][1] == markers[player] and board[2][2] == markers[player]: wonGame = True elif board[0][2] == markers[player] and board[1][1] == markers[player] and board[2][0] == markers[player]: wonGame = True elif board[0][0] == markers[player] and board[1][0] == markers[player] and board[2][0] == markers[player]: wonGame = True elif board[0][1] == markers[player] and board[1][1] == markers[player] and board[2][1] == markers[player]: wonGame = True elif board[0][2] == markers[player] and board[1][2] == markers[player] and board[2][2] == markers[player]: wonGame = True elif board[1][0] == markers[player] and board[1][1] == markers[player] and board[1][2] == markers[player]: wonGame = True elif board[2][0] == markers[player] and board[2][1] == markers[player] and board[2][2] == markers[player]: wonGame = True return wonGame def printBoard(l): for row in l: colIndex = 0 for col in row: if colIndex < 2: print(col, '|', end="") colIndex += 1 else: print(col, end="") print() def getUserMarkerLocation(): return int(input("Player {} please choose a location to place your marker".format(player + 1))) init() while remainingPositions > 0: pos = getUserMarkerLocation() remainingPositions -= 1 print('-------------------------------------') placeInputOnBoard(pos) if checkGame() == True: hasWon = True break printBoard(board) print('-------------------------------------') if player == 0: player = 1 else: player = 0 ''' If there are no more positions on the board left then check if there isnt a winner. The check game checks the last user to place a marker on the board since ''' if hasWon == True: print('Congratulations player ', player + 1, ' you just have won the game') printBoard(board) print('-------------------------------------') elif remainingPositions == 0 and hasWon != True: print('The game ended in a tie') printBoard(board) game()
a382e60f41f1128bf470ce9fbd904bdf9f676cc8
chrisbouton/325Program4
/campusRecycle.py
16,992
3.828125
4
#Christopher Bouton and A..... #Dr. Lori #Advanced Data Structures 325 #Program 4: Campus Recycling import csv import time #data = vertex class Vertex(): def __init__(self, data, index): self.data = data self.edges = LinkedList() self.found = False self.index = index def getData(self): return self.data def setData(self, data): self.data = data class Edge: def __init__(self, weight, origin=None, dest=None): self.origin = origin self.dest = dest self.weight = weight # self.node = Node() def getWeight(self): return self.weight def setWeight(self, w): self.weight = w def getOrigin(self): return self.origin def setOrigin(self, origin): self.origin = origin def getDest(self): return self.dest def setDest(self, dest): self.dest = dest ##might not be right def getEndPoints(self): return self.getOrigin(), self.getDest() def opposite(self, vertex): if (self.getOrigin() == vertex): return self.getDest() elif(self.getDest() == vertex): return self.getOrigin() else: return -1 class Node: ##constructor def __init__(self): self.childs = LinkedList() self.word = False self.data = None self.next = None self.prev = None # Python program to insert in sorted list class LinkedList: numItems = 0 # Function to initialize head def __init__(self): self.head = None def sortedInsert(self, new_node): # Special case for the empty linked list if self.head is None: new_node.next = self.head self.head = new_node self.numItems += 1 # Special case for head at end elif self.head.data >= new_node.data: new_node.next = self.head self.head = new_node self.numItems += 1 else : # Locate the node before the point of insertion current = self.head while(current.next is not None and current.next.data < new_node.data): current = current.next new_node.next = current.next current.next = new_node self.numItems += 1 # Function to insert a new node at the beginning def push(self, new_data): new_node = Node() new_node.data = new_data new_node.next = self.head self.head = new_node self.numItems += 1 # Utility function to prit the linked LinkedList def printList(self): temp = self.head while(temp): print (temp.data) temp = temp.next # # Driver program # llist = LinkedList() # new_node = Node(5) # llist.sortedInsert(new_node) # new_node = Node(10) # llist.sortedInsert(new_node) # new_node = Node(7) # llist.sortedInsert(new_node) # new_node = Node(3) # llist.sortedInsert(new_node) # new_node = Node(1) # llist.sortedInsert(new_node) # new_node = Node(9) # llist.sortedInsert(new_node) # print "Create Linked List" # llist.printList() def goTo(self, m): self.curr = self.head i = 0 while (i < m): if(self.curr.next != None): self.curr = self.curr.next i += 1 else: break return self.curr # def iterate(self): # self.curr = self.head # i = 0 # while(i < self.numItems): ##got queue class from <https://stackoverflow.com/questions/45688871/implementing-an-efficient-queue-in-python> class QNode(object): def __init__(self, item = None): self.item = item self.next = None self.previous = None class Queue(object): def __init__(self): self.length = 0 self.head = None self.tail = None def enqueue(self, x): newNode = QNode(x) if self.head == None: self.head = self.tail = newNode else: self.tail.next = newNode newNode.previous = self.tail self.tail = newNode self.length += 1 def dequeue (self): item = self.head.item self.head = self.head.next self.length -= 1 if self.length == 0: self.last = None return item ##stack class site <https://www.pythoncentral.io/stack-tutorial-python-implementation/> class Stack: #Constructor def __init__(self, max_size): self.stack = list() self.maxSize = max_size self.top = 0 #Adds element to the Stack def push(self,data): if self.top>=self.maxSize: return ("Stack Full!") self.stack.append(data) self.top += 1 return True #Removes element from the stack def pop(self): if self.top<=0: return ("Stack Empty!") item = self.stack.pop() self.top -= 1 return item #Size of the stack def size(self): return self.top # s = Stack(8) # print(s.push(1))#prints True # print(s.push(2))#prints True # print(s.push(3))#prints True # print(s.push(4))#prints True # print(s.push(5))#prints True # print(s.push(6))#prints True # print(s.push(7))#prints True # print(s.push(8))#prints True # print(s.push(9))#prints Stack Full! # print(s.size())#prints 8 # print(s.pop())#prints 8 # print(s.pop())#prints 7 #directed weighted graph class class Graph: def __init__(self, numv, adj, buildings): self.Vertices = [] self.numV = numv self.buildings = buildings self.adj = adj #variable to store prim end time self.end1 = 0 #iterating through matrix and creating vertex and edge objects i = 0 j = 0 while(i < numv): self.Vertices.append(Vertex(buildings[i], i)) while(j < numv): if(adj[i][j] != 1000 or adj[i][j] != 0): z = Edge(adj[i][j], i, j) self.Vertices[i].edges.push(z) j = j + 1 i = i + 1 def getNumV(self): return self.numV def setNumV(self, v): self.numV = v ##function that takes 2 vertices and returns edge connecting or null if not adjacent #returns edge that is going out of v1 to v2 def getEdge(self, v1, v2): j = 0 while(v1.edges.goTo(j).dest != None): if(v1.edges.goTo(j).dest == v2.index): return v1.edges.goTo(j) j = j+1 return None #returns vertex based on index provided def getVertex(self, index): for vertex in self.Vertices: if (vertex.index == index): return vertex return None def addEdge(self, weight): # happens in constructor pass ##function to return all (outgoing) edges of a vertex in a list of the edge objects def incidentEdges(self, v): incidentEdgeList = [] j = 0 while(v.edges.goTo(j) != None): incidentEdgeList.append(v.edges.goTo(j)) return incidentEdgeList #depth first search function def DFS(self, startV, numV): stack = Stack(numV) ##bool array to keep track of visted vertices seen = [False] * numV seen[startV.index] = True stack.push(startV) while (stack.size() != 0): # Pop new node from stack curV = stack.pop() print (curV.data) # Visit new node # ??? # Get neighbors edges = curV.edges i = 0 while (i < edges.numItems): # Get index of destination at edge with index i # then returns vertex object corresponding to that index, outgoing edges btw neighbor = self.getVertex(edges.goTo(i).data.getDest()) if (seen[neighbor.index] == False): seen[neighbor.index] = True stack.push(neighbor) i += 1 print(seen), print("visited bool array") return () def BFS(self, startV, numV): queue = Queue() seen = [False] * numV seen[startV.index] = True queue.enqueue(startV) while (queue.length != 0): curV = queue.dequeue() print (curV.data) # Visit new node # ??? # Get neighbor's Linked List edges = curV.edges i = 0 while (i < edges.numItems): # Get index of destination at edge with index i # then returns vertex object corresponding to that index neighbor = self.getVertex(edges.goTo(i).data.getDest()) if (seen[neighbor.index] == False): seen[neighbor.index] = True queue.enqueue(neighbor) i += 1 print(seen), print("visited bool array ^^^^^") return () def Dijkstra(self, source, prevCost, currPath): for index, vertex in enumerate(self.Vertices): if ((self.adj[source][index] + prevCost < 1000) and (self.adj[source][index] + prevCost) < cost[index]): cost[index] = self.adj[source][index] + prevCost sinktree[index] = currPath + "," + buildings[index] #For each of the primary neighbors, run the Dijkstra algorithm again to #check for additional paths self.Dijkstra(index, cost[index], sinktree[index]) #basically BFS #check neighbors of neighbors index = 0 curEdges = self.Vertices[source].edges while (index < curEdges.numItems): curEdge = curEdges.goTo(index).data neighborIndex = curEdge.dest #neighbor = self.getVertex(neighborIndex) #If the node is a neighbor of a neighbor and the overall cost is less than the #current cost, then it is a shorter path: if ((cost[index] + curEdge.weight + prevCost) < 1000) and ((cost[index] + curEdge.weight + prevCost) < cost[neighborIndex]): cost[neighborIndex] = cost[index] + curEdge.weight + prevCost sinktree[neighborIndex] = sinktree[index] + buildings[neighborIndex] #For each of the neighbor's neighbors, run the Dijkstra function again #to check for additional paths self.Dijkstra(neighborIndex, cost[neighborIndex], sinktree[neighborIndex]) index += 1 return sinktree def slowDijkstra(self, source, prevCost, currPath): for index,vertex in enumerate(self.Vertices): if ((self.adj[source][index] + prevCost < 1000) and (self.adj[source][index] + prevCost) > cost[index]): cost[index] = self.adj[source][index] + prevCost sinktree[index] = currPath + "," + buildings[index] #For each of the primary neighbors, run the Dijkstra algorithm again to #check for additional paths self.Dijkstra(index, cost[index], sinktree[index]) #basically BFS #check neighbors of neighbors index = 0 curEdges = self.Vertices[source].edges while (index < curEdges.numItems): curEdge = curEdges.goTo(index).data neighborIndex = curEdge.dest #neighbor = self.getVertex(neighborIndex) #If the node is a neighbor of a neighbor and the overall cost is less than the #current cost, then it is a shorter path: if ((cost[index] + curEdge.weight + prevCost) < 1000) and ((cost[index] + curEdge.weight + prevCost) > cost[neighborIndex]): cost[neighborIndex] = cost[index] + curEdge.weight + prevCost sinktree[neighborIndex] = sinktree[index] + buildings[neighborIndex] #For each of the neighbor's neighbors, run the Dijkstra function again #to check for additional paths self.Dijkstra(neighborIndex, cost[neighborIndex], sinktree[neighborIndex]) index += 1 return sinktree # A utility function to print the constructed MST stored in parent[] def printMST(self, parent): weight = 0 print("\nPRIM MST, starting from V[0]") print ("Edge \tWeight") for i in range(1, len(self.Vertices)): weight += self.adj[parent[i]][i] print ("{} - {} \t {}".format(parent[i],i, self.adj[parent[i]][i])) #i used the python data structures textbook ch14.7 and <https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/> for reference #UTILITY FUNCTION FROM primMST def minKey(self, key, mstSet): min = 1000 for v in range(len(self.Vertices)): if ((key[v] < min) and (mstSet[v] == False)): min = key[v] min_index = v return min_index def primMST(self): #array to pick minimum weight of edges key = [1000] * (self.numV) #array to store constructed MST parent = [None] * (self.numV) #start with first index of vertices key[0] = 0 mstSet = [False]*(self.numV) #make first node root of MST parent[0] = -1 for mainLoop in range(len(self.Vertices)): # Pick the minimum distance vertex from # the set of vertices not yet processed. # u is always equal to src in first iteration u = self.minKey(key, mstSet) # Put the minimum distance vertex in # the shortest path tree mstSet[u] = True # Update dist value of the adjacent vertices # of the picked vertex only if the current # distance is greater than new distance and # the vertex in not in the shotest path tree for v in range(len(self.Vertices)): # graph[u][v] is non zero only for adjacent vertices of m # mstSet[v] is false for vertices not yet included in MST # Update the key only if graph[u][v] is smaller than key[v] if ((self.adj[u][v] < 1000) and (mstSet[v] == False and key[v] > self.adj[u][v]) and (self.adj[u][v] != 0)): key[v] = self.adj[u][v] parent[v] = u self.end1 = time.time() self.printMST(parent) #######MAIN############ ##open csv files with vertices and edges of La tech main campus academic buildings ##make adjacency list with indexes corresponding to vertices numV = 18 adjMatrix = [] buildings = [] with open('AdjMatrix.csv', "r") as adjmat: reader = csv.reader(adjmat, delimiter=',') next(reader, None) #skip first row #remove letters from array rows and store in vertices for row in reader: buildings.append(row[0]) adjMatrix.append(row[1:19]) #skips the first row #convert to int adjMatrix = [[int(j) for j in i] for i in adjMatrix] # print (buildings) # print (adjMatrix) ##command to intiate static graph of buildings in the constructor of Graph gang = Graph(numV, adjMatrix, buildings) print("!!!!!!BREADTH FIRST SEARCH!!!!!!!!!!") gang.BFS(gang.Vertices[0], numV) print ("!!!!!!!!!!DEPTH FIRST SEARCH!!!!!!!!!!") gang.DFS(gang.Vertices[0], numV) #print (gang.DFS(gang.Vertices[0], numV)) ##dijkstras k = 0 for build in buildings: print ("{}={}".format(build, k)) k +=1 #Dijkstra's algorithim pre setup #set all costs to "inf" cost = [1000]* (gang.numV) #Set all paths to blank: sinktree = [-1]*(gang.numV) print("################") dij = input("Enter start building's index for Dijkstras shortest and longest path algorithim\n") dij = int(dij) cost[dij] = 0 sinktree[dij] = gang.buildings[dij] start = time.time() x = gang.Dijkstra(dij, 0, buildings[dij]) end = time.time() DijElapsed = end - start i = 0 print("\nQUICKEST ROUTE FROM DESIRED START BUILDING") for item in x: print("Path: {}".format(item)) print("{} 10ths of a mile".format(cost[i])) i += 1 y = gang.slowDijkstra(dij, 0, buildings[dij]) j = 0 print("\nSLOWEST ROUTE FROM DESIRED START BUILDING") for item in y: print("Path: {}".format(item)) print("{} 10ths of a mile".format(cost[j])) j += 1 start1 = time.time() gang.primMST() primElapsed = gang.end1 - start1 print("Time analysis in(s) of Dij vs Prim = {} to {}".format(DijElapsed, primElapsed))
9663fb189d01e3f220a18d11d2d246c01244570b
sekiguchikeita/python_pra1
/omikuji.py
365
3.796875
4
import random a = random.randint(0,80) print("あなたの運勢は") print("") if a < 2: print("大吉") elif 2 <= a < 10: print("中吉") elif 10 <= a < 20: print("小吉") elif 20 <= a < 40: print("吉") elif 40 <= a < 50: print("末吉") elif 50 <= a < 55: print("凶") elif 55 <= a < 80: print("中凶") else: print("大凶")
69eb2c097713ae1851b1638c54bf24acc387a88f
jedrzejwalega/projekty
/cwiczenia3.py
310
4.03125
4
if "dog" in "dog": print(True) else: print(False) if "dog" in "god": print(True) else: print(False) # na stringach: # .lower() # .upper() # .replace(x, y) # .count() - ile razy cos wystepuje w stringu # .index() - pierwsze wystapienie danego znaku, jego index # .isalpha() - czy ma same litery
df1da214cc55d92786f4d3c4c85d5f8effef0289
jedrzejwalega/projekty
/best_k/__init__.py
1,500
3.59375
4
import numpy as np # BEST_K FUNKCJA def best_k(nums): biggest = 0 for k in range(0, len(nums) + 1): new_biggest = funkcja(nums, k) if biggest == 0: biggest = new_biggest else: biggest = max(biggest, new_biggest) if type(new_biggest) is str: return new_biggest return biggest # FUNKCJA FUNKCJA def funkcja(nums: list, k: int): list_length = len(nums) k_index = range(k) # checking if the list is alright if list_length == 0: return "Error: Empty list." if list_length < k: return "Error: Index out of range." for num in nums: if num is None: return "Error: Function doesn't accept None as a value." if type(num) is str: return "Error: Function doesn't accept strings." # calculating biggest value for n in range(list_length): if list_length - n >= k: k_counter = 0 # prevents the for loop from adding more values than stated by k biggest = 0 while k_counter < k: for k_part in k_index: biggest += nums[n + k_part] k_counter += 1 if n == 0: biggest_new = biggest else: biggest_new = max(biggest, biggest_new) else: continue if np.isnan(nums).any() == True: return "Error: Function doesn't accept NaN values." return biggest_new
667cce2320c15725e716608c72ef5a58c0b43534
altoid/misc_puzzles
/py/indeed/whiteboard.py
2,881
3.84375
4
#!/usr/bin/env python # syntax rules import unittest def indentation(line): if not line: return 0 return len(line) - len(line.lstrip()) def is_valid(lines): """ :param lines: :return: the line number of the first invalid line, -1 if all lines valid """ indentation_levels = [0] after_block = False counter = 1 for l in lines: stripped = l.strip() if not stripped: counter += 1 continue line_indent = indentation(l) if after_block: after_block = False if line_indent <= indentation_levels[-1]: return counter indentation_levels.append(line_indent) if line_indent < indentation_levels[-1]: # keep popping stack until indent level matches while indentation_levels[-1] > line_indent: indentation_levels = indentation_levels[:-1] if indentation_levels[-1] < line_indent: return counter if line_indent != indentation_levels[-1]: return counter if l[-1] == ':': after_block = True counter += 1 return -1 class MyTest(unittest.TestCase): def test_indentation(self): self.assertEqual(0, indentation(None)) self.assertEqual(0, indentation("")) self.assertEqual(0, indentation("i like cheese")) self.assertEqual(3, indentation(" indented")) self.assertEqual(4, indentation(" ")) def test_valid(self): text = """ x = 5 for i in range(1, 10): if i == 2: print "hard to read" else: x = 3 print "stop" print "done" """ lines = text.split('\n') self.assertEqual(-1, is_valid(lines)) def test_valid_blank_lines(self): text = """ x = 5 for i in range(1, 10): if i == 2: print "hard to read" else: x = 3 print "stop" print "done" """ lines = text.split('\n') self.assertEqual(-1, is_valid(lines)) def test_outdent_after_block(self): text = """ x = 5 for i in range(1, 10): if i == 2: print "hard to read" """ lines = text.split('\n') self.assertEqual(5, is_valid(lines)) def test_invalid(self): text = """ x = 5 for i in range(1, 10): if i == 2: print "hard to read" else: x = 3 print "stop" print "done" """ lines = text.split('\n') self.assertEqual(2, is_valid(lines)) def test_noblocks(self): text = """ x = 5 print "done" """ lines = text.split('\n') self.assertEqual(-1, is_valid(lines)) def test_wrong_indent(self): text = """ if x == 5: print "done" """ lines = text.split('\n') self.assertEqual(3, is_valid(lines))
460f4323140734a4ff38e6fcf79c1ef8966d4010
altoid/misc_puzzles
/py/interview1/BAK/lego.py
3,432
3.90625
4
#!/usr/bin/env python import math import pprint pp = pprint.PrettyPrinter() def choose(n, r): return math.factorial(n) // (math.factorial(r) * math.factorial(n - r)) def count(height_n, width_m): # total # of combinations # - number that have a seam in one position # + number that have a seam in two positions # - number that have a seam in 3 positions # # +/- number that have a seam in width - 1 positions result = brick_combo(width_m) ** height_n print ">>>>>> initial result: %s" % result multiplier = -1 partition_dict = organize_partitions(partition(width_m)) for seams in xrange(1, width_m): print "seams: %s coefficient (%s %s)" % ( seams, width_m - 1, seams) coefficient = choose(width_m, seams) ntowers = seams + 1 print "%s: %s" % (ntowers, pp.pformat(partition_dict[ntowers])) towers = partition_dict[ntowers] partial_sum = 0 for t in towers: partial_product = 1 for s in t: partial_product *= (brick_combo(s) ** height_n) print "checking %s: pproduct = %s" % (t, partial_product) partial_sum += partial_product print "partial sum for seams = %s: %s" % (seams, partial_sum) d = partial_sum * multiplier result += d multiplier = -multiplier result = result % 1000000007 print "### final result: %s" % result return result def organize_partitions(partitions): ''' partitions are sets of comma separated strings turn this into a dict key is length of partition value is list of lists of ints whose length is the key ''' result = {} for p in partitions: sublist = [int(x) for x in p.split(',')] l = len(sublist) if l not in result: result[l] = [] result[l].append(sublist) return result def partition(n): ''' generate partitions of the integer n returns a set of comma-separated strings, each string is a partition ''' if n == 1: return set('1') result = set() for k in range(1, n): # result is the set of all partitions of n - k, to which k has been added. # do this for all k [1..n) # then put n into the set sub = partition(n - k) for s in sub: ilist = [x for x in s.split(',')] for i in xrange(len(ilist)): j = ','.join(ilist[:i] + [str(k)] + ilist[i:]) result.add(j) j = ','.join(ilist + [str(k)]) result.add(j) result.add(','.join([str(n)])) return result def brick_combo(n): ''' how many ways are there to partition n into 1, 2, 3, 4? ''' if n == 1: return 1 if n == 2: return 1 + brick_combo(1) if n == 3: return 1 + brick_combo(1) + brick_combo(2) if n == 4: return 1 + brick_combo(3) + brick_combo(2) + brick_combo(1) return brick_combo(n - 1) + brick_combo(n - 2) + brick_combo(n - 3) + brick_combo(n - 4) # we also need # of ways to partition # a row of width N into 2, 3, .. N chunks # 1: # 1 # # 2: # 2 # 1 1 # # 3: # 3 # 2 1 # 1 2 # 1 1 1 # # 4: # 4 # 1 3 # 1 2 1 # 1 1 2 # 1 1 1 1 # 2 1 1 # 2 2 # 3 1 # # 5 # # 1 4 # 1 1 3 # 1 1 2 1 # 1 1 1 2 # # 1 1 1 1 1 # 1 2 1 1 # 1 2 2 # 1 3 1 # # 2 3 # 2 2 1 # 2 1 2 # 2 1 1 1 # # 3 2 # 3 1 1 # 4 1
75d2375e0d1cd7bde0cee78eaa1c60b1edede051
altoid/misc_puzzles
/py/palindrome/solution.py
1,393
3.796875
4
#!/usr/bin/env python # determine whether an integer is a palindrome. # # cases: # # very large number # 2 digit number # 3 digit number # 1 digit number # negative number import unittest def is_palindrome(x): # reverse the number and see if it's equal x_copy = x rev_x = 0 while x_copy != 0: rev_x *= 10 rev_x += x_copy % 10 x_copy //= 10 return rev_x == x class MyTest(unittest.TestCase): def test_simple(self): self.assertFalse(is_palindrome(12345)) def test_1_digit(self): self.assertTrue(is_palindrome(1)) self.assertTrue(is_palindrome(0)) self.assertTrue(is_palindrome(9)) def test_2_digits(self): self.assertTrue(is_palindrome(11)) self.assertTrue(is_palindrome(99)) self.assertFalse(is_palindrome(42)) self.assertFalse(is_palindrome(10)) def test_3_digits(self): self.assertTrue(is_palindrome(111)) self.assertTrue(is_palindrome(121)) self.assertTrue(is_palindrome(999)) self.assertFalse(is_palindrome(100)) self.assertFalse(is_palindrome(198)) self.assertFalse(is_palindrome(908)) def test_large(self): self.assertTrue(is_palindrome(12345678912345678987654321987654321)) self.assertFalse(is_palindrome(1234567891234567898765432198765321))
b9b0babaf3de0499bbd5253dd1570060c44cb060
altoid/misc_puzzles
/py/file_io/myfileinput.py
3,088
3.59375
4
# my implementation of the FileInput class # processing will stop if a file can't be opened for any reason # this is an iterable import sys _state = None class MyFileInput(): def __init__(self, files=[]): files_to_read = files if not files_to_read: if len(sys.argv) > 1: files_to_read = sys.argv[1:] if not files_to_read: files_to_read = ['-'] self.__filenameiter = iter(files_to_read) self.__currentfilename = None self.__currentfilehandle = None self.__isfirstline = False self.__lineno = 0 self.__filelineno = 0 def filename(self): """ Return the name of the file currently being read. Before the first line has been read, returns None. if the file being read is empty, this will never return the name of that file. we will skip over it. :return: """ if self.__currentfilename == '-': return '<stdin>' return self.__currentfilename def readline(self): try: return next(self) except StopIteration: return '' def fileno(self): pass def lineno(self): """ returns the number of lines that have been read, not the total lines in all files up to here. for example, if we read the first line of a file with 100 lines, and lineno returns 1, then call nextfile(), lineno() will return 2. :return: """ return self.__lineno def filelineno(self): return self.__filelineno def isfirstline(self): return self.__isfirstline def isstdin(self): pass def nextfile(self): if self.__currentfilehandle: if self.__currentfilename != '-': self.__currentfilehandle.close() self.__currentfilehandle = None def close(self): pass def __iter__(self): return self def __nextfile(self): self.__currentfilename = next(self.__filenameiter) if self.__currentfilename == '-': self.__currentfilehandle = sys.stdin else: self.__currentfilehandle = open(self.__currentfilename, 'r') def __next__(self): # has to raise StopIteration when there are no more items if self.__isfirstline: self.__isfirstline = False if self.__currentfilehandle is None: self.__nextfile() self.__isfirstline = True line = self.__currentfilehandle.readline() while not line: if self.__currentfilename != '-': self.__currentfilehandle.close() self.__nextfile() line = self.__currentfilehandle.readline() self.__isfirstline = True self.__filelineno = 0 self.__lineno += 1 self.__filelineno += 1 return line def next(self): return self.__next__() def input(files=None): global _state if not _state: _state = MyFileInput(files) return _state
fe7456456b22ca948b06f1a84c2d9f3b78b909f5
altoid/misc_puzzles
/py/prime_bits/same_bits_successors.py
4,206
3.875
4
#!/usr/bin/env python # not part of prime bits solution, but related fun problem: given a positive integer, find the next # largest number with the same number of bits set. so if we are given this: # # +---+---+---+---+---+---+---+---+---+---+---+---+ # | | | | 1 | | 1 | 1 | | | 1 | 1 | | # +---+---+---+---+---+---+---+---+---+---+---+---+ # # the answer is this: # # +---+---+---+---+---+---+---+---+---+---+---+---+ # | | | | 1 | | 1 | 1 | | 1 | | | 1 | # +---+---+---+---+---+---+---+---+---+---+---+---+ # # the next few in the sequence are # # 0 0 0 1 0 1 1 0 1 0 1 0 # 0 0 0 1 0 1 1 0 1 1 0 0 # 0 0 0 1 0 1 1 1 0 0 0 1 # # method: traverse from the right and find the first 0 following a 1. if there is no 0 following # (to the left of) a 1, the number has no successor. # # otherwise, swap the 0 with the 1 to its right. any 1s to the right of this must be moved # all the way to the right. import unittest import random def same_bits_successor(n, width): """ width is the max number of bits we will permit in any successor. """ assert n < 2 ** width if n == 0: return # convert the number to a bit vector n_str = bin(n)[2:] bits = list(map(int, n_str)) # flip the bit vector around so the indexing arithmetic is easier. bits = bits[::-1] # add 0 padding if necessary bits += [0] * (width - len(bits)) # find the first 0 that comes after a 1. i = 0 zero_span = None if bits[i] == 0: zero_span = [i, i] while bits[i] == 0: # we know we will find at least one 1 bit (we already checked n == 0) if zero_span: zero_span[1] = i i += 1 one_span = [i, i] while i < width and bits[i] == 1: one_span[1] = i i += 1 if i == width: return # swap the 1 and 0 bits[i], bits[i - 1] = bits[i - 1], bits[i] one_span[1] -= 1 # now swap the 0 and 1 spans if zero_span and one_span[0] <= one_span[1]: ones = [1] * (one_span[1] - one_span[0] + 1) zeroes = [0] * (zero_span[1] - zero_span[0] + 1) bits = ones + zeroes + bits[i - 1:] # flip the bit vector around and change it into a number bits = bits[::-1] result = 0 for b in bits: result *= 2 if b: result += 1 return result def successors(n, width): s = n while s is not None: yield s s = same_bits_successor(s, width) def test_random_number(): for i in range(10000): n = random.randint(1, 2 ** 32 - 2) s = same_bits_successor(n, 32) n_bits = list(map(int, bin(n)[2:])) s_bits = list(map(int, bin(s)[2:])) if sum(n_bits) != sum(s_bits): print(bin(n)) print(bin(s)) print("bit counts are different") break if s <= n: print(bin(n)) print(bin(s)) print("successor is <= n") break if __name__ == '__main__': # result = successors(11, 8) # lst = list(result) # for n in lst: # print(n, bin(n)) for n in successors(127, 32): print(n, bin(n)) # test_random_number() class MyTest(unittest.TestCase): def test_degenerate_cases(self): self.assertIsNone(same_bits_successor(0, 8)) self.assertIsNone(same_bits_successor(1, 1)) self.assertIsNone(same_bits_successor(2 ** 8 - 1, 8)) self.assertIsNone(same_bits_successor(7 << 5, 8)) def test_1(self): n = 7 w = 6 successors = [11, 13, 14, 19, 21, 22, 25, 26, 28] for s in successors: self.assertEqual(s, same_bits_successor(n, w)) n = s def test_2(self): self.assertEqual(19, same_bits_successor(14, 6)) def test_3(self): self.assertEqual(21, same_bits_successor(19, 6)) def test_same_bit_count(self): n = random.randint(1, 2 ** 32 - 2) s = same_bits_successor(n, 32) n_bits = list(map(int, bin(n)[2:])) s_bits = list(map(int, bin(s)[2:])) self.assertEqual(sum(s_bits), sum(n_bits)) self.assertGreater(s, n)
30c7f7592ee2dee97e4a6a0af5fd974868b8c033
markusdlugi/aoc-2020
/day08.py
1,118
3.65625
4
from copy import deepcopy def run_command(program, ip, acc): command, arg = program[ip] if command == "acc": acc += int(arg) elif command == "jmp": ip += int(arg) - 1 elif command == "nop": pass ip += 1 return ip, acc def run_program(program, acc, print_on_loop): ip = 0 visited = {0} while ip < len(program): ip, acc = run_command(program, ip, acc) if ip not in visited: visited.add(ip) else: if print_on_loop: print(acc) return False, ip, acc return True, ip, acc program = [line.strip().split() for line in open("input/08.txt")] # Part A run_program(program, 0, True) # Part B i = 0 program_copy = None while i < len(program): command, arg = program[i] if command in ("jmp", "nop"): program_copy = deepcopy(program) program_copy[i][0] = "nop" if command == "jmp" else "jmp" else: i += 1 continue terminated, ip, acc = run_program(program_copy, 0, False) if terminated: print(acc) break i += 1
22ae8a42d2274bd41b67a55578413797c54998db
pythagitup/21_game
/Game_messages.py
422
3.796875
4
from Card import Card def show_score(card): if card.owner == 'Player': print(f'Your hand is worth {card.points}.') else: print(f'The computer\'s hand is worth {card.points}.') def winner(player,computer): if player.points > computer.points: print(f'\nCongratulations! You beat the computer!') elif player.points < computer.points: print(f'\nSorry, the computer beat you.')
6da9510d575469face38b44838a163973e9fe837
Sandeep-Narahari/Regex-Software-Services-Assignments
/Python1/Assignment10.py
259
3.953125
4
d1={"a":1,"b":2,"c":3,"d":4} d2={"b":2,"d":4,"f":6,"g":7} d3={} def disJoint(): union=dict(d1.items() | d2.items()) intersection=dict(d1.items() & d2.items()) d3=dict(union.items() ^ intersection.items()) return d3 print(disJoint())
5a791721dc41503aa74efee27ce3222269d5aa05
MindVersal/CodeForcesSolutions
/000-099/000-009/9A/9A.py
453
3.875
4
""" Program for solution problem 9A """ def calculate_probability(): input_numbers = [x for x in input()] big_number = input_numbers[0] if input_numbers[0] >= input_numbers[2] else input_numbers[2] probability = { '1': '1/1', '2': '5/6', '3': '2/3', '4': '1/2', '5': '1/3', '6': '1/6' } return probability[big_number] if __name__ == '__main__': print(calculate_probability())
d913bf5746d8c059e87cee2d88d26caf3f9d64d5
imsoncod/Coding-Specialist-Professional-1st
/4차/4차 1급 5_solution_code.py
373
3.5
4
def solution(n): answer = '' for i in range(n): answer += str(i%9 + 1) answer = answer[::-1] return answer #아래는 테스트케이스 출력을 해보기 위한 코드입니다. n = 5 ret = solution(n) #[실행] 버튼을 누르면 출력 값을 볼 수 있습니다. print("solution 함수의 반환 값은", ret, "입니다.")
3979d1a1bf4fe936b13030197ef5069f38e07941
imsoncod/Coding-Specialist-Professional-1st
/5차/5차 1급 7_solution_code.py
502
3.609375
4
def find(parent, u): if u == parent[u]: return u parent[u] = find(parent, parent[u]) print(parent) return parent[u] def merge(parent, u, v): u = find(parent, u) v = find(parent, v) if u == v: return True parent[u] = v return False def solution(n, connections): answer = 0 parent = [i for i in range(n+1)] for i, connection in enumerate(connections): if merge(parent, connection[0], connection[1]): answer = i + 1 break return answer
bf9b0a1a41542dde154f1b4217edddbba3a4975b
imsoncod/Coding-Specialist-Professional-1st
/4차/4차 1급 4_solution_code.py
2,036
3.546875
4
n = 4 def find_not_exist_nums(matrix): nums = [] exist = [] for i in range(n*n+1): exist.append(False) for i in range(0, n): for j in range(0, n): if matrix[i][j] != 0: exist[matrix[i][j]] = True for i in range(1, n*n+1): if exist[i] == False: nums.append(i) return nums def find_blank_coords(matrix): coords = [] for i in range(0, n): for j in range(0, n): if matrix[i][j] == 0: coords.append([i, j]) return coords def is_magic_square(matrix): goal_sum = 0 for i in range(1, n*n+1): goal_sum += i goal_sum //= n for i in range(0, n): row_sum = 0 col_sum = 0 for j in range(0, n): row_sum += matrix[i][j] col_sum += matrix[j][i] if row_sum != goal_sum: return False if col_sum != goal_sum: return False main_diagonal_sum = 0 skew_diagonal_sum = 0 for i in range(0, n): main_diagonal_sum += matrix[i][i] skew_diagonal_sum += matrix[i][n-1-i] if main_diagonal_sum != goal_sum: return False if skew_diagonal_sum != goal_sum: return False return True def solution(matrix): answer = [] coords = find_blank_coords(matrix) nums = find_not_exist_nums(matrix) matrix[coords[0][0]][coords[0][1]] = nums[0] matrix[coords[1][0]][coords[1][0]] = nums[1] if is_magic_square(matrix) == True: for i in range(0, 2): answer.append(coords[i][0] + 1) answer.append(coords[i][1] + 1) answer.append(nums[i]) else: matrix[coords[0][0]][coords[0][1]] = nums[1] matrix[coords[1][0]][coords[1][1]] = nums[0] for i in range(0, 2): answer.append(coords[1-i][0] + 1) answer.append(coords[1-i][1] + 1) answer.append(nums[i]) return answer
e4aa0b49485ed2a7c448a6be01865f5143ee22f4
mhtarek/Codeforces-solved-problems
/A. Petya and Strings.py
215
3.53125
4
x = lambda: input().lower() a = x() b = x() if a==b: print(0) for i in range(len(a)): if(a[i] > b[i]): print(1) break elif(a[i]<b[i]): print(-1) break
1e726c2adf6c52542b488f9fa561b17b75c06893
jenniferllee/object-orientation-assessment
/assessment.py
3,913
4.59375
5
""" Part 1: Discussion 1. What are the three main design advantages that object orientation can provide? Explain each concept. ENCAPSULATION: You can combine data and functionality in a package or "capsule" so that similar ideas are organized together. ABSTRACTION: You can hide details that are not crucial in understanding the functionality. It is similar to the mechanics of a doorknob. You do not need to know how the strings/pulleys in the doorknob work to know how to use a doorknob. POLYMORPHISM: Compatible components can be interchangeable. 2. What is a class? A class is a "type" of thing. For example, lists, strings, and files are classes. If you check the type of a class, it will return "type". 3. What is an instance attribute? An instance attribute is a quality/characteristic/property of an instance. This attribute sticks directly to the instance itself. 4. What is a method? A method is a function defined on a class. 5. What is an instance in object orientation? An instance is an individual occurance of a class. 6. How is a class attribute different than an instance attribute? Give an example of when you might use each. A class attribute is a quality/characteristic/property that usually pertains to most instances of that class. For example, if you have a Dog class, an example of a class attribute could be four-legged, because for the most part, all dogs have four legs. However, you can make an instance of the Dog class, Fido, who is a dog with three legs. Therefore, an instance attribute for Fido would be three legs. Fido is still a dog, and although most dogs have four legs, he is unique in that he only has three legs. """ # Parts 2 through 5: # Create your classes and class methods class Student(object): def __init__(self, first_name, last_name, address): self.first_name = first_name self.last_name = last_name self.address = address class Question(object): def __init__(self, question, correct_answer): self.question = question self.correct_answer = correct_answer def ask_and_evaluate(self): answer = raw_input(self.question + " > ") if answer == self.correct_answer: return True else: return False class Exam(object): def __init__(self, name): self.name = name self.questions = [] def add_question(self, question, correct_answer): question_to_add = Question(question, correct_answer) self.questions = self.questions + [question_to_add] return self.questions def administer(self): score = float(0) for question in self.questions: correct = question.ask_and_evaluate() if correct is True: score += 1 final_score = score/(len(self.questions)) return final_score class Quiz(Exam): def administer(self): final_score = super(Quiz, self).administer() if final_score >= 0.5: return True else: return False def take_test(exam, student): """ Takes an exam and student, administers the exam, and assigns the score to the student instance. Also print a message indicating the score. """ student_score = exam.administer() student.score = student_score print "%s %s's score on %s is %s." % (student.first_name, student.last_name, exam.name, student.score) def example(exam_name, student_first_name, student_last_name, student_address): """ Creates an exam and student, adds questions to the exam, and administers the exam for that student.""" exam = Exam(exam_name) exam.add_question("What color is the sky?", "Blue") exam.add_question("What is 2 + 2?", "4") student = Student(student_first_name, student_last_name, student_address) take_test(exam, student)
0602f9b8f2f8e231e571e3db47a677a9083c1341
brownboycodes/problem_solving
/code_signal/reverse_in_paranthesis.py
883
3.9375
4
""" Write a function that reverses characters in (possibly nested) parentheses in the input string. Input strings will always be well-formed with matching ()s. """ def reverseInParentheses(inputString): s=[] for i in range(len(inputString)): # push the index of the current opening bracket if (inputString[i] == '('): s.append(i) # Reverse the substarting after the last encountered opening bracket till the current character elif (inputString[i] == ')'): temp = inputString[s[-1]:i + 1] inputString = inputString[:s[-1]] + temp[::-1] +inputString[(i + 1):] del s[-1] # To store the modified strring res = "" for i in range(len(inputString)): if (inputString[i] != ')' and inputString[i] != '('): res += (inputString[i]) return res
03995a46974520e6d587e3c09a24fa1c98a6423f
brownboycodes/problem_solving
/code_signal/shape_area.py
443
4.1875
4
""" Below we will define an n-interesting polygon. Your task is to find the area of a polygon for a given n. A 1-interesting polygon is just a square with a side of length 1. An n-interesting polygon is obtained by taking the n - 1-interesting polygon and appending 1-interesting polygons to its rim, side by side. You can see the 1-, 2-, 3- and 4-interesting polygons in the picture below. """ def shapeArea(n): return n**2+(n-1)**2
298ce4a268c6242ee4b18db1b5029995ebaa183f
brownboycodes/problem_solving
/code_signal/adjacent_elements_product.py
362
4.125
4
""" Given an array of integers, find the pair of adjacent elements that has the largest product and return that product. """ def adjacentElementsProduct(inputArray): product=0 for i in range(0,len(inputArray)-1): if inputArray[i]*inputArray[i+1]>product or product==0: product=inputArray[i]*inputArray[i+1] return product
d1868513900a2bd788f17592361ef278602dbaaa
brownboycodes/problem_solving
/code_signal/is_lucky.py
347
3.9375
4
""" Ticket numbers usually consist of an even number of digits. A ticket number is considered lucky if the sum of the first half of the digits is equal to the sum of the second half. Given a ticket number n, determine if it's lucky or not. """ def isLucky(n): n=list(map(int, str(n))) l=len(n) return sum(n[:(l//2)])==sum(n[l//2:])
fc6966de40440fc04560b436437f32b94fe82efc
petrovplamenph/Artificial-Intelligence-python-implementations-from-scratch
/kmeans.py
4,327
3.53125
4
import math from statistics import mean import matplotlib.pyplot as plt import random class Cluster: def __init__(self,horiz_pos, vert_pos): self._horiz_center = horiz_pos self._vert_center = vert_pos def horiz_center(self): """ Get the averged horizontal center of cluster """ return self._horiz_center def vert_center(self): """ Get the averaged vertical center of the cluster """ return self._vert_center def copy(self): """ Return a copy of a cluster """ copy_cluster = Cluster(self._horiz_center, self._vert_center) return copy_cluster def distance(self, other_point): """ Compute the Euclidean distance between two clusters """ vert_dist = self._vert_center - other_point[1] horiz_dist = self._horiz_center - other_point[0] return math.sqrt(vert_dist ** 2 + horiz_dist ** 2) def recalculate_center(self, new_points): x = 0 y = 0 for point in new_points: x += point[0] y += point[1] self._horiz_center = x/len(new_points) self._vert_center = y/len(new_points) return def load_data(file_name): with open(file_name) as f: data = [] lines = f.readlines() for line in lines: line = line.split('\t') data.append((float(line[0]),float(line[1]))) return data def load_data2(file_name): with open(file_name) as f: data = [] lines = f.readlines() for line in lines: line = line.split(' ') data.append((float(line[0]),float(line[1]))) return data def kmeans_clustering(data, num_clusters, num_iterations): """ Compute the k-means clustering of a set of clusters Note: the function may not mutate cluster_list Input: List of clusters, integers number of clusters and number of iterations Output: List of clusters whose length is num_clusters """ all_points = list(data) random.shuffle(all_points ) new_clusters = list(all_points[:num_clusters]) centers_cluster_list = [] delta = 0.1 for clust in new_clusters: centers_cluster_list.append(Cluster(clust[0],clust[1])) for dummy_itter in range(num_iterations): cluster_to_points = {} for clust_idx in range(num_clusters): cluster_to_points[clust_idx] = [] for point in all_points: min_dist = float("inf") for clust_idx in range(num_clusters): dist = centers_cluster_list[clust_idx].distance(point) if dist < min_dist: min_dist = dist cluster_index = clust_idx cluster_to_points[cluster_index].append(point) #make_copy_of_cluster_ceters: old_clust = [] for clust_idx in range(num_clusters): old_clust.append(centers_cluster_list[clust_idx].copy()) centers_cluster_list[clust_idx].recalculate_center(cluster_to_points[clust_idx]) Flag = True for clust_idx in range(num_clusters): x = centers_cluster_list[clust_idx].horiz_center() y = centers_cluster_list[clust_idx].vert_center() x_old = old_clust[clust_idx].horiz_center() y_old = old_clust[clust_idx].vert_center() if (abs(x - x_old) < delta) or (abs(y - y_old)< delta): Flag = False break if Flag: break x = [] y = [] final_clusturs = [] for clust_idx in range(num_clusters): for point in cluster_to_points[clust_idx]: x.append(point[0]) y.append(point[1]) final_clusturs += [clust_idx]*len(cluster_to_points[clust_idx]) plt.scatter(x, y, c = final_clusturs) plt.show() return centers_cluster_list def row_data_vis(data): x = [] y = [] for point in data: x.append(point[0]) y.append(point[1]) plt.plot(x, y, 'o') plt.show() #data = load_data2('unbalance.txt') data = load_data('normal.txt') kmeans_clustering(data, 8, 800) #row_data_vis(data)
edd691959c2b746f73c8f57539479f08949c78fa
J3rry-L/python
/intro_loops.py
2,734
3.765625
4
def sumFromZeroToN(n): s = 0 while (n > 0): s = s + n n = n - 1 return s print("sumFromZeroToN tests:") print(sumFromZeroToN(-3)) print(sumFromZeroToN(4)) print(sumFromZeroToN(10)) def sumAtoB(a,b): s = 0 while a <= b: s = s + a a = a + 1 return s print("subAtoB tests:") print(sumAtoB(0, 1)) print(sumAtoB(1, 3)) print(sumAtoB(2, 0)) def fiveSumFromZeroToN(n): s = 0 while n > 0: if n % 5 == 0: s = s + n n = n - 1 return s print("fiveSumFromZeroToN tests:") print(fiveSumFromZeroToN(0)) print(fiveSumFromZeroToN(10)) print(fiveSumFromZeroToN(33)) def specialSumInclusive(n): s = 0 while n > 0: if n % 5 == 0 or n % 3 == 0: s = s + n n = n - 1 return s print("specialSumInclusive tests:") print(specialSumInclusive(0)) print(specialSumInclusive(3)) print(specialSumInclusive(5)) def specialSumExclusive(n): s = 0 while n > 0: if n % 35 == 0: s = s + n n = n - 1 return s print("specialSumExclusive tests:") print(specialSumExclusive(5)) print(specialSumExclusive(7)) print(specialSumExclusive(35)) def sumOfFirstNSquares(n): s = 0 while n > 0: s = s + n**2 n = n - 1 return s print("sumOfFirstNSquares tests:") print(sumOfFirstNSquares(1)) print(sumOfFirstNSquares(2)) print(sumOfFirstNSquares(3)) def sumSquaresBetween(a,b): s = 0 n = int(b**.5) while n**2 >= a: s = s + n**2 n = n - 1 return s print("sumSquaresBetween tests:") print(sumSquaresBetween(30, 101)) print(sumSquaresBetween(1, 10)) print(sumSquaresBetween(5, 10)) def sumOfPowers(n): s = 0 i = 1 while 2**i <= n: s = s + 2**i i = i + 1 return s print("sumOfPowers tests:") print(sumOfPowers(0)) print(sumOfPowers(10)) print(sumOfPowers(2)) def sumDigits(n): s = 0 n = abs(n) while n > 0: s = s + n % 10 n = n // 10 return s print("sumDigits tests:") print(sumDigits(123)) print(sumDigits(19)) print(sumDigits(-25)) def countDigits(n): count = 1 n = abs(n) while n > 9: count = count + 1 n = n // 10 return count print("countDigits tests:") print(countDigits(0)) print(countDigits(4)) print(countDigits(12)) def countOddDigits(n): count = 0 n = abs(n) while n > 0: if n % 10 % 2 == 1: count = count + 1 n = n // 10 return count print("countOddDigits tests:") print(countOddDigits(111)) print(countOddDigits(134)) print(countOddDigits(2)) def isPrime(n): return n == 2 or n == 3 or n == 5 or n == 7 def countPrimeDigits(n): count = 0 n = abs(n) while n > 0: if isPrime(n % 10): count = count + 1 n = n // 10 return count print("countPrimeDigits tests:") print(countPrimeDigits(123)) print(countPrimeDigits(12345)) print(countPrimeDigits(123456))
5f9603cbec0f881926829c976e12db1151b6e811
FuriousFlash/MCDM-Problem
/dataloader.py
212
3.5
4
import csv def loadCsv(filename): lines = csv.reader(open(filename, "r")) dataset = list(lines) for i in range(len(dataset)): #print(dataset[i]) dataset[i] = [float(x) for x in dataset[i]] return dataset
a521e9127959f9d773e819793cb1b34403ab25bb
C109156238/MIDTERN
/4.py
937
3.875
4
x=int(input("please input x:")) y=int(input("please input y:")) if x==0 and y==0 : print("該點位於原點") if x==0 and y>0 : a=y**2 print("該點位於上半平面Y軸上,離原點距離為根號",a) if x==0 and y<0 : a=y**2 print("該點位於下半平面Y軸上,離原點距離為根號",a) if x>0 and y==0 : a=x**2 print("該點位於右半平面X軸上,離原點距離為根號",a) if x<0 and y==0 : a=x**2 print("該點位於左半平面X軸上,離原點距離為根號",a) if x>0 and y>0: a=x**2+y**2 print("該點位於第一象限,離原點距離為根號",a) if x<0 and y<0: a=x**2+y**2 print("該點位於第三象限,離原點距離為根號",a) if x<0 and y>0: a=x**2+y**2 print("該點位於第二象限,離原點距離為根號",a) if x>0 and y<0: a=x**2+y**2 print("該點位於第四象限,離原點距離為根號",a)
7bc4a52c429701105db8cbcae30ff5c69f939365
C109156238/MIDTERN
/12.py
292
3.515625
4
a=input("輸入一整數序列為:").split(' ') tmp=[] ans=0 for i in a: if tmp.count(i)==0: tmp.append(i) for i in tmp: if a.count(i) >= len(a)/2: ans=i if ans ==0: print("過半元素為:NO") elif ans != 0: print("過半元素為:{}".format(ans))
f427e8ea3d097b17c7414b5b3752737441e3e48b
yogeshrakate/Sagveek_Test
/Sagveek_test_solution_8.py
453
3.9375
4
''' Question No. 8 Write a function that takes a list of integers and returns the largest sum of non-adjacent numbers. For example: input:[2,4,6,2,5] ----> Output:13===>2+6+5 input:[5,1,1,5] ----> Output:13===>5+5 ''' def LargeSum(l): incl = 0 excl = 0 for i in l: new_excl = max(excl, incl) incl = excl + i excl = new_excl return max(excl, incl) print(LargeSum([2,4,6,2,5])) print(LargeSum([5,5,1,1,5]))
47edc5e19c8ebd3ea6956d89e52a5ca7eebcebba
timthetinythug/practicePython
/grid.py
17,062
4.125
4
"""Assignment 1 - Node and Grid This module contains the Node and Grid classes. Your only task here is to implement the methods where indicated, according to their docstring. Also complete the missing doctests. """ import functools import sys from container import PriorityQueue @functools.total_ordering class Node: """ Represents a node in the grid. A node can be navigable (that is located in water) or it may belong to an obstacle (island). === Attributes: === @type navigable: bool navigable is true if and only if this node represents a grid element located in the sea else navigable is false @type grid_x: int represents the x-coordinate (counted horizontally, left to right) of the node @type grid_y: int represents the y-coordinate (counted vertically, top to bottom) of the node @type parent: Node represents the parent node of the current node in a path for example, consider the grid below: 012345 0..+T.. 1.++.++ 2..B..+ the navigable nodes are indicated by dots (.) the obstacles (islands) are indicated by pluses (+) the boat (indicated by B) is in the node with x-coordinate 2 and y-coordinate 2 the treasure (indicated by T) is in the node with x-coordinate 3 and y-coordinate 0 the path from the boat to the treasure if composed of the sequence of nodes with coordinates: (2, 2), (3,1), (3, 0) the parent of (3, 0) is (3, 1) the parent of (3, 1) is (2, 2) the parent of (2, 2) is of course None @type in_path: bool True if and only if the node belongs to the path plotted by A-star path search in the example above, in_path is True for nodes with coordinates (2, 2), (3,1), (3, 0) and False for all other nodes @type gcost: float gcost of the node, as described in the handout initially, we set it to the largest possible float @type hcost: float hcost of the node, as described in the handout initially, we set it to the largest possible float """ def __init__(self, navigable, grid_x, grid_y): """ Initialize a new node @type self: Node @type navigable: bool @type grid_x: int @type grid_y: int @rtype: None Preconditions: grid_x, grid_y are non-negative >>> n = Node(True, 2, 3) >>> n.grid_x 2 >>> n.grid_y 3 >>> n.navigable True """ self.navigable = navigable self.grid_x = grid_x self.grid_y = grid_y self.in_path = False self.parent = None self.gcost = sys.float_info.max self.hcost = sys.float_info.max def set_gcost(self, gcost): """ Set gcost to a given value @type gcost: float @rtype: None Precondition: gcost is non-negative >>> n = Node(True, 1, 2) >>> n.set_gcost(12.0) >>> n.gcost 12.0 """ self.gcost = gcost def set_hcost(self, hcost): """ Set hcost to a given value @type hcost: float @rtype: None Precondition: gcost is non-negative >>> n = Node(True, 1, 2) >>> n.set_hcost(12.0) >>> n.hcost 12.0 """ self.hcost = hcost def fcost(self): """ Compute the fcost of this node according to the handout @type self: Node @rtype: float """ return self.gcost + self.hcost def set_parent(self, parent): """ Set the parent to self @type self: Node @type parent: Node @rtype: None """ self.parent = parent def distance(self, other): """ Compute the distance from self to other @self: Node @other: Node @rtype: int """ dstx = abs(self.grid_x - other.grid_x) dsty = abs(self.grid_y - other.grid_y) if dstx > dsty: return 14 * dsty + 10 * (dstx - dsty) return 14 * dstx + 10 * (dsty - dstx) def __eq__(self, other): """ Return True if self equals other, and false otherwise. @type self: Node @type other: Node @rtype: bool """ if type(self) == type(other) and self.navigable == other.navigable and \ self.grid_x == other.grid_x and self.grid_y == self.grid_y: return True else: return False def __lt__(self, other): """ Return True if self less than other, and false otherwise. @type self: Node @type other: Node @rtype: bool """ if self.fcost() < other.fcost(): return True else: return False def __str__(self): """ Return a string representation. @type self: Node @rtype: str """ return "{} {} {}".format(self.navigable, self.grid_x, self.grid_y) class Grid: """ Represents the world where the action of the game takes place. You may define helper methods as you see fit. === Attributes: === @type width: int represents the width of the game map in characters the x-coordinate runs along width the leftmost node has x-coordinate zero @type height: int represents the height of the game map in lines the y-coordinate runs along height; the topmost line contains nodes with y-coordinate 0 @type map: List[List[Node]] map[x][y] is a Node with x-coordinate equal to x running from 0 to width-1 and y-coordinate running from 0 to height-1 @type treasure: Node a navigable node in the map, the location of the treasure @type boat: Node a navigable node in the map, the current location of the boat === Representation invariants === - width and height are positive integers - map has dimensions width, height """ def __init__(self, file_path, text_grid=None): """ If text_grid is None, initialize a new Grid assuming file_path contains pathname to a text file with the following format: ..+..++ ++.B..+ .....++ ++..... .T....+ where a dot indicates a navigable Node, a plus indicates a non-navigable Node, B indicates the boat, and T the treasure. The width of this grid is 7 and height is 5. If text_grid is not None, it should be a list of strings representing a Grid. One string element of the list represents one row of the Grid. For example the grid above, should be stored in text_grid as follows: ["..+..++", "++.B..+", ".....++", "++.....", ".T....+"] @type file_path: str - a file pathname. See the above for the file format. - it should be ignored if text_grid is not None. - the file specified by file_path should exists, so there is no need for error handling Please call open_grid to open the file @type text_grid: List[str] @rtype: None """ if file_path == "": self.text_grid = text_grid else: final_list = [] file = open(file_path) for line in file.read().splitlines(): if line != "": final_list.append(line) self.text_grid = final_list self.width = len(text_grid[0]) self.height = len(text_grid) empty_map = [] for i in range(self.width): x_map = [] counter_y = 0 for k in text_grid: z = list(k) x = z[i] if x == "+": node = Node(False, i, counter_y) else: node = Node(True, i, counter_y) x_map.append(node) counter_y += 1 empty_map.append(x_map) self.map = empty_map found_tresure = False found_boat = False counter_y = 0 counter_x = 0 while found_tresure is False or found_boat is False: row = text_grid[counter_y] lofrow = list(row) while (found_tresure is False or found_boat is False) and counter_x < \ self.width: point = lofrow[counter_x] if point == "T": self.treasure = Node(True, counter_x, counter_y) found_tresure = True counter_x += 1 elif point == "B": self.boat = Node(True, counter_x, counter_y) found_boat = True counter_x += 1 else: counter_x += 1 counter_y += 1 counter_x = 0 @classmethod def open_grid(cls, file_path): """ @rtype TextIOWrapper: """ return open(file_path) def __str__(self): """ Return a string representation. @type self: Grid @rtype: str >>> g = Grid("", ["B.++", ".+..", "...T"]) >>> print(g) B.++ .+.. ...T """ final = "" for text in self.text_grid: final += str(text) + "\n" return final.rstrip() def move_helper(self, x, y): a = self.boat.grid_x a_ = a + x b = self.boat.grid_y b_ = b - y if self.map[a_][b_].navigable is True \ and self.width >= a_ >= 0 \ and self.height >= b_ >= 0: self.boat = Node(True, a_, b_) row = self.text_grid[b] row = list(row) other_row = self.text_grid[b_] other_row = list(other_row) other_row[a_], row[a] = row[a], other_row[a_] new_row = "".join(row) new_other_row = "".join(other_row) self.text_grid[b] = new_row self.text_grid[b_] = new_other_row else: raise ValueError("sorry m8, path cannot be manuevered") def move(self, direction): """ Move the boat in a specific direction, if the node corresponding to the direction is navigable Else do nothing @type self: Grid @type direction: str @rtype: None direction may be one of the following: N, S, E, W, NW, NE, SW, SE (north, south, ...) 123 4B5 678 1=NW, 2=N, 3=NE, 4=W, 5=E, 6=SW, 7=S, 8=SE >>> g = Grid("", ["B.++", ".+..", "...T"]) >>> g.move("S") >>> print(g) ..++ B+.. ...T """ if direction == "NW": self.move_helper(-1, 1) elif direction == "N": self.move_helper(0, 1) elif direction == "NE": self.move_helper(1, 1) elif direction == "W": self.move_helper(-1, 0) elif direction == "E": self.move_helper(1, 0) elif direction == "SW": self.move_helper(-1, -1) elif direction == "S": self.move_helper(0, -1) elif direction == "SE": self.move_helper(1, -1) def neighbourhood(self, node): """ lists each neighbouring node of current node """ a = node.grid_x b = node.grid_y community = [] for x in [-1, 0, 1]: a_ = a + x for y in [-1, 0, 1]: b_ = b - y if x == 0 and y == 0: pass elif a_ >= 0 and a_ < self.width and b_ >= 0 and b_ < self.height: neighbour = self.map[a_][b_] community.append(neighbour) else: pass return community def find_path(self, start_node, target_node): """ Implement the A-star path search algorithm If you will add a new node to the path, don't forget to set the parent. You can find an example in the docstring of Node class Please note the shortest path between two nodes may not be unique. However all of them have same length! @type self: Grid @type start_node: Node The starting node of the path @type target_node: Node The target node of the path @rtype: None """ open_list = [] closed_list = [] start_node.set_gcost(0) start_node.set_hcost(0) open_list.append(start_node) treasure = False while treasure is False: current_node = open_list[0] for i in open_list: if (i.fcost() < current_node.fcost()) or (i.fcost() == current_node.fcost() and i.hcost < current_node.hcost): current_node = i else: pass closed_list.append(current_node) open_list.remove(current_node) if current_node == target_node: treasure = True target_node.parent = current_node.parent else: for neighbour in self.neighbourhood(current_node): if (neighbour.navigable is False) or (neighbour in closed_list): pass else: moving_fee = current_node.gcost + current_node.distance(neighbour) if moving_fee < neighbour.gcost or neighbour in closed_list: neighbour.gcost = moving_fee neighbour.hcost = current_node.distance(neighbour) neighbour.parent = current_node if neighbour not in open_list: open_list.append(neighbour) else: pass else: pass def retrace_path(self, start_node, target_node): """ Return a list of Nodes, starting from start_node, ending at target_node, tracing the parent Namely, start from target_node, and add its parent to the list. Keep going until you reach the start_node. If the chain breaks before reaching the start_node, return and empty list. @type self: Grid @type start_node: Node @type target_node: Node @rtype: list[Node] """ empty_path = [] current_node = target_node while current_node != start_node: empty_path.append(current_node) current_node = current_node.parent empty_path.reverse() return empty_path def get_treasure(self, s_range): """ Return treasure node if it is located at a distance s_range or less from the boat, else return None @type s_range: int @rtype: Node, None """ if self.boat.distance(self.treasure) < s_range: return self.treasure else: return None def plot_path(self, start_node, target_node): """ Return a string representation of the grid map, plotting the shortest path from start_node to target_node computed by find_path using "*" characters to show the path @type self: Grid @type start_node: Node @type target_node: Node["B.++", ".+..", "...T"] @rtype: str >>> g = Grid("", ["B.++", ".+..", "...T"]) >>> print(g.plot_path(g.boat, g.treasure)) B*++ .+*. ...T """ self.find_path(self.boat, self.treasure) traced_path = self.retrace_path(self.boat, self.treasure) traced_path.pop() for i in traced_path: x = i.grid_x y = i.grid_y a = self.boat.grid_x b = self.boat.grid_y a_ = a + x b_ = b + y other_row = self.text_grid[b_] other_row = list(other_row) other_row[a_] = "*" new_other_row = "".join(other_row) self.text_grid[b_] = new_other_row return self if __name__ == '__main__': import doctest doctest.testmod() import python_ta python_ta.check_all(config='pylintrc.txt')
925821fed0786002a29bde0804c4408e5fc6302f
mbilalashraf/AILabAssignment
/Assignment1.py
1,153
3.78125
4
#1. Considering the image below, develop the adjacency matrix representation of the graph. # Find the in-degree and out-degree of V6 from IPython.display import Image Image(filename='img.png') adj =[[0,1,0,0,0,0,0,0,0], [0,0,0,1,0,0,0,0,0], [1,0,0,0,0,0,0,0,0], [0,0,0,0,1,0,1,0,0], [0,1,1,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0], [0,0,0,0,0,0,0,1,0], [0,0,0,0,1,1,0,0,1], [0,0,0,0,0,0,1,0,0]] i=0 o=0 y=5 print("Indegree:",end=" ") for z in range(0,9): p= adj[z][y] if(p==1): i = i+1 print(z+1,end=" ") print("\nIndegree of v6 is: ",i) print("Outdegree:",end=" ") for z in range(0,9): p= adj[y][z] if(p==1): o = o+1 print(z+1,end=" ") print("\nOutdegree of v6 is: ",o) #2. Using numpy, create a matrix of 100 elements with values from 101 to 200 import numpy as np x = np.arange(101,201) print(x) #3. Now, convert the above matrix to 10 X 10 array x = x.reshape(10,10) print(x) #4. Assign the upper 5 X 5 sub-matrix, value equals to -1 for y in range(0,5): for z in range(0,5): x[y][z]=-1 print(x)
b13732fe04f00f6247b61565a1090bfb5b6a3e52
kirubeltadesse/Python
/examq/test2.py
1,004
4.0625
4
# kirubel Tadesse # Dr.Gordon Skelton # J00720834 # Applied Programming # Jackson State University # Computer Engineering Dept. # Write a program that uses the same file. Have that program produce the largest and smallest value from the file. You can just modify the program in No. 6 above to solve this problem. import pandas as pd # import numpy as np # I have transposed the numbers.csv and resaved it as numbers2.csv path = '/home/aniekan/Downloads/numbers2.csv' # reading data from the file df = pd.read_csv(path, names=['Data','Index']) ###k = df.set_index(['columens',[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]]) #print(k) #print(len(k)) #for i, row in k.iterrows(): # print(i) #for i in k: #s = pd.Series(k, index=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]) df1 = df.reset_index() print("value of df1") print(df1) print("value of k") #print(k.head()) print("value of df1 tail") print(df1.tail(2)) print("value of df max") print(df.max()) print("checking ") print(df1.head())
98edf9ce118f9641f55d08c6527da8d01f03b49a
kirubeltadesse/Python
/examq/q3.py
604
4.28125
4
# Kirubel Tadesse # Dr.Gordon Skelton # J00720834 # Applied Programming # Jackson State University # Computer Engineering Dept. #create a program that uses a function to determine the larger of two numbers and return the larger to the main body of the program and then print it. You have to enter the numbers from the keyboard so you have to use input. #defining the function def printLarg(): x = input("Enter your first number: ") y = input("Enter your second number: ") holder=[x,y] larg = max(holder) print("the larger number is : ") print(larg) return larg #calling the function printLarg()
9b773282655c5e3a6a35f9b59f22ddb221386870
AyvePHIL/MLlearn
/Sorting_alogrithms.py
2,275
4.21875
4
# This is the bubbleSort algorithm where we sort array elements from smallest to largest def bubbleSort(arr): n = len(arr) # Traverse through all array elements for i in range(n - 1): # range(n) also work but outer loop will repeat one time more than needed (more efficient). # Last i elements are already in place for j in range(0, n - i - 1): # traverse the array from 0 to n-i-1. Swap if the element found is greater than the next element if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] return arr # Another bubble sort algorithm but returns the no. of times elements were swapped from small to large def minimumSwaps(arr): swaps = 0 temp = {} for i, val in enumerate(arr): temp[val] = i for i in range(len(arr)): # because they are consecutive, I can see if the number is where it belongs if arr[i] != i + 1: swaps += 1 t = arr[i] # Variable holder arr[i] = i + 1 arr[temp[i + 1]] = t # Switch also the tmp array, no need to change i+1 as it's already in the right position temp[t] = temp[i + 1] return swaps def minimumSwappnumber(arr): noofswaps = 0 for i in range(len(arr)): while arr[i] != i + 1: temp = arr[i] arr[i] = arr[arr[i] - 1] arr[temp - 1] = temp noofswaps += 1 print noofswaps # A QuickSort algorithm where we pivot about a specified int in a array by partitioning the array into two parts def quick_sort(sequence): if len(sequence)<=1: return(sequence) else: pivot = sequence.pop() items_bigger = [] items_smaller = [] for item in sequence: if item > pivot: items_bigger.append(item) else: items_smaller.append(item) return quick_sort(items_smaller) + [pivot] + quick_sort(items_bigger) # This is the testing phase, where the above algorithms are tested and tried by FIRE🔥🔥🔥 testing_array = [3, 56, 0, 45, 2324, 2, 12, 123, 434, 670, 4549, 3, 4.5, 6] print(bubbleSort(testing_array)) print(quick_sort(testing_array)) print(minimumSwappnumber(testing_array))
2486925e16396536f048f25889dc6d3f7675549a
NathanielS/Week-Three-Assignment
/PigLatin.py
500
4.125
4
# Nathaniel Smith # PigLatin # Week Three Assignment # This program will take input from the usar, translate it to PigLatin, # and print the translated word. def main (): # This section of code ask for input from the usar and defines vowels word = input("Please enter an English word: ") vowels = "AEIOUaeiou" # This section of code translates the usars input into PigLatin if word[0] in vowels: print(word + "yay") else: print(word[1:] + word[0] + "ay") main ()