blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
3985ff8d76a45cefc9e337163b1c3a977c2491f5 | kim4t/Baekjoon-Online-Judge | /Baekjoon Algorithm (ktkt508)/10039번 평균 점수/Answer.py | 124 | 3.765625 | 4 | total = 0
for i in range(5):
score = int(input())
if score<40:
score = 40
total += score
print(total//5) |
888aec8c3a76f3b599aee3d77a742737cca9a41c | JahedHossenBangladesh/Python_Crush_course | /Introducing_List.py | 2,730 | 3.734375 | 4 | # This is capter 3
bicycles = ["trek","cannondale",'redline','specialize']
print(bicycles)
print(bicycles[1])
print(bicycles[0].upper())
print(bicycles[-1])
print(bicycles[-2].title())
message = f"My first bicycles is {bicycles[-3].lower()}"
print(message)
friends =['Tuhin','Shahed','Tohid','Munna']
print(friends[3].upper())
message = "Hello"
message2 = f"hi and {message} {friends[0].upper()}"
print(message2)
myVachel =['car','Hunda','neno']
message = f"I would like to take {myVachel[2]}"
print(message)
motorcycles = ['honda','yamaha','suzuki']
motorcycles[0] ='ducati'
print(motorcycles)
motorcycles.append('honda')
print(motorcycles)
motorcycles.insert(2,'ducati')
print(motorcycles)
del motorcycles[2]
print(motorcycles)
popend_motorcycles = motorcycles.pop()
print(motorcycles)
print(popend_motorcycles)
print(f"The last pop is {popend_motorcycles}")
motorcycles.append('nano')
print(motorcycles)
first_delete = motorcycles.pop(0)
print(first_delete)
too_expensive = 'suzuki'
motorcycles.remove(too_expensive)
print(motorcycles)
# task ..
dinner_list =["Noyon","Jony","Munna","Tohid","Tuhin","Jonak"]
message = f'please {dinner_list[0]} come in the birthday'
print(message)
not_attend = dinner_list.pop()
print(not_attend)
dinner_list.append('Efan')
print(dinner_list)
pop_end = dinner_list.pop()
print(f'please come {pop_end.upper()}')
dinner_list.insert(0,'Sahed')
print(dinner_list)
dinner_list.insert(3,'Bipu')
print(dinner_list)
dinner_list.append('Humaiyun')
message =f'Please come {dinner_list.pop()} in the party'
print(message)
message = f'please {dinner_list[0]} and {dinner_list[4]} come to the dinner'
print(message)
del dinner_list[0]
print(dinner_list)
dinner_list.remove('Tuhin')
print(dinner_list)
dinner_list.sort()
print(dinner_list)
dinner_list.sort(reverse = True)
print('\nHerer is the orginal list:')
print(dinner_list)
print('\n Here is the sorted list:')
short_list = sorted(dinner_list)
print(short_list)
short_list.reverse()
print(f'the reverse is not working {dinner_list} ')
invited_person = len(dinner_list)
print(f'the invited person is {invited_person}')
# Task 3-8
wanna_visit = ["Kashmir","Makka","Madinatul Munabra","Finland"]
print('The orginal lis :')
print(wanna_visit)
sort_visit = sorted(wanna_visit)
print(f'shorted list {sort_visit}')
sort_visit.reverse()
print(f'the reverse is not working {sort_visit} ')
print(f'orginal list: {wanna_visit}')
wanna_visit.sort()
print(wanna_visit)
wanna_visit.reverse()
print(wanna_visit)
wanna_visit.sort()
print(wanna_visit)
visted_place = len(wanna_visit)
print(f'total place {visted_place}')
# Avoiding index error when working with lists
motorcycles =['honda','yamaha','sukuki']
print(motorcycles[2])
print(motorcycles[-1])
|
d21445efe57d70c513f621f5db3613183a563e05 | glados17/CS61A_2019Falls | /practise/cats/typing.py | 10,400 | 3.703125 | 4 | """Typing test implementation"""
from utils import *
from ucb import main, interact, trace
from datetime import datetime
###########
# Phase 1 #
###########
def choose(paragraphs, select, k):
"""Return the Kth paragraph from PARAGRAPHS for which SELECT called on the
paragraph returns true. If there are fewer than K such paragraphs, return
the empty string.
"""
# BEGIN PROBLEM 1
"*** YOUR CODE HERE ***"
results = []
for paragraph in paragraphs:
if select(paragraph):
results.append(paragraph)
if len(results) == k+1:
return results[k]
return ''
# END PROBLEM 1
def about(topic):
"""Return a select function that returns whether a paragraph contains one
of the words in TOPIC.
>>> about_dogs = about(['dog', 'dogs', 'pup', 'puppy'])
>>> choose(['Cute Dog!', 'That is a cat.', 'Nice pup!'], about_dogs, 0)
'Cute Dog!'
>>> choose(['Cute Dog!', 'That is a cat.', 'Nice pup.'], about_dogs, 1)
'Nice pup.'
"""
assert all([lower(x) == x for x in topic]), 'topics should be lowercase.'
# BEGIN PROBLEM 2
"*** YOUR CODE HERE ***"
def select_about(paragraph):
# para = lower(remove_punctuation(paragraph))
# para = lower(para)
for words in topic:
if words in split(lower(remove_punctuation(paragraph))):
return True
return False
return select_about
# END PROBLEM 2
def accuracy(typed, reference):
"""Return the accuracy (percentage of words typed correctly) of TYPED
when compared to the prefix of REFERENCE that was typed.
>>> accuracy('Cute Dog!', 'Cute Dog.')
50.0
>>> accuracy('A Cute Dog!', 'Cute Dog.')
0.0
>>> accuracy('cute Dog.', 'Cute Dog.')
50.0
>>> accuracy('Cute Dog. I say!', 'Cute Dog.')
50.0
>>> accuracy('Cute', 'Cute Dog.')
100.0
>>> accuracy('', 'Cute Dog.')
0.0
"""
typed_words = split(typed)
reference_words = split(reference)
# BEGIN PROBLEM 3
"*** YOUR CODE HERE ***"
if len(typed_words) == 0:
return 0.00
correct_count = 0
for word_index in range(min(len(typed_words),len(reference_words))):
if typed_words[word_index] == reference_words[word_index]:
correct_count += 1
return correct_count*100. / len(typed_words)
# END PROBLEM 3
def wpm(typed, elapsed):
"""Return the words-per-minute (WPM) of the TYPED string."""
assert elapsed > 0, 'Elapsed time must be positive'
# BEGIN PROBLEM 4
"*** YOUR CODE HERE ***"
return len(typed) / 5 / elapsed *60.
# END PROBLEM 4
def autocorrect(user_word, valid_words, diff_function, limit):
"""Returns the element of VALID_WORDS that has the smallest difference
from USER_WORD. Instead returns USER_WORD if that difference is greater
than LIMIT.
"""
# BEGIN PROBLEM 5
"*** YOUR CODE HERE ***"
if user_word in valid_words:
return user_word
result_word = user_word
diff = limit + 1
for word in valid_words:
diff_now = diff_function(user_word,word,limit)
if diff_now <= limit and diff_now < diff:
diff, result_word = diff_now, word
return result_word
# END PROBLEM 5
def swap_diff(start, goal, limit):
"""A diff function for autocorrect that determines how many letters
in START need to be substituted to create GOAL, then adds the difference in
their lengths.
"""
# BEGIN PROBLEM 6
# assert False, 'Remove this line'
### First I try to use a helper function to calculate limit exceeding, it works
### but when I come to the edit_diff, it became unclear, then the next one come out
# min_len = min(len(start), len(goal))-1
# def diff_helper(sum_diff, n):
# if n > min_len or sum_diff > limit:
# return sum_diff
# elif start[n] != goal[n]:
# return diff_helper(sum_diff+1, n+1)
# else:
# return diff_helper(sum_diff, n+1)
# return diff_helper(0,0) + abs(len(start) - len(goal))
if len(start) == 0 or len(goal) == 0:
return abs(len(start) - len(goal))
elif limit < 0:
return 1
elif start[0] != goal[0]:
diff = swap_diff(start[1:], goal[1:],limit-1) + 1
# if diff > limit:
# return limit + 1
else:
diff = swap_diff(start[1:], goal[1:],limit)
return diff
## This is a solution using iteration instead of recursion
# min_len = min(len(start),len(goal))
# diff = 0
# for word_index in range(min_len):
# if start[word_index] != goal[word_index]:
# diff += 1
# if diff > limit:
# return diff
# return diff + abs(len(start) - len(goal))
# END PROBLEM 6
def edit_diff(start, goal, limit):
"""A diff function that computes the edit distance from START to GOAL."""
# assert False, 'Remove this line'
if len(start) == 0 or len(goal) == 0: # Fill in the condition
# BEGIN
return max(len(goal),len(start))
# END
elif limit < 0:
return 1
elif start[-1] == goal[-1]: # Feel free to remove or add additional cases
# BEGIN
return edit_diff(start[:-1], goal[:-1], limit)
# END
else:
# BEGIN
"*** YOUR CODE HERE ***"
add_diff = edit_diff(start, goal[:-1], limit-1) # Fill in these lines
remove_diff = edit_diff(start[:-1], goal, limit-1)
substitute_diff = edit_diff(start[:-1], goal[:-1], limit-1)
diff = min(add_diff, remove_diff, substitute_diff)
return diff + 1
# END
def final_diff(start, goal, limit):
"""A diff function. If you implement this function, it will be used."""
assert False, 'Remove this line to use your final_diff function'
###########
# Phase 3 #
###########
def report_progress(typed, prompt, id, send):
"""Send a report of your id and progress so far to the multiplayer server."""
# BEGIN PROBLEM 8
"*** YOUR CODE HERE ***"
correct_count = 0
for word_index in range(min(len(typed),len(prompt))):
if typed[word_index] == prompt[word_index]:
correct_count += 1
else:
break
progress_now = correct_count / len(prompt)
send({'id': id, 'progress': progress_now})
return progress_now
# END PROBLEM 8
def fastest_words_report(word_times):
"""Return a text description of the fastest words typed by each player."""
fastest = fastest_words(word_times)
report = ''
for i in range(len(fastest)):
words = ','.join(fastest[i])
report += 'Player {} typed these fastest: {}\n'.format(i + 1, words)
return report
def fastest_words(word_times, margin=1e-5):
"""A list of which words each player typed fastest."""
n_players = len(word_times)
n_words = len(word_times[0]) - 1
assert all(len(times) == n_words + 1 for times in word_times)
assert margin > 0
# BEGIN PROBLEM 9
"*** YOUR CODE HERE ***"
def get_time_resuming(word_times,player,word_togo):
return word_time(word(word_times[player][word_togo]),
elapsed_time(word_times[player][word_togo])
- elapsed_time(word_times[player][word_togo-1]))
def get_resuming_words(word_times,n_players,n_words):
result = [[] for x in range(n_players)]
for player in range(n_players):
for word_togo in range(1,n_words+1):
result[player].append(get_time_resuming(word_times,player,word_togo))
return result
def get_n_word(word_times,n):
return [row[n] for row in word_times]
def get_min_word_col(word_col):
return min([elapsed_time(word_time) for word_time in word_col])
time_resuming_words = get_resuming_words(word_times,n_players,n_words)
result = [[] for x in range(n_players)]
for word_togo in range(n_words):
nth_word_time_col = get_n_word(time_resuming_words,word_togo)
min_time = get_min_word_col(nth_word_time_col)
for player in range(n_players):
if elapsed_time(time_resuming_words[player][word_togo]) - min_time < margin:
result[player].append(word(time_resuming_words[player][word_togo]))
return result
# END PROBLEM 9
def word_time(word, elapsed_time):
"""A data abstrction for the elapsed time that a player finished a word."""
return [word, elapsed_time]
def word(word_time):
"""An accessor function for the word of a word_time."""
return word_time[0]
def elapsed_time(word_time):
"""An accessor function for the elapsed time of a word_time."""
return word_time[1]
enable_multiplayer = False # Change to True when you
##########################
# Command Line Interface #
##########################
def run_typing_test(topics):
"""Measure typing speed and accuracy on the command line."""
paragraphs = lines_from_file('data/sample_paragraphs.txt')
select = lambda p: True
if topics:
select = about(topics)
i = 0
while True:
reference = choose(paragraphs, select, i)
if not reference:
print('No more paragraphs about', topics, 'are available.')
return
print('Type the following paragraph and then press enter/return.')
print('If you only type part of it, you will be scored only on that part.\n')
print(reference)
print()
start = datetime.now()
typed = input()
if not typed:
print('Goodbye.')
return
print()
elapsed = (datetime.now() - start).total_seconds()
print("Nice work!")
print('Words per minute:', wpm(typed, elapsed))
print('Accuracy: ', accuracy(typed, reference))
print('\nPress enter/return for the next paragraph or type q to quit.')
if input().strip() == 'q':
return
i += 1
@main
def run(*args):
"""Read in the command-line argument and calls corresponding functions."""
import argparse
parser = argparse.ArgumentParser(description="Typing Test")
parser.add_argument('topic', help="Topic word", nargs='*')
parser.add_argument('-t', help="Run typing test", action='store_true')
args = parser.parse_args()
if args.t:
run_typing_test(args.topic)
|
ee998126fa6b227c394364e8e048df85db8f67a5 | ayman12-tech/AStar-Algorithm | /testingAstar.py | 4,083 | 3.859375 | 4 | #TASK1-a :Develop code to implement the A* algorithm in order to find the optimal path in the Travel
# in Romania problem. Use the heuristic given in the text above.
from queue import Queue, PriorityQueue
graph = {
'Arad': ['Zerind', 'Timisoara','Sibiu'],
'Zerind': ['Arad', 'Oradea'],
'Timisoara': ['Arad', 'Lugoj'],
'Sibiu': ['Oradea','Arad','Fagaras','Rimincu_Vilcea'],
'Oradea': ['Zerind','Sibiu'],
'Lugoj': ['Timisoara','Mehadia'],
'Fagaras':['Sibiu','Bucharest'],
'Rimincu_Vilcea':['Sibiu','Pitesti','Craiova'],
'Mehadia':['Lugoj','Dobreta'],
'Bucharest':['Fagaras','Pitesti','Urziceni','Giurgia'],
'Pitesti':['Rimincu_Vilcea','Craiova','Bucharest'],
'Craiova':['Pitesti','Rimincu_Vilcea','Dobreta'],
'Dobreta':['Mehadia','Craiova'],
'Urziceni':['Hirsova','Bucharest','Vaslui'],
'Giurgia':['Bucharest'],
'Hirsova':['Eforle','Urziceni'],
'Vaslui':['Lasi','Urziceni'],
'Eforle':['Hirsova'],
'Lasi':['Neamt','Vaslui'],
'Neamt':['Lasi']
}
cost = {
('Arad', 'Zerind'): 75, # tuple
('Arad', 'Timisoara'): 118,
('Arad','Sibiu'):140,
('Zerind', 'Arad'): 75,
('Zerind', 'Oradea'): 71,
('Timisoara', 'Arad'): 118,
('Timisoara', 'Lugoj'): 111,
('Oradea', 'Zerind'): 71,
('Oradea', 'Sibiu'): 151,
('Lugoj', 'Timisoara'): 111,
('Lugoj', 'Mehadia'): 70,
('Sibiu', 'Arad'): 140,
('Sibiu', 'Fagaras'): 99,
('Sibiu', 'Oradea'): 151,
('Sibiu', 'Rimincu_Vilcea'): 80,
('Mehadia', 'Lugoj'): 70,
('Mehadia', 'Dobreta'): 75,
('Fagaras', 'Sibiu'): 99,
('Fagaras', 'Bucharest'): 211,
('Rimincu_Vilcea', 'Sibiu'): 80,
('Rimincu_Vilcea', 'Pitesti'): 97,
('Rimincu_Vilcea', 'Craiova'): 146,
('Dobreta', 'Mehadia'): 75,
('Dobreta', 'Craiova'): 120,
('Bucharest', 'Pitesti'): 101,
('Bucharest', 'Fagaras'): 211,
('Bucharest', 'Giurgia'): 90,
('Bucharest', 'Urziceni'): 85,
('Pitesti', 'Bucharest'): 101,
('Pitesti', 'Craiova'): 138,
('Pitesti', 'Rimincu_Vilcea'): 97,
('Craiova', 'Rimincu_Vilcea'): 146,
('Craiova', 'Pitesti'): 138,
('Craiova', 'Dobreta'): 120,
('Giurgia', 'Bucharest'): 90,
('Urziceni', 'Bucharest'): 85,
('Urziceni', 'Hirsova'): 98,
('Urziceni', 'Vaslui'): 142,
('Hirsova', 'Eforle'): 86,
('Hirsova', 'Urziceni'): 98,
('Vaslui', 'Urziceni'): 142,
('Vaslui', 'Lasi'): 92,
('Eforle', 'Hirsova'): 86,
('Lasi', 'Neamt'): 87,
('Lasi', 'Vaslui'): 92,
('Neamt', 'Lasi'): 87
}
heur={
'Arad':366,
'Bucharest':0,
'Craiova':160,
'Dobreta':242,
'Eforle':161,
'Fagaras':176,
'Giurgia':77,
'Hirsova':151,
'Lasi':226,
'Lugoj':244,
'Mehadia':241,
'Neamt':234,
'Oradea':380,
'Pitesti':10,
'Rimincu_Vilcea':193,
'Sibiu':253,
'Timisoara':329,
'Urziceni':80,
'Vaslui':199,
'Zerind':374
}
def aStar_Cost(from_node, to_node, cost=None):
return cost.get((from_node, to_node), 10e100) # func. for getting the cost (Reference:Python book)
def aStar(graph, heur,start, goal, cost=None):
fringe = PriorityQueue() # setting my fringe as a priority queue
fringe.put((0, start)) # (cost, node) #giving zero cost to the root node
explored = [] # for explored node
while fringe:
astarC, current_node = fringe.get() #starting cost,start state
explored.append(current_node) #appending in explored queue to keep the track of explored node
if current_node == goal: # goal test
return explored
for leaves in graph[current_node]: # generate child
if leaves not in explored: # always check the node, beacuse we dont explored the node again in Astar
h_value=heur[leaves]
fringe.put((astarC +h_value+ aStar_Cost(current_node, leaves, cost), leaves))
print(aStar(graph, heur,'Arad', 'Bucharest', cost)) |
27b23931b7ef789dd9ea116bfb263c070b48dcaf | vesche/snippets | /python/cw/triangle.py | 479 | 3.546875 | 4 | #!/usr/bin/env python
import sys
with open(sys.argv[1]) as f:
data = f.read().splitlines()
def triangle(n_rows):
results = []
for _ in range(n_rows):
row = [1]
if results:
last_row = results[-1]
row.extend([sum(pair) for pair in zip(last_row, last_row[1:])])
row.append(1)
results.append(row)
return results
for line in data:
row, col = map(int, line.split())
print triangle(row+1)[-1][col] |
6b30e44132690fe90eb8e916fbeb3c8c5ac62006 | kovacs-roland2/football_graphs | /4_world_players_scripts/3_filter_players.py | 1,107 | 3.578125 | 4 | #Delete the records from the players df with the unwanted teams
#%%
import pandas as pd
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import itertools
from networkx.algorithms import community
import operator
from itertools import islice
import glob
import os
df_players = pd.read_excel('/Scripts/world/df.xlsx')
print(df_players)
df_teams = pd.read_excel('/Scripts/world/teams_to_use.xlsx')
df_teams = df_teams[['Name', 'League']]
print(df_teams)
#%%
#define teams of the players df
player_teams = df_players['Team'].unique()
player_teams = pd.Series(player_teams)
print(list(player_teams))
#%%
#define teams included in the teams df also
searchfor = df_teams['Name']
found = player_teams[player_teams.str.contains('|'.join(searchfor))]
print(found)
# %%
#save found teams to excel
found.to_excel('/Scripts/world/teams_to_use_2.xlsx', encoding = 'UTF-8')
# %%
#excluded the records with not found teams
df_final= df_players[df_players.Team.isin(found)]
print(df_final)
# %%
#save player df to excel
df_final.to_excel('/Scripts/world/df_final.xlsx', encoding = 'UTF-8')
# %%
|
b5105cc872471d5834e41822d5c912723429dfa2 | crain9412/pyalgos | /PriorityQueue.py | 2,188 | 4.0625 | 4 | """Priority queue with a min heap implementation"""
class PriorityQueue:
def __init__(self):
self.heap = []
def add(self, item):
self.heap.append(item)
self.heapify_up(len(self.heap) - 1)
def poll(self):
self.swap(0, len(self.heap) - 1)
removed_item = self.heap.pop()
self.heapify_down(0)
return removed_item
def get_parent_index(self, index):
return (index - 1) // 2
def get_left_child_index(self, index):
return index * 2 + 1
def get_right_child_index(self, index):
return index * 2 + 2
def try_get(self, index):
if index < 0 or index > len(self.heap) - 1:
return None
return self.heap[index]
def heapify_up(self, index):
child = self.try_get(index)
parent_index = self.get_parent_index(index)
parent = self.try_get(parent_index)
if parent and parent > child:
self.swap(parent_index, index)
self.heapify_up(parent_index)
def heapify_down(self, index):
left_child_index = self.get_left_child_index(index)
right_child_index = self.get_right_child_index(index)
left_child = self.try_get(left_child_index)
right_child = self.try_get(right_child_index)
parent = self.try_get(index)
if not left_child and not right_child or not parent:
return
elif left_child and not right_child:
if parent > left_child:
self.swap(index, left_child_index)
self.heapify_down(left_child_index)
else:
return
elif left_child < right_child and parent > left_child:
self.swap(index, left_child_index)
self.heapify_down(left_child_index)
elif right_child < left_child and parent > right_child:
self.swap(index, right_child_index)
self.heapify_down(right_child_index)
def swap(self, i, j):
temp = self.heap[i]
self.heap[i] = self.heap[j]
self.heap[j] = temp
def is_empty(self):
return len(self.heap) == 0
def __str__(self):
return str(self.heap) |
5d05866f01932ca1225eb03685aa9466a67eb016 | PooPooPidoo/SimpleCalculate | /calc.py | 2,095 | 4.03125 | 4 | import math as m
import re
def op(x,y,operator):
if(checknum(x,y)):
if operator == '+': return x+y,
if operator == '-': return x-y,
if operator == '*': return x*y,
if operator == "/" and y != 0: return x/y,
if operator == "/" and y == 0: return ["division by zero",]
else:
return "bad expression"
def parse(str):
numbers = []
operators = 0
operator = ''
flag = False
num = ''
# re.sub(str, '', ' ')
if str[0] in '-+':
num += str[0]
str = str[1:len(str)]
for symbol in str:
if symbol == ' ':
continue
if symbol in '123456789.0':
flag = True
num += symbol
continue
else:
if symbol in '+-*/':
operators += 1
if operators > 1: symbol = ''
if operators == 1:
operator = symbol
numbers.append(float(num))
num = ''
flag = False
continue
if not flag:
print("Bad expression")
return
if operators < 1:
print("No operators found")
return
numbers.append(float(num))
if operators==1 and flag==True and len(numbers)>1:
return numbers, operator
def checknum(*args):
for var in args:
if type(var) is float:
pass
else:
print("at least one value is not a number")
return False
return True
def main():
print("Welcome to the standart calc!")
print("Type two numeric values with an operation between")
while True:
expr = input()
if expr != '':
try:
numbers, operator = parse(expr)
except TypeError:
print("Bad Expression")
except ValueError:
print("Bad Expression")
else:
print(op(numbers[0], numbers[1], operator)[0])
main() |
a3d8ae3509482be9519dddcbf457914355342917 | shariqx/codefights-python | /livingOnTheRoads.py | 1,456 | 3.59375 | 4 |
def getConnectedCities(city_arr):
out = []
for idx, boolean in enumerate(city_arr):
if boolean:
out.append(idx)
return out
def livingOnTheRoads(roadRegister):
city_num = -1
city_dict = {}
iniesta = [] # iniesta's last classico 07/05/2018, Gracias Maestro :')
for i in range(0, len(roadRegister)):
x = list()
x.extend(getConnectedCities(roadRegister[i]))
if len(x) == 0 :
continue
for y in x:
city_name = str(i)+'_'+str(y)
iniesta.append(city_name)
city_num += 1
city_dict[city_name] = city_num
roadRegister[y][i] = False
out_arr = [[False for x in range(len(iniesta))] for x in range(len(iniesta))]
for i in range(len(iniesta)):
curr_city = iniesta[i]
for j in range(i + 1, len(iniesta)):
curcity_arr = curr_city.split('_')
nextcity_arr = iniesta[j].split('_')
if curcity_arr[0] in nextcity_arr or curcity_arr[1] in nextcity_arr:
out_arr[city_dict[curr_city]][city_dict[iniesta[j]]] = True
out_arr[city_dict[iniesta[j]]][city_dict[curr_city]] = True
print(out_arr)
print(city_dict)
return out_arr
if __name__ == '__main__':
roadRegister = [[False,True,True,True],
[True,False,False,True],
[True,False,False,True],
[True,True,True,False]]
print(livingOnTheRoads(roadRegister))
|
9b8733f263bec0d35b80bcb65309c2c5b9e4ca77 | fernandaars/UFMG-4-ALG-TP | /solucoes/cap06_12.py | 1,447 | 3.796875 | 4 | # -*- coding: utf-8 -*-
import sys
import random
from math import log
from math import pow
NUM_TESTS = 10000
NUM_RANGE = 100
def createCSV(nameCSV, string):
csv = open(nameCSV, "a")
csv.write(string)
def greatestCommonDivisor(a, b):
if a == 0: return b;
if b == 0: return a;
return greatestCommonDivisor(a, a%b);
def hasInverse(a, p):
if greatestCommonDivisor(a,p) == 1:
return True
else:
return False
def calculateInverse(a, p):
def countPrimes(num, n):
type1 = type3 = 0
i = 0
while i < n:
if num[i] == True:
if typeOfPrime(i) == True:
type1 += 1
else:
type3 += 1
i += 1
return type1, type3
def main():
print(".::::: Capítulo 03 - Exercício 12 :::::.\n")
print("----------------------------------------\n")
numTests = NUM_TESTS
numRange = NUM_RANGE
createCSV("cap03_exer12.csv", "Número de Testes, Proporção entre Possuir e Não Possuir Inverso\n")
i = 1
count = 0
while i <= (numTests):
a = random.randint(numRange)
b = random.randint(numRange)
p = random.randint(numRange)
if hasInverse(a, p) == True:
inverse = calculateInverse(a, p)
x = calculateSolution(a, b, p)
count += 1
createCSV("cap03_exer12.csv", str(numTests)+str(float(numTests)/float(count)))
i += 1
main() |
0639372d729acec9eb7f3249a5c4fc574d539ce8 | Jsonlmy/leetcode | /人生苦短/回文链表.py | 2,553 | 4 | 4 | '''
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
链接:https://leetcode-cn.com/problems/palindrome-linked-list
'''
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
'''
解法1:两遍遍历,第一遍获取长度,第二遍将前一半链表的值入栈,后一半一遍出栈一遍比较
'''
# length = 0
# stack = []
# node = head
# while node:
# length += 1
# node = node.next
# half = length // 2
# node = head
# while half:
# stack.append(node.val)
# node = node.next
# half -= 1
# if length % 2: node = node.next
# while stack:
# if stack.pop() != node.val: return False
# node = node.next
# return True
'''
解法2:一遍遍历,将所有值装入列表,比较列表左边部分和右边翻转的部分
'''
# lis = []
# while head:
# lis.append(head.val)
# head = head.next
# return lis[:(len(lis)+1)//2] == lis[len(lis)//2:][::-1]
'''
解法3:双指针+反转链表,常数空间复杂度,
快指针走完时慢指针正好到链表的中间,将后半部分链表反转再与原链表前半部分比较
'''
def reverse(node: ListNode) -> ListNode:
prev = None
while node:
node_next = node.next
node.next = prev
prev = node
node = node_next
return prev
if not (head and head.next): return True
slow, fast = head, head.next
while fast and fast.next:
slow, fast = slow.next, fast.next.next
tail = reverse(slow.next if fast else slow)
if fast: slow.next = None
while tail and head:
if tail.val != head.val: return False
tail, head = tail.next, head.next
return True
if __name__ == "__main__":
head = ListNode(0)
head.next = ListNode(0)
# head.next.next = ListNode(3)
res = Solution().isPalindrome(head)
# while res:
# print(res.val)
# res = res.next |
7b4a2a62b6c12d5c0f47a728c207e8cd226cf573 | thiago-machado/alura_python_jogos | /criar_arquivo_para_jogo_forca.py | 1,159 | 4.3125 | 4 | '''
Para abrir um arquivo, o Python possui a função built-in open().
Ela recebe dois parâmetros: o primeiro é o nome do arquivo a ser aberto,
e o segundo parâmetro é o modo que queremos trabalhar com esse arquivo, se queremos ler,
escrever ou fazer append.
O modo é passado através de uma string: "w" para escrita, "r" para leitura ou "a" para append.
Vale lembrar que o w sobrescreve o arquivo, se o mesmo existir. Se só quisermos adicionar conteúdo ao
arquivo, utilizamos o a.
Podemos também passar o encoding desejado.
Além do r, w e a existe o modificador b que devemos utilizar quando queremos trabalhar
no modo binário. Para abrir uma imagem devemos usar:
imagem = open("foto.jpg", "rb")
'''
def criar_arquivo():
arquivo = open("palavras.txt", "w", encoding="utf-8")
arquivo.write("banana\n") # escrevendo no arquivo
arquivo.write("maçã\n")
arquivo.write("laranja\n")
arquivo.write("kiwi\n")
arquivo.write("tamarindo\n")
arquivo.write("uva\n")
arquivo.write("pêra\n")
arquivo.write("acabaxi\n")
arquivo.close() # sempre fechar o aquivo
if (__name__ == "__main__"):
criar_arquivo()
|
0d28d8e35f4f35272b8d9e2de4ad09a3d1d44a2f | lijubjohn/python-stuff | /core/conditions.py | 2,828 | 4.28125 | 4 | # days = int(input("How many days in a leap year? "))
# if days == 366:
# print("Congrats!You have cleared the test.")
# else:
# print("please read and level up")
# If Else in one line - Syntax
num = 2
result = 'Even' if num % 2 == 0 else 'Odd'
print(result)
# Python if-Elif-Else Statement
'''
while True:
response = input("Which Python data type is an ordered sequence? ").lower()
print("You entered:", response)
if response == "list":
print("You have cleared the test.")
break
elif response == "tuple":
print("You have cleared the test.")
break
else:
print("Your input is wrong. Please try again.")
'''
a = 10
b = 20
if not a > b:
print("The number %d is less than %d" % (a, b))
X = 0
if not X:
print("X is not %d" % (X))
else:
print("X is %d" % (X))
a = 10
b = 20
c = 30
avg = (a + b + c) / 3
print("avg =", avg)
if avg > a and avg > b and avg > c:
print("%d is higher than %d, %d, %d" % (avg, a, b, c))
elif avg > a and avg > b:
print("%d is higher than %d, %d" % (avg, a, b))
elif avg > a and avg > c:
print("%d is higher than %d, %d" % (avg, a, c))
elif avg > b and avg > c:
print("%d is higher than %d, %d" % (avg, b, c))
elif avg > a:
print("%d is just higher than %d" % (avg, a))
elif avg > b:
print("%d is just higher than %d" % (avg, b))
elif avg > c:
print("%d is just higher than %d" % (avg, c))
# Example of "in" operator with Python If statement
num_list = [1, 10, 2, 20, 3, 30]
for num in num_list:
if not num in (2, 3):
print("Allowed Item:", num)
# Find players who play both games
team1 = ["Jake", "Allan", "Nick", "Alex", "Dave"]
team2 = ["David", "John", "Chris", "Alex", "Nick"]
for aplayer in team1:
if aplayer in team2:
print("%s also plays for team2." % (aplayer))
#Implement Python Switch Case Statement
def monday():
return "monday"
def tuesday():
return "tuesday"
def wednesday():
return "wednesday"
def thursday():
return "thursday"
def friday():
return "friday"
def saturday():
return "saturday"
def sunday():
return "sunday"
def default():
return "Incorrect day"
switcher = {
1: monday,
2: tuesday,
3: wednesday,
4: thursday,
5: friday,
6: saturday,
7: sunday
}
def switch(dayOfWeek):
return switcher.get(dayOfWeek, default)()
print(switch(1))
print(switch(0))
# Implement Python Switch Case Statement using Class
class PythonSwitch:
def switch(self, dayOfWeek):
default = "Incorrect day"
return getattr(self, 'case_' + str(dayOfWeek), lambda: default)()
def case_1(self):
return "Monday"
def case_2(self):
return "Tuesday"
def case_3(self):
return "Wednesday"
s = PythonSwitch()
print(s.switch(1))
print(s.switch(0)) |
cabf178247533109aca9f17cd5712a860fe507d2 | sumeetsarkar/art-of-python | /oop/singleton.py | 967 | 4.375 | 4 | """
Demonstrating implementation of Singleton class in python
If __new__ returns instance of it’s own class,
then the __init__ method of newly created instance will be invoked with instance
as first(like __init__(self, [, ….]) argument following by arguments passed to __new__ or call of class.
So, __init__ will called implicitly.
If __new__ method return something else other than instance of class,
then instances __init__ method will not be invoked.
In this case you have to call __init__ method yourself.
"""
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = object.__new__(cls)
return cls._instance
def __init__(self, somedata):
self.somedata = somedata
def __str__(self):
return str(self.somedata)
s1 = Singleton(10)
print(s1) # 10
s1.somedata += 10
print(s1) # 20
s2 = Singleton(100)
print(s2) # 100
print(s1) # 100
|
3e812e36b3081aed665e2e537cc8186920820cff | rafaeltorrese/slides_programming-lecture | /03_executing-programs/activity01/distributions.py | 1,108 | 3.640625 | 4 | import random
import math
import statistics
import matplotlib.pyplot as plt
def parts_distr(a, b):
'This function returns a uniform random variable between a and b'
return a + random.random() * (b - a)
def demand_distribution(mu, sigma):
'This function returns a normal random variable with standard deviation sigma and mean mu'
return (math.sqrt(-2 * math.log(1 - random.random())) * math.cos(2 * math.pi * random.random())) * sigma + mu
def work_distr(*args):
'This function returns a discrete probability distribution for the workforce cost'
R = random.random()
for a in args[::2]:
print(a)
# cumulative_distr = []
# cum = 0
# for probability in args:
# cum += probability
# cumulative_distr.append(cum)
# return cumulative_distr
if __name__ == '__main__':
print(parts_distr(80, 100))
demand_values = [demand_distribution(15000, 4500) for _ in range(1000)]
print(statistics.mean(demand_values))
print(statistics.stdev(demand_values))
print(work_distr(43, 0.10, 44, 0.30, 45, 0.70, 46, 0.90, 47, 1.))
|
2457a03e8be2d2ed175fd3cb5ff9a597261a7e2f | harsh95/codeforces_python | /Translation.py | 107 | 3.9375 | 4 | str1, str2 = str(input()), str(input())
str1 = str1[::-1]
if str1 == str2:
print("YES")
else:
print("NO") |
a95b42f3f5a5ec161a1ffdb5273d2312b78395e7 | Anandhakrishnan2000/Python_PS_Programs | /Abstract.py | 253 | 3.59375 | 4 | from abc import ABC,abstractmethod
class Computer(ABC):
@abstractmethod
def process(self):
pass
class Laptop(Computer):
def process(self):
print("its running")
#com = Computer()
lap = Laptop()
lap.process()
#com.process() |
31185165bee99371a625345036a2da64cc94ece5 | puneetb97/Python_course | /day4/generator.py | 224 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 25 00:01:53 2019
@author: Puneet
"""
input_list = list(input("enter elements").split(","))
input_tuple = tuple(input_list)
print("list:",input_list)
print("tuple:",input_tuple) |
759ea65e99bbd394ea1ff16e5e767550fb81d6b3 | starmon00/161HW | /HW4_1.py | 312 | 3.875 | 4 | import math
def main(S, k):
print(S)
print(k)
if k <= len(S):
counter = 0
mid = math.floor(len(S)/2)
distance = math.floor(k/2)
print(counter)
elif k > len(S) :
print("MUST BE LESS THAN SIZE S")
elif k <= 0:
print("USE POSTIVE INT ONLY")
|
f3dcf8266caef2de5420252a857db757756cc0f2 | benja956/Python-based | /koch.py | 942 | 3.640625 | 4 | #v1
"""
import turtle
def koch(size,n):
if n == 0:
turtle.fd(size)
else:
for angle in [0,60,-120,60]:
turtle.left(angle)
koch(size/3,n-1)
def main():
turtle.speed(8)
turtle.pencolor("blue")
turtle.penup()
turtle.fd(-200)
turtle.pendown()
for i in range(6):
koch(100,3)
turtle.right(60)
turtle.hideturtle()
main()
"""
#v2
import turtle
import turtle
def koch(size,n):
if n == 0:
turtle.fd(size)
else:
for angle in [0,60,-120,60]:
turtle.left(angle)
koch(size/3,n-1)
def main():
turtle.setup(600,600)
turtle.speed(10)
turtle.pensize(2)
turtle.pencolor("blue")
turtle.penup()
turtle.goto(-200,100)
turtle.pendown()
for i in range(3):
koch(400,3)
turtle.right(120)
turtle.hideturtle()
main()
|
a602ce5558bcc1dd3c4d270ce3edf250ab4d89ac | DilyanTsenkov/SoftUni-Software-Engineering | /Python Fundamentals/07 Dictionaries/Exercises/10_softuni_exam_results.py | 1,134 | 3.640625 | 4 | def stat(language, points):
if name not in statistic:
statistic[name] = points
else:
if statistic[name] < points:
statistic[name] = points
if language in language_submissions:
language_submissions[language] += 1
else:
language_submissions[language] = 1
return statistic, language_submissions
statistic = {}
language_submissions = {}
while True:
receive = input()
if receive == "exam finished":
break
receive = receive.split("-")
name = receive[0]
if "banned" in receive:
del statistic[name]
else:
statistic, language_submissions = stat(receive[1], int(receive[2]))
statistic = dict(sorted(statistic.items(), key=lambda k: (-k[1], k[0])))
language_submissions = dict(sorted(language_submissions.items(), key=lambda k: (-k[1], k[0])))
print("Results:")
for name, points in statistic.items():
print(f"{name} | {statistic[name]}")
print("Submissions:")
for language, submission in language_submissions.items():
print(f"{language} - {language_submissions[language]}")
|
407a2e8a447c3dd2949a1c719b6ec95c5585fe2d | kuchunbk/PythonBasic | /2_String/Sample/string_ex34.py | 803 | 4.625 | 5 | '''Question:
Write a Python program to print the following integers with '*' on the right of specified width.
'''
# Python code:
x = 3
y = 123
print("\nOriginal Number: ", x)
print("Formatted Number(right padding, width 2): "+"{:*< 2d}".format(x));
print("Original Number: ", y)
print("Formatted Number(right padding, width 6): "+"{:*< 6d}".format(y));
print()
'''Output sample:
Original Number: 3
Formatted Number(right padding, width 2): 3*
Original Number: 123
Formatted Number(right padding, width 6): 123***
''' |
6a76f905994d09b1a3308fc85e00fc63d44062c1 | Hanlen520/Leetcode-4 | /src/136. Single Number.py | 884 | 3.53125 | 4 | class Solution:
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
demo = set()
for i in nums:
if i in demo:
demo.remove(i)
else:
demo.add(i)
return demo.pop()
# 1. python中的^ 运算符代表按位异或,所以如果对nums中的所有元素进行异或,那么有两个的元素都会被抵消,剩下的就是single number了。
# 2. 求和相减也是一种方法
# 下面每个函数都是个不同的方法
def singleNumber2(self, nums):
res = 0
for num in nums:
res ^= num
return res
def singleNumber3(self, nums):
return 2*sum(set(nums))-sum(nums)
def singleNumber4(self, nums):
return reduce(lambda x, y: x ^ y, nums)
def singleNumber(self, nums):
return reduce(operator.xor, nums)
|
56506839d6abd9b6ef4f9590c3409e40350fff1c | josefeg/adventofcode2017 | /src/day_twelve.py | 3,844 | 4.15625 | 4 | #!/usr/bin/env python3
# --- Day 12: Digital Plumber ---
#
# Walking along the memory banks of the stream, you find a small village that
# is experiencing a little confusion: some programs can't communicate with
# each other.
#
# Programs in this village communicate using a fixed system of pipes. Messages
# are passed between programs using these pipes, but most programs aren't
# connected to each other directly. Instead, programs pass messages between
# each other until the message reaches the intended recipient.
#
# For some reason, though, some of these messages aren't ever reaching their
# intended recipient, and the programs suspect that some pipes are missing.
# They would like you to investigate.
#
# You walk through the village and record the ID of each program and the IDs
# with which it can communicate directly (your puzzle input). Each program has
# one or more programs with which it can communicate, and these pipes are
# bidirectional; if 8 says it can communicate with 11, then 11 will say it can
# communicate with 8.
#
# You need to figure out how many programs are in the group that contains
# program ID 0.
#
# For example, suppose you go door-to-door like a travelling salesman and
# record the following list:
#
# 0 <-> 2
# 1 <-> 1
# 2 <-> 0, 3, 4
# 3 <-> 2, 4
# 4 <-> 2, 3, 6
# 5 <-> 6
# 6 <-> 4, 5
#
# In this example, the following programs are in the group that contains
# program ID 0:
#
# Program 0 by definition.
# Program 2, directly connected to program 0.
# Program 3 via program 2.
# Program 4 via program 2.
# Program 5 via programs 6, then 4, then 2.
# Program 6 via programs 4, then 2.
#
# Therefore, a total of 6 programs are in this group; all but program 1, which
# has a pipe that connects it to itself.
#
# How many programs are in the group that contains program ID 0?
#
# --- Part Two ---
#
# There are more programs than just the ones in the group containing program
# ID 0. The rest of them have no way of reaching that group, and still might
# have no way of reaching each other.
#
# A group is a collection of programs that can all communicate via pipes
# either directly or indirectly. The programs you identified just a moment ago
# are all part of the same group. Now, they would like you to determine the
# total number of groups.
#
# In the example above, there were 2 groups: one consisting of programs
# 0,2,3,4,5,6, and the other consisting solely of program 1.
#
# How many groups are there in total?
import re
import sys
def build_network(lines: list) -> map:
network = {}
pattern = re.compile(r"(\d+)\s+<->\s+(.*)")
for line in lines:
match = pattern.match(line)
network[match.group(1)] = match.group(2).split(", ")
return network
def find_connected_to(network: map, target: str) -> set:
already_encountered = set()
to_traverse = network[target][:]
index = 0
connected = set()
while index < len(to_traverse):
element = to_traverse[index]
index += 1
if element in already_encountered:
continue
already_encountered.add(element)
to_traverse.extend(network[element])
connected.add(element)
return connected
def count_groups(lines: list) -> int:
groups = 0
connected = set()
network = build_network(lines)
for key in network.keys():
if key in connected:
continue
groups += 1
current_group = find_connected_to(network, key)
connected.update(current_group)
return groups
def main():
input_file = sys.argv[1]
with open(input_file) as f:
lines = f.readlines()
network = build_network(lines)
connected = find_connected_to(network, "0")
print("connected =>", len(connected))
print("groups =>", count_groups(lines))
if __name__ == "__main__":
main()
|
98e82ab2c9fd2dc873a723e3ff3e90bd29a121cf | Aasthaengg/IBMdataset | /Python_codes/p03281/s886838147.py | 371 | 3.59375 | 4 | def divisors(n):
lower_divisors=[]
upper_divisors=[]
i=1
while i*i<=n:
if n%i==0:
lower_divisors.append(i)
if i!=n//i:
upper_divisors.append(n//i)
i+=1
return lower_divisors+upper_divisors[::-1]
n=int(input())
cnt=0
for i in range(1,n+1,2):
if len(divisors(i))==8:
cnt+=1
print(cnt) |
edfe417449a9a1d860127fb36b25fdd50ec9f5b5 | daftstar/learn_python | /00_DataCamp/07_Functions/bringing_it_all_together_1.py | 1,531 | 3.78125 | 4 | # Bringing it all together
# campus.datacamp.com/courses/python-data-science-toolbox-part-1/writing-your-own-functions?ex=12
import pandas as pd
# Import twitter data as DataFrame
# tweets.csv is a large flat 100 row file containing
# general user information + recent tweets & retweets
df = pd.read_csv("tweets.csv")
# Column header names
# contributors, coordinates, created_at, entities, extended_entities,
# favorite_count, favorited, filter_level, geo, id, id_str,
# in_reply_to_screen_name, in_reply_to_status_id, in_reply_to_status_id_str
# in_reply_to_user_id, in_reply_to_user_id_str, is_quote_status
# lang, place, possibly_sensitive, quoted_status, quoted_status_id
# quoted_status_id_str, retweet_count, retweeted, retweeted_status
# source, text, timestamp_ms, truncated, user
# #########################################################
""" PART 1: Count how many times each language is used """
# #########################################################
# Initialize an empty dictionary: langs_count
langs_count = {}
# Extract column from DataFrame: col
col = df["lang"]
# Iterate over lang column within DataFrame
for entry in col:
# If language is in langs_count dictionary, add 1:
if entry in langs_count.keys():
langs_count[entry] += 1
# If language does not exist, add it and set value to 1
else:
langs_count[entry] = 1
# Show values for dictionary: langs_count
for language, amount in langs_count.items():
print ("language: %s - %s" % (language, amount)) |
23fb67c6989ed6b6b1aaa5235319e9786d30c194 | seyyalmurugaiyan/Django_projects | /Demo_Projects/Day_1 - Basics/addcondition.py | 241 | 4.03125 | 4 | number1 = int(input("Enter your first Number: "))
number2 = int(input("Enter your second Number: "))
if number1 == number2:
print(f"{number1}+{number2}*2 = {(number1+number2)*2}")
else:
print(f"{number1}+{number2}={number1+number2}") |
39608068257850326449c86cd91316b1f4f5857b | SoheeKwak/Python | /DL15-1_Corpus.py | 4,794 | 3.796875 | 4 | ## corpus(말뭉치):특정 도메인에 등장하는 단어들의 집합
#1. 10개의 문장 수집 -> 워드 벡터 생성
corpus = ['boy is a young man',
'girl is a young woman',
'queen is a wise woman',
'king is a strong man',
'princess is a young queen',
'prince is a young king',
'woman is pretty',
'man is strong',
'princess is a girl will be queen',
'prince is a boy will be king']
#2. 불필요한 단어 제거
def remove_stop_words(corpus):
# it's-> it is 등의 전처리 작업
stop_words = ['is','a','will','be']
results=[]
for text in corpus:
#print(text)
tmp = text.split(' ')
# print(tmp)
for stop_word in stop_words:
if stop_word in tmp:
tmp.remove(stop_word)
print(tmp)
results.append(" ".join(tmp))
return results
corpus = remove_stop_words(corpus) #corous에 위에서 리턴된 results가 들어감
words = []
for text in corpus:
for word in text.split(' '):
words.append(word)
words = set(words) #set: 중복 단어 제거
print(words)
word2int={}
for i, word in enumerate(words):
print(i, word)
word2int[word]=i
print(word2int) #{'wise': 11, 'queen': 1,....}
sentences=[]
for sentence in corpus:
sentences.append(sentence.split())
print("sentences:",sentences)
#skipgram 적용, window size:2
WINDOW_SIZE = 2
"""
['boy', 'young', 'man'] 좌로 2칸, 우로 2칸까지 모두 참조
xdata ydata
boy young
boy man
young boy
young man
man boy
man young
"""
data=[]
for sentence in sentences:
print(sentence)
for idx, word in enumerate(sentence): #word: boy
print(idx, word)
for neighbor in sentence[ #['boy', 'young', 'man']...
max(idx-WINDOW_SIZE,0): #max(0-2, 0)=>0, min(0+2, 3)+1=>3 즉, 최소0에서 최대3까지만 허용
min(idx+WINDOW_SIZE, len(sentence))+1]: #[0:3]의 범위로 정해주는 설정(WINDOW SIZE:2)
if neighbor!=word:
data.append([word, neighbor])
print("data:",data)
import pandas as pd
for text in corpus:
print("corpus:", text)
df = pd.DataFrame(data, columns=['input', 'label'])
print(df)
print(df.shape)#(52, 2)
########### deep learning##############
import tensorflow as tf
import numpy as np
ONE_HOT_DIM = len(words)#중복되지 않은 단어들의 개수
def to_one_hot_encoding(data_point_index):
to_one_hot_encoding = np.zeros(ONE_HOT_DIM)
to_one_hot_encoding[data_point_index]=1
return to_one_hot_encoding
X=[] #input
Y=[] #target
for x,y in zip(df['input'],df['label']):
X.append(to_one_hot_encoding(word2int[x]))
Y.append(to_one_hot_encoding(word2int[y]))
print(X) #input
print(Y) #label
xtrain = np.asarray(X)
ytrain = np.asarray(Y)
#텐서플로우에서 사용하기 위한 다차원 배열로 변경
x = tf.placeholder(tf.float32, shape=(None, ONE_HOT_DIM))
ylabel = tf.placeholder(tf.float32, shape=(None, ONE_HOT_DIM))
EMBBDDING_DIM=2 #weight를 2개 줌
#히든 계층(워드 벡터) #(11, 2)
W1 = tf.Variable(tf.random_normal([ONE_HOT_DIM, EMBBDDING_DIM]))
b1 = tf.Variable(tf.random_normal([EMBBDDING_DIM])) #EMBBDDING_DIM 대신 1써도 됨, but 어차피 최종 출력은 1이므로
hidden_layer = tf.add(tf.matmul(x,W1),b1)
W2 = tf.Variable(tf.random_normal([EMBBDDING_DIM, ONE_HOT_DIM]))
b2 = tf.Variable(tf.random_normal([1]))
prediction = tf.nn.softmax(tf.add(tf.matmul(hidden_layer, W2), b2))
cost = tf.reduce_mean(-tf.reduce_sum(ylabel*tf.log(prediction), axis=1))
train = tf.train.GradientDescentOptimizer(0.05).minimize(cost)
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
iteration = 20000
for i in range(iteration):
sess.run(train, feed_dict={x:xtrain, ylabel:ytrain})
if i %3000==0:
print('interation'+str(i)+'cost is:',
sess.run(cost, {x:xtrain, ylabel:ytrain}))
print(sess.run(W1+b1))
vextors = sess.run(W1+b1)
df2 = pd.DataFrame(vextors, columns=['x1','x2'])
df2['word']=words
df2 = df2[['word','x1','x2']]
print(df2)
import matplotlib.pyplot as plt
fig,ax = plt.subplots()
for word, x1, x2 in zip(df2['word'],df2['x1'],df2['x2']):
ax.annotate(word, (x1,x2)) #word로 좌표 위 구현
padding=1.0
x_axis_min = np.amin(vextors,axis=0)[0]-padding
y_axis_min = np.amin(vextors,axis=0)[1]-padding
x_axis_max = np.amax(vextors,axis=0)[0]+padding
y_axis_max = np.amax(vextors,axis=0)[1]+padding
plt.xlim(x_axis_min, x_axis_max)
plt.ylim(y_axis_min, y_axis_max)
plt.rcParams["figure.figsize"]=(10,10)
plt.show()
|
78a5f603c8a9dcece05db7f11790dfcae62b7d96 | evgenii20/two_python | /lesson_1_hw/06_test_file.py | 2,221 | 4.21875 | 4 | """
lesson 1 hw
6. Создать текстовый файл test_file.txt, заполнить его тремя строками: «сетевое
программирование», «сокет», «декоратор». Проверить кодировку файла по умолчанию.
Принудительно открыть файл в формате Unicode и вывести его содержимое.
"""
# Работа с файловой системой
# Чтобы обратиться к определенному файлу и прочесть его содержимое, применяется следующая
# конструкция:
# with open(file_name) as f_n:
# for el_str in f_n:
# print(el_str)
# import locale
#
# # определяем установленную в ОС кодировку по умолчанию
# def_coding = locale.getpreferredencoding()
# print(def_coding)
# cp1251
# При работе с файлами также можно определить наименование кодировки, которая будет
# использоваться при операциях с ними
STR = ['сетевое программирование', 'сокет', 'декоратор']
# with open("test_file.txt", "w") as f:
file = open("test_file.txt", "r+")
for el in range(len(STR)):
# file = file.write(STR[el] +'\n')
# file1 = file.write(STR[el] + '\n')
file.write(STR[el] + '\n')
# file.write(STR[el])
print(f'Кодировка в файле по умолчанию:\n{file.encoding}')
file.close()
# op_file = open("test_file.txt", 'r', encoding='cp1251').read()
op_file = open("test_file.txt", 'r', encoding='unicode-escape').read()
# op_file = open("test_file.txt", 'r', encoding='utf-8').read()
print(op_file)
# op_file.close()
# При использовании utf-8 выходит ошибка декодирования юникода:
# UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf1 in position 0: invalid continuation byte
# Кодировка utf-8, для декодирования не подходит, не допустимый байт продолжения в позиции 0
|
0acb4f6ad12514ba91f01c2376a7da311152eebe | brunarafaela/aulas_programacao_banco_de_dados | /aula-4/aula.py | 2,507 | 3.609375 | 4 | from matplotlib import pyplot as plt
from collections import Counter
def grafico_linha ():
years = [1950, 1960, 1970, 1980, 1990, 2000, 2010]
gdp = [300.2, 543.3, 1075.9, 2862.5, 5979.6, 10289.7, 14958.3]
plt.plot (years, gdp, color='green', marker='o', linestyle='solid')
plt.title ("GDP Nominal")
plt.ylabel ("Bilhões de $")
plt.show()
def grafico_barra ():
movies = ["Annie Hall", "Ben-Hur", "Casablanca", "Gandhi", "West Side Story"]
num_oscars = [5, 11, 3, 8, 10]
xs = [i for i, _ in enumerate (movies)]
plt.bar(xs, num_oscars)
plt.ylabel ("# de Premiações")
plt.xlabel ("Filmes favoritos")
plt.xticks ([i for i, _ in enumerate(movies)], movies)
plt.show()
def grafico_histograma():
grades = [83, 95, 91, 87, 70, 0, 85, 82, 100, 67, 73, 77, 0]
decil = lambda grade: grade // 10 * 10
decis = [decil (grade) for grade in grades]
histograma = Counter (decis)
plt.bar(
[
x for x in histograma.keys()
],
histograma.values(),
8
)
plt.axis ([-5, 105, 0, 5])
plt.xticks ([10 * i for i in range (11)])
plt.xlabel ("Decil")
plt.ylabel ("# de Alunos")
plt.title ("Distribuição das Notas do Teste 1")
plt.show()
def mencoes_data_science_sem_valor_zero ():
mencoes = [500, 505]
anos = [2013, 2014]
plt.bar (anos, mencoes, 0.4)
plt.xticks(anos)
plt.ylabel ("# de vezes que ouvimos alguem falar de data science")
plt.axis ([2012.5, 2014.5, 499, 506])
plt.title ("Olhe o grande aumento")
plt.show()
def mencoes_data_science_com_valor_zero():
mencoes = [500, 505]
anos = [2013, 2014]
plt.bar(anos, mencoes, 0.4)
plt.xticks(anos)
plt.ylabel("# de vezes que ouvimos alguem falar de data science")
plt.axis([2012.5, 2014.5, 0, 550])
plt.title("Veja a diferença")
plt.show()
def grafico_dispersao ():
amigos = [70, 65, 72, 63, 71, 64, 60, 64, 67]
minutos = [175, 170, 205, 120, 220, 130, 105, 145, 190]
rotulos = ['a', 'b', 'c', 'd', 'e', 'f', 'g' ,'h', 'i']
plt.scatter(amigos, minutos)
for rotulo, num_amigos, total_minutos in zip (rotulos, amigos, minutos):
plt.annotate(
rotulo,
xy = (num_amigos, total_minutos),
xytext= (5, -5),
textcoords = 'offset points'
)
plt.title ("Minutos diários vs. Números de amigos")
plt.xlabel ("# amigos")
plt.ylabel ("Média de minutos diária passados na rede")
plt.show()
def main():
#grafico_linha()
#grafico_barra()
#grafico_histograma()
#mencoes_data_science_com_valor_zero()
grafico_dispersao()
main() |
f3efea7b834beb16287a50cc4c12d66586debb49 | leo-885/Fernanda | /Fernanda.py | 566 | 3.734375 | 4 | #aprendendo if... else
num = float(input(' Fernanda é apaixonada por Pablo, seu colega de classe, e por isso quer se casar com ele mas, a sua mãe diz que é preciso esperar um pouco mais... Se Ana Clara, a irmã mais velha (que tem um gato chamado Lucrécio) tem 25 anos de idade, Amanda é 4 anos mais nova e Fernanda nasceu 10 anos depois de Ana Clara, Fernanda tem ainda de esperar quantos anos para se casar no Brasil? \n\n '))
if num == 3:
print(" Acertou!")
if num != 3:
print(" tá meio errado mano")
|
bf7ada2e37a88534e10d0c84d3c365e329e3ce86 | Axaxaxas-Mlo/Python101 | /cicloWhile.py | 199 | 3.640625 | 4 | """
cuadrado = 1
while cuadrado <= 10:
print (cuadrado)
cuadrado += 1
print ('Fin')
"""
cuadrado = 0
base = 0
while base < 100:
cuadrado = base ** 2
print (cuadrado)
base += 1 |
cb49aa0e14a776a186ad9c690e896569c7af9c27 | ivan-yosifov88/python_oop_june_2021 | /python_advanced_retake_18_08_2021/fill_the_box.py | 794 | 4.09375 | 4 | def fill_the_box(*args):
height = args[0]
length = args[1]
width = args[2]
cube_size = height * length * width
for i in range(3, len(args)):
if args[i] == "Finish":
return f"There is free space in the box. You could put {cube_size} more cubes."
if cube_size < args[i]:
cubes_left = args[i] - cube_size
for c in range(i + 1, len(args)):
if args[c] == "Finish":
break
cubes_left += args[c]
return f"No more free space! You have {cubes_left} more cubes."
cube_size -= args[i]
print(fill_the_box(2, 8, 2, 2, 1, 7, 3, 1, 5, "Finish"))
print(fill_the_box(5, 5, 2, 40, 11, 7, 3, 1, 5, "Finish"))
print(fill_the_box(10, 10, 10, 40, "Finish", 2, 15, 30))
|
c65d3affa2888bf0186ff76ff1c5570fa97cf511 | ASU-CompMethodsPhysics-PHY494/final-2017-openthepodbaydoors_hal | /work/rules_governing_cars_contd.py | 8,452 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 29 21:43:06 2017
@author: MSmith
"""
import numpy as np
import random
k_north = 0
k_south = 1
k_east = 2
k_west = 3
grid = np.genfromtxt('roadmap.csv',delimiter =',')
def road(grid):
#function that creates a value from excel .csv file for both
#x and y directions that can later be used to create our streets
x , y = grid.shape
hor = []
vert = []
for i in range(x):
if grid[i,0] == 1:
hor.append(i)
#print("hor", hor)
for j in range(y):
if grid[0,j] == 1:
vert.append(j)
#print("vert", vert)
return hor, vert
def initial_grid(d = 4):
#takes our info from excel .csv file and using 'road' function
#then spits out some info/does stuff:
#identifies where cars can and can't be on grid based on excel input
#gives random assignment of cars on locations that are 'roads'
#and not in places we've chosen to be obstructions
#stores the number of cars in each position
car_position = np.zeros((len(grid),len(grid),4))
x , y = road(grid)
for k in range(4):
for i in range(len(grid)):
for j in range(len(grid)):
if grid[i,j] == 0:
car_position[i,j] = 0
else:
for n in range(len(x)):
for j in range(len(grid)):
car_position[x[n],j,0] = random.randint(0,d) #north
car_position[x[n],j,1] = random.randint(0,d) #south
for m in range(len(y)):
for i in range(len(grid)):
car_position[i,y[m],3] = random.randint(0,d) #west
car_position[i,y[m],2] = random.randint(0,d) #east
return car_position
"""
def is_intersection(grid,i,j):
#top = grid[i,j+1] == 1
#bottom = grid[i, j-1] == 1
#left = grid[i-1,j] == 1
#right = grid[i+1,j] == 1
if j == 0:
top = grid[i,-1] == 1
else:
top = grid[i,j-1] == 1
if j == (grid.shape[1]-1):
bottom = grid[i,0] == 1
else:
bottom = grid[i, j+1] == 1
if i == 0:
left = grid[-1,j] == 1
else:
left = grid[i-1,j] == 1
if i == (grid.shape[1]-1):
right = grid[0,j] == 1
else:
right = grid[i+1,j] == 1
return top and bottom and left and right
for n in range(grid.shape[0]):
#print(grid.shape[0])
for m in range(grid.shape[1]):
#print(grid.shape[1])
if is_intersection(grid, n, m):
intersection_array[n,m] = 1
#list of intersections locations
intersections = []
for n in range(grid.shape[0]):
for m in range(grid.shape[1]):
if is_intersection(grid, n, m):
intersections.append((n,m))
print("intersections", intersections)
"""
d = 4
number_of_cars = initial_grid()
"""
def simulation_north(Nsteps=50):
#attempt at simulating movement of our cars outside intersections
#have conditions that I think will work moves even if we change d.
x,y = road(grid)
print("x", x)
print("y", y)
number_of_cars = initial_grid()
#for k in range(1):
for S in range(Nsteps):
for n in x:
for g in range(len(grid)):
#here's our main move conditions. 0 and d are the boundaries
#then our main else statement is about how to sum remainders
#without breaking rules.
if number_of_cars[x[n],j+1] == 0:
number_of_cars[x[n],j+1] = number_of_cars[x[n],j]
number_of_cars[x[n],j] = 0
if number_of_cars[x[n],j+1] == d:
number_of_cars[x[n],j] = number_of_cars[x[n],j]
else:
#if number of cars anywhere inbetween bounds, then we either
#move all of cars from current spot to next spot
#or in the else below, we move a partition that can fit, given d
if number_of_cars[x[n],j+1] > 0 and number_of_cars[x[n],j+1] < d:
if (number_of_cars[x[n],j]) + (number_of_cars[x[n],j+1]) <= d:
number_of_cars[x[n],j+1] += number_of_cars[x[n],j]
number_of_cars[x[n],j] = 0
else:
enroute = 0
enroute = (d - number_of_cars[x[n],j+1])
number_of_cars[x[n],j+1] += enroute
number_of_cars[x[n],j] -= enroute
return number_of_cars
#else:
total_d = d*2
#since our array will never have intersection at a beginning or ending index
#first,confirm there is space beyond intersection, otherwise, no need to check intersection
if number_of_cars[x[n],j+2,k] == d:
number_of_cars[x[n],j,k] = number_of_cars[x[n],j,k]
if number_of_cars[x[n],j+2,k] < d:
#north plus south plus east
spot_check = [number_of_cars[x[n],j-2,1], number_of_cars[i,y[m],2], number_of_cars[i+2,y[m],3]]
for spot in spot_check:
count = 0
count = count + spot
if count + number_of_cars[x[n],j,k] <= total_d:
if (number_of_cars[x[n],j,k]) + (number_of_cars[x[n],j+2,k]) <=d:
number_of_cars[x[n],j+2,k] += number_of_cars[x[n],j,k]
number_of_cars[x[n],j,k] = 0
else:
enroute2 = 0
enroute2 = (d - number_of_cars[x[n],j+2,k])
number_of_cars[x[n],j+2,k] += enroute2
number_of_cars[x[n],j,k] -= enroute2
else:
take_turns(number_of_cars[x[n],j,k])
number_of_cars[x[n],j+2,k]
"""
def how_many_cars_here(x, y, z):
howmany = int(number_of_cars[x][y][z])
return howmany
alex
#we should have tests for the functions to make sure they are working.
#Alex function list(then simple, don't need intersection mumbo)
#1) How many cars at x,y,z(direction)?
#2) Can add car at x,y,z(direction)? query's map at that location, make sure traffic moving in correct direction, and
#max value not hit
#3) Remove car from location x,y,z(direction).
#4) Then i would have another function that adds car from location x,y,z(direction)
"""
for x = 0, x< map size x:
for y = 0, y< map size y:
for direction in k_north, k_south, east, west:
if Number_of_cars_function(how many cars at a point at x,y,direction) > 0:
UpdatelocationFunction( to find new location.)
Can_add_car_at_new_x_y_directionFunction(checks for maximum space is available)
then remove car current x, current y
add car new x, new y to new spot
UpdateLocationFunction (which takes original x and y and direction and return new x and new y)
if og x and y are 0 and og direction is k-east, then incriment x by 1,
if k-south, then incriemtn that way:
but then check to see if you're off edge of the map
if x = 14
x = 0
or something like if y = -1, then y = 0
""" |
447ffb2c9d2dece83cb7e3dea552251d52501145 | SmerlinFernandez/PiedraPapelOTijeras | /main.py | 1,255 | 3.90625 | 4 | #Esta una recreación del juego piedra, papel o tijeras en Python
import random
import sys
aleatorio = random.randrange(1,4)
eleccion_m = ''
while True:
print("Elige Piedra(p), Papel(a) o Tijera(t) [Presiona s para salir]")
eleccion = input().lower()
if eleccion == 'p' or eleccion == 'a' or eleccion == 't':
break
if eleccion == 's':
print("Gracias por jugar")
sys.exit()
if aleatorio == 1:
eleccion_m = 'p'
print("La computadora selecciono Piedra")
elif aleatorio == 2:
eleccion_m = 'a'
print("La computadora selecciono Papel")
else:
eleccion_m = 't'
print("La computadora selecciono Tijeras")
if eleccion == 'p':
print("Seleccionaste Piedra")
elif eleccion == 'a':
print("Seleccionaste Papel")
else:
print("Seleccionaste Tijeras")
if eleccion == eleccion_m:
print("Empate")
elif eleccion == 'a' and eleccion_m == 't':
print("Perdiste")
elif eleccion == 't' and eleccion_m == 'p':
print("Perdiste")
elif eleccion_m == 'a' and eleccion == 'p':
print("Perdiste")
elif eleccion_m == 'a' and eleccion == 't':
print("Ganaste")
elif eleccion_m == 't' and eleccion == 'p':
print("Ganaste")
elif eleccion == 'a' and eleccion_m == 'p':
print("Ganaste") |
2d4a7c1388d054167bdf2489959bf2d499301dc5 | sarck1/RoadPython | /chapter014/chapter_01405.py | 939 | 3.796875 | 4 | # 线程同步问题:同时操作全局变量的情况
import time
import threading
# 类声明
class MyThread(threading.Thread):
def __init__(self, name=None):
super().__init__()
self.name = name
def run(self):
print('-----------------start:%s--------------------' % self.getName())
global num
temp = num
time.sleep(0.2)
temp -= 1
num = temp
print('t_name = %s : num = %s' % (self.getName(), temp))
print('-----------------end:%s-----------------------' % self.getName())
# 主线程
print('-------------启动:主线程------------------')
thread_lst = []
num = 10 # 全局变量
# 对象创建
for i in range(10):
t = MyThread(name=str(i),)
thread_lst.append(t)
t.start()
# 等待执行
[t.join() for t in thread_lst]
print('num最后的值为:{}'.format(num))
print('-------------结束:主线程------------------')
|
284e80bf70b03735dc3c1af71ad2f403fde793f6 | sejongkang/Baekjoon_programming | /14.분할정복/11729_하노이.py | 633 | 3.875 | 4 | def Hanoi(n, f, b, t):
global count
global moves
count += 1
if n == 1:
# 맨 위 원반이면 바로 from에서 to로 이동
moves.append('{} {}'.format(f, t))
else:
# n번 위에 원반들 from에서 by로 옮겨놓기
Hanoi(n-1, f, t, b)
# n번 원반 from에서 to로 옮기기
moves.append('{} {}'.format(f, t))
# n번 위에 원반들 by에서 to로 옮기기
Hanoi(n-1, b, f, t)
if __name__ == '__main__':
num = int(input())
count = 0
moves = []
Hanoi(num, 1, 2, 3)
print(count)
for move in moves:
print(move)
|
b46422b1be2db4d98506e59d325507a39d48631c | yuqmettal/python-training | /arrays/new_year_chaos.py | 453 | 3.546875 | 4 | def minimumBribes(queue: list):
movements = 0
for ix, val in enumerate(queue):
if val - 3 > ix:
print("Too chaotic")
return
for pos in range(max(0, val - 2), ix):
if queue[pos] > queue[ix]:
movements += 1
print(movements)
test_numbers = int(input())
for _ in range(test_numbers):
_ = int(input())
queue = list(map(int, input().split()))
minimumBribes(queue)
|
4fda751869edec154261b4610630cc173d58bc39 | HotsauceLee/Leetcode | /Categories/DP/RRR513.Perfect_Squares.py | 938 | 3.640625 | 4 | """
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
Have you met this question in a real interview? Yes
Example
Given n = 12, return 3 because 12 = 4 + 4 + 4
Given n = 13, return 2 because 13 = 4 + 9
"""
# ============== DP ==============
# Time: O(n)
# Space: O(n)
class Solution:
# @param {int} n a positive integer
# @return {int} an integer
def numSquares(self, n):
# Write your code here
if n <= 0:
return 0
if n <= 3:
return n
dp = [float('inf')]*(n + 1)
i = 1
while i**2 <= n:
dp[i**2] = 1
i += 1
for i in xrange(1, len(dp)):
j = 1
while j**2 <= i:
# dp[i - j**2] + 1 = dp[i - j**2] + dp[j**2]
dp[i] = min(dp[i], dp[i - j**2] + 1)
j += 1
return dp[-1]
|
6a88f8b056325c2766b41ce0834e86efd4e550cb | rockpz/leetcode-py | /algorithms/firstUniqueCharacterInAString/firstUniqueCharacterInAString.py | 590 | 3.65625 | 4 | # Source : https://leetcode.com/problems/first-unique-character-in-a-string/
# Author : Ping Zhen
# Date : 2017-04-11
'''***************************************************************************************
*
* Given a string, find the first non-repeating character in it and return it's index.
* If it doesn't exist, return -1.
*
* Examples:
*
* s = "leetcode"
* return 0.
*
* s = "loveleetcode",
* return 2.
*
* Note: You may assume the string contain only lowercase letters.
***************************************************************************************''' |
0720ce0d4032274bcaf376845cdbd6baa3e8cf5a | chao-shi/lclc | /236_lca_bt_m/ret3.py | 899 | 3.65625 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
def recur(root):
if not root:
return None, False, False
l_lca, lp, lq = recur(root.left)
if l_lca:
return l_lca, True, True
r_lca, rp, rq = recur(root.right)
if r_lca:
return r_lca, True, True
pin, qin = (root == p) or lp or rp, (root == q) or lq or rq
lca = root if pin and qin else None
return lca, pin, qin
return recur(root)[0] |
2fc71505bf233553b2855bb6285069d17f9ba278 | xiaodonggua1/leetcode | /两个数组的交集II.py | 738 | 4.15625 | 4 | """
给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2,2]
示例 2:
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[4,9]
"""
from typing import List
def intersect(nums1: List[int], nums2: List[int]) -> List[int]:
n = len(nums1)
m = len(nums2)
if n > m:
short_list = nums2
long_list = nums1
else:
short_list = nums1
long_list = nums2
intersect_list = []
for i in short_list:
if i in long_list:
long_list.remove(i)
intersect_list.append(i)
return intersect_list
# a = [1, 2, 2, 1]
a = [4, 9, 5]
# b = [2, 2]
b = [9, 4, 9, 8, 4]
print(intersect(a, b)) |
7d867e13f8709f8dd5e6a2a3a563885433c68fbe | JohnBatmanMySlinky/cs231n | /NUMPY_QUESION.py | 256 | 4.0625 | 4 | import numpy as np
# so say we had the follow array X
x = np.arange(12).reshape(3,4)
# and I wanted to index each row of x by an array y
# essentially select the diagonals
y = np.arange(3)
# why does this work
x[np.arange(3),y]
# and this don't
x[:,y]
|
4c98d33788eff6b141f695325e516ce9b595ac91 | gabee1987/codewars | /CodeWars/6kyu/bitcount.py | 212 | 3.546875 | 4 | def countBits(n):
bits = format(n, "08b")
return len(bits)
print(len(bits))
print(countBits(0))
print(countBits(4))
print(countBits(7))
print(countBits(9))
print(countBits(10))
print(countBits(1234)) |
4be57aec2d3bed0c69ca1235d3d3b3a024670bce | bgoonz/UsefulResourceRepo2.0 | /MY_REPOS/web-dev-notes-resource-site/core-site/other-pages/weeks/solution/directory-browsed/DIRECTORY/Data-Structures/Python/compression/huffman_coding.py | 10,517 | 3.96875 | 4 | """
Huffman coding is an efficient method of compressing data without losing information.
This algorithm analyzes the symbols that appear in a message.
Symbols that appear more often will be encoded as a shorter-bit string
while symbols that aren't used as much will be encoded as longer strings.
"""
from collections import defaultdict, deque
import heapq
class Node:
def __init__(self, frequency=0, sign=None, left=None, right=None):
self.frequency = frequency
self.sign = sign
self.left = left
self.right = right
def __lt__(self, other):
return self.frequency < other.frequency
def __gt__(self, other):
return self.frequency > other.frequency
def __eq__(self, other):
return self.frequency == other.frequency
def __str__(self):
return "<ch: {0}: {1}>".format(self.sign, self.frequency)
def __repr__(self):
return "<ch: {0}: {1}>".format(self.sign, self.frequency)
class HuffmanReader:
def __init__(self, file):
self.file = file
self.buffer = []
self.is_last_byte = False
def get_number_of_additional_bits_in_the_last_byte(self) -> int:
bin_num = self.get_bit() + self.get_bit() + self.get_bit()
return int(bin_num, 2)
def load_tree(self) -> Node:
"""
Load tree from file
:return:
"""
node_stack = deque()
queue_leaves = deque()
root = Node()
current_node = root
is_end_of_tree = False
while not is_end_of_tree:
current_bit = self.get_bit()
if current_bit == "0":
current_node.left = Node()
current_node.right = Node()
node_stack.append(
current_node.right
) # going to left node, right push on stack
current_node = current_node.left
else:
queue_leaves.append(current_node)
if node_stack:
current_node = node_stack.pop()
else:
is_end_of_tree = True
self._fill_tree(queue_leaves)
return root
def _fill_tree(self, leaves_queue):
"""
Load values to tree after reading tree
:param leaves_queue:
:return:
"""
leaves_queue.reverse()
while leaves_queue:
node = leaves_queue.pop()
s = int(self.get_byte(), 2)
node.sign = s
def _load_byte(self, buff_limit=8) -> bool:
"""
Load next byte is buffer is less than buff_limit
:param buff_limit:
:return: True if there is enough bits in buffer to read
"""
if len(self.buffer) <= buff_limit:
byte = self.file.read(1)
if not byte:
return False
i = int.from_bytes(byte, "big")
self.buffer.extend(list("{0:08b}".format(i)))
return True
def get_bit(self, buff_limit=8):
if self._load_byte(buff_limit):
bit = self.buffer.pop(0)
return bit
else:
return -1
def get_byte(self):
if self._load_byte():
byte_list = self.buffer[:8]
self.buffer = self.buffer[8:]
return "".join(byte_list)
else:
return -1
class HuffmanWriter:
def __init__(self, file):
self.file = file
self.buffer = ""
self.saved_bits = 0
def write_char(self, char):
self.write_int(ord(char))
def write_int(self, num):
bin_int = "{0:08b}".format(num)
self.write_bits(bin_int)
def write_bits(self, bits):
self.saved_bits += len(bits)
self.buffer += bits
while len(self.buffer) >= 8:
i = int(self.buffer[:8], 2)
self.file.write(bytes([i]))
self.buffer = self.buffer[8:]
def save_tree(self, tree):
"""
Generate and save tree code to file
:param tree:
:return:
"""
signs = []
tree_code = ""
def get_code_tree(T):
nonlocal tree_code
if T.sign is not None:
signs.append(T.sign)
if T.left:
tree_code += "0"
get_code_tree(T.left)
if T.right:
tree_code += "1"
get_code_tree(T.right)
get_code_tree(tree)
self.write_bits(
tree_code + "1"
) # "1" indicates that tree ended (it will be needed to load the tree)
for int_sign in signs:
self.write_int(int_sign)
def _save_information_about_additional_bits(self, additional_bits: int):
"""
Overwrite first three bits in the file
:param additional_bits: number of bits that were appended to fill last byte
:return:
"""
self.file.seek(0)
first_byte_raw = self.file.read(1)
self.file.seek(0)
first_byte = "{0:08b}".format(int.from_bytes(first_byte_raw, "big"))
# overwrite first three bits
first_byte = first_byte[3:]
first_byte = "{0:03b}".format(additional_bits) + first_byte
self.write_bits(first_byte)
def close(self):
additional_bits = 8 - len(self.buffer)
if additional_bits != 8: # buffer is empty, no need to append extra "0"
self.write_bits("0" * additional_bits)
self._save_information_about_additional_bits(additional_bits)
class TreeFinder:
"""
Class to help find signs in tree
"""
def __init__(self, tree):
self.root = tree
self.current_node = tree
self.found = None
def find(self, bit):
"""
Find sign in tree
:param bit:
:return: True if sign is found
"""
if bit == "0":
self.current_node = self.current_node.left
elif bit == "1":
self.current_node = self.current_node.right
else:
self._reset()
return True
if self.current_node.sign is not None:
self._reset(self.current_node.sign)
return True
else:
return False
def _reset(self, found=""):
self.found = found
self.current_node = self.root
class HuffmanCoding:
def __init__(self):
pass
@staticmethod
def decode_file(file_in_name, file_out_name):
with open(file_in_name, "rb") as file_in, open(file_out_name, "wb") as file_out:
reader = HuffmanReader(file_in)
additional_bits = reader.get_number_of_additional_bits_in_the_last_byte()
tree = reader.load_tree()
HuffmanCoding._decode_and_write_signs_to_file(
file_out, reader, tree, additional_bits
)
print("File decoded.")
@staticmethod
def _decode_and_write_signs_to_file(
file, reader: HuffmanReader, tree: Node, additional_bits: int
):
tree_finder = TreeFinder(tree)
is_end_of_file = False
while not is_end_of_file:
bit = reader.get_bit()
if bit != -1:
while not tree_finder.find(bit): # read whole code
bit = reader.get_bit(0)
file.write(bytes([tree_finder.found]))
else: # There is last byte in buffer to parse
is_end_of_file = True
last_byte = reader.buffer
last_byte = last_byte[
:-additional_bits
] # remove additional "0" used to fill byte
for bit in last_byte:
if tree_finder.find(bit):
file.write(bytes([tree_finder.found]))
@staticmethod
def encode_file(file_in_name, file_out_name):
with open(file_in_name, "rb") as file_in, open(
file_out_name, mode="wb+"
) as file_out:
signs_frequency = HuffmanCoding._get_char_frequency(file_in)
file_in.seek(0)
tree = HuffmanCoding._create_tree(signs_frequency)
codes = HuffmanCoding._generate_codes(tree)
writer = HuffmanWriter(file_out)
writer.write_bits(
"000"
) # leave space to save how many bits will be appended to fill the last byte
writer.save_tree(tree)
HuffmanCoding._encode_and_write_signs_to_file(file_in, writer, codes)
writer.close()
print("File encoded.")
@staticmethod
def _encode_and_write_signs_to_file(file, writer: HuffmanWriter, codes: dict):
sign = file.read(1)
while sign:
int_char = int.from_bytes(sign, "big")
writer.write_bits(codes[int_char])
sign = file.read(1)
@staticmethod
def _get_char_frequency(file) -> dict:
is_end_of_file = False
signs_frequency = defaultdict(lambda: 0)
while not is_end_of_file:
prev_pos = file.tell()
sign = file.read(1)
curr_pos = file.tell()
if prev_pos == curr_pos:
is_end_of_file = True
else:
signs_frequency[int.from_bytes(sign, "big")] += 1
return signs_frequency
@staticmethod
def _generate_codes(tree: Node) -> dict:
codes = dict()
HuffmanCoding._go_through_tree_and_create_codes(tree, "", codes)
return codes
@staticmethod
def _create_tree(signs_frequency: dict) -> Node:
nodes = [
Node(frequency=frequency, sign=char_int)
for char_int, frequency in signs_frequency.items()
]
heapq.heapify(nodes)
while len(nodes) > 1:
left = heapq.heappop(nodes)
right = heapq.heappop(nodes)
new_node = Node(
frequency=left.frequency + right.frequency, left=left, right=right
)
heapq.heappush(nodes, new_node)
return nodes[0] # root
@staticmethod
def _go_through_tree_and_create_codes(tree: Node, code: str, dict_codes: dict):
if tree.sign is not None:
dict_codes[tree.sign] = code
if tree.left:
HuffmanCoding._go_through_tree_and_create_codes(
tree.left, code + "0", dict_codes
)
if tree.right:
HuffmanCoding._go_through_tree_and_create_codes(
tree.right, code + "1", dict_codes
)
|
6411cdfba024801faafa4bac24ec899239bdc33d | seanlab3/algorithms | /UU_PRACTICE/19.strings/36.Strings_atbash_cipher.py | 273 | 3.796875 | 4 | """
Atbash cipher is mapping the alphabet to it's reverse.
So if we take "a" as it is the first letter, we change it to the last - z.
Example:
Attack at dawn --> Zggzxp zg wzdm
Complexity: O(n)
"""
from algorithms.strings import atbash
a="Attack at dawn"
print(atbash(a)) |
405d8bff96f7913ea605006fe8fbc372e0b313a7 | pavelpianov/python_learning | /AByteofPython/str_methods.py | 761 | 3.9375 | 4 | name = 'Swaroop' # Это объект строки
if name.startswith('Swa'):
print('Да, строка начинается на "Swa"')
if 'a' in name:
print('Да, она содержит строку "a"')
if name.find('war') != -1: #find используется для определения позиции данной подстроки в строке; find возвращает -1, если подстрока не обнаружена
print('Да, она содержит строку "war"')
delimiter = '_*_'
mylist = ['Бразилия', 'Россия', 'Индия', 'Китай']
print(delimiter.join(mylist))
print('||'.join(mylist)) # Второй вариант если указать разделить сразу в команде
|
f0b624a12554bd5d1b3fff77f84a79896cb96c1e | gyrkslevente/f0006 | /f0006d.py | 232 | 4 | 4 | hely=int(input("Hanyadik lettél?"))
if hely ==1:
print("Grat aranyérmes vagy:)")
elif hely ==2:
print ("Grat ezüstérmes vagy:)")
elif hely ==3:
print ("Grat bronzérmes vagy:)")
else:
print("Te nem is kaptál érmet:(")
|
781cd80732cecbfa8e83010226c0d788e4de77a8 | dylantho/pytho189 | /Module_13/gui_assignment_2nd_attempt.py | 3,040 | 3.859375 | 4 | """
Program: gui_assignment_2nd_attempt.py
Author: Dylan Thomas
Last date modified: 11/23/2020
"""
from tkinter import *
from random import randrange
class NumberGuesser:
# Constructor
def __init__(self, guessed_list=[]):
self.guessed_list = guessed_list
# Used to check if guesses were being added
def __str__(self):
return 'Guesses: ={}'.format(self.guessed_list)
# Add guess to list object
def add_guess(self, guess):
self.guessed_list.append(guess)
return self.guessed_list.__str__()
# Initialize game
game = Tk()
game.title("Guessing Game")
# Start button and main labels
startButton = Button(game, text="Start Game", command=lambda: start_game()).grid(row=0, column=0, columnspan=5)
instruction = Label(game, text="Guess a number from 0 to 9").grid(row=1, column=0, columnspan=5)
space = Label(game, text=" ").grid(row=3, column=0, columnspan=5)
space_bottom = Label(game, text=" ").grid(row=14, column=0, columnspan=5)
# Create the number buttons in disabled state
buttons = []
for number in range(0, 10):
button = Button(game, text=number, command=lambda number=number: check(number), state=DISABLED)
buttons.append(button)
# Add buttons to the game grid
for row in range(0, 2):
for col in range(0, 5):
i = row * 5 + col
buttons[i].grid(row=row+10, column=col)
# Global variables
guess = 0
answer = randrange(10)
newgame = NumberGuesser()
current_game = "none"
def start_game():
global current_game
# Make buttons clickable for use
for b in buttons:
b["state"] = NORMAL
if current_game == "none":
current_game = "In progress"
else:
current_game = "Reset"
# call restart function
restart_game()
print("New game started")
# Reset game variables, hide previous result text
def restart_game():
global buttons, guess, answer, newgame
newgame.guessed_list = []
answer = randrange(10)
guess = 0
hide_result = Label(game, text=" ").grid(row=13, column=0, columnspan=5)
# Check if the user guess correctly
def check(i):
# Allow use of buttons list and newgame object
global buttons, newgame
guess = i
# If user guessed correctly
if guess == answer:
answer_reaction_correct = Label(game, text=" Correct! You win! ", fg="green").grid(row=13, column=0, columnspan=5)
# If correct disable all buttons
for button in buttons:
button["state"] = DISABLED
# If wrong add to guessed list, tell user
else:
newgame.add_guess(guess)
answer_reaction_incorrect = Label(game, text="Incorrect. Try again!", fg="red").grid(row=13, column=0, columnspan=5)
# if wrong disable button
buttons[i]["state"] = DISABLED
game.mainloop()
|
7a67b68215262d35e5b1f3aa8e4226d23205f2ed | LizaShengelia/100-Days-of-Code--Python | /Day11.BlackJack.py | 2,364 | 4 | 4 | import random
from replit import clear
from art import logo
def deal_card():
"""return random car from deck."""
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10,10, 10, 10]
item = random.choice(cards)
return item
deal_card()
def calculate_score(cards):
""" Take a list of cards and calculates it """
if sum(cards) == 21 and len(cards) == 2:
return 0
if sum(cards) > 21 and 11 in cards:
cards.remove(11)
cards.append(1)
return sum(cards)
def play():
print(logo)
user_cards = []
computer_cards = []
is_game_over = False
for _ in range(2):
user_cards.append(deal_card())
computer_cards.append(deal_card())
while not is_game_over:
user_score = calculate_score(user_cards)
computer_score = calculate_score(computer_cards)
print(f"Your cards: {user_cards} {user_score}")
print(f"computer first card: {computer_cards[0]}")
if user_score == 0 or user_score > 21 or computer_score == 0:
is_game_over = True
else:
ask = input("Do you want another card? say 'y' or 'n' ")
if ask == 'y':
user_cards.append(deal_card())
else:
is_game_over = True
while computer_score < 17 and computer_score != 0:
computer_cards.append(deal_card())
computer_score = calculate_score(computer_cards)
#def calculate_score(l):
# total = 0
#for val in l:
# total = total + val
# return total
#print(calculate_score(user_cards))
def compare(user_score, computer_score):
if user_score == computer_score:
print("its a draw")
is_game_over = True
elif computer_score == 0:
print("you lost")
is_game_over = True
elif user_score == 0:
print("you won")
is_game_over = True
elif user_score > 21:
print("you lost")
is_game_over = True
elif computer_score > 21:
print("you won")
is_game_over = True
elif computer_score > user_score:
print("you lost")
is_game_over = True
elif user_score > computer_score:
print("you won")
is_game_over = True
print(f" your final hand: {user_cards}, Final score: {user_score}")
print(f" computer final hand: {computer_cards}, Final score: {computer_score}")
compare(user_score, computer_score)
while input("Do you want to play a game of Blackjack? Type 'y' or 'n': ") == "y":
clear()
play()
|
f3800c3cfa98b8cd343c21013128953317c2a4a7 | wesley-998/Python-Exercicies | /085_List-compos.py | 422 | 3.90625 | 4 | '''Programa que recebe 7 números que cadastra todos em uma única lista que mantenha separados os valores impares e pares.
No final mostre os valores impares e pares em ordem crescente.'''
lista = [[],[]]
n = 0
for n in range(0,7):
n = int(input('Digite o valor: '))
if n % 2 == 0:
lista[0].append(n)
else:
lista[1].append(n)
lista[0].sort()
lista[1].sort()
print(lista)
|
359e889bb16ae5487d307f46487a8e346da5154c | tristan-oa/Data-Structure-Programming-with-Python | /code/task_3.py | 6,743 | 4.34375 | 4 | # importing the module 'random' to be able to generate random numbers
import random
# A function which validates the input entered by the user such that the user is informed
# and requested to re-enter a value if characters are inputted instead of numbers.
# This function has no parameters passed to it but returns 3 integer values
def user_input():
# A counter variable is initialised to 1
i = 1
# A while loop which runs indefinitely
while True:
# Section of code which handles exceptions
try:
# This section of code runs again each time until correct input is entered by the
# user and accepted by the program thus increasing the value of i to 2
if i is 1:
x = int(input("\nEnter the max amount of integers in the list: "))
i += 1
continue
# This section of code runs again each time until correct input is entered by the
# user and accepted by the program thus increasing the value of i to 3
elif i is 2:
y = int(input("\nEnter the min value an integer present in the list can have: "))
i += 1
continue
# This section of code runs again each time until correct input is entered by the
# user and accepted by the program thus increasing the value of i to 4
elif i is 3:
z = int(input("\nEnter the max value an integer present in the list can have: "))
i += 1
continue
# The user is informed in this part that all inputs were correct and these
# values are then returned back
elif i is 4:
print("All inputs were successfully stored and the list is shown below:\n")
return x, y, z
# Informs the user if anything other than an integer is inputted
except ValueError:
print("Invalid input!")
# A function which based on the 3 parameters passed (size of list, min value in list and
# max value in list) which were previously entered by the user, generates a list of randoms
# These numbers are then stored to the 'arr' array passed as the 4th parameter
def generate_list(x, y, z, arr):
# A for loop which loops through each individual empty element in the array
# and populates it
for i in range(x):
# Generates a random number from y-z each time and stores it in the array
arr.append(random.randint(y, z))
# The main function for a quick sort which also calls the 'partition()' function.
# This is a recursive function taking 3 parameters which are the array to be sorted,
# the starting position and ending position for the sorting procedure.
# This function does not return anything.
def quick_sort(array, start, end):
# Statement runs if the end of the list is not yet reached
if start < end:
# The value returned from the sub-function being called is stored in
# the placeholder split
split = partition(array, start, end)
# The recursive part of the function which proceeds to sorting 2 smaller
# sections of the list separated by the split variable
quick_sort(array, start, split-1)
quick_sort(array, split+1, end)
# The sub-function of the quick sort which switches different numbers in the
# list to be sorted based on the pin. This takes 3 parameters:
# the array to be sorted, the starting and ending point.
# This function returns the value stored in i which determines the split
# for the next iteration
def partition(array, start, end):
# Sets the pin to be the one approximately in the middle of the list
pinPosition = (start + end) // 2
pinValue = array[pinPosition]
# Swaps the pin with the last element in the list
array[pinPosition], array[end] = array[end], array[pinPosition]
# Sets the counter i to 1 less than the first position of the list
i = start - 1
# Loops through the list from start to end excluding the pin
for j in range(start, end):
# If the pin is greater than an element being compared, the
# counter variable i is incremented and the values stored in
# positions i and j are swapped
if array[j] <= pinValue:
i += 1
array[j], array[i] = array[i], array[j]
# i is incremented
i += 1
# The pin is now swapped back in it's appropriate position in the list
array[i], array[end] = array[end], array[i]
# The counter value i is returned
return i
# A function which finds the extreme points in an array
# It has 2 parameters passed to it (the array whose extreme points are to be found
# and the size of the array passed) but returns nothing back
def extreme(arr, x):
# An empty list to store the extreme points is created
points = []
# The statement which loops through all the possible extreme points
# (from the second to the element before the last) and adds any extreme
# points found to the newly created array
for i in range(1, x-1):
if (arr[i-1] < arr[i] > arr[i+1]) or (arr[i-1] > arr[i] < arr[i+1]):
points.append(arr[i])
# This statement checks if any extreme points have been found
# If none are found, the user is informed that the list is sorted
# If not, the extreme points found are printed out to the user
if len(points) == 0:
print("\nSORTED")
print("This array had no extreme points")
else:
print("\nThe extreme points are: ")
print(points)
# An empty array to be randomly populated is created
arrayA = []
print("This program will print the extreme points of a given array.")
# The input entered by the user for the size, min and max values of the list
# are validated in the user_input() function. These are then
# returned and stored in the variables a, b & c respectively
a, b, c = user_input()
# The function generate_list() is then called and the placeholders a, b, c are
# passed as parameters to this function
generate_list(a, b, c, arrayA)
# The generated list is displayed to the user
print("ARRAY:", arrayA)
# The extreme() function is called with the 'arrayA' list passed as the first
# parameter and its size as the second parameter
extreme(arrayA, a)
# The quick_sort() function is called which sorts the list to show that a
# sorted list has no extreme points
# This has the 'arrayA' list passed as the 1st parameter, 0 as the 2nd and
# the length of the array - 1 as the 3rd
quick_sort(arrayA, 0, a-1)
print("\nSorted Array: ", arrayA)
# The extreme() method is called once again to prove that a sorted list
# contains no extreme points
extreme(arrayA, a)
|
7df484fbf66ff8a449aa1c37351a4bc3973e3c29 | zirui-HIT/HIT_Lab | /Compile_System/Lab2/src/syntactic_analyzer.py | 4,756 | 3.515625 | 4 | from typing import Dict, List
class Word(object):
def __init__(self, word: str, kind: str, line: int):
self.__word = word
self.__kind = kind
self.__line = line
def word(self):
return self.__word
def kind(self):
return self.__kind
def line(self):
return self.__line
def __eq__(self, other):
if not isinstance(other, Word):
return False
if self.__kind != other.kind():
return False
if self.__word != other.word():
return False
return True
def __hash__(self):
return hash(self.__word + self.__kind)
def load_table(path: str) -> Dict[int, Dict[str, str]]:
ret = {}
with open(path, 'r') as f:
for line in f:
current = line.split()
state = int(current[0])
if not state in ret:
ret[state] = {}
ret[state][current[1]] = current[2]
return ret
def load_words(path: str) -> List[Word]:
'''加载词法分析结果
Args:
path: 加载路径
Returns:
格式为[{'class': ..., 'value': ...}, ...]
'''
ret = []
with open(path, 'r') as f:
for line in f:
if len(line.strip()) == 0:
continue
if line.strip() == 'lexical analyse finished':
break
current = line.split()[1:]
current[0] = current[0][1:-1]
current[1] = current[1][:-1]
ret.append(Word(current[1], current[0], int(current[2])))
ret.append(Word('_', '$', -1))
return ret
def analyse(words: List[Word], action: Dict[int, Dict[str, str]],
goto: Dict[int, Dict[str, str]]):
'''根据action和goto表构造语法分析树
采用恐慌模式处理语法错误
Args:
words: 词法分析结果,格式为value (class, value)
action: action表
goto: goto表
Returns:
语法分析树,格式为[{'word': ..., 'child': [id1, id2, ...], 'id': ...}]
其中id为节点在返回列表中的角标
'''
stack = [{'state': 0, 'id': -1}]
ret = []
roots = []
error = []
i = 0
while i < len(words):
current_action = action[stack[-1]['state']][words[i].kind()]
if current_action.startswith('s'):
next_state = int(current_action[1:])
stack.append({'state': next_state, 'id': len(ret)})
roots.append(len(ret))
ret.append({'word': words[i], 'child': [], 'id': len(ret)})
i += 1
elif current_action[0].isupper():
current_action = current_action.split('-')
current_grammar_length = int(current_action[1])
current_node = {
'word':
Word('_', current_action[0],
ret[stack[-current_grammar_length]['id']]['word'].line()),
'child': [],
'id':
len(ret)
}
roots.append(len(ret))
for j in range(current_grammar_length):
current_node['child'].append(stack[-1]['id'])
roots.remove(stack[-1]['id'])
stack.pop()
current_node['child'].reverse()
next_state = int(goto[stack[-1]['state']][current_action[0]])
stack.append({'state': next_state, 'id': len(ret)})
ret.append(current_node)
elif current_action == 'acc':
print('analyse finished')
return ret, roots, error
else:
error.append('Syntax error at Line [%d]: illegal %s' %
(words[i].line(), words[i].kind()))
i += 1
continue
raise Exception('syntactic analyze error')
def DFS(tree: List[Dict], current: int, depth: int, f):
'''遍历输出语法树
'''
sentence = '\t' * depth + tree[current]['word'].kind()
if tree[current]['word'].word() != '_':
sentence = sentence + ' : ' + tree[current]['word'].word()
sentence = sentence + ' (' + str(tree[current]['word'].line()) + ')'
f.write(sentence + '\n')
for c in tree[current]['child']:
DFS(tree, c, depth + 1, f)
if __name__ == '__main__':
action = load_table('Compile_System/Lab2/data/table/action.txt')
goto = load_table('Compile_System/Lab2/data/table/goto.txt')
words = load_words('Compile_System/Lab1/data/result.txt')
tree, root, error = analyse(words, action, goto)
with open('Compile_System/Lab2/data/result.txt', 'w') as f:
for r in root:
DFS(tree, r, 0, f)
with open('Compile_System/Lab2/data/error.log', 'w') as f:
for e in error:
f.write(e + '\n')
|
c14a6991e2fd303d7cbf2951245387e2067d5857 | lemuelkbj/python_basics | /list_the_even_number.py | 557 | 4.34375 | 4 | # lists the even numbers
def show_even(my_list):
for numbers in my_list: # iterate through the list
if int(numbers) % 2 == 0: # select the numbers which are even
print("\n", numbers, end=" ") # print it
# Also if you want the numbers as a list just append it to an empty list
# create an empty list
mylist1 = []
for i in range(0, int(input("Enter the range :"))):
mylist1.append(input("Enter the input : "))
# print the list
print(mylist1)
# direct the lists to the function
show_even(mylist1)
|
819ce5d1816486d096f1c44e781f427210e244af | omaspelikan/phpwebserver | /codechef/jonnyandbeanstalk.py | 864 | 3.859375 | 4 | #python Johnny and the Beanstalk
test_time = int(input("How many bean will you plant? "))
while test_time > 0 and test_time <=20:
rule = True
level_beanstalk = int(input("How many level will your beanstalk grow? "))
leaf = input("How many leaf will each level have? ")
leaf = leaf.split()
sum = 1
level_index = 1
# y = 0
if level_beanstalk > 0 and level_beanstalk <= 10**6:
for x in leaf:
if sum == 1 and int(x) == 0:
rule == True
elif sum == 2 and int(x) == 1:
rule = True
elif int(x) > 2**(sum-2):
rule = False
print('it false')
sum = sum +1
if rule == True:
print("Yes")
else:
print("No")
else:
print("exceed limit level")
test_time = test_time -1
|
a730167b05bd910b0ca4cbd14a862734145f3c33 | lib-hfut/lib-hfut | /Python玩转大数据_9900066X/Python玩转大数据资料 宣善立(2019)/Python课堂演示文档/统计小说字频率.py | 457 | 4.03125 | 4 | #分析小说中汉字出现率最多的前20个
fname=input("请输入文件名:")
f1=open(fname,'r',encoding="utf-8").read()
for ch in ' ,。“‘’”:!、《》;? 」「…":':
f1=f1.replace(ch,"")
f1=f1.replace("\n","")
words={}
for w in f1:
words[w]=words.get(w,0)+1
its=list(words.items())
its.sort(key=lambda x:x[1],reverse=True)
for i in range(10):
word,count=its[i]
print("{0:<10}{1:>5}".format(word,count))
|
0b128c4ce4f9b4057d8c0e040973787410e7e737 | krishmadutta/Python-Stuff | /FileOperations.py | 1,035 | 3.6875 | 4 | def enter_text_file(performances):
file = open("schedule.txt", 'a')
for show,time in performances.items():
file.write(show + ' ' + time + '\n')
#print("Writing to the file")
file.close()
def read_text_file():
file = open("schedule.txt",'r')
for data in file:
print(data)
#print ("Reading"+data)
file.close()
def read_log_file():
file = open("apache.txt", 'r')
for data in file:
print(data.split()[0] + ' ' + data.split()[5]+data.split()[6])
file.close()
def read_comma_separated():
file = open("commas", 'r')
for data in file:
print(data.strip().split(','))
file.close()
def read_log_fixed_length():
width = [0,12]
file = open("apache.txt", 'r')
for data in file:
print(data[:12] + " ** " + data[18:39] )
#Reverse String str[::-1]
def main():
#performances = {'Night at the Museum': '10:00 PM', 'Yanky Doodle': '11:00 AM'}
#enter_text_file(performances)
#read_text_file()
#read_log_file()
#read_log_fixed_length()
read_comma_separated()
main()
|
41c6d169f2040730dd471ea95d0b89978ab20873 | alisen39/algorithm | /algorithms/sword_offer/27_mirrorTree.py | 912 | 3.71875 | 4 | #!/usr/bin/env python
# encoding: utf-8
# author: Alisen
# time: 2022/6/13 21:35
# desc:
""" 剑指 Offer 27. 二叉树的镜像
https://leetcode.cn/problems/er-cha-shu-de-jing-xiang-lcof/
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def mirrorTree(self, root: TreeNode) -> TreeNode:
if not root:
return root
root.left, root.right = root.right, root.left
self.mirrorTree(root.left)
self.mirrorTree(root.right)
return root
if __name__ == '__main__':
ta = TreeNode(3)
ta_4 = TreeNode(4)
ta_5 = TreeNode(5)
ta_1 = TreeNode(1)
ta_2 = TreeNode(2)
ta.left = ta_4
ta.right = ta_5
ta_4.left = ta_1
ta_4.right = ta_2
tb = TreeNode(4)
tb_1 = TreeNode(1)
tb.left = tb_1
res = Solution().mirrorTree(ta)
print(res)
|
f2b37448c71e0cf5af3938aec599c742e9e7162c | nidhi06/Algorithm-Design-Projects-and-Assignments | /2591_prj1_fib_part2.py | 709 | 4.28125 | 4 | import time
def fibonacci(num):
if num == 0:
return 0
elif num == 1:
return 1
else:
return fibonacci(num-1)+fibonacci(num-2)
def time_taken():
my_num=int(input("Enter the number: "))
start=time.time()
print(fibonacci(my_num))
end=time.time()
print(end-start)
"""
The The largest number that the recursive algorithm (Algorithm 1.6)
can accept as its argument and compute the answer within 60 seconds: 39 (55.26 seconds),
40th element takes 91.60 seconds
----------------------------------------------------------------------
The time the iterative algorithm (Algorithm 1.7)
takes to compute this answer(39th element): 1.120 seconds
""" |
f3ab1e124451f6127e4f846a10b4233bb68af666 | RadkaSindelarova/learntocode | /session3/exercise14.py | 748 | 3.96875 | 4 | def merge(xs, ys):
# return a sorted list with the merged contents of the sorted lists xs and ys
def merge_sort(xs):
# sort xs
def test(test_case_xs, expected):
actual = merge_sort(test_case_xs)
if actual == expected:
print("Passed test for " + str(test_case_xs))
else:
print("Didn't pass test for " + str(test_case_xs))
print("The result was " + str(actual) + " but it should have been " + str(expected))
test([], [])
test([0], [0])
test([1, 2], [1, 2])
test([2, 1], [1, 2])
test([4, 3, 2, 1], [1, 2, 3, 4])
test([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8])
test([8, 7, 6, 5, 4, 3, 2, 1], [1, 2, 3, 4, 5, 6, 7, 8])
test([8, 7, 6, 5, 4, 3, 2, 1, 10, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) |
531c3b090b326223916f205c858c890bb5e26b51 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/222/users/4085/codes/1684_1099.py | 683 | 3.875 | 4 | # Teste seu código aos poucos. Não teste tudo no final, pois fica mais difícil de identificar erros.
# Ao testar sua solução, não se limite ao caso de exemplo. Teste as diversas possibilidades de saída
a = float(input("escreva o valor do lado1: "))
b = float(input("escreva o valor do lado2: "))
c = float(input("escreva o valor do lado3: "))
print ("Entradas:", a, "," ,b, ",", c)
if ((a >= b + c) or (b >= a + c) or (c >= a + b)):
print ("Tipo de triangulo: invalido")
elif ((a == b) and (b == c)):
print ("Tipo de triangulo: equilatero")
elif ((a == b) or (a == c) or (b == c)):
print ("Tipo de triangulo: isosceles")
else:
print ("Tipo de triangulo: escaleno") |
a5824dc48ead5c122a1f08a1f51cd66cdfd2a439 | SocialRecord/TX_Covid_Vulnerability | /jada/jada_clean.py | 1,169 | 3.703125 | 4 | import pandas as pd
def acquire_income_data():
'''
This function cleans the Income csv housed in the Data file of the repository
and returns a dataframe ready to be joined on
'''
# Read in csv
df = pd.read_csv('../Data/Income.csv')
# Create a boolean mask where only observations where TX is the state are counted as true
# Then apply the mask to the whole dataframe
mask = df['State'] == 'TX'
df = df[mask]
# Drop columns we don't need
df = df.drop(
columns = ['PerCapitaInc',
'PovertyUnder18Pct',
'PovertyAllAgesPct',
'Deep_Pov_Children',
'State',
'County'])
return df
def acquire_food_data():
'''
Clean and prepare the Food1 excel file and
return it as a dataframe ready to be joined on
'''
# Pull in only the columns I want
file_loc = "../Data/Food1.xlsx"
df = pd.read_excel(file_loc, index_col=None, na_values=['NA'], usecols = "A,B,E")
# Restrict df to Texas only
mask = df['State'] == 'TX'
df = df[mask]
# Drop the state column
df = df.drop(columns = 'State')
return df
def merge_dfs():
|
ae30753c43e7878c9d18f2cdb2902c7b52be845c | JackParryQA/Python-exercises | /easy/times-tables.py | 171 | 3.71875 | 4 | def times_table(num):
for i in range(1,(num+1)):
print(i)
for j in range(2, (num+1)):
print(i*j)
print(" ")
times_table(5)
|
dd17ab10c83537ef5df377d332546aed71c4730a | IamBikramPurkait/100DaysOfAlgo | /Day 5/ChainMatrixMultiplication.py | 1,424 | 4.09375 | 4 | '''Matrix Chain Multiplication using dynamic Programming - Determine the optimal parenthesization of product of n matrices
Problem : Given a series of n arrays to multiply A1*A2*A3*......*An.Determine where to place parenthesis to minimize the number of multiplications
Key Fact : Multipliying an i*j matrix by j*k matrix requires i*j*k operations'''
import sys
def matrixChainOrderMuliplication(p, i, j): #i is starting index of array/list and j is the ending index
# Base case when only one matrix is there
if i==j:
return 0
_min = sys.maxsize #An integer giving the maximum size a variable of type Py_ssize_t can take
for k in range(i , j):
# Recursively place parenthesis at different position between first and last position and calculate count of multiplications for each placement
count = (matrixChainOrderMuliplication(p, i, k) + matrixChainOrderMuliplication(p, k+1, j) +
p[i-1] * p[k] * p[j])
if count <_min:
_min = count
return _min
# Function for printing the result
def printResult(val):
print('Minimum number of multiplications required are : ' + str(val))
# Sample inputs and driver code
array = [40, 20, 30, 10, 30]
n = len(array)
res = matrixChainOrderMuliplication(array, 1, n-1)
printResult(res)
array2 = [1,4,5,6,7,8,9]
n2 = len(array2)
res2 = matrixChainOrderMuliplication(array2, 1, n2-1)
printResult(res2)
|
9012b2a2ff8cb462aeb022db66fcc0cb46ee2571 | tigiridon/python | /algorithms_and_data_structures/HW3/task_4.py | 653 | 3.5 | 4 | # Задание №4
# Определить, какое число в массиве встречается чаще всего.
import random
SIZE = 10
MIN_ITEM = 0
array = [random.randint(MIN_ITEM, SIZE // 1.5) for _ in range(SIZE)]
SIZE = len(array)
print(array)
num = array[0]
frequency = 1
for i in range(SIZE):
spam = 1
for j in range(i + 1, SIZE):
if array[i] == array[j]:
spam += 1
if spam > frequency:
frequency = spam
num = array[i]
if frequency > 1:
print(f'Число {num} встречается {frequency} раз(а)')
else:
print('Все элементы уникальны')
|
61d847a5bc869447834cc4f2c83b89d2b8959c30 | eavpsp/pythonDocs | /LoopPrint.py | 662 | 3.859375 | 4 | """
Psuedo Loop Trace
Program Info
Elisha Victor
CSC 119 - 005
Psuedo Loop Printer
10/17/2018
follow the trace, print it out
Version: Uno
"""
def main(): #definition of main program
#Data to solve problem
#Variables
#Constants
#Design Solution
print("Trace Print C")
for i in range(10,1, -1) :
print(i, end=",")
print("Trace Print D")
for p in range(10) :
print(p, end=",")
print("Trace Print E")
for q in range(1,10) :
if q % 2 == 0:
print(q, end=",")
#Process
#Output
main() # execution of main program
|
7f429d8c5d4677fc423437b0e47f0a3141125b83 | sixthkrum/IMDB-sentiment-analysis | /homebrewStopwords.py | 923 | 3.765625 | 4 | from nltk.corpus import stopwords
from sklearn.feature_extraction._stop_words import ENGLISH_STOP_WORDS
stopwords = set(stopwords.words('english')).union(set(ENGLISH_STOP_WORDS))
#words to remove from stopwords
removedWords = set([
"wouldn't", 'hasn', "doesn't", 'weren', 'wasn',
"weren't", 'didn', 'mightn', "couldn't",
"that'll", "didn't", "haven't", 'needn',
"shouldn't", 'haven', "isn't", 'couldn', "it's",
'not', 'aren', 'isn', 'doesn', "wasn't",
'mustn', "should've", "shan't", "you'll", 'wouldn',
"aren't", "won't", 'hadn', 'shouldn', "needn't",
"hasn't", "mustn't", "hadn't", "mightn't", "you'd", "don't",
"wouldnt", "doesnt", "werent", "couldnt",
"thatll", "didnt", "youve", "havent",
"shouldnt", "isnt", "its", "wasnt",
"shouldve", "shant", "arent", "wont", "neednt",
"hasnt", "mustnt", "hadnt", "mightnt", "dont"
])
stopwords = stopwords - removedWords
|
536e489b7e6eb6058e8c1a50527b6d3581f7d7b0 | Dylamn/macgyver-maze | /src/interfaces.py | 2,406 | 3.71875 | 4 | import pygame.sprite as sprite
from abc import ABCMeta, abstractmethod
class ICollectableItem(metaclass=ABCMeta):
"""The interface which define a collectable item."""
@classmethod
def __subclasshook__(cls, subclass):
return (
hasattr(subclass, 'collect')
and callable(subclass.collect)
or NotImplemented
)
# The name of the item.
name = None
# Image that represents the object.
_image_file = None
@property
@abstractmethod
def item_file(self) -> str:
"""The file (name) used for the visual representation of the item."""
return self._image_file
@abstractmethod
def collect(self, inventory: sprite.Group) -> None:
"""Collect an item and add it to the given inventory."""
raise NotImplementedError
class ICraftableItem(metaclass=ABCMeta):
"""The interface which define a craftable item."""
@classmethod
def __subclasshook__(cls, subclass):
return (
hasattr(subclass, 'items_required')
and hasattr(subclass, 'can_be_crafted')
and callable(subclass.can_be_crafted)
and hasattr(subclass, 'craft') and callable(subclass.craft)
and hasattr(subclass, 'missing_items')
and callable(subclass.missing_items)
or NotImplemented
)
# The name of the item.
name = None
# Image that represents the object.
_image_file = None
# Determines if the item can be crafted
craftable = False
# The list of items needed for the craft of this item.
items_required = []
@property
@abstractmethod
def item_file(self) -> str:
"""The file (name) used for the visual representation of the item."""
raise self._image_file
@classmethod
@abstractmethod
def can_be_crafted(cls, inventory: sprite.Group) -> bool:
"""Determine if the item can be crafted with the given inventory."""
raise NotImplementedError
@classmethod
@abstractmethod
def craft(cls, inventory: sprite.Group) -> bool:
"""Craft the item and destroy required items for craft."""
raise NotImplementedError
@classmethod
@abstractmethod
def missing_items(cls, inventory: sprite.Group) -> list:
"""Determine which items are missing for the craft."""
raise NotImplementedError
|
54ccba9c3fa5a8e39af76325de6dfc7a34b7bce2 | Thirumurugan-12/Python-programs-11th | /#Write a program to input the total seconds and convert it into hours ,minutes.py | 300 | 4.34375 | 4 | #Write a program to input the total seconds and convert it into hours ,minutes
#,seconds.
def conversion():
sec1=int(input("Enter the time(in seconds)"))
hrs=sec1//3600
rem=sec1%3600
min=rem//60
sec=rem%60
print("hrs:min:sec",hrs,":",min,":",sec)
conversion()
|
622ac1765dffc89d13bb6683b0483579d279786d | IlosvayAron/script-languages | /Lesson4/homework/teacher-s_solutions/hangrend.py | 1,090 | 3.671875 | 4 | #!/usr/bin/env python3
MELY, MAGAS, VEGYES, SEMMILYEN = range(1,5)
MELY_MGHK = 'aáoóuú'
MAGAS_MGHK = 'eéiíöőüű'
def hangrend(szo):
magas = 0
mely = 0
for s in szo:
if s in MELY_MGHK:
mely += 1
if s in MAGAS_MGHK:
magas += 1
if magas != 0 and mely != 0:
return VEGYES
elif magas != 0 and mely == 0:
return MAGAS
elif magas == 0 and mely != 0:
return MELY
else:
return SEMMILYEN
def main():
words = ["ablak", "erkély", "kisvasút", "magas", "mély", "Pfffffff"]
for word in words:
hr = hangrend(word)
if hr == MELY:
print("{w} -> mély hangrendű".format(w = word))
elif hr == MAGAS:
print("{w} -> magas hangrendű".format(w = word))
elif hr == VEGYES:
print("{w} -> vegyes hangrendű".format(w = word))
else:
print("{w} -> semmilyen hangrendű".format(w = word))
##############################################################################
if __name__ == "__main__":
main() |
a06e3794211e4e0b89425a13c1f2fadfbd5382a0 | manusarath57/set1 | /prog3.py | 133 | 4.0625 | 4 | a =(input("Enter a character: "))
if a=='a'or a=='e' or a=='i' or a=='o'or a=='u':
print("vowel")
else:
print("consonent")
|
af04165b73091003a82ef39d38ede12a7c35164f | chandan114/Programming_Questions | /CodeChef July 2020/codechef August 1.py | 322 | 3.671875 | 4 | for _ in range(int(input())):
Health , power = map(int , input().split())
strike = power
val = power
while(True):
if( power <= 0 ):
break
strike += power//2
power = power//2
if(strike>=Health):
print(1)
else:
print(0) |
bd783f2bbff327f2ff6bd146ea08361cdf0d0e2a | Mownicaraja/python-programs | /factorial.py | 114 | 3.625 | 4 | no=int(input())
f=1
if no==0:
print("1")
else:
for i in range(1,no+1):
f=f*i
print(f)
|
0b797aadd83c53f6435035b12c123b4ffeb97974 | KevinMichaelCamp/Python-HardWay | /Algorithms/Chapter1_Fundamentals1/Page16/15_The_Final_Countdown.py | 771 | 3.984375 | 4 | # This is based on "Flexible Countdown". The parameter names are not
# as helpful, but the problem is essentially identical. Given 4
# parameters (param1, param2, param3, param4), print the multiples
# of param1, starting at param2 and extending to param3. One exeption:
# if a multiple is equal to param4, then skip (don't print) that one.
# Do this using a WHILE loop. Given (3,5,17,9) print 6,12,15 (which
# are all the multiples of 3 between 5 and 17, except for the value 9.
def finalCountdown(param1, param2, param3, param4):
i = param2
while i <= param3:
if i == param4:
i += 1
continue
elif i % param1 == 0:
print(i)
i += 1
# Test Cases
finalCountdown(3,5,17,9)
finalCountdown(7,0,100,77)
|
7a5bf3fbed35c48b9e31afe0e77fabf93b6009c3 | carlitomm/python_prog_course | /practica4.py | 947 | 3.953125 | 4 | try:
money = float(input("ingrese la cantidad de dinero depostado ")) #dinero depositado
if money < 0:
raise TypeError
#se calcula la taza de interes suponeindo interes compuesto
frtYearSaves = (money + (money*6.25/100))
sndYearSaves = (frtYearSaves + (frtYearSaves * 6.25/100)) #suponiendo que es interes compuesto
trdYearSaves = (sndYearSaves + (sndYearSaves * 6.25/100)) #suponiendo que es interes compuesto
print("con una cantidad inicial de: " + str(round(money,3)))
print("se tienen ahorros de:")
print(str(round(frtYearSaves,3)) + " pesos en el primer año")
print(str(round(sndYearSaves,3)) + " pesos en el segundo año")
print(str(round(trdYearSaves,3)) + " pesos en el tercer año ")
print("durante los proximos 3 años\n")
except: #ya sea una entrada de datos negativo como un caracter se maneja el mismo error
print("-------ERROR, entrada incorrecta de datos--------")
|
b31b75a07554977b744dce7fe7236691c4ebae05 | liujiamingustc/phd | /surrogate/crossover/cxTwoPoint.py | 1,708 | 3.578125 | 4 | # Copyright 2016 Quan Pan
#
# 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.
#
# Author: Quan Pan <quanpan302@hotmail.com>
# License: Apache License, Version 2.0
# Create: 2016-12-02
import random
def cxTwoPoint(var1, var2):
"""Executes a two-point crossover on the input :term:`sequence`
individuals. The two individuals are modified in place and both keep
their original length.
:param var1: The first variable participating in the crossover.
:param var2: The second variable participating in the crossover.
:returns: A tuple of two variables.
This function uses the :func:`~random.randint` function from the Python
base :mod:`random` module.
"""
size = min(len(var1), len(var2))
# size = min(var1.size, var2.size)
cxpoint1 = random.randint(1, size)
cxpoint2 = random.randint(1, size - 1)
if cxpoint2 >= cxpoint1:
cxpoint2 += 1
else: # Swap the two cx points
cxpoint1, cxpoint2 = cxpoint2, cxpoint1
var1[cxpoint1:cxpoint2], var2[cxpoint1:cxpoint2] = var2[cxpoint1:cxpoint2], var1[cxpoint1:cxpoint2]
# var1[cxpoint1:cxpoint2], var2[cxpoint1:cxpoint2] = var2[cxpoint1:cxpoint2].copy(), var1[cxpoint1:cxpoint2].copy()
return var1, var2
|
e25c8885f1b4a92717bcc6175f99b9217b5cc0b9 | ravindrasinghinbox/learn-python | /machine-learning-w3schools-v2/linear_regressuib.py | 1,403 | 4.28125 | 4 | import matplotlib.pyplot as plt
from scipy import stats
# x = [5,7,8,7,2,17,2,9,4,11,12,9,6]
# y = [99,86,87,88,81,86,82,87,94,78,77,85,86]
'''
Linear regression uses the relationship between the data-points to draw a straight line through all them.
This line can be used to predict future values.
In the example below, the x-axis represents age, and the y-axis represents speed. We have registered the age and speed of 13 cars as they were passing a tollbooth. Let us see if the data we collected could be used in a linear regression:
R-Squared
It is important to know how well the relationship between the values of the x-axis and the values of the y-axis is, if there are no relationship the linear regression can not be used to predict anything.
The relationship is measured with a value called the r-squared.
The r-squared value ranges from 0 to 1, where 0 means no relationship, and 1 means 100% related.
Python and the Scipy module will computed this value for you, all you have to do is feed it with the x and y values:
'''
x = [1,2,3,4,5]
y = [10,20,30,40,50]
# x = [1,2,3,4,5,6,7,8,9,10]
# y = [2,4,8,16,32,64,128,256,512,1024]
slope, intercept, r, p, std_err = stats.linregress(x, y)
print(slope, intercept, r, p, std_err)
def myfunc(x):
return slope * x + intercept
mymodel = list(map(myfunc, x))
plt.scatter(x, y)
plt.plot(x, mymodel)
speed = myfunc(6)
print(speed)
plt.show() |
95e9716d7143ffae4b9d13d207a06b639fc67faf | Harini-Pavithra/GFG-11-Week-DSA-Workshop | /Week 1/Problem/Mathematics/Absolute Value.py | 1,137 | 4.5625 | 5 | Absolute Value
You are given an interger I, find the absolute value of the interger I.
Example 1:
Input:
I = -32
Output: 32
Explanation:
The absolute value of -32 is 32.
Example 2:
Input:
I = 45
Output: 45
Explanation:
The absolute value of 45 is 45 itself.
Your Task:
You don't need to read input or print anything. Your task is to complete the function absolute() which takes an integer I as input parameter and return the absolute value of I.
Expected Time Complexity: O(1)
Expected Auxiliary Space : O(1)
Constraints:
-106 <= I <= 106
Solution:
#{
#Driver Code Starts
# Initial Template for Python 3
# } Driver Code Ends
# User function Template for python3
import math
def absolute(I):
m=abs(I)
return m
# code here
#{
#Driver Code Starts.
def main():
T = int(input()) #Input the number of testcases
while(T > 0):
I = int(input()) #input number
print(absolute(I)) #Call function and print
T -= 1 #Reduce number of testcases
if __name__ == "__main__":
main()
#} Driver Code Ends |
f4b47c0377bd17b5341906a7038991bc71b665e9 | LizaSantanaC/JuegoAhorcado-Python | /juego_ahorcado.py | 3,287 | 3.71875 | 4 | from random import random, choice
from oportunidades import Oportunidades
class JuegoAhoracado:
oportunidades = Oportunidades()
_letras_disponibles = "abcdefghijklmnopqrstuvwxyz"
def inicio_ahorcado(self, palabra):
palabra = palabra.lower()
print("********************************")
print("Estoy pensado en una palabra de {} letras".format(len(palabra)))
print("")
letras_ingresadas = []
while self.oportunidades.oportunidades > 0:
print("-------------------------------------------------")
print("Te quedan {} oportunidades para adivinar.".format(self.oportunidades.oportunidades))
print("Letras disponibles: "+ self.obtener_letras_disponibles(letras_ingresadas))
letra_ingresada = self.pedir_letra(letras_ingresadas)
letras_ingresadas.append(letra_ingresada)
if letra_ingresada not in palabra:
self.oportunidades.reducir_oportunidades()
print("¡Bien hecho!")
else:
print("Oops! Esa letra no está en la palabra secreta")
print("PALABRA SECRETA: "+self.obtener_palabra_adivinada(palabra,letras_ingresadas) + "\n")
if self.se_adivino_palabra(palabra,letras_ingresadas):
print("**************************************************")
print("** FELICIDADES HAS ADIVINADO LA PALABRA SECRETA **")
print("**************************************************")
return
if self.oportunidades.oportunidades == 0:
print("**********GAME OVER***************")
print("La palabra secreta era: "+palabra.upper())
print("Suerte para la proxima")
def elegir_palabra(self,listaPalabras):
return choice(listaPalabras)
def se_adivino_palabra(self, palabra_secreta,letras_ingresadas):
num_letras = 0
for letra in palabra_secreta:
if letra in letras_ingresadas:
num_letras = num_letras + 1
return len(palabra_secreta) == num_letras
def obtener_palabra_adivinada(self,palabra_secreta,letras_ingresadas):
palabra_guiones = ""
for caracter in palabra_secreta:
if caracter in letras_ingresadas:
palabra_guiones = palabra_guiones + " " +caracter
else:
palabra_guiones = palabra_guiones + " _ "
return palabra_guiones.upper()
def obtener_letras_disponibles(self,letras_ingresadas):
if len(letras_ingresadas) == 0:
return self._letras_disponibles
letras = self._letras_disponibles
for letra in letras_ingresadas:
letras = letras.replace(letra, " _ ")
return letras
def pedir_letra(self,algunaLetra):
while True:
letra = input("Por favor ingresa una letra: ")
letra = letra.lower()
if len(letra) != 1:
print('Introduce una sola letra.')
elif letra in algunaLetra:
print('Ya has elegido esa letra, elige otra.')
elif letra not in 'abcdefghijklmnopqrstuvwxyz':
print('Elije una letra.')
else:
return letra |
303eb02f34ea7fd1171936fcb2b6e196bc80eb85 | rishabhusc/Python-leetcode | /mergerInterval.py | 206 | 3.578125 | 4 | arr=[[1,3],[2,6],[8,10],[15,18]]
arr.sort()
merger=[]
for i in arr:
if not merger or merger[-1][-1]<i[0]:
merger.append(i)
else:
merger[-1][-1]=max(merger[-1][-1],i[0])
print(merger) |
899a6da7831d1fce12aead0a03ccb5a846f8020b | CheungZeeCn/bigDataHomeWork | /Assignment1/dCount.py | 889 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# by zhangzhi @2013-10-11 22:06:40
# Copyright 2013 NONE rights reserved.
import math
def count(aList, d=2):
N = 0
SUM = [0] * d
SUMSQ = [0] * d
for each in aList:
N += 1
for i in range(d):
SUM[i] += each[i]
SUMSQ[i] += each[i] ** 2
return N, SUM, SUMSQ
def countVD(N, SUM, SUMSQ):
VD = []
N *= 1.0
for i in range(len(SUM)):
Vi = SUMSQ[i]/N - (SUM[i]/N)**2
Di = math.sqrt(Vi)
VD.append((Vi, Di))
return VD
if __name__ == '__main__':
a = ([(4, 10), (7, 10), (4, 8), (6, 8)], \
[(3, 4), (2, 2), (5, 2)], \
[(9, 3), (10, 5), (12, 6), (11, 4), (12, 3)], \
)
for each in a:
print "======="
ret = count(each)
print ret
print countVD(ret[0], ret[1], ret[2])
|
a2460047f93eac861494fd66e5a3f57d730484ea | daniel-reich/ubiquitous-fiesta | /p6uXeD7JC7cmxeD2Z_20.py | 519 | 3.609375 | 4 |
def calculate_score(lst):
a =0
b =0
for ab,be in lst:
if ab=='R':
if be == 'P':
b+=1
if be == 'S':
a+=1
if ab == "P":
if be =='S':
b+=1
if be =="R":
a+=1
if ab == 'S':
if be == 'R':
b+=1
if be == 'P':
a+=1
if a>b:
return "Abigail"
if b>a:
return "Benson"
if a==b:
return "Tie"
|
2da251dba4c7fe6f0281cd1a36f11e90b5b20b10 | thamilarasi43/thamilarasi | /index.py | 253 | 3.5 | 4 | n1=int(input("enter n1"))
q=int(input("enter q"))
l=[]
for i in range(n1):
a=int(input("enter n1 val"))
l.append(a)
for j in range(q):
c1=0
u=int(input())
v=int(input())
for i in range(u,v):
c1=c1+int(l[i])
print(c1)
|
d26891082d7d9e22837e73243a780f9d6cd7041a | Xevion/exercism | /python/hamming/hamming.py | 340 | 3.5625 | 4 | def distance(strand_a, strand_b):
if len(strand_a) != len(strand_b):
raise ValueError(f'strand_a (length {len(strand_a)}) has a different length from strand_b (length {len(strand_b)}), hamming distance cannot be computed.')
return len(strand_a) - len([char for index, char in enumerate(strand_a) if char == strand_b[index]]) |
b8845a0a1701b0efe3877a12d3f875333d0483f1 | pranaymate/Python_3_Deep_Dive_Part_1 | /Section 7 Scopes, Closures and Decorators/113. Decorator Application (Decorating Classes).py | 9,168 | 4.34375 | 4 | from fractions import Fraction
Fraction.speak = lambda self: 'This is a late parrot.'
f = Fraction(2, 3)
print(f)
print(f.speak())
print('#' * 52 + ' Yes, this is obviously nonsense, but you get the idea that you can add attributes to classes'
' even if you do not have direct control over the class, or after your class has been defined.')
Fraction.is_integral = lambda self: self.denominator == 1
f1 = Fraction(1, 2)
f2 = Fraction(10, 5)
print(f1.is_integral())
print(f2.is_integral())
print('#' * 52 + ' Now, we can make this change to the class by calling a function to do it instead:')
def dec_speak(cls):
cls.speak = lambda self: 'This is a very late parrot.'
return cls
Fraction = dec_speak(Fraction)
f = Fraction(10, 2)
print(f.speak())
print('#' * 52 + ' We can use that function to decorate our custom classes too, using the short **@** syntax too.')
@dec_speak
class Parrot:
def __init__(self):
self.state = 'late'
polly = Parrot()
print(polly.speak())
print('#' * 52 + ' Decorators are useful when they are able to be reused in more general ways.')
Fraction.recip = lambda self: Fraction(self.denominator, self.numerator)
f = Fraction(2, 3)
print(f)
print(f.recip())
print('#' * 52 + ' As a first example, lets say you typically like to inspect various properties of an object'
' for debugging purposes, maybe the memory address, its current state (property values),'
' and the time at which the debug info was generated.')
from datetime import datetime, timezone
def debug_info(cls):
def info(self):
results = []
results.append('time: {0}'.format(datetime.now(timezone.utc)))
results.append('class: {0}'.format(self.__class__.__name__))
results.append('id: {0}'.format(hex(id(self))))
if vars(self):
for k, v in vars(self).items():
results.append('{0}: {1}'.format(k, v))
# we have not covered lists, the extend method and generators,
# but note that a more Pythonic way to do this would be:
# if vars(self):
# results.extend('{0}: {1}'.format(k, v)
# for k, v in vars(self).items())
return results
cls.debug = info
return cls
@debug_info
class Person:
def __init__(self, name, birth_year):
self.name = name
self.birth_year = birth_year
def say_hi():
return 'Hello there!'
p1 = Person('John', 1939)
print(p1.debug())
print('#' * 52 + ' And of course we can decorate other classes this way too, not just a single class:')
@debug_info
class Automobile:
def __init__(self, make, model, year, top_speed_mph):
self.make = make
self.model = model
self.year = year
self.top_speed_mph = top_speed_mph
self.current_speed = 0
@property
def speed(self):
return self.current_speed
@speed.setter
def speed(self, new_speed):
self.current_speed = new_speed
s = Automobile('Ford', 'Model T', 1908, 45)
print(s.debug())
print('#' * 52 + ' ')
from math import sqrt
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __abs__(self):
return sqrt(self.x ** 2 + self.y ** 2)
def __repr__(self):
return 'Point({0},{1})'.format(self.x, self.y)
p1, p2, p3 = Point(2, 3), Point(2, 3), Point(0, 0)
print(abs(p1))
print(p1, p2)
print(p1 == p2)
print('#' * 52 + ' Hmm, we probably would have expected `p1` to be equal to `p2` since it has the same coordinates.'
' But by default Python will compare memory addresses, since our class does not implement'
' the `__eq__` method used for `==` comparisons.')
# print(p2 > p3) # TypeError: '>' not supported between instances of 'Point' and 'Point'
del Point
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __abs__(self):
return sqrt(self.x ** 2 + self.y ** 2)
def __eq__(self, other):
if isinstance(other, Point):
return self.x == other.x and self.y == other.y
else:
return NotImplemented
def __lt__(self, other):
if isinstance(other, Point):
return abs(self) < abs(other)
else:
return NotImplemented
def __repr__(self):
return '{0}({1},{2})'.format(self.__class__.__name__, self.x, self.y)
p1, p2, p3 = Point(2, 3), Point(2, 3), Point(0, 0)
print(p1, p2, p1 == p2)
print(p2, p3, p2 == p3)
print('#' * 52 + ' As we can see, `==` now works as expected')
p4 = Point(1, 2)
print(abs(p1), abs(p4), p1 < p4)
print(p1 > p4)
def complete_ordering(cls):
if '__eq__' in dir(cls) and '__lt__' in dir(cls):
cls.__le__ = lambda self, other: self < other or self == other
cls.__gt__ = lambda self, other: not (self < other) and not (self == other)
cls.__ge__ = lambda self, other: not (self < other)
return cls
print('#' * 52 + ' For example, a better way to implement `__ge__` would be as follows:')
def ge_from_lt(self, other):
# self >= other iff not(other < self)
result = self.__lt__(other)
if result is NotImplemented:
return NotImplemented
else:
return not result
print('#' * 52 + ' ')
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __abs__(self):
return sqrt(self.x ** 2 + self.y ** 2)
def __eq__(self, other):
if isinstance(other, Point):
return self.x == other.x and self.y == other.y
else:
return NotImplemented
def __lt__(self, other):
if isinstance(other, Point):
return abs(self) < abs(other)
else:
return NotImplemented
def __repr__(self):
return '{0}({1},{2})'.format(self.__class__, self.x, self.y)
Point = complete_ordering(Point)
p1, p2, p3 = Point(1, 1), Point(3, 4), Point(3, 4)
print(abs(p1), abs(p2), abs(p3))
print(p1 < p2, p1 <= p2, p1 > p2, p1 >= p2, p2 > p2, p2 >= p3)
print('#' * 52 + ' Now the `complete_ordering` decorator can also be directly applied to any class'
' that defines `__eq__` and `__lt__`.')
@complete_ordering
class Grade:
def __init__(self, score, max_score):
self.score = score
self.max_score = max_score
self.score_percent = round(score / max_score * 100)
def __repr__(self):
return 'Grade({0}, {1})'.format(self.score, self.max_score)
def __eq__(self, other):
if isinstance(other, Grade):
return self.score_percent == other.score_percent
else:
return NotImplemented
def __lt__(self, other):
if isinstance(other, Grade):
return self.score_percent < other.score_percent
else:
return NotImplemented
g1 = Grade(10, 100)
g2 = Grade(20, 30)
g3 = Grade(5, 50)
print(g1 <= g2, g1 == g3, g2 > g3)
print('#' * 52 + ' Often, given the `==` operator and just **one** of the other comparison operators'
' (`<`, `<=`, `>`, `>=`), then all the rest can be derived.')
print('#' * 52 + ' Our decorator insisted on `==` and `<`. but we could make it better by insisting'
' on `==` and any one of the other operators. ')
print('#' * 52 + ' This will of course make our decorator more complicated,'
' and in fact, Python has this precise functionality built in to the, you guessed it,'
' `functools` module!')
print('#' * 52 + ' It is a decorator called `total_ordering`.')
from functools import total_ordering
@total_ordering
class Grade:
def __init__(self, score, max_score):
self.score = score
self.max_score = max_score
self.score_percent = round(score / max_score * 100)
def __repr__(self):
return 'Grade({0}, {1})'.format(self.score, self.max_score)
def __eq__(self, other):
if isinstance(other, Grade):
return self.score_percent == other.score_percent
else:
return NotImplemented
def __lt__(self, other):
if isinstance(other, Grade):
return self.score_percent < other.score_percent
else:
return NotImplemented
g1, g2 = Grade(80, 100), Grade(60, 100)
print(g1 >= g2, g1 > g2)
print('#' * 52 + ' Or we could also do it this way:')
@total_ordering
class Grade:
def __init__(self, score, max_score):
self.score = score
self.max_score = max_score
self.score_percent = round(score / max_score * 100)
def __repr__(self):
return 'Grade({0}, {1})'.format(self.score, self.max_score)
def __eq__(self, other):
if isinstance(other, Grade):
return self.score_percent == other.score_percent
else:
return NotImplemented
def __gt__(self, other):
if isinstance(other, Grade):
return self.score_percent > other.score_percent
else:
return NotImplemented
g1, g2 = Grade(80, 100), Grade(60, 100)
print(g1 >= g2, g1 > g2, g1 <= g2, g1 < g2)
|
b4aec5c58bbcf7b71b85e71cf5a4cc26bf3c7901 | xufengshuang/grokking_algorithms_practice | /04_quicksort/03_recursive_max.py | 358 | 4.21875 | 4 | def find_max(arr):
'''
Use recursion to find the max.
'''
if arr==[]:
return None
elif len(arr)==1:
return arr[0]
else:
max_ = arr[0]
sub_max = find_max(arr[1:])
if max_ < sub_max:
max_ = sub_max
return max_
if __name__=='__main__':
arrs = [[1],[2,3,4,59,17],[]]
for arr in arrs:
print 'max of {}'.format(arr)
print find_max(arr)
|
59469e92d30164fb76413ea231e6365dd6b1c976 | K-atc/vega-solver | /vega/Functions.py | 370 | 3.5 | 4 | from .AST import *
### Check expr a and b are identical (not follows equality of a nor b)
def eq(a, b):
assert isinstance(a, AST)
assert isinstance(b, AST)
return a == b
def is_expr(expr):
if isinstance(expr, And) or isinstance(expr, Or):
return bool(expr.v) # Assume blank And() is not expression
else:
return isinstance(expr, AST) |
fd0eb7a4f33d0add77e2bb18be9c96101b495120 | keenosimms/conditionals | /simplifiedconditional.py | 110 | 3.78125 | 4 | oranges = 5
grapes = 7
if 0 < oranges and grapes < 10:
print('There are less oranges than grapes.')
|
d9bfd2bb1e75db62fe58048b842fddb306414e41 | tberhanu/all_trainings | /HACKERRANK/reverse_LL.py | 385 | 3.953125 | 4 | """
https://www.hackerrank.com/challenges/reverse-a-linked-list/problem?h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen
"""
def reverse(head):
if head is None or head.next is None:
return head
p = None
while head:
save = head.next
head.next = p
p = head
head = save
if save:
save = save.next
return p
|
6e075343ab0d6a449a2317a8899515b84d250b92 | kajendranL/Daily-Practice | /dict_excersis/10.sum_dict.py | 479 | 4.1875 | 4 |
print('''
Write a Python program to sum all the items in a dictionary
''')
print()
import operator
d_colour = {'Red' : 10, 'Green' : 20, 'White':30, 'Purple': 40}
print(sum(d_colour.values()))
print(sorted(d_colour.items(),key=operator. itemgetter(0),))
print()
dic = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
dict = {'d': 4, 'e': 5, 'f': 6, 'a': 1, 'b': 2, 'c': 3}
print(sum(dic.values()))
print(sum(dict.values()))
print(sum(dic.keys())) |
c0cd92102d724a47810e6b0222a771ed07f44d45 | donnevspankeren/Python-Basic | /2-vervolg datatypes/taak01-lists/index.py | 1,210 | 3.640625 | 4 | Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> maanden =['januari','februari','maart','april','mei','juni','july','augustus','september','oktober','november','december']
>>> type(maanden)
<class 'list'>
>>> maanden[0]
'januari'
>>> maanden[6]='juli'
>>> maanden
['januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli', 'augustus', 'september', 'oktober', 'november', 'december']
>>> print(maanden)
['januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli', 'augustus', 'september', 'oktober', 'november', 'december']
>>> print(maanden). <br>
SyntaxError: invalid syntax
>>> for elem in maanden
SyntaxError: invalid syntax
>>> for elem in maanden:
print elem
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(elem)?
>>> for elem in maanden:
print(elem)
januari
februari
maart
april
mei
juni
juli
augustus
september
oktober
november
december
>>> len(maande[2])
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
len(maande[2])
NameError: name 'maande' is not defined
>>> len(maanden)
12
>>> len(maanden[2])
5
>>> |
e40588c07dc56e77be954e3fb1ab38f9dc64aff3 | ten2net/Leetcode-solution | /104. Maximum Depth of Binary Tree.py | 751 | 3.734375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
from collections import deque
ret = 0
queue = deque()
if root is not None:
queue.append((root, 1))
while len(queue) > 0:
top, level = queue.popleft()
ret = max(ret, level)
if top.left is not None:
queue.append((top.left, level+1))
if top.right is not None:
queue.append((top.right, level+1))
return ret
|
33515813c75dc1cc99e6f1709598c0e3fcb41547 | karteekpv77/Year-round-Orienteering | /lab1/graph.py | 8,045 | 3.625 | 4 | _authors = "kvp"
"""
Author 1: Venkata Karteek Paladugu (vp3982@rit.edu)
"""
from math import sqrt, cos, atan
from Node import Node
class Graph:
"""
A graph implemented as an adjacency list of vertices.
:slot: vertList (dict): A dictionary that maps a vertex key to a Vertex
object
:slot: numVertices (int): The total number of vertices in the graph
:slot speed_dict (dict): dictionary of terrains and their speeds
:sl
"""
__slots__ = 'vertList', 'numVertices', 'speed_dict', 'season', 'waterlist'
def __init__(self, all_pixels, elevations, width, length, season):
"""
:param all_pixels: all pixels of image
:param elevations: all elevations of image
:param width: widht of image
:param length: length of image
:param season: season type
"""
self.vertList = {}
self.waterlist = []
self.numVertices = 0
self.speed_dict = {(248, 148, 18): 1.4,
(255, 192, 0): 1.25,
(255, 255, 255): 1.33,
(2, 208, 60): 1.15,
(2, 136, 40): 1.05,
(5, 73, 24): 0.15,
(0, 0, 255): 0.1,
(71, 51, 3): 1.55,
(0, 0, 0): 1.45,
(205, 0, 101): 0.001, # out of bounds
(63, 208, 212): 0.9, # ice
(139, 69, 19): 0.95 # mud
}
if season.lower() == 'fall':
self.speed_dict[255, 255, 255] = 1.10
self.season = season
is_winter = False
if self.season.lower() == 'winter' or self.season.lower() == 'spring':
is_winter = True
has_land = False
is_water = False
for x in range(width):
for y in range(length):
if all_pixels[x][y] == (0, 0, 255):
is_water = True
has_land = False
if x - 1 >= 0 and y - 1 >= 0:
if is_water and is_winter and all_pixels[x - 1][y - 1] != (0, 0, 255):
has_land = True
self.addEdge(x, y, x - 1, y - 1, elevations, all_pixels)
if x + 1 < width and y + 1 < length:
if is_water and is_winter and all_pixels[x + 1][y + 1] != (0, 0, 255):
has_land = True
self.addEdge(x, y, x + 1, y + 1, elevations, all_pixels)
if x - 1 >= 0:
if is_water and is_winter and all_pixels[x - 1][y] != (0, 0, 255):
has_land = True
self.addEdge(x, y, x - 1, y, elevations, all_pixels)
if y - 1 >= 0:
if is_water and is_winter and all_pixels[x][y - 1] != (0, 0, 255):
has_land = True
self.addEdge(x, y, x, y - 1, elevations, all_pixels)
if x + 1 < width:
if is_water and is_winter and all_pixels[x + 1][y] != (0, 0, 255):
has_land = True
self.addEdge(x, y, x + 1, y, elevations, all_pixels)
if y + 1 < length:
if is_water and is_winter and all_pixels[x][y + 1] != (0, 0, 255):
has_land = True
self.addEdge(x, y, x, y + 1, elevations, all_pixels)
if x + 1 < width and y - 1 >= 0:
if is_water and is_winter and all_pixels[x + 1][y - 1] != (0, 0, 255):
has_land = True
self.addEdge(x, y, x + 1, y - 1, elevations, all_pixels)
if x - 1 >= 0 and y + 1 < length:
if is_water and is_winter and all_pixels[x - 1][y + 1] != (0, 0, 255):
has_land = True
self.addEdge(x, y, x - 1, y + 1, elevations, all_pixels)
if has_land and is_winter and is_water:
self.waterlist.append((x, y))
is_water = False
def get_waterlist(self):
return self.waterlist
def get_speed_dict(self):
return self.speed_dict
def addNode(self, node):
"""
Add a new vertex to the graph.
:param node: node to be added
:return: Vertex
"""
# count this vertex if not already present
if self.getNode((node.x, node.y)) is None:
self.numVertices += 1
self.vertList[(node.x, node.y)] = node
return node
def getNode(self, key):
"""
Retrieve the vertex from the graph.
:param key: The vertex identifier
:return: Vertex if it is present, otherwise None
"""
if key in self.vertList:
return self.vertList[key]
else:
return None
def __contains__(self, key):
"""
Returns whether the vertex is in the graph or not. This allows the
user to do:
key in graph
:param key: The vertex identifier
:return: True if the vertex is present, and False if not
"""
return key in self.vertList
def addEdge(self, src_x, src_y, dest_x, dest_y, elevations, pixels):
"""
Add a new directed edge from a source to a destination of an edge cost.
:param pixels: all pixels in image
:param src_x: source x coordinate
:param src_y: source y coordinate
:param elevations: all elevations of image
:param dest_y: destination x coordinate
:param dest_x:destination y coordinate
:return: None
"""
src_z = elevations[src_x][src_y]
dest_z = elevations[dest_x][dest_y]
if (src_x, src_y, src_z) not in self.vertList:
self.addNode(Node(src_x, src_y, src_z, pixels[src_x][src_y]))
if (dest_x, dest_y, dest_z) not in self.vertList:
self.addNode(Node(dest_x, dest_y, dest_z, pixels[dest_x][dest_y]))
cost = self.get_cost(src_x, src_y, src_z, dest_x, dest_y, dest_z)
self.vertList[(src_x, src_y)].add_neighbor(self.vertList[(dest_x, dest_y)], cost)
def get_cost(self, src_x, src_y, src_z, dest_x, dest_y, dest_z):
"""
Add a new directed edge from a source to a destination of an edge cost.
:param src_x: source x coordinate
:param src_y: source y coordinate
:param src_z: source elevation
:param dest_y: destination x coordinate
:param dest_x:destination y coordinate
:param dest_z: destination elevation
:return: None
"""
distance = sqrt((((dest_x - src_x) * 10.29) ** 2) + (((dest_y - src_y) * 7.55) ** 2))
angle = (dest_z - src_z) / distance
multiplier = 1
if angle != 0:
multiplier = cos(atan(angle))
if angle < 0:
multiplier = 2 * multiplier
cost = distance / (self.speed_dict[self.vertList[(dest_x, dest_y)].terrain] * multiplier)
return cost
def get_distance(self, src_x, src_y, src_z, dest_x, dest_y, dest_z):
"""
Add a new directed edge from a source to a destination of an edge cost.
:param src_x: source x coordinate
:param src_y: source y coordinate
:param src_z: source elevation
:param dest_y: destination x coordinate
:param dest_x:destination y coordinate
:param dest_z: destination elevation
:return: distance
"""
distance = sqrt((((dest_x - src_x) * 10.29) ** 2) + (((dest_y - src_y) * 7.55) ** 2) + ((dest_z - src_z) ** 2))
return distance
def __iter__(self):
"""
Return an iterator over the vertices in the graph. This allows the
user to do:
for vertex in graph:
...
:return: A list iterator over Vertex objects
"""
return iter(self.vertList.values())
|
71e6ed4686d723afec129446fe391c63db43a56c | heartlesshound/python-pygame-experiments | /numpy_mouse_grid.py | 3,189 | 3.71875 | 4 | import pygame
import numpy as np
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
YELLOW = (255,255,0)
BROWN = (124, 85, 17)
DARKGREEN = (36, 94, 36)
# Set the width and height of each grid location
WIDTH = 10
HEIGHT = 10
# Set the width of the gridlines
MARGIN = 1
xgridtile = MARGIN + WIDTH
ygridtile = MARGIN + HEIGHT
# Set the Width and Height of the map
MAPWIDTH = 20
MAPHEIGHT = 20
# Create the array
mapArray = np.zeros((MAPWIDTH, MAPHEIGHT))
# Screen and pygame init
pygame.init()
# Set the width and height of the screen [width, height]
X_WIN_SIZE = ((WIDTH * (MAPWIDTH))+ (MARGIN * MAPWIDTH))
Y_WIN_SIZE = ((HEIGHT * (MAPHEIGHT))+ (MARGIN * MAPHEIGHT))
WINDOW_SIZE = [(X_WIN_SIZE), (Y_WIN_SIZE)]
print("Screen size ",WINDOW_SIZE)
screen = pygame.display.set_mode(WINDOW_SIZE)
pygame.display.set_caption("My Game")
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
directions = ["north", "east", "south", "east", "north", "north", "west", "west", "south"]
def choose_direction(directions):
directions_len = int(len(directions))
print("directions len = ", directions_len)
for i in range(directions_len):
current_direction = directions[i]
print("current direction = ", current_direction)
#return (current_direction)
def paint_map(mapArray):
print("Starting row")
for row in range(MAPHEIGHT):
for column in range(MAPWIDTH):
if mapArray[row][column] == 0:
color = BLUE
if mapArray[row][column] == 1:
color = GREEN
#print(mapArray[row][column])
#print(color)
if mapArray[row][column] == 2:
color = YELLOW
if mapArray[row][column] == 3:
color = BROWN
if mapArray[row][column] == 4:
color = DARKGREEN
xpos = column + MARGIN
xsquare = xgridtile * xpos
ypos = row + MARGIN
ysquare = ygridtile * ypos
pygame.draw.rect(screen, color,[(MARGIN + WIDTH) * column + MARGIN,
(MARGIN + HEIGHT) * row + MARGIN,
WIDTH,
HEIGHT])
choose_direction(directions)
paint_map(mapArray)
# -------- Main Program Loop -----------
while not done:
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop
elif event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
column = pos[0] // (WIDTH + MARGIN)
row = pos[1] // (HEIGHT +MARGIN)
print("Click ", pos, "Grid coords: ", row, column)
# Limit to 60 frames per second
clock.tick(60)
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
pygame.quit()
#print(mapArray)
#print("Should be sea",mapArray[3][LANDENDE])
#print("Should be land",mapArray[3][LANDENDE - 1])
|
f6a4ef383ca46e6c04fbf378bb2a98ceae2e6543 | KSRohan/python | /python_files/Strings/find_a_string.py | 606 | 3.734375 | 4 | def count_substring(string, sub_string):
countt=0
temp1=0
for i in range(len(string)):
if(string[i]==sub_string[0]):
temp=1
temp1=i+1
for j in range(1,len(sub_string)):
if (temp1<len(string) and string[temp1]==sub_string[j]):
temp=temp+1
temp1=temp1+1
else:
break
if(temp==len(sub_string)):
countt=countt+1
i=temp
return countt
if __name__ == '__main__': |
e3c77e9df64f307e55f85a4ca387276fb6f5e6a8 | rtain/RM_ICS_Debugging_Challenge | /ICS_Q3_Snyder_Debugging_Challenge/Snyder_ICS_DC_01.py | 1,984 | 4.03125 | 4 | # Alem Snyder
# Introduction to Computer Science
# Rock, Paper, Scissors, Lizard, Spock.
# Errors: ~6
hands = ["R","P","S" #nothing to see here...
]
from random import randint as ran
def position(List, Object):
for x in range(len(List)):
if List(x) == Object:
return x
def RPS:
hands = ["R","P","S"]
Win = 0
Los = 0
Tie = 0
print("Q to leave")
while True:
person_rps = input("Which one? Rock, Paper, or Scissors? (R/P/S)")
if person_rps.upper() == "Q":
break
elif person_rps.upper() in hands:
computer_rps = str(hands[ran(1,3)-1])
print(computer_rps)
if computer_rps.upper() == person_rps.upper():
print ("Tie")
Tie += 1
elif hands[position(hands,computer_rps)-1] == person_rps.upper():
print("Los")
Los+ = 1
else:
Win += 1
else:
print("Cheaters lose.")
print("Wins : %s, Losses: %s, Ties %s." % (Win, Los, Tie))
def RPSLSp():
hands = ["R","SP","P","L","S",]
Win = 0
Los = 0
Tie = 0
print("q to leave")
while True:
person_rps = input("Which one? Rock, Paper, Scissors, Lizard, or Spock? (R/P/S/L/SP)")
if person_rps.upper() == "Q":
break
elif person_rps.upper() in hands:
computer_rps = str(hands[ran(1,5)-1])
print computer_rps
if computer_rps.upper() == person_rps.upper():
print ("Tie")
Tie += 1
elif hands[position(hands,computer_rps)-1] == person_rps.upper() or hands[position(hands,computer_rps)-2] == person_rps.upper():
print("Lose")
Los += 1
else:
Win += 1
print("Win")
else:
print("Cheaters loose")
print("Wins : %s, Losses: %s, Ties %s." % (Win,Los,Tie))
while True:
RPSLSp()
|
3472d69cc5be4466cfc7380ca83bb3c3d3bc9ed2 | Shashanknew47/OOP | /Raymond Hettinger/Super/init and method.py | 858 | 3.578125 | 4 | class GFather:
def __init__(self):
print('Gf')
self.G = 'G'
def getvalue(self):
print('gf')
class Father(GFather):
Hair_color = 'Brown_hair'
def __init__(self):
self.F = 'Father'
print('Father')
super().__init__()
def getvalue(self):
print('getfather')
super().getvalue()
class Mother(GFather):
Mo = 'Mom'
def __init__(self):
print('Mother')
self.M = 'Mother'
super().__init__()
def getvalue(self):
print('getmother')
super().getvalue()
class Child(Mother,Father):
def __init__(self):
print('Child')
self.B = 'Baby'
super().__init__()
def getvalue(self):
print('getchild')
super().getvalue()
C1 = Child()
print(C1.Mo)
print(Child.__mro__)
(C1.getvalue())
|
5d8a97965d9ad6381880f4a86db8a6f124c32f2d | Rptiril/pythonCPA- | /chapter-2-practice-set/Qno_3.py | 122 | 3.65625 | 4 | '''
Check the type of the variable assigned using the input() function.
'''
x = input("enter something : ")
print(type(x)) |
48257c9799550dcb74cf18b0ad06acfea033bc5d | Erick-ViBe/Platzi | /PythonPlatzi/borrar2.py | 205 | 3.765625 | 4 | # -*- coding: utf-8 -*-
def run ():
x = int(raw_input())
y = int(raw_input())
result = power(x, y)
print result
def power(x, y):
return x**y
if __name__ == '__main__':
run()
|
a898093ae84280c5d1f18adefc755cdd27251f2b | yanxiaoyan2020/cpython-performance | /CalcPerformance.py | 339 | 3.625 | 4 | from timeDiff import timeDiff
import time
#timeCheck = timeDiff()
def calc():
sum =0
time0 = time.time()
for i in range(0,10000):
for j in range(0,10000):
sum =sum +i*i
time1= time.time()
diff = time1-time0
print("the time diff is :%f" %diff)
if __name__=='__main__':
st = calc()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.