blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
30720872f4126e68d7544c211b48b2ac8f9bc44b | CARLOSC10/T07_LIZA.DAMIAN_ROJAS.CUBAS | /LIZA_DAMIAN_CARLOS/ITERACION_RANGO/bucle_iteracion_rango03.py | 290 | 3.515625 | 4 | #REPETITIVAS ITERACION RANGO QUE CALCULA CUALQUER CADENA CON SU RESPECTIVO NUMERO DEL 0 AL 15
import os
#ARGUMENTO
#ASIGNACION DE VALORES
cadena=os.sys.argv[1]
#PROCESSING DE LA ESTRUCTURA "INTERACION RANGO"
for x in range(0,16):
print(cadena,"",x)
#fin_iterar
print("FIN DEL BUCLE")
|
546670a5f6a51627123c5b1c8f03f307f368fc65 | wizardshowing/pyctise | /count_words.py | 1,139 | 4.375 | 4 | #
# Count the words in a string. Usually we use regular expression to do this kind of string related works.
#
from typing import Dict
def filter_str(sentence: str) -> str:
"""Filter a sentence, replacing every the non-alphabet character with a space.
"""
chars = list(sentence)
for i in range(len(chars)):
if not chars[i].isalpha():
chars[i] = ' '
# join them together
return ''.join(chars)
def count_words(sentence: str) -> Dict[str, int]:
"""Count words in sentence. Return a dictionary mapping from word to frequency
"""
counter = {}
filtered_sentence = filter_str(sentence)
words = filtered_sentence.split(' ')
for word in words:
if word != '': # only care about non-empty strings
lower_case_word = word.lower()
if lower_case_word not in counter:
counter[lower_case_word] = 0
counter[lower_case_word] += 1
return counter
if __name__ == '__main__':
sentence = 'This is a good day!Hello world!!! There are some words that are repeated repeated repeated....'
print(count_words(sentence)) |
7ac94d0ae75a5bec4014b289114f8c3f5db881c3 | urchaug/python-scripts | /hcf and gcd.py | 699 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 31 10:18:52 2018
@author: Urchaug
"""
#python program to find the HCF of two input number
#define a function
def hcf(x,y):
"""this function takes two integers
and returns the HCF"""
# choose the smaller number
if x>y:
smaller = y
else:
smaller = x
for i in range(1,smaller + 1):
if((x%i==0) and (y%i==0)):
hcf = i
return hcf
#take input from user
num1 = int(input("Enter first number:"))
num2 = int(input("Enter second number:"))
print("The H.C.F. of",num1,"and",num2,"is",hcf(num1,num2))
|
09cea7ebd9298becabf9c476dbfbf0aba1f85122 | JohnnyRisk/intro_to_robotics | /project_runaway_robot_chase.py | 16,508 | 3.515625 | 4 | # ----------
# Part Three
#
# Now you'll actually track down and recover the runaway Traxbot.
# In this step, your speed will be about twice as fast the runaway bot,
# which means that your bot's distance parameter will be about twice that
# of the runaway. You can move less than this parameter if you'd
# like to slow down your bot near the end of the chase.
#
# ----------
# YOUR JOB
#
# Complete the next_move function. This function will give you access to
# the position and heading of your bot (the hunter); the most recent
# measurement received from the runaway bot (the target), the max distance
# your bot can move in a given timestep, and another variable, called
# OTHER, which you can use to keep track of information.
#
# Your function will return the amount you want your bot to turn, the
# distance you want your bot to move, and the OTHER variable, with any
# information you want to keep track of.
#
# ----------
# GRADING
#
# We will make repeated calls to your next_move function. After
# each call, we will move the hunter bot according to your instructions
# and compare its position to the target bot's true position
# As soon as the hunter is within 0.01 stepsizes of the target,
# you will be marked correct and we will tell you how many steps it took
# before your function successfully located the target bot.
#
# As an added challenge, try to get to the target bot as quickly as
# possible.
from robot import *
from math import *
from matrix import *
import random
import numpy as np
def make_plan(hunter_position, target_measurement, target_heading, distance, d_heading, max_distance):
solved = False
i = 1
while not solved:
next_target_position, next_target_heading = calc_next_position(
target_measurement, target_heading, distance, d_heading)
print('next_target_position: {}'.format(next_target_position))
print('i: {}'.format(i))
distance_to_position = distance_between(hunter_position, next_target_position)
if distance_to_position / (max_distance * i) <= 1:
solved = True
else:
i += 1
target_measurement = next_target_position
target_heading = next_target_heading
return next_target_position
def calc_next_position(target_measurement, target_heading, distance, d_heading):
x, y = target_measurement[0], target_measurement[1]
new_heading = target_heading + d_heading
dy = distance * sin(new_heading)
dx = distance * cos(new_heading)
predicted_xy = [round(x + dx, 3), round(y + dy, 3)]
return predicted_xy, new_heading
def update_guassian(mu_old,sigma_old, obs, var_obs):
mu_prime = (var_obs*mu_old + sigma_old*obs) / (sigma_old + var_obs)
sigma_prime = sigma_old * var_obs / (sigma_old + var_obs)
return mu_prime, sigma_prime
def dist_head_estimates(measurements, sigma_dist_measurement=1, sigma_d_heading_measurement=5):
for k in range(len(measurements) - 1):
if k == 0:
mu_dist = distance_between(measurements[k], measurements[k + 1])
heading1 = get_heading(measurements[k], measurements[k + 1])
if k == 1:
new_dist = distance_between(measurements[k], measurements[k + 1])
new_heading = get_heading(measurements[k], measurements[k + 1])
mu_d_heading = new_heading - heading1
## update the expectation of mu_dist
mu_dist, sigma_dist = update_guassian(
mu_dist, sigma_dist_measurement, new_dist, sigma_dist_measurement)
old_heading = new_heading
if k == 2:
new_dist = distance_between(measurements[k], measurements[k + 1])
new_heading = get_heading(measurements[k], measurements[k + 1])
new_d_heading = new_heading - old_heading
old_heading = new_heading
## update the expectation of mu but this time use our new sigma
mu_dist, sigma_dist = update_guassian(
mu_dist, sigma_dist, new_dist, sigma_dist_measurement)
## update the expectation of mu_d_heading
mu_d_heading, sigma_d_heading = update_guassian(
mu_d_heading, sigma_d_heading_measurement, new_d_heading, sigma_d_heading_measurement)
if k >= 3:
new_dist = distance_between(measurements[k], measurements[k + 1])
new_heading = get_heading(measurements[k], measurements[k + 1])
new_d_heading = new_heading - old_heading
old_heading = new_heading
mu_dist, sigma_dist = update_guassian(
mu_dist, sigma_dist, new_dist, sigma_dist_measurement)
## update the expectation of mu_d_heading but this time use our new sigma
mu_d_heading, sigma_d_heading = update_guassian(
mu_d_heading, sigma_d_heading, new_d_heading, sigma_d_heading_measurement)
return mu_dist, mu_d_heading
def next_move(hunter_position, hunter_heading, target_measurement, max_distance, OTHER=None):
# This function will be called after each time the target moves.
# The OTHER variable is a place for you to store any historical information about
# the progress of the hunt (or maybe some localization information). Your return format
# must be as follows in order to be graded properly.
if not OTHER: # first time calling this function, set up my OTHER variables.
measurements = [target_measurement]
hunter_positions = [hunter_position]
hunter_headings = [hunter_heading]
plan = []
hunter_params = []
OTHER = [measurements, hunter_positions, hunter_headings, plan,
hunter_params] # now I can keep track of history
else: # not the first time, update my history
OTHER[0].append(target_measurement)
OTHER[1].append(hunter_position)
OTHER[2].append(hunter_heading)
measurements, hunter_positions, hunter_headings, plan, hunter_params = OTHER # now I can always refer to these variables
# now we start taking steps
# Step One: we just go as close as we can to the starting position of the hunted
if len(measurements) == 1:
heading_to_target = get_heading(hunter_position, target_measurement)
heading_difference = heading_to_target - hunter_heading
turning = heading_difference # turn towards the target
distance = min(distance_between(hunter_position, target_measurement), max_distance)
# Step Two: Now we know the distance it travels but not the heading, so extrapolate and try to go
# as close to the targets next point if it didnt turn
elif len(measurements) == 2:
# find the distance it will travel
dist = distance_between(measurements[-2], measurements[-1])
# find the heading the target is going
target_heading = get_heading(measurements[-2], measurements[-1])
# now we need to find the x,y of the prediction given the dist
dx = dist * cos(target_heading)
dy = dist * sin(target_heading)
pred_target = (measurements[-1][0] + dx, measurements[-1][1] + dy)
# finally we get our position relative to the pred and move to that spot
heading_to_target = get_heading(hunter_position, pred_target)
heading_difference = heading_to_target - hunter_heading
turning = heading_difference # turn towards the target
distance = min(distance_between(hunter_position, pred_target), max_distance)
# we add the hunter params for later use
hunter_params = [dist, target_heading]
OTHER[4] = hunter_params
# Step Three: we will finally know the system determinalistically so we can find the optimal path
# we will find the turning angle, create a plan, then execute the plan.
elif len(measurements) >= 3:
# get the direction the target just moved and calculate how much its steering angle is
target_heading = get_heading(measurements[-2], measurements[-1])
dist = np.mean([distance_between(measurements[j], measurements[j+1]) for j in range(len(measurements)-1)])
d_heading = np.mean(np.diff([get_heading(measurements[j], measurements[j+1]) for j in range(len(measurements)-1)]))
dist, d_heading = dist_head_estimates(measurements)
print("heading: {}".format(d_heading))
print("distance: {}".format(dist))
# make a plan
plan = make_plan(hunter_position, target_measurement, target_heading, dist, d_heading, max_distance)
# store the plan (it is just the destination we will hit the target)
OTHER[3] = plan
heading_to_target = get_heading(hunter_position, plan)
heading_difference = heading_to_target - hunter_heading
turning = angle_trunc(heading_difference) # turn towards the target
distance = min(distance_between(hunter_position, plan), max_distance)
else:
print('ERROR')
return turning, distance, OTHER
def distance_between(point1, point2):
"""Computes distance between point1 and point2. Points are (x, y) pairs."""
x1, y1 = point1
x2, y2 = point2
return sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
def demo_grading(hunter_bot, target_bot, next_move_fcn, OTHER=None):
"""Returns True if your next_move_fcn successfully guides the hunter_bot
to the target_bot. This function is here to help you understand how we
will grade your submission."""
max_distance = 1.94 * target_bot.distance # 1.94 is an example. It will change.
separation_tolerance = 0.02 * target_bot.distance # hunter must be within 0.02 step size to catch target
caught = False
ctr = 0
# We will use your next_move_fcn until we catch the target or time expires.
while not caught and ctr < 1000:
# Check to see if the hunter has caught the target.
hunter_position = (hunter_bot.x, hunter_bot.y)
target_position = (target_bot.x, target_bot.y)
separation = distance_between(hunter_position, target_position)
if separation < separation_tolerance:
print("You got it right! It took you ", ctr, " steps to catch the target.")
caught = True
# The target broadcasts its noisy measurement
target_measurement = target_bot.sense()
# This is where YOUR function will be called.
turning, distance, OTHER = next_move_fcn(hunter_position, hunter_bot.heading, target_measurement, max_distance,
OTHER)
# Don't try to move faster than allowed!
if distance > max_distance:
distance = max_distance
# We move the hunter according to your instructions
hunter_bot.move(turning, distance)
# The target continues its (nearly) circular motion.
target_bot.move_in_circle()
ctr += 1
if ctr >= 1000:
print("It took too many steps to catch the target.")
return caught
def angle_trunc(a):
"""This maps all angles to a domain of [-pi, pi]"""
while a < 0.0:
a += pi * 2
return ((a + pi) % (pi * 2)) - pi
def get_heading(hunter_position, target_position):
"""Returns the angle, in radians, between the target and hunter positions"""
hunter_x, hunter_y = hunter_position
target_x, target_y = target_position
heading = atan2(target_y - hunter_y, target_x - hunter_x)
heading = angle_trunc(heading)
return heading
def demo_grading1(hunter_bot, target_bot, next_move_fcn, OTHER = None):
"""Returns True if your next_move_fcn successfully guides the hunter_bot
to the target_bot. This function is here to help you understand how we
will grade your submission."""
max_distance = 1.94 * target_bot.distance # 1.94 is an example. It will change.
separation_tolerance = 0.02 * target_bot.distance # hunter must be within 0.02 step size to catch target
caught = False
ctr = 0
#For Visualization
import turtle
window = turtle.Screen()
window.bgcolor('white')
chaser_robot = turtle.Turtle()
chaser_robot.shape('arrow')
chaser_robot.color('blue')
chaser_robot.resizemode('user')
chaser_robot.shapesize(0.3, 0.3, 0.3)
broken_robot = turtle.Turtle()
broken_robot.shape('turtle')
broken_robot.color('green')
broken_robot.resizemode('user')
broken_robot.shapesize(0.3, 0.3, 0.3)
size_multiplier = 15.0 #change Size of animation
chaser_robot.hideturtle()
chaser_robot.penup()
chaser_robot.goto(hunter_bot.x*size_multiplier, hunter_bot.y*size_multiplier-100)
chaser_robot.showturtle()
broken_robot.hideturtle()
broken_robot.penup()
broken_robot.goto(target_bot.x*size_multiplier, target_bot.y*size_multiplier-100)
broken_robot.showturtle()
measuredbroken_robot = turtle.Turtle()
measuredbroken_robot.shape('circle')
measuredbroken_robot.color('red')
measuredbroken_robot.penup()
measuredbroken_robot.resizemode('user')
measuredbroken_robot.shapesize(0.1, 0.1, 0.1)
broken_robot.pendown()
chaser_robot.pendown()
#End of Visualization
# We will use your next_move_fcn until we catch the target or time expires.
while not caught and ctr < 1000:
# Check to see if the hunter has caught the target.
hunter_position = (hunter_bot.x, hunter_bot.y)
target_position = (target_bot.x, target_bot.y)
separation = distance_between(hunter_position, target_position)
if separation < separation_tolerance:
print("You got it right! It took you ", ctr, " steps to catch the target.")
caught = True
# The target broadcasts its noisy measurement
target_measurement = target_bot.sense()
# This is where YOUR function will be called.
turning, distance, OTHER = next_move_fcn(hunter_position, hunter_bot.heading, target_measurement, max_distance, OTHER)
# Don't try to move faster than allowed!
if distance > max_distance:
distance = max_distance
# We move the hunter according to your instructions
hunter_bot.move(turning, distance)
# The target continues its (nearly) circular motion.
target_bot.move_in_circle()
#Visualize it
measuredbroken_robot.setheading(target_bot.heading*180/pi)
measuredbroken_robot.goto(target_measurement[0]*size_multiplier, target_measurement[1]*size_multiplier-100)
measuredbroken_robot.stamp()
broken_robot.setheading(target_bot.heading*180/pi)
broken_robot.goto(target_bot.x*size_multiplier, target_bot.y*size_multiplier-100)
chaser_robot.setheading(hunter_bot.heading*180/pi)
chaser_robot.goto(hunter_bot.x*size_multiplier, hunter_bot.y*size_multiplier-100)
#End of visualization
ctr += 1
if ctr >= 1000:
print("It took too many steps to catch the target.")
return caught
def naive_next_move(hunter_position, hunter_heading, target_measurement, max_distance, OTHER):
"""This strategy always tries to steer the hunter directly towards where the target last
said it was and then moves forwards at full speed. This strategy also keeps track of all
the target measurements, hunter positions, and hunter headings over time, but it doesn't
do anything with that information."""
if not OTHER: # first time calling this function, set up my OTHER variables.
measurements = [target_measurement]
hunter_positions = [hunter_position]
hunter_headings = [hunter_heading]
OTHER = (measurements, hunter_positions, hunter_headings) # now I can keep track of history
else: # not the first time, update my history
OTHER[0].append(target_measurement)
OTHER[1].append(hunter_position)
OTHER[2].append(hunter_heading)
measurements, hunter_positions, hunter_headings = OTHER # now I can always refer to these variables
heading_to_target = get_heading(hunter_position, target_measurement)
heading_difference = heading_to_target - hunter_heading
turning = heading_difference # turn towards the target
distance = max_distance # full speed ahead!
return turning, distance, OTHER
target = robot(0.0, 10.0, 0.0, 2 * pi / 30, 1.5)
measurement_noise = .05*target.distance
target.set_noise(0.0, 0.0, measurement_noise)
hunter = robot(-10.0, -10.0, 0.0)
#print(demo_grading(hunter, target, next_move))
print(demo_grading1(hunter, target, next_move))
|
c8c9f7b0e7109683be9b8620c53e67fbf0ec487a | chendonna/interview_practice | /mergeSort.py | 1,591 | 3.890625 | 4 | """
mergeSort.py
"""
def mergeTwoLists(l1, l2):
# if not l1 and not l2:
# return []
i = 0
j = 0
newList = []
while (i != len(l1)) and (j != len(l2)):
if l1[i] < l2[j]:
newList.append(l1[i])
i = i + 1
else:
newList.append(l2[j])
j = j + 1
if i == len(l1):
newList = newList + l2[j:]
if j == len(l2):
newList = newList + l1[i:]
return newList
def mergeSort(l1):
if not l1:
return []
i = len(l1)
if i == 1:
return l1
j = int(i/2)
return mergeTwoLists(mergeSort(l1[:j]), mergeSort(l1[j:]))
print(mergeSort([2, 1]))
print(mergeSort([2, 1, 3]))
print(mergeSort([2, 1, 3, 0, 10, 5, 7, 6]))
"""
js version
function merge(arr, l, m, r) {
var l1 = arr.slice(l, m+1);
var l2 = arr.slice(m+1, r+1);
var i = 0;
var j = 0;
var k = l;
while ((i != l1.length) && (j != l2.length)){
if (l1[i] < l2[j]) {
arr[k] = l1[i];
i++;
} else {
arr[k] = l2[j]
j++;
}
k++;
}
/* adding the remaining elements of l1 to arr*/
while (i != l1.length) {
arr[k] = l1[i];
k++;
i++;
}
/* adding remaining elements to l2 to arr */
while (j != l2.length) {
arr[k] = l2[j];
k++;
j++;
}
}
function mergeSort(roster, l, r) {
if (l < r) {
var m = Math.floor((l + r)/2)
mergeSort(roster, l, m)
mergeSort(roster, m+1, r)
merge(roster, l, m, r)
}
}
var arr = [2, 1, 4, 10, 8, 9, 7, 3, 1]
mergeSort(arr, 0, arr.length - 1);
console.log(arr)
"""
|
6b32aabbeb120a16e40cdebb1d07bbd82eee12f3 | Neodim5/GeekPython | /lesson2/test02/test1.py | 320 | 3.875 | 4 | for el in reversed("abrakadbra"):
print(el)
print(len("abrakadbra"))
print("ัะฐะท ะดะฒะฐ ััะธ".split())
print("ัะตัััะต_ะฟััั_ัะตััั".split('_'))
print('_'.join(['ัะฐะท', 'ะดะฒะฐ', 'ััะธ']))
print(''.join(['ัะฐะท', 'ะดะฒะฐ', 'ััะธ']))
print("ะตั
ะฐะป ะณัะตะบะฐ ัะตัะตะท ัะตะบั".title())
|
ae5dd255fc15694ac7d81b09a9f914617ac4010d | AssiaHristova/SoftUni-Software-Engineering | /Programming Fundamentals/list_advanced/inventory.py | 909 | 3.828125 | 4 | journal = input().split(', ')
command = input()
while not command == "Craft!":
command_list = command.split(" - ")
if 'Collect' in command_list:
if command_list[1] not in journal:
journal.append(command_list[1])
elif "Drop" in command_list:
if command_list[1] in journal:
journal.remove(command_list[1])
elif "Combine Items" in command_list:
item_list = command_list[1].split(':')
old_item = item_list[0]
new_item = item_list[1]
if old_item in journal:
for i in range(len(journal)):
if journal[i] == old_item:
journal.insert(i + 1, new_item)
elif "Renew" in command_list:
if command_list[-1] in journal:
journal.remove(command_list[-1])
journal.append(command_list[-1])
command = input()
result = ', '.join(journal)
print(result)
|
511bc4d9e44f395dfff24c81d5cec9235d42bd6f | AlexanderMer/SkillUp | /Python/Homeworks/Black_Jack_GUI/Test.py | 219 | 3.578125 | 4 | from tkinter import *
main = Tk()
canvas = Canvas(main, height=500, width=500, bg="pink")
canvas.grid()
rec = canvas.create_rectangle(50, 50, 150, 150)
print(canvas.coords(rec))
canvas.move(rec, 50, 50)
main.mainloop() |
f85e0e2325671358dee94874f6009a3e94b43c84 | akbota123/BFDjango | /week1/informatics/inf2E.py | 113 | 3.8125 | 4 | import math
x=int(input())
y=int(input())
if x>y:
print("1")
if x<y:
print("2")
if x==y:
print("0") |
8fa337e71a30f574228737e2c5123458e7a5ad5c | webable9/webable-python | /codeing_interview/125_Vaild_Palindrome.py | 591 | 3.90625 | 4 | # page_138 : ์ ํจํ ํฐ๋ฆฐ๋๋กฌ
import re
# ๋จ์ ํด๊ฒฐ ๋ฐฉ๋ฒ
def isPalindrome(s):
return s == s[::-1]
s = "malayalam"
ans = isPalindrome(s)
if ans:
print("Yes")
else:
print("No")
# ๋๋ฒ๋ ํด๊ฒฐ ๋ฐฉ๋ฒ
class Solution:
def isPalindrome2(self, s: str) -> bool:
s = s.lower() # ์๋ฌธ์๋ก ๋ณ๊ฒฝ
s = re.sub('[^a-z0-9]', '', s) # ์ ๊ท์์ผ๋ก ๋ถํ์ํ ๋ฌธ์ ํํฐ๋ง
return s == s[::-1] # ์ญ์ฌ๋ผ์ด์ฑ
solution = Solution()
s = "race a car"
ans = solution.isPalindrome2(s)
if ans:
print("Yes")
else:
print("No")
|
cc7e92738caa9f06bb08d645ed939c006e2bbdb3 | nandakishore723/cspp-1 | /cspp1-assignments/m11/p4/p4/assignment4.py | 1,002 | 3.84375 | 4 | '''
@author : nandakishore723
#Exercise: Assignment-4
#We are now ready to begin writing the code that interacts with the player.
# We'll be implementing the playHand function. This function allows the user
# to play out a single hand.
# First, though, you'll need to implement the helper calculateHandlen function,
#which can be done in under five lines of code.
'''
def calculate_handlen(hand):
"""
Returns the length (number of letters) in the current hand.
hand: dictionary (string int)
returns: integer
"""
sum_a = 0
for iter_ in hand:
sum_a += hand[iter_]
return sum_a
def main():
'''
Returns the length (number of letters) in the current hand.
hand: dictionary (string int)
returns: integer
'''
n_num = input()
adict = {}
for data in range(int(n_num)):
data = input()
l_list = data.split()
adict[l_list[0]] = int(l_list[1])
print(calculate_handlen(adict))
if __name__ == "__main__":
main()
|
409c23bb3bd1c8af62911e0baf29558bbc8a4f4f | annalundberg/raw-patient-data-to-sql | /py_scripts/timedate.py | 6,622 | 3.875 | 4 | #!/usr/bin/env python
'''This program was written to convert various time and date forms found in
raw patient csvs into SQL smalldatetime format'''
import argparse
def get_arguments():
parser = argparse.ArgumentParser(
description="reads in csv file, designates columns to convert time&date and designates type of separator")
parser.add_argument("-f", "--filename", help="name of file",
required=True, type=str)
parser.add_argument("-c", "--columns", action='append', help="columns to split, column per -c",
required=True, type=str)
parser.add_argument("-s", "--date_sep", help="date separator, choose slash or space",
required=True, type=str)
return parser.parse_args()
def month_trans(month):
'''(string) -> string
this fxn takes in a string containing month in 3 letter abbreviated form
and converts it to its 2 digit numerical representation in a string.
>>>month_trans('Mar')
'03'
>>>month_trans('Oct')
'10'
'''
m_dict={'Jan':'01','Feb':'02','Mar':'03','Apr':'04','May':'05','Jun':'06',
'Jul':'07','Aug':'08','Sep':'09','Oct':'10','Nov':'11','Dec':'12'}
return m_dict[month]
def timedate(date, time):
'''(list, list)->str
read list of month day year time to convert to sql compatible
smalldatetime.
>>>timedate(['12','05','2009'],['12','00','00','AM'])
'2009-12-05 00:00:00'
>>>timedate(['03','15','2012'],['03','30','00','PM'])
'20012-03-15 15:30:00'
'''
# Identify Year
year = date[2]
# Identify/check Month
if len(date[0]) == 1:
date[0] = '0'+date[0]
month = date[0]
# Identify/check Day
if len(date[1]) == 1:
date[1] = '0'+date[1]
day = date[1]
# Pull together date in proper format
date = year+'-'+month+'-'+day
# Check hour
if len(time[0]) == 1:
time[0] = '0'+time[0]
# check for AM/PM & convert to military time
if len(time) == 4:
if 'AM' in time[3] and time[0] == '12':
time[0] = '00'
if 'PM' in time[3]:
if time[0] != '12':
time[0] = str(int(time[0])+12)
# Rejoin time & date for output in final format
time = ':'.join(str(bit) for bit in time[0:3])
date_time = date+' '+time
return date_time
def file_parse_sp(file, cols):
'''(file, list)->file
parses a csv file and separates lines, will incorporate other functions
to convert time and date into sql smalldatetime format. Compatible when
time/date is written as "Mon DD YYYY HH:MM:SS XM". AKA story format
New timedate is YYYY-MM-DD hh:mm:ss
'''
# Use original filename & path to build output filename & path
filename = file.split('/')
filepath = "/".join(filename[:-1])
new_file = filepath + "/tmp_" + filename[-1]
ln = 0 # init line count
# Open original file to edit write changes in new file
with open(file) as o_data, open(new_file, 'w') as n_file:
for line in o_data:
ln += 1
entry = line.split(',') #split csv into list by columns
if ln == 1: #header
newline = entry
else:
# Timedate conversion for each specified column
for i in range(len(cols)):
date_time = entry[int(cols[i])-1]
date_time = date_time.split(' ') #split date and time
date_time[0] = month_trans(date_time[0]) # Mon -> MM
date = date_time[0:3] # isolate date list
time = date_time[3].split(':') # result: ['hh','mm','ss']
if len(date_time) == 5: # If time includes AM/PM
time.append(date_time[4])
entry[int(cols[i])-1] = timedate(date, time) # Update entry
# Convert list back to csv line and write to newfile
newline = ','.join(str(item) for item in entry)
n_file.write(newline)
return None
def file_parse_sl(file, cols):
'''(file, list) -> file
parses a csv file and separates lines, will incorporate other functions
to convert time and date into sql smalldatetime format. Compatible when
date is in MM/DD/YYYY HH:MM:SS format in a csv'''
# Use original filename & path to build output filename & path
filename = file.split('/')
filepath = "/".join(filename[:-1])
new_file = filepath + "/tmp_" + filename[-1]
ln = 0 # init line count
# Open original file to edit write changes in new file
with open(file) as o_data, open(new_file, 'w') as n_file:
for line in o_data:
ln += 1
entry = line.split(',') #split csv into list by columns
if ln == 1: #header
newline = entry
else:
# Timedate conversion for each specified column
for i in range(len(cols)):
date_time = entry[int(cols[i])-1]
if len(date_time) == 0 or date_time[0] == 'NULL': # handle blank column
break
date_time = date_time.split(' ') # Split date and time
date = date_time[0]
if len(date_time) == 1 or date_time[1] == 'NULL': # no time entry
time = '00:00:00'.split(':')
else:
time = date_time[1].split(':')
if len(time) == 2: # add seconds if needed
time.append('00')
if len(date_time) == 3: # add AM/PM if present
time.append(date_time[2])
date = date.split('/') # resulting format ['MM','DD','YYYY']
entry[int(cols[i])-1] = timedate(date, time)
# Convert list back to csv line and write to newfile
newline = ','.join(str(item) for item in entry)
n_file.write(newline)
return None
def main():
'''runs fxns for converting date and time into smalldatetime format. uses
arg parse to get file, columns to be converted and the type of date present.'''
args = get_arguments()
# handle MM/DD/YYYY format
if args.date_sep == 'slash':
file_parse_sl(args.filename, args.columns)
# handle Mon DD YYYY format
elif args.date_sep == 'space':
file_parse_sp(args.filename, args.columns)
# currently other formats not supported
else:
print('Invalid date separator given. Choose "slash" or "space".')
return None
if __name__ == '__main__':
main()
|
74d69f7228d50cf43f8b181e949616109f8edf1c | JovanJevtic/Algorithms | /py/Quicksort.py | 508 | 3.5625 | 4 | def partition(arr, l, r):
i = l - 1
pivot = arr[r]
for j in range(l, r):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[r] = arr[r], arr[i+1]
return i + 1
def qs(arr, l, r):
if l >= r:
return arr
p = partition(arr, l, r)
qs(arr, l, p - 1)
qs(arr, p + 1, r)
arr = [1, 2, 4, 6, 16, 21, 54, 12, 4, 3, 8, 32, 512]
print('Unsorted array: ', arr)
qs(arr, 0, len(arr) - 1)
print('Sorted array: ', arr)
|
8d9be2afe4604be7dc515a0c17315176697175d0 | nchriz/Euler | /proj12/main.py | 999 | 3.578125 | 4 | import math
INF = float('inf')
def numberOfDiv(n):
x = 0
nsqrt = math.sqrt(n)
for i in range(1, int(nsqrt)+1):
if n%i == 0:
x += 2
if nsqrt*nsqrt == n:
x-=1
return x
def tri(stop):
sum = 0
n = 1
while n < stop:
sum += n
yield sum
n += 1
def proj12():
n = 1
sum = 0
while True:
sum += n
tmp = 2
max = sum
for x in range(2,int(max**0.5)+1):
if not n%x:
tmp+=2
max = max/x
if tmp>5:
return sum, tmp
n+=1
def main():
#n = 7
#sum = 0
#tmp = 0
#for x in range(1,n+1):
# sum += x
# if n%x:
# tmp+=1
#sum, tmp = proj12()
#print tmp
#print sum
stop = 500
for x in tri(INF):
num = numberOfDiv(x)
if num > stop:
print("x: " + str(x) + " num: " + str(num))
break
if __name__ == "__main__":
main()
|
1b74f4c1e5eb8c8e9f91d1b271c9f7ce345d2a07 | marcosfelt/sysid-neural-structures-fitting | /common/metrics.py | 704 | 3.5 | 4 | import numpy as np
def r_square(y_pred, y_true, w=1, time_axis=0):
""" Get the r-square fit criterion per time signal """
SSE = np.sum((y_pred - y_true)**2, axis=time_axis)
y_mean = np.mean(y_true, axis=time_axis)
SST = np.sum((y_true - y_mean)**2, axis=time_axis)
return 1.0 - SSE/SST
def error_rmse(y_pred, y_true, time_axis=0):
""" Compute the Root Mean Square Error (RMSE) per time signal """
SSE = np.mean((y_pred - y_true)**2, axis=time_axis)
RMS = np.sqrt(SSE)
return RMS
if __name__ == '__main__':
N = 20
ny = 2
SNR = 10
y_true = SNR*np.random.randn(N,2)
y_pred = np.copy(y_true) + np.random.randn(N,2)
r_square(y_true, y_pred)
|
d8cf70210d0463734838b24dfc61709d8095a495 | junaid340/AnomalyDetection-in-SurveillanceVideos | /Evaluate_V2.py | 2,271 | 3.65625 | 4 | from matplotlib import pyplot as plt
import pickle
def PlotHistory(history, name, show=True, save=False, path=None):
'''
A function to plot the Training loss and Validation loss of the model.
Parameters
----------
history : dictionary
Dictionary that contains all the training loss and validation loss values.
name : string
Name for the graph, or title for the graph
show : boolean, optional
The default is True.
save : strin, optional
To save the plot at the given destination in '.png' format. The default is False.
path : string, optional
Path for storing the plots of the model. The default is None.
Raises
------
ValueError
If you want to save the plots, give a valid path where the image of plots
could be saved.
Returns
-------
None.
'''
plt.clf()
plt.ioff()
plt.figure(1)
#plots the training loss of the model
plt.plot(history['loss'])
#plots the validation loss of the model
plt.plot(history['val_loss'])
#Assigning Titles to the graph
plt.title('Model loss- '+name)
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Training Loss', 'Val Loss'], loc='upper right')
#Saving the graph as .png image
if save:
if path==None:
raise ValueError('Path cannot be None when `save` is set to True, please provide valid path.')
plt.savefig(path+'/'+name+'_Loss.png')
plt.figure(2)
#plots accuracy of the model
plt.plot(history['accuracy'])
#Assigning Titles to the graph
plt.title('Model Accuracy- '+name)
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Model Accuracy'], loc='lower right')
#Saving the graph as .png image
if save:
if path==None:
raise ValueError('Path cannot be None when `save` is set to True, please provide valid path.')
plt.savefig(path+'/'+name+'_Accuracy.png')
if show:
plt.show()
#pass the saved history file to evaluate the model
with open('checkpoints/Model_History', 'rb') as f:
hist = pickle.load(f)
PlotHistory(hist, name='Our_Model', show=True, save=True, path='./') |
39648326d277b4462cdaa937e9958f58d0f9e424 | pvr30/Python-Tutorial | /Basic Of Python Section 1 of Course/Strings in Python.py | 1,621 | 4.75 | 5 | my_string = "Hello Python"
print(my_string)
my_string = 'Hello Python2' # we can also use '' in python
print(my_string)
another_string = "Hello! 'What are you doing'."
print(another_string)
another_string = 'Hello ! "What are you doing". '
print(another_string)
first_string = "Vishal Parmar"
print("Hello "+first_string)
first_name = "Vishal"
greeting = "Hello" + first_name
print(greeting)
another_greeting = f"How are You {first_name} ?" # This is called fstream .
# In f-strings, {name} gets replaced by the value of the variable name.
print(another_greeting)
# This is called format method .
# The {} gets replaced by whatever is inside the brackets of the .format()
final_greeting = "Hey What are you doing ? {}".format(first_name)
print(final_greeting)
# You can also give names to variables inside a formattable string:
friend_name = "Harsh"
goodbye = "Goodbye, {first_name}!"
goodbye_harsh = goodbye.format(first_name=friend_name)
print(goodbye_harsh)
greeting = "Hey How are you {} "
print(greeting.format(first_name))
# Usually you will be using f-strings, just because they are shorter and more readable.
# However sometimes you may need to re-use a format string, and that is when using .format() is useful.
# Multi-line String
name = "Rolf Smith"
street = "123 No Name Road"
postcode = "PY10 1CP"
address = f"""Name: {name}
Street: {street}
Postcode: {postcode}
Country: United Kingdom"""
print(address)
description = "{} is {age} years old."
print(description.format("Bob", age=30))
# Slicing in Python.
demo = "Vishal Parmar"
print(demo[:4])
print(demo[0:6])
print(demo[7:-1]) # here -1 is r
print(demo[:-1]) |
4b34bbc30595863c8f248a5e64a294abcd700b54 | deepakdas777/anandology | /Modules/wget.py | 441 | 4.15625 | 4 | """Write a program wget.py to download a given URL. The program should accept a URL as argument, download it and save it with the basename of the URL. If the URL ends with a /, consider the basename as index.html."""
import os
import urllib
import sys
def wget(x):
r=urllib.urlopen(x)
cont=r.read()
name=x.split('/')
n=name[-1]
if n=='':
n='index.html'
f=open(n,'w')
print "saving %s as %s" %(x,n)
f.write(cont)
wget(sys.argv[1])
|
a01fc4a94ac45814fe041db385d746ad87487adf | rafaelperazzo/programacao-web | /moodledata/vpl_data/59/usersdata/158/47434/submittedfiles/testes.py | 103 | 3.828125 | 4 | # -*- coding: utf-8 -*-
#COMECE AQUI ABAIXO
l=int(input('digite o valor de l:'))
a=l*l
A=a*a
print(A)
|
c42e9e31a2ffd2d59b576aabef22283c4a7ed0ee | Kunika28/positive-numbers-in-a-list | /list.py | 184 | 3.8125 | 4 | list1=[12,-7,5,64,-14]
for num in list1:
if num>=0:
print(num,end=",")
list2=[12,14,-95,3]
for num2 in list2:
if num2>=0:
print(num2,end=",")
|
994b0186a999afd8386d63144b4ef1b565236f07 | iamsid2/Machine-Learning-using-Python | /Part 2 - Regression/Section 6 - Polynomial Regression/PolynomialRegression.py | 1,356 | 3.65625 | 4 | #polynomial regression
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#getting the dataset
dataset = pd.read_csv("Position_Salaries.csv")
X = dataset.iloc[:,1:2].values
y = dataset.iloc[:,2].values
#fitting linear regression in the model
from sklearn.linear_model import LinearRegression
lin_reg_1 = LinearRegression()
lin_reg_1.fit(X, y)
#fitting Polynomial Regression in the model
from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures(degree = 4)
X_poly = poly_reg.fit_transform(X, y)
lin_reg_2 = LinearRegression()
lin_reg_2.fit(X_poly, y)
#visualising the Linear Regression Model
plt.scatter(X, y, color = 'red')
plt.plot(X,lin_reg_1.predict(X), color = 'blue')
plt.title('Truth or Bluff(Lineqr Regression)')
plt.xlabel('Position Level')
plt.ylabel('Salary')
plt.show()
#visualising the Polyomial Regression model
X_grid = np.arange(min(X), max(X), 0.1)
X_grid = X_grid.reshape((len(X_grid), 1))
plt.scatter(X, y, color = 'red')
plt.plot(X_grid,lin_reg_2.predict(poly_reg.fit_transform(X_grid)), color = 'blue')
plt.title('Truth or Bluff(Lineqr Regression)')
plt.xlabel('Position Level')
plt.ylabel('Salary')
plt.show()
#Predicting a new result using Linear Regression
lin_reg_1.predict(6.5)
#Predicting a new result using Polynomial Regression
lin_reg_2.predict(poly_reg.fit_transform(6.5)) |
9ae9ccd2971941bc7438c58ae952af50d89b6a3b | tsuganoki/practice_exercises | /ProjectEuler/4.py | 515 | 4.125 | 4 | """A palindromic number reads the same both ways. The largest
palindrome made from the product of two 2-digit numbers is 9009 = 91 * 99.
Find the largest palindrome made from the product of two 3-digit numbers.
998001
10000
"""
import itertools
import functools
def is_pal(n):
fwd = list(str(n))
back = list(reversed(fwd))
return fwd == back
def products():
for i in range(999,900,-1):
for j in range(i,900,-1):
yield (i*j)
ans = max(filter(is_pal,products()))
print(ans)
|
4008e011efc9d7f07f84df1ace49027f8130e447 | sunilktm23/Python-Practice | /for_loop_list.py | 69 | 3.5 | 4 | fruits=['orange','apple','kiwi']
for fruits in fruits:
print(fruits) |
827ab4519ca041ff32394a5b77afee3db2c627a3 | swati-1008/Miles-to-Km-Converter | /main.py | 694 | 4.03125 | 4 | from tkinter import *
window = Tk()
window.title("Miles to Km Converter")
window.minsize(width=400, height=300)
window.config(padx = 20, pady = 20)
entry = Entry()
entry.grid(row = 0, column = 1)
label1 = Label(text = "Miles")
label1.grid(row = 0, column = 2)
label2 = Label(text = "is equal to")
label2.grid(row = 1, column = 0)
label3 = Label(text = "")
label3.grid(row = 1, column = 1)
label4 = Label(text = "Km")
label4.grid(row = 1, column = 2)
def button_clicked():
miles = float(entry.get())
km = miles * 1.609
km = int(km)
label3.config(text = km)
button = Button(text = "Calculate", command = button_clicked)
button.grid(row = 2, column = 1)
window.mainloop() |
032cb390599f9b0b085efb52176a63473cf85848 | Leyni/mycode | /acm/leetcode_0009.py | 479 | 3.625 | 4 | # -*- coding: utf-8 -*-
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0 : return False
y = 0
z = x
while z != 0 :
y = y * 10 + z % 10
z = z / 10
if x == y :
return True
else :
return False
# test data
# run
solution = Solution()
result = solution.isPalindrome(1000)
# output check
print result
|
9906bd4ba9a1f27f07612c2ee197381b94857fc3 | Rubixdude7/Python | /DijkstraAlgorithm.py | 1,390 | 3.78125 | 4 | #Python 3
#Nolan Aubuchon
#Dijkstra's Algorithm
'''
Still needs work, but nonetheless is a proof of concept
Note: the leftmost entry of the matrix is the starting position. The furthest right is the goal
With the given graph.txt file the output is:
minimum cost: 8
0 -> 4 -> 5 -> 6 -> 7
'''
from Matrix import Matrix
from pathstring import pathstring
matrix = Matrix()
blank = Matrix()
file = open("graph.txt")
string = file.readline()
while(string != ""):
matrix.addRow(eval(string))
string = file.readline()
size = matrix.size()
flags = [None] * size
paths = [None] * size
flags[0] = 0;
count = 1
for i in range(size):
blank.addRow([None] * size)
while(flags[-1] == None):
for i in range(size):
for j in range(i+1,size):
if(flags[i] != None and matrix.get(i,j) != None and
matrix.get(i,j) + flags[i] <= count and
(flags[j] == None or flags[j] > flags[i] + matrix.get(i,j))):
flags[j] = flags[i] +matrix.get(i,j)
paths[j] = i
blank.set(i,j,matrix.get(i,j))
blank.set(j,i,matrix.get(i,j))
count += 1
file.close()
print("minimum cost: %d\n" % flags[-1])
print(pathstring(paths))
input()
def pathstring(a = [0], index = -1):
if(index == 0):
return "0"
elif(index == -1):
return pathstring(a,a[index]) + " -> " + str(len(a)-1)
else:
return pathstring(a,a[index]) + " -> " + str(index)
#end
|
5a7b64c01048c0cbae17f299247b58370de7f21c | noobcakes33/Ladder11 | /282A_bit++.py | 254 | 4.0625 | 4 | statements = int(input())
x = 0
for i in range(statements):
statement = input()
if ("++X" in statement) or ("X++" in statement):
x += 1
elif ("--X" in statement) or ("X--" in statement):
x -= 1
else:
pass
print(x) |
3cd48bd12673a18c17c16ff9f02a890ab51826b1 | tkoz0/problems-project-euler | /p193a.py | 898 | 3.625 | 4 | import libtkoz as lib
import math
limit = 2**50
# count with inclusion-exclusion
# subtract numbers with 1 prime square as a factor
# add numbers with 2 prime squares as a factor
# continue until limit / (2^2*3^2*5^2*7^2*...) is 0
# ~45sec (pypy / i5-2540m)
plist = lib.list_primes2(int(math.sqrt(limit)))
print(': listed',len(plist),'primes up to',int(math.sqrt(limit)))
count = limit
# product of prime squares, count of prime squares, next prime index
def recurse(sqprod,sqcount,pi):
global limit, plist, count
if sqcount != 0: # count with inclusion-exclusion
if sqcount % 2 == 0: count += limit//sqprod
else: count -= limit//sqprod
for nextp in range(pi,len(plist)):
nsqprod = sqprod * (plist[nextp]**2)
if nsqprod > limit: return # never call with too large square product
recurse(nsqprod,sqcount+1,nextp+1)
recurse(1,0,0)
print(count)
|
2375fc9ba793e91170bd7d3b3526ee22d92eaca9 | NearJiang/PythonReview | /Class.py | 880 | 3.90625 | 4 | #ๅจPythonไธญ๏ผๅฎไพ็ๅ้ๅๅฆๆไปฅ__ๅผๅคด๏ผๅฐฑๅๆไบไธไธช็งๆๅ้๏ผprivate๏ผ
#ๅชๆๅ
้จๅฏไปฅ่ฎฟ้ฎ๏ผๅค้จไธ่ฝ่ฎฟ้ฎ
class Student(object):
def __init__(self, name, gender):
self.name = name
self.__gender = gender
def get_gender(self): #get่ทๅไปไน็ ็ดๆฅreturnๅฐฑ่ก
return self.__gender
def set_gender(self,gender): #setๅบไธ่ฆๅ =
if gender not in ('male','female'):
print('่ฏท้ๆฐ่พๅ
ฅ')
self.__gender=gender
class Student(object):
def get_score(self):
return self._score
def set_score(self, value):
if not isinstance(value, int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueError('score must between 0 ~ 100!')
self._score = value
|
4500f2a8fefcee1b622eb8e5dab68bd6ee0ea933 | Suvey57/assignment2 | /pa10.py | 702 | 3.953125 | 4 | def change_snake_case(str):
res = [str[0].lower()]
for c in str[1:]:
if c in ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
res.append('_')
res.append(c.lower())
else:
res.append(c)
return ''.join(res)
def changekebabcase(str):
res = [str[0].lower()]
for c in str[1:]:
if c in ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
res.append('-')
res.append(c.lower())
else:
res.append(c)
return ''.join(res)
a=input("enter a string in camel case::")
print("the output in snake_case is::",change_snake_case(a))
print("the output in kebab-case is::",changekebabcase(a)) |
e1f049b8cf95110cda5d2f786b58892881075320 | fhansmann/coding-basics | /module-1/email-slicer.py | 328 | 3.9375 | 4 | # get user email
email = input("What is your email address?:").strip()
# slice out user name
user = email[:email.index("@")]
# slice out domain name
domain = email[email.index("@")+1:]
# format message
output = "Your username is {} and you domain name is {}".format(user,domain)
# display output message
print(output)
|
5f8112047b4f9cd13c544e00e4e2bfdb68857517 | pockerman/tech3python | /applications/numerics/example_2.py | 1,075 | 3.6875 | 4 | """
Category: Numerics, Integration
ID: Example 2
Description: Calculate PI using Monte Carlo integration
Taken From the book: Kalman and Bayesian Filters in Python
Dependencies:
Details:
# TODO: Write details for Monte Carlo integration
"""
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import uniform
def f(x):
return x*x
def main():
N = 20000
radius = 1
area = (2*radius)**2
pts = uniform(-1, 1, (N,2))
# distance from center
dist = np.linalg.norm(pts, axis=1)
in_circle = dist <= 1
pts_in_circle = np.count_nonzero(in_circle)
pi = area * (pts_in_circle/N)
print('mean pi(N={})= {:.4f}'.format(N, pi))
print('err pi(N={})= {:.4f}'.format(N, np.pi - pi))
# plot results
plt.scatter(pts[in_circle,0], pts[in_circle,1], marker=',', edgecolor='k', s=1)
plt.scatter(pts[~in_circle,0], pts[~in_circle,1], marker=',', edgecolor='r', s=1)
plt.axis('equal')
plt.show()
if __name__ == '__main__':
print("Running Example numerics/example_2")
main()
print("Done...") |
fc988e33387dbdc8c5c68687efca8aa8eba5105d | kashyap92/python-training | /file1.py | 263 | 3.59375 | 4 | #!/usr/bin/python
import sys
#file=raw_input("enter the file name:")
#filename=sys.argv[0]
#file=str(sys.argv[1])
file1=open(str(sys.argv[1]))
lines=file1.readline()
a=1
while lines:
print a,lines
lines=file1.readline()
a+=1
file1.close()
|
be6e414d39a47cd95a32531efdf81bfb0aef89c4 | gahan9/DS_lab | /LPW/two_pass_sort_based.py | 11,522 | 3.84375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Author: Gahan Saraiya
GiT: https://github.com/gahan9
StackOverflow: https://stackoverflow.com/users/story/7664524
Implementation of sorting based two pass algorithm
for difference operator
"""
import os
import math
from itertools import islice
from faker import Faker
fak = Faker()
class Iterator(object):
"""
Iterator class to add tuple in form of table
attributes -> <attrib1, attrib2, attrib3,...>
Adding values
values -> <val1, val2, val3, ....>
"""
def __init__(self, attribute_tuple, data_one_path, data_two_path, *args, **kwargs):
"""
:param attribute_tuple: attribute tuple in form of string containing attributes of file (if to be created)
:param data_one_path: path to first data file
:param data_two_path: path to second data file
:param args:
:param kwargs:
"""
self.attributes = attribute_tuple
self.data_one_path = data_one_path
self.data_two_path = data_two_path
self.write_back_folder = kwargs.get("write_back_path", "phase_one_write_back")
self.separator = "\t"
self.records_per_block = kwargs.get("records_per_block", 30)
self.initialize_file()
# print("{0}\n{1}Consideration{1}\n"
# "Records per block: {2}\n"
# "Total Records: {3}\n{0}\n".format("#"*50, "-"*10, self.records_per_block, self.total_records)
# )
@property
def free_memory(self):
# calculate how many blocks can be accommodated in memory buffer
num_lines = sum(1 for line in open(self.data_one_path))
no_of_records = num_lines - 2 # remove header line and last new line
return 101 # for now return available memory statically for basic implementation
@property
def total_blocks(self):
# calculate total number of blocks by record size
return math.ceil(self.total_records / self.records_per_block)
@property
def total_records(self):
# calculate total number of blocks by record size
num_lines = sum(1 for line in open(self.data_one_path))
no_of_records = num_lines - 2 # remove header line and last empty line
return no_of_records
@property
def can_be_one_pass(self):
return False # for testing
# return True if self.total_blocks < self.free_memory else False
@property
def can_be_two_pass(self):
return True # for testing
# return True if self.free_memory > math.ceil(math.sqrt(self.total_blocks)) else False
def initialize_file(self):
# create write back directory for phase 1
os.makedirs(self.write_back_folder, exist_ok=True)
# check if file exits or not
for file_path in [self.data_one_path, self.data_two_path]:
if os.path.exists(file_path):
pass
else:
# create file with header if file not exist
with open(file_path, "w") as f:
f.write(self.separator.join(self.attributes))
f.write("\n")
return True
@staticmethod
def summary(total_results, total_records):
print("-"*30)
print("Total Results: {}".format(total_results))
print("Total Records: {}".format(total_records))
return True
@staticmethod
def split_file_in_blocks(file_obj, split_size):
blocks = []
while True:
block_records = list(islice(file_obj, split_size))
if not block_records:
break
else:
blocks.append(block_records)
return blocks
@staticmethod
def create_file_obj(attribute):
file_name = "output_distinct_on_{}.tsv".format(attribute)
return open(file_name, "w")
def difference_of(self, on_attribute, only_summary=True, output_write=False):
output_obj = self.create_file_obj(on_attribute) if output_write else None
sort_key = on_attribute
print("{0}\n DIFFERENCE ON ATTRIBUTE {1}\n{0}".format('#'*50, sort_key))
_result_set = []
if self.can_be_one_pass:
print("Processing One Pass Algorithm")
print("Exiting as the program meant to be use two-pass sort based algorithm")
raise NotImplementedError
elif self.can_be_two_pass:
# apply 2 pass algorithm to sort and use operation on database
print("Processing Two Pass Algorithm")
# PHASE 1 -----------------------------------------------------------------------------------------------
file_pointer_one = open(self.data_one_path, "r")
file_pointer_two = open(self.data_two_path, "r")
header_one = file_pointer_one.readline()
header_two = file_pointer_two.readline()
# writer = open(self.write_back_path, "w")
# writer.write(header)
_idx = header_one.split(self.separator).index(sort_key)
file_order_one = 0 # finally a number contains total number of split/sublist file
file_order_two = 0 # finally a number contains total number of split/sublist file
for i, f in enumerate([file_pointer_one, file_pointer_two]):
file_order = 0
while True:
block_records = list(islice(f, self.free_memory - 1))
# read blocks one by one
if not block_records:
break
else:
file_order += 1
# sort sublist by "ssn" or any other attribute
writer = open(os.path.join(self.write_back_folder, "temp{}_00{}".format(i+1, file_order)), "w")
# writer.write(header)
sorted_sublist = sorted(block_records, key=lambda x: x.split(self.separator)[_idx])
# write sorted block/sublist data back to disk(secondary memory)
writer.writelines(sorted_sublist)
writer.close()
f.close()
if i == 0:
file_order_one = file_order
else:
file_order_two = file_order
# PHASE 2 -----------------------------------------------------------------------------------------------
# Performing difference of first - second
partition_ptr_lis_one = [open(os.path.join(self.write_back_folder, "temp1_00{}".format(i)), "r")
for i in range(1, file_order_one+1)]
partition_ptr_lis_two = [open(os.path.join(self.write_back_folder, "temp2_00{}".format(i)), "r")
for i in range(1, file_order_two+1)]
phase2_data_one = [i.readline().split(self.separator)[_idx] for i in partition_ptr_lis_one] # get first element from each sublist
phase2_data_two = [i.readline().split(self.separator)[_idx] for i in partition_ptr_lis_two] # get first element from each sublist
# read sublist from each block and output desire result
total_results = 0
total_ignored = 0
last_read = None
# for line in open(self.write_back_path, "r"):
while any(phase2_data_one): # loop over data from whose you will perform minus operator
temp_lis_one = list(filter(None, phase2_data_one)) if None in phase2_data_one else phase2_data_one
temp_lis_two = list(filter(None, phase2_data_two)) if None in phase2_data_two else phase2_data_two
min_one = min(temp_lis_one)
chunk_no_one = phase2_data_one.index(min_one)
next_record_one = partition_ptr_lis_one[chunk_no_one].readline()
if temp_lis_two:
min_two = min(temp_lis_two)
chunk_no_two = phase2_data_two.index(min_two)
next_record_two = partition_ptr_lis_two[chunk_no_two].readline()
if min_one < min_two:
if next_record_one:
phase2_data_one[chunk_no_one] = next_record_one.split(self.separator)[_idx]
else:
# file/sublist has nothing to load/read
del partition_ptr_lis_one[chunk_no_one]
del phase2_data_one[chunk_no_one]
elif min_one > min_two:
if next_record_two:
phase2_data_two[chunk_no_two] = next_record_one.split(self.separator)[_idx]
else:
# file/sublist has nothing to load/read
del partition_ptr_lis_two[chunk_no_two]
del phase2_data_two[chunk_no_two]
elif min_one == min_two:
for i, next_record in enumerate([next_record_one, next_record_two]):
if i == 0:
phase2_data, chunk_no, partition_ptr_lis = phase2_data_one, chunk_no_one, partition_ptr_lis_one
else:
phase2_data, chunk_no, partition_ptr_lis = phase2_data_two, chunk_no_two, partition_ptr_lis_two
if next_record:
phase2_data[chunk_no] = next_record_one.split(self.separator)[_idx]
else:
# file/sublist has nothing to load/read
del partition_ptr_lis[chunk_no]
del phase2_data[chunk_no]
if min_one != min_two and min_one != last_read:
if not only_summary:
print(min_one)
if output_write:
output_obj.write(min_one + "\n")
total_results += 1
last_read = min_one
else:
# if there is data in first data table but no data in second data table
if next_record_one:
phase2_data_one[chunk_no_one] = next_record_one.split(self.separator)[_idx]
else:
# file/sublist has nothing to load/read
del partition_ptr_lis_one[chunk_no_one]
del phase2_data_one[chunk_no_one]
if min_one:
if not only_summary:
print(min_one)
if output_write:
output_obj.write(min_one + "\n")
total_results += 1
self.summary(total_results, self.total_records)
else:
# can not proceed all given blocks with memory constraint
print("Require more than two pass to handle this large data")
raise NotImplementedError
return _result_set
if __name__ == "__main__":
table = Iterator(attribute_tuple=("name", "ssn", "gender", "job", "company", "address"),
data_one_path="data_two.dbf",
data_two_path="data_one.dbf")
# table.difference_of(on_attribute="name", only_summary=True, output_write=True)
table.difference_of(on_attribute="name", only_summary=False, output_write=True)
|
4328f2e45afab5e8e4eef6cf21f440e3fd530f49 | Lucas-vdr-Horst/Mastermind-extraExercises | /exercise-1/Palindroom.py | 336 | 4.0625 | 4 | def reverse_string(string):
return string[::-1]
"""new_string = ""
for i in range(len(string)):
new_string += string[len(string) - (i+1)]
return new_string"""
def is_palindrome(string):
return string.lower() == reverse_string(string).lower()
if __name__ == "__main__":
print(is_palindrome("Racecar")) |
945d56447945142d04c61682df1a13794d043a23 | MastProTech/Advent-of-Code | /2015/25.py | 665 | 3.609375 | 4 | def part_1(find_row, find_col):
size=max(find_col, find_row)*2 # Because the table should be square (cols=rows) and half of the table is zero
table=[[0 for i in range(size)] for i in range(size)] # Declaring table with zeros
num=20151125 # Initial number
for limit in range(0,size+1):
for i in range(0, limit):
row=limit-i
col=i+1
if row==find_row and col==find_col: # Required location found or not?
print('Part 1: At location (',row,',',col,') :',num)
return
table[row-1][col-1]=num
num=(num*252533)%33554393
part_1(find_row=2947, find_col=3029)
|
57127981adcc3f050b48217c3f8423419983565d | SvenLC/CESI-Algorithmique | /boucles/exercice1.py | 282 | 3.953125 | 4 | # Ecrire un algorithme demande ร lโutilisateur un nombre compris entre 1 et 3 jusquโร ce que la rรฉponse convienne.
def nombre_entre_1_et_3():
nb = 0
while (nb < 1 or nb > 3):
nb = int(input("Veuillez saisir un nombre entre 1 et 3"))
nombre_entre_1_et_3()
|
9aea7e155bb6f5ac47460baa2c1ac732f321c507 | shifteight/python | /pythontips/decorator_demo.py | 566 | 3.640625 | 4 | from functools import wraps
def a_new_decorator(a_func):
@wraps(a_func)
def wrapTheFunction():
print("I am doing some boring work before executing a_func()")
a_func()
print("I am doing some boring work after executing a_func()")
return wrapTheFunction
@a_new_decorator
def a_function_requiring_decoration():
"""Hey yo! Decorate me!"""
print("I'm the function which need some decoration to "
"remove my foul smell")
print(a_function_requiring_decoration.__name__)
print(a_function_requiring_decoration.__doc__) |
30ada7240528be8d842042b57b97b202e8e553a3 | IntAlgambra/candyapi | /candyapi/candyapi/utils.py | 866 | 3.921875 | 4 | from datetime import datetime
class WrongTimezoneError(Exception):
"""
ะะพะทะฒัะฐัะฐะตััั ะฟัะธ ะฟะพะฟััะบะต ะฟะตัะตะดะฐัั ะดะฐัั ะธ ะฒัะตะผั ะฝะต ะฒ UTC ะธะปะธ ะฑะตะท ะฒัะตะผะตะฝะฝะพะน ะทะพะฝั
"""
def __init__(self):
super(WrongTimezoneError, self).__init__("Datetime is not timezone aware")
def format_time(t: datetime) -> str:
"""
ะคะพัะผะฐัะธััะตั datetime ะพะฑัะตะบั ะบ ัะพัะผะฐัั "YYYY-MM-DDTHH:MM:SS.ssZ"
(ะบะฐะบ ะฒ assigment). ะัะตะณะดะฐ ะฟัะธะฝะธะผะฐะตั ะพะฑัะตะบั datetime ั ะฒัะตะผะตะฝะฝะพะน ะทะพะฝะพะน UTC,
ะตัะปะธ ะฝะตั ะฒัะตะผะตะฝะฝะพะน ะทะพะฝั, ะธะปะธ ะฒัะตะผั ะฝะต ะฒ UTC ะฒะพะทะฑัะถะดะฐะตััั ะธัะบะปััะตะฝะธะต
"""
if t.tzname() != "UTC":
raise WrongTimezoneError()
return "{}{}".format(t.isoformat(timespec="microseconds")[:-10], "Z")
|
959fcee23e4fac49ebfbf745cc7ec6f3e38e3a2e | ElephantGit/tensorflow_learn | /tf_basic/my_mnist.py | 3,439 | 3.59375 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# save mnist dataset in the folder of MNIST_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
# define variable weights and biases
def weight_variable(shape):
initial = tf.random_normal(shape)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.random_normal(shape)
return tf.Variable(initial)
# define convolution and pooling operation
def conv2d(x, w):
return tf.nn.conv2d(x, w, strides=[1,1,1,1], padding='SAME')
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='VALID')
# define the shape of input and output and keep probability
xs = tf.placeholder(tf.float32, [None, 784])
ys = tf.placeholder(tf.float32)
keep_prob = tf.placeholder(tf.float32)
# reshape the input image
x_image = tf.reshape(xs, [-1, 28, 28, 1])
# the first layer
w_conv1 = weight_variable([5,5,1,32]) # shape=[kernel, kernel, channel, featuremap]
b_conv1 = bias_variable([32]) # shape=[featuremap]
# convolution layer of layer1
h_conv1 = tf.nn.relu(conv2d(x_image, w_conv1) + b_conv1)
# pooling layer of layer1
h_pool1 = max_pool_2x2(h_conv1)
# the second layer
w_conv2 = weight_variable([5, 5, 32, 64]) # 64 is manual determine
b_conv2 = bias_variable([64])
# convolution layer of layer2
h_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2) + b_conv2)
# pooling layer of layer2
h_pool2 = max_pool_2x2(h_conv2)
# fully connected layer
# [n_samples, 7, 7, 64] ->> [n_samples, 7*7*64] reshape the h_pool2 from 3D tensor to 1D tensor
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) # the output of second pooling layer is 7*7*64
w_fc1 = weight_variable([7*7*64, 1024]) # 1024 is manual determine
b_fc1 = bias_variable([1024])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, w_fc1) + b_fc1)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
# the last layer: output fully connected layer
w_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
prediction = tf.nn.softmax(tf.matmul(h_fc1_drop, w_fc2) + b_fc2)
# loss function defined by cross entropy
cross_entropy = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=ys) )
# train
train_step = tf.train.AdamOptimizer(0.0001).minimize(cross_entropy)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
# start the train
batch_size = 128
hm_epoches = 10
#for i in range(1000):
# epoch_x, epoch_y = mnist.train.next_batch(1)
# _, c = sess.run([train_step, cross_entropy], feed_dict={xs: epoch_x, ys: epoch_y, keep_prob: 0.5})
# if i % 50 == 0:
# print(c)
saver = tf.train.Saver()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for epoch in range(hm_epoches):
epoch_loss = 0
for _ in range(int(mnist.train.num_examples/batch_size)):
epoch_x, epoch_y = mnist.train.next_batch(batch_size)
_, c = sess.run([train_step, cross_entropy], feed_dict={xs: epoch_x, ys: epoch_y, keep_prob: 0.5})
epoch_loss += c
print('Epoch', epoch, 'completed out of', hm_epoches, 'loss:', epoch_loss)
correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(ys, 1))
accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
print('Accuracy:', accuracy.eval({xs: mnist.test.images, ys: mnist.test.labels}))
save_path = saver.save(sess, "my_mnist_net.ckpt")
print("Save to path: ", save_path)
|
bec44ca975a1444b5a61b738d9a62b3eea96c5f0 | zipxup/SearchAlgorithm | /SearchAlgorithm/WeightedGraph.py | 4,167 | 3.765625 | 4 | class Node:
def __init__(self, key, heuristic = 0):
# self.key is the key of node
# self.successors are the successors nodes
# self.weight is the weight of edges
self.key, self.heuristic = key, heuristic
self.precessors, self.weight_precessors = [], {}
self.successors, self.weight_successors = [], {}
#return node's key
def getKey(self):
return self.key
#return node's heuristic that estimates the cost of the cheapest path from n to the goal
def getHeuristic(self):
return self.heuristic
#return precessors of node
def getPrecessors(self):
return self.precessors
#return successors of node
def getSuccessors(self):
return self.successors
#return weight of precessors:
def getWeightPrecessors(self):
return self.weight_precessors
#return weight of successors:
def getWeightSuccessors(self):
return self.weight_successors
def addPrecessors(self, node, weight):
# check whether this node exists
if node.getKey() not in self.weight_precessors:
self.precessors.append(node)
self.weight_precessors[node.getKey()] = weight
def addSuccessors(self, node, weight):
# check whether this node exists
if node.getKey() not in self.weight_successors:
self.successors.append(node)
self.weight_successors[node.getKey()] = weight
class Graph:
def __init__(self):
# key is the key of node
# value is the instance of Node
self.nodes = {}
# add a node in the graph
def addNode(self, key, heuristic = 0):
# check if the key already exists
if key not in self.nodes:
node = Node(key, heuristic)
self.nodes[key] = node
else:
print('key: %s already exists' % key)
def getNodeHeuristic(self, key):
if key not in self.nodes:
print('key: %s not exist' % key)
else:
node = self.nodes[key]
return node.getHeuristic()
# connect two nodes with weight
def connectNodes(self, sourceKey, destKey, weight):
# check if those keys exist in the graph
if sourceKey not in self.nodes or destKey not in self.nodes:
print('key does not exist')
return
# check whether they share same key
if sourceKey == destKey:
print('same keys')
return
# check weight, only accept positive numbers
if weight <= 0:
print('weight should be positive')
return
self.nodes[sourceKey].addSuccessors(self.nodes[destKey], weight)
self.nodes[destKey].addPrecessors(self.nodes[sourceKey], weight)
#return weight of edge
def getEdgeWeight(self, sourceKey, successor):
if sourceKey not in self.nodes or successor not in self.nodes:
print('key does not exist')
return
# check whether they share same key
if sourceKey == successor:
print('same keys')
return
weight_successors = self.nodes[sourceKey].getWeightSuccessors()
# check if successor is in successors list
if successor not in weight_successors:
print('successor not exist')
return
return weight_successors[successor]
# return keys of all precessors of a node
def getPrecessors(self, key):
if key not in self.nodes:
print('key does not exist')
return
precessors = self.nodes[key].getPrecessors()
key_precessors = [node.getKey() for node in precessors]
return sorted(key_precessors)
# return keys of all successors of a node
def getSuccessors(self, key):
if key not in self.nodes:
print('key does not exist')
return
successors = self.nodes[key].getSuccessors()
key_successors = [node.getKey() for node in successors]
return sorted(key_successors)
# return all nodes
def getNodes(self):
return self.nodes
|
3f165f5bdaa14f0808d4b416beb188e707ff0384 | ruozhizhang/leetcode | /problems/string/Maximum_Score_After_Splitting_a_String.py | 1,288 | 3.921875 | 4 | '''
https://leetcode.com/problems/maximum-score-after-splitting-a-string/
Given a string s of zeros and ones, return the maximum score after splitting the
string into two non-empty substrings (i.e. left substring and right substring).
The score after splitting a string is the number of zeros in the left substring
plus the number of ones in the right substring.
Example 1:
Input: s = "011101"
Output: 5
Explanation:
All possible ways of splitting s into two non-empty substrings are:
left = "0" and right = "11101", score = 1 + 4 = 5
left = "01" and right = "1101", score = 1 + 3 = 4
left = "011" and right = "101", score = 1 + 2 = 3
left = "0111" and right = "01", score = 1 + 1 = 2
left = "01110" and right = "1", score = 2 + 1 = 3
Example 2:
Input: s = "00111"
Output: 5
Explanation: When left = "00" and right = "111", we get the maximum score = 2 + 3 = 5
Example 3:
Input: s = "1111"
Output: 3
Constraints:
2 <= s.length <= 500
The string s consists of characters '0' and '1' only.
'''
class Solution:
def maxScore(self, s: str) -> int:
res = 0
l0, r1 = 0, s.count('1')
for i in range(len(s) - 1):
if s[i] == '0':
l0 += 1
else:
r1 -= 1
res = max(res, l0 + r1)
return res
|
0abab0a476f9870916343fbd4bbea8c8ccd09e86 | collin-li/mitx-6.00.1x | /ps4/ps4_2.py | 1,434 | 4.25 | 4 | # PROBLEM
#
# The player starts with a hand, a set of letters. As the player spells out
# words, letters from this set are used up. For example, the player could start
# out with the following hand: a, q, l, m, u, i, l. The player could choose to
# spell the word quail. This would leave the following letters in the player's
# hand: l, m. Your task is to implement the function updateHand, which takes in
# two inputs - a hand and a word (string). updateHand uses letters from the
# hand to spell the word, and then returns a copy of the hand, containing only
# the letters remaining.
#
# Implement the updateHand function. Make sure this function has no side
# effects: i.e., it must not mutate the hand passed in.
# SOLUTION
def updateHand(hand, word):
"""
Assumes that 'hand' has all the letters in word.
In other words, this assumes that however many times
a letter appears in 'word', 'hand' has at least as
many of that letter in it.
Updates the hand: uses up the letters in the given word
and returns the new hand, without those letters in it.
Has no side effects: does not modify hand.
word: string
hand: dictionary (string -> int)
returns: dictionary (string -> int)
"""
handCopy = hand.copy() # Create copy of hand to prevent mutation
# Remove used letters from hand
for letter in word:
handCopy[letter] -= 1
return handCopy
|
439a0bc5f2b7091c4452deac803ccea1a0e5b756 | 19973466719/Python-- | /ๅพ็ตๅญฆ้ข่ฏพ็จ/self learning/003ใๅๆฏ็ปๆ/2ใๅพช็ฏ็ปๆ.py | 1,304 | 3.640625 | 4 | '''
forๅพช็ฏ
for ๅ้ in ๅบๅ๏ผ
่ฏญๅฅ1
่ฏญๅฅ2...
'''
stu_list=['็ๅคง็','ๆ็พไธฝ','็ๆ้']
for stu in stu_list:
if stu=='็ๆ้':
print('ni you')
else:
print('sorry')
'''
for else่ฏญๅฅ
ๆๅฐๅ่กจไธญ็ๅๅญฆ๏ผ
ๅฆๆๆฒกๆๅจๅ่กจไธญ๏ผๆไปฌ้่ฆๆๅฐๆ็คบ่ฏญๅฅ่กจ็คบๅพช็ฏ็ปๆ
'''
'''
break:ๆ ๆกไปถ็ปๆๆดไธชๅพช็ฏ๏ผๅพช็ฏ็ๆญป
continue๏ผ็ปง็ปญไธไธๆฌกๅพช็ฏ
pass๏ผๅ ไฝ็ฌฆ ,ไปฃ่กจ่ฟๅฅ่ฏๅฅไนไธๅนฒ๏ผๆฒกๆ่ทณ่ฟ็ๅ่ฝ
'''
#break ็กฎๅฎๆฏๅฆๅ
ๅซ7 ็กฎๅฎๅฐฑ็ดๆฅๆๅฐไธไธช ๅบ็ฐไบไนๅ็ดๆฅ่ทณๅบๅพช็ฏ
num_list=[1,2,3,4,5,6,7,8]
for i in num_list:
if i==7:
print(i)
break
else:
print(i)
#continue ็ปๆๆฌ่ฝฎๅพช็ฏ๏ผ็ปง็ปญไธไธๆฌกๅพช็ฏ
dig_list=[1,2,3,4,5,6,7,8,9,10]
for i in dig_list:
if i%2==1:
continue
print(i)
#passๆกไพ1 ๅ ไฝ็ฌฆ
age=19
if age>19:
pass
else:
print("ไฝ ่ฟๅฐ")
#passๆกไพ2
ages=[2,23,43,54,65,2]
for age in ages:
pass
print(age)
#rangeๅฝๆฐ๏ผ็ๆๆๅบๆฐๅ ๅทฆ้ญๅณๅผ ๅจPythonไธญๅชๆrandintๆฏๅๅค
'''
#whileๅพช็ฏ๏ผ้็จไบไธ็ฅ้ๅพช็ฏๆฌกๆฐ
while ๆกไปถ่กจ่พพๅผ:
่ฏญๅฅ1
else๏ผ
่ฏญๅฅ2
'''
benqian=100000
year=0
while benqian<200000:
benqian *=1.067
year+=1
print(year) |
ac24d2718663efeea5d745a125c24df26192c41d | lotar69/projet_lj | /src/file.py | 461 | 3.609375 | 4 | #Class Imports:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv("data/water_potability.csv")
#Class Info:
print(df.info())
print(df.shape)
print(df.head())
#Class Cleaning:
print(df["Potability"].value_counts())
print(df.isna().sum())
df["Potability"] = df["Potability"].astype("category")
print(df.info())
#Class Visualisation:
#Class MachineLearning:
#Preprocessing
#Training
#Predict
|
d3cc5d7da27a71e943eb97d010c98e3d651f34e7 | psaux0/ExData_Plotting1 | /fl.py | 504 | 3.625 | 4 | #! /usr/bin/env python3.5
def main():
i = 0
with open("data.txt") as f:
for line in f:
if line.startswith("1/2/2007"):
j = i
break
else:
i += 1
for line in f:
if line.startswith("3/2/2007"):
k = i
break
else:
i += 1
print("{0} lines to be skipped and {1} to be read".format(j,k - j + 1))
if __name__ == "__main__":
main()
|
f5950952a13e2e244ae58adda6cedb959870aa36 | thisisparthjoshi/Basic-Programs | /Swap.py | 156 | 4.0625 | 4 | # -*- coding: utf-8 -*-
x=eval(input("enter x"))
y=eval(input("enter y"))
x,y=y,x
print("after swapping x =",x)
print("after swapping y =",y)
|
2e3fa9b718fb26a1bbf67ed442a65fcb3820e137 | ansj11/DeepLearning | /code/python/find_value.py | 455 | 3.703125 | 4 | # -*- coding:utf-8 -*-
class Solution:
def Find(self,target,array):
if len(array)==1 and len(array[0])==0:
return False
has_value = 0
for i in array:
for j in i:
if j==target:
has_value += 1
else:
has_value +=0
if has_value==0:
return False
else:
return True
|
ccea36440cb4663ff9fb4edfc78779bb64bf795a | MrHamdulay/csc3-capstone | /examples/data/Assignment_8/mrkpet004/question1.py | 554 | 4.34375 | 4 | """program with a recursive function to calculate whether or not a string is a palindrome
peter m muriuki
9/5/14"""
def reverse(string):
# base case - empty string
if len(string)==0:
return string
# recursive step
else:
return reverse(string[1:]) + string[0]
string=input("Enter a string:\n")
s_not="Not a palindrome!"
s_is="Palindrome!"
def palstr(string):
if string=="":
return s_not
elif string==reverse(string):
return s_is
else:
return s_not
print (palstr(string)) |
203ca8622da45f73d6f198a9bf5a85b0ea51fb00 | engineer-kufre/Python-Task-1 | /app.py | 128 | 4.28125 | 4 | radius = int(input('Enter radius: '))
area = 3.142 * radius ** 2
print(f'The area of a circle with radius {radius} is {area}') |
8eca291454dad5c0db3ed8bcb9412f6fff2552ae | JoaoCFN/Exercicios_DS2 | /contabanco/Banco.py | 564 | 3.578125 | 4 | class Banco():
def __init__(self, nome_banco, ano_fundacao):
self.nome_banco = nome_banco
self.ano_fundacao = ano_fundacao
self._lista_agencias = []
def adicionar_agencia(self, agencia):
agencia_nao_existe = self._lista_agencias.count(agencia) == 0
if agencia_nao_existe:
self._lista_agencias.append(agencia)
def listar_agencias(self):
for agencia in self._lista_agencias:
print("Nรบmero da agรชncia: {}".format(agencia.numero))
agencia.listar_contas()
|
b7f09db495f6a0cdcafc68293537472b22853c30 | mervecakirr/study.lib | /2_sinif/donem2/h2/algo_odev_1/main.py | 1,602 | 3.703125 | 4 | # python 3.7 ile รงalฤฑลtฤฑrฤฑm0
from collections import defaultdict
class Graph:
def __init__(self, matrix, select):
self.visited = []
self.select = select;
self.graph = defaultdict(list);
self.edge_count = 0
for ix, line in enumerate(matrix):
for iy, edge in enumerate(line):
if int(edge):
self.edge_count += 1
self.add_edge(ix + 1, iy + 1)
def add_edge(self, u, v):
self.graph[u].append(v)
def dfs(self):
self.dfs_partition(self.select)
print()
def dfs_partition(self, node):
if node not in self.visited:
print(node, end=" ")
self.visited.append(node)
for neighbour in self.graph[node]:
self.dfs_partition(neighbour)
def edge_count(self):
pass
def print_io(self):
out = len(self.graph[self.select])
_in = 0
for i in self.graph:
if self.select in self.graph[i]:
_in += 1
print(f"Giris: {_in} Cฤฑkฤฑs: {out}")
def main():
matrix = []
with open("./matrix.txt") as f:
for line in f.readlines():
line = line.replace("\n", "")
line = line.replace(" ", "")
matrix.append(line)
g = Graph(matrix, int(input("Dรผgรผm >> ")))
print("DFS", end=" ")
g.dfs()
g.print_io()
print("Kenar sayฤฑsฤฑ", g.edge_count)
print(g.graph)
def print_matrix(m):
for line in m:
print(line)
if __name__ == "__main__":
main(); |
56fff0c8cd74a37ea1d5bf58a310fcc2f0dd0eb7 | SwathiChennamaneni/repo1 | /Assignments/Assignment_15.py | 324 | 4.3125 | 4 | #Assignment 15
#Take a string from the user and check contains atleast one small letter or not?
user_string = raw_input("Enter a String:")
count = False
for char in user_string:
if char.islower():
count = True
if count == True:
print "\nContains Small Letter"
else:
print "\nContains No Small Letters"
|
fded9b144cddb6c04e4789421b4fc11ab1bc4849 | KrylovKA/Pytest_iTrack | /Learning Python/Learning_Python.py | 1,579 | 3.875 | 4 | import sys
"""Day_1 - 23.03.2020"""
# Chapter_1(Arguments)
print('Hello World!')
var = 555 # ะฆะตะปะพะต ัะธัะปะพ
print(var)
var = 3.155 # ะงะธัะปะพ ั ะฟะปะฐะฒะฐััะตะน ัะพัะบะพะน
print(var)
var = True # ะัะปะตะฒะฐั ะปะพะณะธะบะฐ True/False
print(var)
semantic = 5
print(semantic*5+5)
# Chapter_2(Input)
# # ะะฝะธัะธะฐะปะธะทะธััะตะผ ะฟะตัะตะผะตะฝะฝัั ะทะฝะฐัะตะฝะธะตะผ, ะฒะฒะตะดะตะฝะฝัะผ ะฟะพะปัะทะพะฒะฐัะตะปะตะผ
# user = input('My name is Buldakov Mazafaka. What is your name?:')
# ะัะฒะพะดะธะผ ัััะพะบั ะธ ะทะฝะฐัะตะฝะธะต ะฟะตัะตะผะตะฝะฝะพะน
# print('Welcome', user)
# # ะะฝะธัะธะฐะปะธะทะธััะตะผ ะตัะต ะพะดะฝั ะฟะตัะตะผะตะฝะฝัั ะทะฝะฐัะตะฝะธะตะผ, ะฒะฒะตะดะตะฝะฝัะผ ะฟะพะปัะทะพะฒะฐัะตะปะตะผ
# user_Kirayl = input('My name is Aleksandr Buldakov Mazafaka. What is your name?:')
# # ะัะฒะพะดะธะผ ัััะพะบั ะธ ะทะฝะฐัะตะฝะธะต ะฟะตัะตะผะตะฝะฝะพะน
# print('Yo', 'Ho', 'Ho,', 'Hello', user_Kirayl, sep='*', end='555')
# Chapter_3(Operators)
a = 20
b = 2
c = 5
print('Addition:\t', a, '+', b, '=', a+b) # 3.1
print('Subtraction:\t', a, '-', b, '=', a-b) # 3.2
print('Multiplication:\t', a, '*', b, '=', a*b) # 3.3
print('Division:\t', a, '/', b, '=', a/b) # 3.4
print('Floor Division:\t', a, '//', b, '=', a//b) # 3.5
print('Modulus:\t', a, '%', b, '=', a % b) # 3.6
print('Modulus of number:\t', a, 'abs(a)', b, '=', abs(a)) # 3.7
print('a^b for modules c:\t', a, 'pow(a,b[,c])', b, '=', pow(a, b)) # 3.8
print('Less c:\t', a, '<', b, a < b) # 3.9
print('Less c:\t', a, '>', b, a > b) # 3.10
print(sys.platform)
print(2**5)
x = 'Buldakov!'
print(x*8)
|
90bf7f7191abc70e67746a2664f2cff2109596ef | arif-zaman/CSE_BUET | /pagerank-simulation/pagerank.py | 6,655 | 3.71875 | 4 |
# CSE411 - Simulation and Modeling
"""
Instructions:
This assignment is to "simulate" Google's pagerank as discussed in class.
This is a skeleton program where you need to add your code in places.
The program first reads web.txt to load the page network. Each row refers to a page
and 0/1 indicates which other pages it visits to (1 mean visit, else no).
It then populates transition probability matrix, P. Recall that a page visits to
the pages it has links to with uniform probability, and with some residual probability
it visits to any other page (may be to itself) uniformly at random. The parameter Alpha defines this split.
Given P, the program then analytically finds ranks of pages (i.e., pi's of underlying Markov chain
of pages). It also "simulates" a navigation process to compute the same.
The program then computes the difference between the two measurements and show them in a plot.
Add your codes at designated places.
Answer the following question at the end of your program
Q. Change the seed (currently 100) to different values. Do you see changes in results?
Can you explain why? Can you measure how much variation you see?
WORK INDEPEDENTLY. CODE SHARING IS STRICTLY PROHIBITED, AND IF HAPPENS WILL LEAD TO PENALTY.
"""
import numpy as np
import random
import matplotlib.pyplot as plt
def printP(P):
for row in range(len(P)):
for col in range(len(P[row])):
print '%5.3f' % P[row][col],
print
# Compute transition probability matrix
def populateP(file_name):
alpha = 0.85
P = None
with open(file_name) as fhandle:
alpho = 0.85
total_pages = int(fhandle.readline())
# Create Blank NxN Matrix
P = [[0 for x in range(total_pages)] for y in range(total_pages)]
row,col = 0,0
for line in fhandle:
line = list(line.replace(' ','').replace('\n',''))
link_count = line.count('1')
# http://en.wikipedia.org/wiki/PageRank#Damping_factor
# Stanford pagerank algorithm :
# At First, ((1-alpha)/total_pages) is Distributed to all page.
# Thus, Creating Linked among all the pages on the web. This is known as teleportation link.
# Then all page that are connected , (alpha/connected_link) are added to them.
for word in line:
if word == '1':
linked = (alpha/link_count) + ((1-alpha)/total_pages)
P[row][col] = linked
else:
non_linked = (1-alpha)/total_pages
P[row][col] = non_linked
col += 1
row,col = row+1,0
printP(P)
return P
def computeDiff(pi, simpi):
if len(pi) != len(simpi):
raise Error('Pi dimension does not match!!')
sumdiff = 0
for i in range(len(pi)):
sumdiff += abs(pi[i] - simpi[i])
return sumdiff
# Compute rank analytically
def solveForPi(P):
A = np.array(P)
A = A.transpose()
B = None
total_pages = len(P)
B = [0 for x in range(total_pages)]
B[total_pages-1] = 1 # 0,0,0,0,0,0,0,0,0,1
B = np.array(B,float)
for x in range(total_pages):
A[x][x] = A[x][x]-1
for x in range(total_pages):
A[total_pages-1][x] = 1
pi = np.linalg.solve(A,B)
return pi
# Compute rank by simulation
# Visit pages for 'iterations' number of times
def computeRankBySimulation(P, iterations):
total_pages = len(P)
simPi = [0 for i in range(total_pages)]
page_no = 0
count = 0
for i in range(iterations):
page_no=choosePage(P[page_no])
if page_no>=0 and page_no<total_pages:
simPi[page_no] += 1
count +=1
for i in range(len(P)):
simPi[i]= simPi[i]/float(count)
simPi = np.array(simPi)
simPi= simPi/sum(simPi)
return simPi
"""
Sample X as defined by distribution "prob"
prob is a list of probability values, such as [0.2, 0.5, 0.3].
These are the values index positions take, that is, O happens with prob 0.2, 1 with 0.5 and so on.
"""
def choosePage(prob):
U = random.random()
P = 0
for i in range(len(prob)):
P = P + prob[i]
if U < P:
return i
return len(prob)
def plotResult(P,analyticalPi):
X,Y,Y1,Y2 = [],[],[],[]
print "\n@ SEED = 100 :\n"
for itr in range(1,11):
itr = itr * 10000
simulatedPi = computeRankBySimulation(P, itr)
diff = computeDiff(analyticalPi, simulatedPi)
print "%d\t%f" %(itr,diff)
X.append(itr / 1000)
Y1.append(diff)
# ANSWER
# Cahnging The Seed
random.seed(10)
print "\n@ SEED = 10 :\n"
for itr in range(1,11):
itr = itr * 10000
simulatedPi = computeRankBySimulation(P, itr)
diff = computeDiff(analyticalPi, simulatedPi)
print "%d\t%f" %(itr,diff)
Y2.append(diff)
print "\nVARIATION :\n"
for x in range(0,10):
Y.append(abs(Y1[x]-Y2[x]))
itr = (x+1) * 10000
print "%d\t%f" %(itr, Y[x])
# Plotting Seed_10 Vs Seed_100
seed_100, = plt.plot(X,Y1,'b-',label='SEED_100')
seed_10, = plt.plot(X,Y2,'r-',label='SEED_10')
variation, = plt.plot(X,Y,'g-',label='VARIATION')
plt.legend([seed_10, seed_100, variation], ['@ SEED 10', '@ SEED 100', 'VARIATION'])
plt.suptitle('Impact of Seed Changes', fontsize=16)
# Plotting AnalyticalPi Vs SimulatedPi
newPlot = plt.figure()
plt2 = newPlot.add_subplot(111)
plt2.plot(X,Y1)
plt.suptitle('Differrence between analyticalPi & simulatedPi', fontsize=16)
plt.xlabel("Iterations (1000's)")
plt.ylabel("Pi difference")
plt.show()
# main function
def main():
P = populateP('web.txt')
# Compute rank analytically
analyticalPi = solveForPi(P)
print "\nAnalyticalPi : \n",analyticalPi
random.seed(100)
simulatedPi = computeRankBySimulation(P, 1000)
print "\nsimulatedPi : \n",simulatedPi
# PLOTTING
plotResult(P,analyticalPi)
if __name__ == "__main__":
main()
'''
Your answer for the question goes here.
...
## We have changed the value of seed and noticed change in the result.
## We also calculated the variation and plotted the result.
## please see plotResult Functions.
...
## Explation
Due to change of seed to differet numbers, simPi changes
because python random is actually pseudo-random i.e it
generates same number sequence for a particular seed.
So choosePage always returns their diffrent number
sequence for differnt seed and so simuPi varies for
differnt seed.
''' |
9b7bbc53bdfaeb2e7ba2e2d23c4783c4d55a7cf6 | sendos/matlab_utils_for_python | /utils_test.py | 1,688 | 3.59375 | 4 | """
Script with sample usage of the functions in matlab_utils.py
Copyright (c) 2017 Andrew Sendonaris.
"""
# In this script, we convert the following Matlab script for use in Python
"""
function D = mydist(X)
if isempty(X)
error('Input matrix is empty\n');
end
% Get the number of points
num_points = size(X, 1);
if num_points < 2
error('Number of points should be more than one\n');
end
% Initialize the result
D = zeros(num_points, num_points);
for i = 1:num_points-1
for j = 1:num_points
if(i < j)
% Ensure the matrix is symmetric
D(i,j) = sqrt(sum((X(i,:)-X(j,:)).^2));
D(j,i) = D(i,j);
end
end
end
end
X = [[1, 2, 3]; [4, 5, 6]; [7, 8, 9]];
D = mydist(X);
fprintf('D = [\n')
for I = [1:size(D,1)]
fprintf(' %5.2f %5.2f %5.2f\n', D(I,:))
end
fprintf(']\n')
"""
from matlab_utils import *
def mydist(X):
if isempty(X):
error('Input matrix is empty\n');
end
# Get the number of points
num_points = size(X, 1);
if num_points < 2:
error('Number of points should be more than one\n');
end
# Initialize the result
D = zeros(num_points, num_points);
for i in mrange[1:num_points-1]:
for j in mrange[1:num_points]:
if(i < j):
# Ensure the matrix is symmetric
D[i,j] = sqrt(sum((X[i,:]-X[j,:])**2));
D[j,i] = D[i,j];
end
end
end
return D
end
X = marray([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
D = mydist(X);
fprintf('D = [\n')
for I in mrange[1:size(D,1)]:
fprintf(' %5.2f %5.2f %5.2f\n', *D[I,:])
end
fprintf(']\n')
|
6dc8cc63107b9593c6bb622fa9e35e0f7af20e09 | krumbot/data-structures | /linked_list.py | 2,299 | 4.125 | 4 | # Linked List implementation
class Node:
def __init__(self, val=None, next=None):
self.val = val
self.next = next
class LinkedList:
def __init__(self, head=None):
self.head = head
def insert_first(self, val):
first_node = Node(val)
first_node.next = self.head
self.head = first_node
return first_node
def insert_after(self, prev_node, val):
if prev_node is None:
raise ValueError("Cannot insert after a node of None type")
new_node = Node(val, prev_node.next)
prev_node.next = new_node
return new_node
def insert_last(self, val):
last_node = Node(val)
loop_node = self.head
if loop_node is None:
self.head = last_node
else:
while loop_node.next is not None:
loop_node = loop_node.next
loop_node.next = last_node
return last_node
# Returns the nth node in the linked list with the given val
def search(self, val, n=1):
loop_node = self.head
num_found = 0
def validate_node(node, found):
if node.val == val:
found += 1
if found == n:
return True, found
return False, found
while loop_node.next is not None:
found_node, num_found = validate_node(loop_node, num_found)
if found_node:
return loop_node
loop_node = loop_node.next
found_node, num_found = validate_node(loop_node, num_found)
if found_node:
return loop_node
return None
def remove(self, node):
if node is None:
raise ValueError("Please specify a node to remove from the Linked List.")
def remove_node(prev):
if self.head == node:
self.head = node.next
return
prev.next = node.next
loop_node = self.head
prev_node = None
while loop_node.next is not None:
if node == loop_node:
remove_node(prev_node)
return
prev_node = loop_node
loop_node = loop_node.next
if node == loop_node:
remove_node(prev_node)
|
bca421661bc6664f385afaba96ce2d0b18d53ea9 | xigaoli/lc-challenges | /295. Find Median from Data Stream.py | 1,396 | 3.8125 | 4 | class MedianFinder:
def __init__(self):
"""
initialize your data structure here.
"""
#store larger half of numbers
self.minh=[]
#store smaller half of numbers
self.maxh=[] #max heap store the negative value of elem
def balance(self)->None:
#remove top from minh
elem1 = heapq.heappop(self.minh)
#add to maxh
heapq.heappush(self.maxh,elem1*-1)
#adjust size
if(len(self.minh)<len(self.maxh)): #minh=[a,b],maxh=[c,d,e]
elem1 = heapq.heappop(self.maxh)*-1
heapq.heappush(self.minh,elem1)
def addNum(self, num: int) -> None:
#len of self.minh == self.maxh or len of self.minh-1 == self.maxh
heapq.heappush(self.minh,num)
self.balance()
def findMedian(self) -> float:
rslt=-1
if(len(self.minh) == len(self.maxh)):
#equal, peek 2 elements
elem1=self.minh[0]
elem2=self.maxh[0]*-1
rslt= (elem1+elem2)/2.0
else:
#unequal, top of minh
elem1 = self.minh[0]
rslt= elem1
#print("rslt={}".format(rslt))
return rslt
# Your MedianFinder object will be instantiated and called as such:
# obj = MedianFinder()
# obj.addNum(num)
# param_2 = obj.findMedian() |
36724dbda0c2945978342c0c8e3d3f86efee2127 | angelm1974/Python-zajecia | /pakiety/pakiet_szkoleniowy/moj_modul2.py | 2,649 | 4 | 4 | import time
import locale
# Korzystajฤ
c z bibiloteki time oraz metody sleep():
# Program 1
# Napisz program, ktรณry odlicza od 1 do 5, wypisujฤ
c liczby co sekundฤ.
def count_down1(number):
for i in range(number):
print(i+1)
time.sleep(1)
#count_down(5)
# for a in range(1,6):
# time.sleep(1)
# print(a)
# x = 1
# while x < 6:
# print(x)
# x +=1
# time.sleep(1)
# Program 2
# Napisz podobny program ktรณry odlicza od 1 do 5, wypisujฤ
c liczby co sekundฤ.
# Dodatkowo liczba zapisywana jest do zmiennej T inkrementujฤ
c jฤ
za kaลผdym razem o swojฤ
wartoลฤ
def dodawanie_do_zmiennej1(number):
T = 0
for i in range(1, number+1):
T += i
print(f'sekundy:{i}, Suma: {T}')
time.sleep(1)
#wywoลanie metody z parametrem
#dodawanie_do_zmiennej(5)
# Program 3
# Napisz podobny program ktรณry pobiera liczbฤ sekund od uลผytkownika i jeลli uลผytkownik podaล
# liczbฤ mniejszฤ
od 10 to program zatrzyma siฤ na tak dลugo jakฤ
uลผytkownik podaล liczbฤ.
# Jeลผeli liczba jest wiฤksza od 10 to uลผytklownik otrzyma komunikat ลผe program nie bฤdzie
# czekaล tak dลugo
def pobierz_czekaj1(number):
if number<10:
print(f'Bฤdฤ czekaล {number} sekund.')
time.sleep(number)
print('Koniec czekania!')
else:
print('Nie bฤdฤ czekaล tak dลugo!')
def pobierz_czekaj21():
number=int(input("Podaj ile sekund mam poczekaฤ:"))
if number<10:
print(f'Bฤdฤ czekaล {number} sekund.')
time.sleep(number)
print('Koniec czekania!')
else:
print('Nie bฤdฤ czekaล tak dลugo!')
#wywoลanie metody pobierz_czekaj
#pobierz_czekaj2()
# Program 4
# Napisz program ktรณry przy pomocy bibiloteki time i funkcji gmtime() pobiera aktualnฤ
datฤ
def pobierz_date1():
data= time.gmtime()
print(data.tm_year,'-',data.tm_mon,'-',data.tm_mday)
# Program 5
# Napisz program ktรณry przy pomocy bibiloteki time i funkcji strftime() pobiera aktualnฤ
datฤ
def pobierz_pelna_date1():
locale.setlocale(locale.LC_ALL,'')
print(time.strftime("%A %d %B %Y %H:%M:%S"))
# Program 6
# Napisz program uลผywajฤ
c metody time(), ktรณry zapamiฤtuje czas, a nastฤpnie prosi uลผytkownika
# o wpisanie wyniku mnoลผenia liczb 5x6. Potem pobiera nowy czas, liczy rรณลผnicฤ czasรณw
# i wyลwietla je na ekranie.
def czas_reakcji1():
czas =time.time()
wynik=int(input("Podaj wynik dziaลana 5x6:"))
czas2=time.time()
if wynik==30:
print(f'Potrzebowaลeล {czas2-czas}sekund na rozwiฤ
zanie zadania')
else:
print(f'Popeลniลeล bลฤ
d!!!')
|
0efcc274ca440345ef531c17f95d883d001eb664 | LeeKrane/Python1 | /chapters/chapter2/Part04.py | 175 | 3.59375 | 4 | from random import randrange
a = randrange(100, 401)
b = randrange(100, 401)
if a < b:
print("{:3d} < {:3d}".format(a, b))
else:
print("{:3d} < {:3d}".format(b, a))
|
90c6b4d1a25ee75a6caa5f98e3ed6c17411e9abf | sundaqing221/test1101 | /ๅทฅไฝ็ฉบ้ด0801/python0807/P0807/__init__.py | 490 | 3.78125 | 4 | # -*- coding: UTF-8 -*-
# 1
print "hello world !";
# ๆๅฐ
# ๆไปฅๅฆๆๅคงๅฎถๅจๅญฆไน ่ฟ็จไธญ๏ผไปฃ็ ไธญๅ
ๅซไธญๆ๏ผๅฐฑ้่ฆๅจๅคด้จๆๅฎ็ผ็ ใ
counter = 100 # ๆดๅๅ้
miles = 1000.0 # ๆตฎ็นๅๅ้
name = "runoob" # ๅญ็ฌฆไธฒ
print (counter)
print (miles)
print (name)
# Key=True
#
# if Key==True:
# print "Answer"
# print "True"
# else:
# print "Answer"
# # ๆฒกๆไธฅๆ ผ็ผฉ่ฟ๏ผๅจๆง่กๆถไผๆฅ้
# print "False"
|
85024025e0f9d66d54b1d2c1fb2079aa858d86f1 | gwambui/MathLogic | /Q3c.py | 1,458 | 3.59375 | 4 | #[p -> (q -> r)] -> [(p -> q) -> r]
def IMP(a): # imlies method
result =[]
for row in a:
if row[0] == row[1]:
result.append(1)
elif row[0] > row[1]:
result.append(0)
elif row[0] < row[1]:
result.append(1)
return result
def JOIN(a,b): # puts together 2 propositions to be passed to operation
jn=[]
i=0
for n in a:
jn.append([a[i],b[i]])
i=i+1
return jn
def GETP(a,x):# extracts a column of p from a table of propositions p,q,r
result =[]
for row in a:
result.append(row[x])
return result
def truthtable (n):#generates a table of n propositions
if n < 1:
return [[]]
subtable = truthtable(n-1)
return [ row + [v] for row in subtable for v in [0,1] ]
def Q3(a):
p = GETP(a,0)
q = GETP(a,1)
r = GETP(a,2)
A = IMP(JOIN(q,r))
A2 = IMP(JOIN(p,A))
print "(q -> r)"
print A
print "[p -> (q -> r)]"
print A2
B = IMP(JOIN(p,q))
B2 = IMP(JOIN(B,r))
print "(p -> q)"
print B
print "[(p -> q) -> r]"
print B2
sol = IMP(JOIN(A2,B2))
print "[p -> (q -> r)] -> [(p -> q) -> r] =sol"
print sol
def MAIN():
print "[p -> (q -> r)] -> [(p -> q) -> r]"
prop =3
ttable = truthtable(prop)
print ttable
print ("p,q,r")
Q3(ttable)
MAIN()
|
4eecdd704a6b975d31487b2ba8b2824edd62a3ed | edneyefs/curso_python_fundamentos | /08DESAFIO017.py | 237 | 4.125 | 4 | from math import sqrt
co = float(input('Digite o comprimento do cateto oposto: '))
ca = float(input('Digite o comprimento do cateto adjacente: '))
hy = (co**2) + (ca**2)
print('O comprimento da hipotenusa รฉ de {:.2f}'.format(sqrt(hy)))
|
4f438d90649683115f9c7f299b45a61c76d5bf07 | christophemcguinness/DifferentTypesofListsProgram | /main.py | 1,316 | 4.0625 | 4 | num_strings = ['13', '44', '100', '23']
num_int = [13, 44, 100, 23]
num_float = [2.0, 3.4, 55.0, 12]
num_list = [[1, 2, 3], [2.3, 34.4, 100.0], ['test', 'new', '12345'], [4, 3, 2]]
# Stings
print("\nThe variable num_strings is a {0}".format(type(num_strings)))
print("It contains the elements: {0}".format(num_strings))
print("The element {0} is a {1}".format(num_strings[0], type(num_strings[0])))
# Int
print("\nThe variable num_strings is a {0}".format(type(num_int)))
print("It contains the elements: {0}".format(num_int))
print("The element {0} is a {1}".format(num_int[0], type(num_int[0])))
# Float
print("\nThe variable num_strings is a {0}".format(type(num_float)))
print("It contains the elements: {0}".format(num_float))
print("The element {0} is a {1}".format(num_float[0], type(num_float[0])))
# Lists
print("\nThe variable num_strings is a {0}".format(type(num_list)))
print("It contains the elements: {0}".format(num_list))
print("The element {0} is a {1}".format(num_list[0], type(num_list[0])))
# sort variables
num_strings.sort()
num_int.sort()
# Sorting lists
print("\nNow sorting num_strings and num_int...")
print("Sorted num_strings: {0}".format(num_strings))
print("Sorted num_int: {0}".format(num_int))
print("\nStrings are sorted alphabetically whiel intefers are sorted numerically!")
|
9f2763a042e319ff7023c2e05f351d95d87e0954 | Uncccle/Learning-Python | /22.py | 1,517 | 3.640625 | 4 | # ้ขๅๅฏน่ฑก
# ้ขๅๅฏน่ฑกๅฐฑๆฏๅ็ฎไปฃ็
# ้ขๅๅฏน่ฑกๅฐฑๆฏๅฐๅๆๅฝๆไธไธชไบ็ฉ๏ผๆด่กฃๆบ๏ผ
# ้ขๅๅฏน่ฑก--็ฑปๅๅฏน่ฑก
# ้ขๅๅฏน่ฑก็ผ็จ่ฟ็จไธญ๏ผๆไธคไธช้่ฆ็็ปๆ้จๅ๏ผ ็ฑปไธๅฏน่ฑก
# ็ผ็จๅฐฑๆฏ่ฎพ็ฝฎๆด่กฃๆบ่ฝๅคๅไปไนไบๆ
๏ผๅ็จ่ฟไธชๆด่กฃๆบ
# ้ฃไนๆด่กฃๆบๆไนๆฅ็๏ผ
# ๅ็ญ๏ผ--------ๅทฅๅ
# ๅ็กฎๅ็ญๆฏ๏ผ ๅทฅๅๅทฅไบบๆ นๆฎ่ฎพ่ฎกๅธ็ๅ่ฝๅพ็บธ่ฎพ่ฎกๅบๆฅ็
# ่ฏฆ็ป็ป่ๅ็ญ๏ผ ๅพ็บธ ---> ๆด่กฃๆบ ---> ๆด่กฃๆ
# ๅพ็บธ๏ผ ็จๆฅๅๅปบๆด่กฃๆบ
# ๅจ้ขๅๅฏน่ฑก็ผ็จไธญ๏ผ
# โ็ฑปโ ๅฐฑๆฏ่ฟไธชๅพ็บธ๏ผ โๅฏน่ฑกโ ๅฐฑๆฏ่ฟไธชๅฎ็ฉ๏ผๆด่กฃๆบ๏ผ
# ็ฑปๅๅฏน่ฑก็ๅ
ณ็ณป๏ผ ็จ็ฑปๅปๅๅปบไธไธชๅฏน่ฑก
# โ็ฑปโ ๆฏๅถ้ ๆด่กฃๆบๆถ่ฆ็จๅฐ็ๅพ็บธ
# ๆณไธไธ๏ผๅถ้ ๆด่กฃๆบ็จๅฐ็ๅพ็บธ้้ข้ฝๆไปไน๏ผ
# ๅ็ญ๏ผ ้ฟๅบฆ๏ผๅฎฝๅบฆ๏ผๅ่ฝ ๅ่ฝ๏ผ 1ใๆพๆฐด 2ใๆฝๆฐด 3ใๆด่กฃ 4ใ็ๅนฒ
# ่ฟไบๅ่ฝๅช่ฆๆไธไธๆ้ฎ๏ผๆด่กฃๆบๅฐฑๅฏไปฅ็จไบ
# ๅจ็ผ็จๅฝไธญ ่ฟไบๅ่ฝๅฐฑๆฏๅฝๆฐ
# โ็ฑปโ ้้ขๆๅฑๆงๅๆนๆณ๏ผๅฐฑๆฏๅ้ๅๅฝๆฐ
# โๅฏน่ฑกโ ๆฏ็ฑปๅๅปบๅบๆฅ็็ๅฎๅญๅจ็ไบ็ฉ๏ผไพๅฆ:ๆด่กฃๆบ
# ๅผๅไธญ๏ผๅ
ๆ็ฑป๏ผๅๆๅฏน่ฑก
###################################################
# ๅฎไน---็ฑป
#่ฏญๆณ:
# class ็ฑปๅ():
# ไปฃ็
# ......
# ๅฎไน๏ผๅๅปบ๏ผ---ๅฏน่ฑก
# ๅฏน่ฑกๅๅๅฎไพ
#่ฏญๆณ๏ผ
# ๅฏน่ฑกๅ = ็ฑปๅ() |
a5a9b31ef832af71f58347688f3df331ab0d96c9 | zxldev/helloPy | /hello/helloLIstGen.py | 637 | 3.78125 | 4 | # -*- coding: utf-8 -*-
import os
#็ๆๅ่กจ
print([x*x for x in range(1,50)])
#ๅธฆๆกไปถ็ๆ
print([x*x for x in range(1,50) if x % 5 == 0])
#ๅพช็ฏ็ๆ
print ([(m,n) for m in 'ABC' for n in range(1,6)])
#ๅพช็ฏ็ๆ๏ผๅธฆๆกไปถ
print([ (a,b,c) for a in range(1,100) for b in range(a,100) for c in range(b,100) if (a*a + b*b == c*c)])
#ๆๅฐๅฝๅ็ฎๅฝๆไปถ
print ([file for file in os.listdir('.') if file != '__init__.py'])
#่ฐ็จๅฝๆฐ
L = ['Hello', 'World', 'IBM', 'Apple']
print ([l.lower() for l in L])
#ไฝไธ
L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = [l.lower() for l in L1 if isinstance(l,str)]
print (L2) |
de20e0ad8a269698e996fb09ff3ab8ae16d201da | aloix123/Simple-pingpong | /ball.py | 827 | 3.515625 | 4 | import pygame
from settings import Settings
"""klasa , ktรณra tworzy piลeczkฤ , jej rozmiary krztaลt i ruch"""
class Ball(Settings):# piลeczka
def __init__(self, screen,f):
super().__init__()
self.bal_rect=pygame.Rect(self.ball_gps1,self.ball_gps2,self.ball_size,self.ball_size)# kwadracik
self.screen=screen
self.bal_color=(255,128,0)# kolor piลki
self.a=1
self.b=1
self.f=f
def draw_ball(self):#funkcja rysujฤ
ca piลke na ekranie
pygame.draw.rect(self.screen,self.bal_color,self.bal_rect)
def ball_run(self):# trajektoria ruchu piลki
self.bal_rect.x-=self.a
self.bal_rect.y+=self.b
if self.bal_rect.y==700:# tego nie tykaj to jest dobrze
self.b=-1
if self.bal_rect.y==0:
self.b=1
|
88d434e8be5945e48062950cda5a7ebbd52a3ad2 | 109156247/C109156247 | /41.py | 257 | 3.703125 | 4 | import math
a = int(input("a:"))
b = int(input("b:"))
c = int(input("c:"))
x1 = (-b+(((b**2)-(4*a*c)))**0.5)/(2*a)
x2 = (-b-(((b**2)-(4*a*c)))**0.5)/(2*a)
if x1==x2:
print(str(x1))
elif (b*2)-(4*a*c)<0:
print("0")
else:
print(str(x1),str(x2)) |
33aaebf0bebff605ed5fa4cb112064b4abbb76a0 | freeshyam/lc | /207_course_schedule.py | 3,116 | 3.734375 | 4 | #!/usr/bin/env python
import unittest
from collections import deque, defaultdict
"""
class Solution(object):
def canFinish(self, numCourses, prerequisites):
# :type numCourses: int
# :type prerequisites: List[List[int]]
# :rtype: bool
courses = list(range(numCourses))
course_to_prerequisites = defaultdict(set)
prerequisite_to_courses = defaultdict(set)
for course, prerequisite in prerequisites:
course_to_prerequisites[course].add(prerequisite)
prerequisite_to_courses[prerequisite].add(course)
topo_sort = []
# put courses without prerequisites in the queue
q = deque(c for c in courses if c not in course_to_prerequisites)
while q:
completed_course = q.popleft()
topo_sort.append(completed_course)
if completed_course in prerequisite_to_courses:
# given that we completed a course completed_course:
# for all courses k that have completed_course as a prerequisite,
# remove completed_course from k's prerequisite list
for k in prerequisite_to_courses[completed_course]:
course_to_prerequisites[k].remove(completed_course)
if not course_to_prerequisites[k]:
q.append(k)
return len(topo_sort) == numCourses
"""
class Solution:
def canFinish(self, numCourses, prerequisites):
courses = list(range(numCourses))
course_to_num_prerequisites = defaultdict(int)
prerequisite_to_courses = defaultdict(set)
for course, prerequisite in prerequisites:
prerequisite_to_courses[prerequisite].add(course)
course_to_num_prerequisites[course] += 1
num_courses_completed = 0
# put courses without prerequisites in the queue
q = deque(c for c in courses if c not in course_to_num_prerequisites)
while q:
completed_course = q.popleft()
num_courses_completed += 1
# if completed_course is a prerequisite for other courses
if completed_course in prerequisite_to_courses:
# given that we completed a course completed_course:
# for all courses k that have completed_course as a prerequisite,
# decrement k's prerequisite course count by 1
for k in prerequisite_to_courses[completed_course]:
course_to_num_prerequisites[k] -= 1
if course_to_num_prerequisites[k] == 0:
q.append(k)
return num_courses_completed == numCourses
class UT1(unittest.TestCase):
def setUp(self):
self.s = Solution()
self.f = self.s.canFinish
def test_base(self):
self.assertEqual(self.f(2, [[1,0]]), True)
self.assertEqual(self.f(2, [[1,0],[0,1]]), False)
def unit_test(cls):
suite = unittest.TestLoader().loadTestsFromTestCase(cls)
unittest.TextTestRunner(verbosity=2).run(suite)
if __name__ == "__main__":
unit_test(UT1)
|
43871db3ced13d9cc15b9710d9135ae57324a32d | AngryBird3/gotta_code | /leetcode_oj/countAndSay.py | 866 | 3.90625 | 4 | '''
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth sequence.
'''
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
s = "1"
for i in range(1, n):
last = s
s = ""
prev = last[0]; count = 1
for j in range(1, len(last)):
if prev == last[j]:
count += 1
else:
s += str(count) + str(prev)
prev = last[j]; count = 1
s += str(count) + str(prev)
return s
def countAndSay2(self, n):
import re
s = "1"
for i in range(1, n):
counts, repeating = re.findall(r'((.)\2*)',s)[0]
s = str(len(counts)) + str(repeating)
return s
s = Solution()
print s.countAndSay2(3)
|
f30b80441fb7eceeae3a87da409555ffb262dbbb | alvinaashraf/PythonAssignment | /assignment1.py | 485 | 3.890625 | 4 |
import sys
import datetime
print("Twinkle , twinkle little star, \n \t how wonder what you are\n\t\t up above the world so high\n\t\tlike a diamond in the sky\n twinkle twinke little star\n \t how i wonder what you are ")
print(sys.version)
n=datetime.datetime.now()
print(n.time)
print(n.date)
num = input('Enter a length: ')
num2= input("enter width")
print(num*num2)
add1= input("enter number 1")
add2=input("enter number 2 ")
print(add1+add2)
|
9131710037a5917640893e39b18afb207d242106 | esraertsak/Python-Projelerim | /Kosullu Durumlar/รถdev_1.py | 767 | 4.09375 | 4 | """ Problem 1
Kullanฤฑcฤฑdan alฤฑnan boy ve kilo deฤerlerine gรถre beden kitle indeksini hesaplayฤฑn ve ลu kurallara gรถre ekrana ลu yazฤฑlarฤฑ yazdฤฑrฤฑn.
Beden Kitle ฤฐndeksi: Kilo / Boy(m) * Boy(m)
BKฤฐ 18.5'un altฤฑndaysa -------> Zayฤฑf
BKฤฐ 18.5 ile 25 arasฤฑndaysa ------> Normal
BKฤฐ 25 ile 30 arasฤฑndaysa --------> Fazla Kilolu
BKฤฐ 30'un รผstรผndeyse -------------> Obez """
boy=int(input("boyunuz:"))
kilo=int(input("kilonuz:"))
beden_kitle_indeksi= kilo / boy * boy
if (beden_kitle_indeksi <18.5):
print("zayฤฑf")
elif (beden_kitle_indeksi >=18.5 and beden_kitle_indeksi < 25):
print("normal")
elif (beden_kitle_indeksi >=25 and beden_kitle_indeksi <30):
print("fazla kilolu")
elif(beden_kitle_indeksi>30):
print("obez")
|
472e0df87d0ecd7acdba9b52e68b36ee8401b118 | sellenth/algorithms | /q1.4.py | 422 | 3.640625 | 4 | def isPalindrome(s1):
d = {}
for c in s1:
if c is not ' ':
if c not in d:
d[c] = 1;
else:
d[c] += 1;
found_single = False;
for key in d:
if d[key] % 2 != 0:
if found_single == False:
found_single = True;
else:
return False;
return True;
print(isPalindrome('racec ar'));
|
08028043ced5a509a9614954724650a435235378 | SebaGiordano/Programacion_Orientada_a_Objetos | /Ejercitacion_2/ejercicio_8.py | 1,050 | 4.5 | 4 | '''
8. Operaciones de orden con tres nรบmeros
Realizar un programa que tome tres nรบmeros, los ordene de mayor a menor,
y diga si el tercero es el resto de la divisiรณn de los dos primeros.
'''
print("Debera ingresar 3 numeros\n")
lista = []
for i in range(0, 3):
num = input(f"Numero {i+1}: ")
lista.append(num)
print(f"\nLos tres numeros ingresados son: {lista}\n")
lista.sort()
lista.reverse()
print(f"Ordenados de Mayor a Menor: {lista}")
division_dos_primeros = int(lista[0]) / int(lista[1])
print(f"\nEl resultado de dividir los 2 primeros numeros es: {division_dos_primeros:.2f}\n")
resto_division = division_dos_primeros % 1
if resto_division == lista[2]:
print(f"El resto de la division de los 2 primeros numeros es {resto_division:.2f}\n"
"Por lo tanto, el tercer numero es el resto de la divisiรณn de los dos primeros")
else:
print(f"El resto de la division de los 2 primeros numeros es {resto_division:.2f}\n"
"Por lo tanto, el tercer numero no es el resto de la divisiรณn de los dos primeros")
|
02c3a59708f89e6c76f6a077433e67e386e4758b | Brendan8497/game_example | /ex45.py | 20,127 | 3.96875 | 4 | # Brendan Ryan
# 11/2/2016
# Ex45
from sys import exit
from random import randint
from stats import luckCount
from stats import strength
from stats import stealth
from stats import intelligence
class Scene(object):
def enter(self):
print "This scene has not been made."
exit(1) # ends the program
# Engine of the game.
class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
# play function. Plays the game.
def play(self):
current_scene = self.scene_map.opening_scene() # defines the current scene as the opening scene
while True:
print "\n--------"
# name of the next is given the value of the enter function of the current scene's Class
next_scene_name = current_scene.enter()
# The current scene is given the value of the next_scene_name's Class
current_scene = self.scene_map.next_scene(next_scene_name)
# Death class
class Death(Scene):
# random taunts are displayed when you die
taunts = [
"Better luck in the next life...",
"RIP in Pepperoni",
"Oh well, at least you tried.",
"Just give up.",
"It's okay, at least your mom still likes you.",
"Just stop trying.",
"A valiant effort, but a failure is a failure.",
]
def enter(self):
print Death.taunts[randint(0, len(self.taunts)-1)]
exit(1)
class Intro(Scene):
def enter(self):
print "Thanks for playing The Adventure of Mount Spooky!"
print ""
print "Press 'Enter' to play. Press any other button to quit.\n"
answer = raw_input("[INPUT] ")
if (answer == ''):
return 'stats_screen'
else:
return 'death'
class StatsScreen(Scene):
def enter(self):
print "Here are your stats.\n"
print "Luck:", luckCount
print "Strength:", strength
print "Stealth:", stealth
print "Intelligence:", intelligence
raw_input("")
return 'start_room'
class Home(Scene):
def enter(self):
print "You go back home defeated. You got scared and gave up on your dream"
print "of becoming a treasure hunter. You become a blacksmith instead,"
print "doomed to forever regret your cowardice. Congratulations, I guess."
return 'death'
class StartRoom(Scene):
def enter(self):
print "You awake in a field under a starry sky. You get up and look around you."
print "All you can see is Mount Spooky in the distance. You are hesitant to go,"
print "but remember the only reason you are here is to find the lost treasure"
print "you heard about that's supposed to be hidden in a cave somewhere on"
print "Mount Spooky. Do you go forward to Mount Spooky or back home?\n"
answer = raw_input("[INPUT] ")
if (answer == 'Mount Spooky'):
return 'goblin_room'
elif (answer == 'Home'):
return 'home'
class GoblinRoom(Scene):
def enter(self):
print "You head out towards Mount Spooky. By the time you reach the mountain"
print "the sun has already started to rise. You look around for a while and find"
print "a cave. You go in and see a goblin in the corner. What do you do?\n"
print "A) Sneak Past Him"
print "B) Charge Him"
print "C) Talk to Him\n"
answer = raw_input("[INPUT] ")
if (answer == 'A'):
if (stealth >= 30):
print "You sneak past the Goblin without making a sound. You find a door"
print "a little farther in the cave. You enter further into the cave."
return 'spirit_room'
else:
print "You attempt to sneak past the Goblin, but he hears you and"
print "stabs you in the back. You scream one last time before"
print "your vision turns to black."
return 'death'
elif (answer == 'B'):
if (strength >= 30):
print "You charge the goblin and take him by surprise. You knock him"
print "to the ground and knock him out with a rock."
print "You proceed further into the cave and find a door. You enter"
print "into the next room."
return 'spirit_room'
else:
print "You charge the goblin and attempt to overpower him. He sees"
print "you coming and pulls a rusty dagger from out of his loincloth."
print "As you attempt to tackle him, he thrusts it into your stomach."
print "You feel agonizing pain and then nothing as all fades to black."
return 'death'
elif (answer == 'C'):
if (luckCount >= 85):
print "You hail the goblin in Goblin Speech as you approach."
print "He turns and hails you back, and you start a conversation."
print "You ask him if there is any treasure in this cave.\n"
if (luckCount >= 95):
print "The goblin pauses for a moment, then tells you to follow him."
print "He leads you through the cave, past ghosts and a dragon,"
print "beckoning for you to keep close. Finally he stops in"
print "front of another door and tells you this is where the treasure"
print "is hidden. You thank him and enter."
return 'treasure_room'
else:
print "The goblin pauses for a moment, then tells you to follow him."
print "He leads you through the cave, past ghosts and a dragon,"
print "beckoning for you to keep close. Finally he stops in"
print "front of another door and tells you this is where the treasure"
print "is hidden. You thank him and enter.\n"
print "As you enter you realize the goblin lied to you."
print "You hear a lock click behind you and focus on what's ahead."
print "What's ahead is an army of goblins marching in the distance."
print "One of them sees you and directs the rest's attention to you."
print "A group of archers fire at you. An arrow hits you and you fall to"
print "the ground."
return 'death'
elif (strength >= 30):
print "You hail the goblin in Goblin Speech as you approach."
print "He snarls at you and replies with a goblin speech curse word."
print "He pulls a dagger from his loincloth and lunges at you."
print "You dodge the attack and reverse the dagger towards him."
print "He stabs himself and you advance further into the cave through"
print "a door that you find in the back of the cave."
return 'spirit_room'
else:
print "You hail the goblin in Goblin Speech as you approach."
print "He snarls at you and replies with a goblin speech curse word."
print "He pulls a dagger from his loincloth and stabs you. You die in"
print "agonizing pain."
return 'death'
class SpiritRoom(Scene):
def enter(self):
print "You are in an open area of the cave. It appears to be a goblim cemetery."
print "You also see ghosts everywhere. You can't fight or talk to ghosts, and you're"
print "not sure if they've noticed you or not. What do you do?\n"
print "A) Walk Through the Graveyard"
print "B) Sneak Past the Ghosts"
print "C) Wait For a While"
print "D) Attempt to Banish the Dead\n"
answer = raw_input("[INPUT] ")
if (answer == 'A'):
if (luckCount >= 75 and stealth >= 75):
print "You walk straight through the graveyard to a door at the other"
print "end of the room. You reach the door undisturbed and enter."
return 'dragon_room'
else:
print "You try to waltz through the graveyard with purpose, but the"
print "ghosts notice you and start to wail. They start to crowd around you"
print "and you are forced to endure the feeling of aging 1,000 years in"
print "seconds. You turn to dust and cease to exist."
return 'death'
elif (answer == 'B'):
if (stealth >= 75):
print "You attempt to sneak past the ghosts, ducking and weaving"
print "in and out of the shadows. The ghosts suspect nothing, and you"
print "reach the door at the end of the room with ease. You enter into"
print "the next room of the cave."
return 'dragon_room'
elif (luckCount >= 75):
print "You are terrible at sneaking, but you try anyway. You end up"
print "alerting a ghost or two as you clumsily make your way to"
print "the end of the cave, but they leave you alone. Lucky you."
print "You reach the door at the end of the room and enter."
return 'dragon_room'
else:
print "You attempt to sneak past the ghosts, but trip over a grave"
print "on your way to the back of the cave. Every ghost notices you"
print "and crowds around you. You are forced to endure the feeling"
print "of aging 1,000 years in seconds. You turn to dust and cease to exist."
return 'death'
elif (answer == 'C'):
if (luckCount >= 50):
print "You wait for a while and ghosts go away. You don't know when"
print "they'll be back, so you hurry to the end of the room."
print "You find a door and enter through it."
return 'dragon_room'
else:
print "You wait a while, and eventually the ghosts detect you."
print "They start to gather around you slowly, until there's a"
print "mob of ghosts around you. They drain your life away until"
print "there's nothing left of you but dust. You cease to exit."
return 'death'
elif (answer == 'D'):
if (intelligence >= 80):
print "You start to perform anti-necromancy magic that you"
print "learned from watching mages in the Magic Guild."
print "You finish the ritual and successfully banish the dead."
print "You enter the next room."
return 'dragon_room'
elif (intelligence >= 60 and luckCount >= 80):
print "You struggle to remember the anti-necromancy magic that"
print "you watched the mages at the Magic Guild perform, but"
print "nonetheless perform the ritual successfully. You"
print "watch the ghosts banish and then proceed to the next room."
return 'dragon_room'
else:
print "You attempt to perform anti-necromancy magic, but"
print "don't know the proper spells. You end up killing yourself"
print "and wake up as a ghost. You are doomed to roam the bowels of"
print "Mount Spooky as a ghost forever."
return 'death'
class DragonRoom(Scene):
def enter(self):
print "As you enter the next room the first thing you feel is the heat."
print "It feels like a furnace. You notice a few gold objects lying on the"
print "floor all over the place, as well as huge sleeping dragon between you"
print "and the door at the other end of the cave. You are starting to notice"
print "a pattern in the cave's architecture. You are convinced this is the cave"
print "with the treasure. What do you do?\n"
print "A) Sneak Past the Dragon"
print "B) Kill the Dragon"
print "C) Take Some Gold and Leave"
print "D) Leave\n"
answer = raw_input("[INPUT] ")
if (answer == 'A'):
if (stealth >= 90):
print "You successfully sneak past the dragon. You look back once"
print "you are at the door and see the dragon still sleeping."
print "You quickly slip into the next room."
return 'treasure_room'
elif (luckCount >= 90):
print "You somehow sneak past the dragon without waking it up."
print "You are amazed at the outcome, but aren't going to complain."
print "After a silent celebration, you slip into the next room."
return 'treasure_room'
elif (intelligence >= 90 and luckCount >= 50):
print "The dragon wakes up due to your inability to sneak."
print "Instead of panicking, you keep a level head and attempt to"
print "speak to it with broken Dragon Speech, and he responds."
print "He says he will grant you one thing if you agree to leave"
print "and never come back. What do you ask for?\n"
print "A) Gold"
print "B) Survival"
print "C) Knowledge"
print "D) Refuse\n"
answer = raw_input("[INPUT] ")
if (answer == 'A'):
if (luckCount >= 90):
print "The dragon curses your greed and gives you a golden sword."
print "He then tries to claw at you. You duck under his swipe and"
print "manage to flee.\n"
print "Congratulations, You Won! (Coward)"
exit(1)
if (strength >= 90):
print "The dragon curses your greed and gives you a golden sword."
print "He then tries to claw at you. You dodge his attack and"
print "thrust the golden sword you just received into the dragon's"
print "heart, killing it instantly. You proceed to the next room."
return 'treasure_room'
else:
print "The dragon curses your greed and gives you a golden sword."
print "He then tries to claw at you. His attack hits you, and you"
print "are sliced in two."
return 'death'
elif (answer == 'B'):
print "He let's you leave with your life under the condition"
print "you never return. You agree and flee with haste."
print "You gain no wealth and waste your life wondering what"
print "could have been."
return 'death'
elif (answer == 'C'):
print "He gives you a thick, dusty tome that he claims"
print "contains ancient magic. He then tries to claw at you."
print "You duck and fire a spell from the tome at the dragon."
print "A black and red arrow shoots from your hand towards the"
print "dragon. It goes through the dragon and it falls to the ground"
print "dead. You proceed to the next room."
return 'treasure_room'
elif (answer == 'D'):
print "You refuse his offer and attack. You pick up a golden sword"
print "and duck under his claws."
if (strength >= 90):
print "You stab the dragon in the heart, killing him"
print "instantly. You rest for a while, then proceed to"
print "the next room."
return 'treasure_room'
else:
print "You attempt to lunge at the dragon, but you are incinerated"
print "in a blast of the dragon's flames."
return 'death'
else:
print "You wake the dragon up attempting to sneak past it. You"
print "notice it's eyelid's slowly open as you are standing right"
print "in front of it's face. It yawns as you try to run, then"
print "blasts you with fire. You are burnt to cinders."
return 'death'
elif (answer == 'B'):
if (strength >= 90):
print "You pick up a golden sword and stab the dragon in the"
print "heart, killing him instantly. You rest for a while, then proceed to"
print "the next room."
return 'treasure_room'
elif (intelligence >= 90):
print "You mutter a curse of death towards the dragon, and suddently"
print "the soft sound of snoring slows down and stops. The dragon"
print "has ceased to breath, and you enter the next room."
return 'treasure_room'
else:
print "You lack the strength and experience to take on a dragon."
print "You slash at it's scaly arm with a golden sword you found"
print "on the ground and wake it up. It glares down at you and"
print "swiftly eats you."
return 'death'
elif (answer == 'C'):
if (stealth >= 75):
print "You hastily and stealthily pocket some gold coins and pick up"
print "some golden artifacts. You leave with a small fortune, and are able"
print "to live a comfortable life.\n"
print "Congratulations, You Won!"
exit(1)
elif (luckCount >= 75):
print "You hastily pocket some gold coins and pick up"
print "some golden artifacts. You leave with a small fortune, and are able"
print "to live a comfortable life.\n"
print "Congratulations, You Won!"
exit(1)
else:
print "You start picking up golden artifacts noisily. You wake up the dragon"
print "and stand in fear as it stares at you. It finally decides to eat you."
return 'death'
elif (answer == 'D'):
return 'home'
class TreasureRoom(Scene):
def enter(self):
print "The room is filled with treasure. Gold, silver, gems of all kinds,"
print "and various other artifacts litter the room. Literally mountains of"
print "gold coins pile up against the cave walls. You stare in incredulity."
print "It is then you realize you were born to be a Treasure Hunter."
print "You take as much as you can carry back with you, and use the"
print "money you earned to fund multiple expeditions back to Mount"
print "Spooky.\n"
print "Congratulations, You Won!"
exit(1)
class Map(object):
# creates a dictionary of the map.
scenes = {
'intro': Intro(),
'stats_screen': StatsScreen(),
'home': Home(),
'start_room': StartRoom(),
'goblin_room': GoblinRoom(),
'spirit_room': SpiritRoom(),
'dragon_room': DragonRoom(),
'treasure_room': TreasureRoom(),
'death': Death()
}
# the __init__ function
def __init__(self, start_scene):
self.start_scene = start_scene
# next_scene function that returns the next scene in the game.
def next_scene(self, scene_name):
return Map.scenes.get(scene_name)
# returns the opening scene of the game.
def opening_scene(self):
return self.next_scene(self.start_scene)
a_map = Map('intro')
a_game = Engine(a_map)
a_game.play()
|
3f4e02068c4da5c08bce30b7b943e42db67afaa5 | rayvantsahni/after-MATH | /Permutations/permutations_with_repetition.py | 480 | 3.984375 | 4 | def get_permutations(arr, left, right):
if left == right:
print("".join(arr))
else:
for i in range(left, right + 1):
arr[i], arr[left] = arr[left], arr[i]
get_permutations(arr, left + 1, right)
arr[i], arr[left] = arr[left], arr[i]
if __name__ == "__main__":
string = input("Enter string\n")
n = len(string) - 1
print("All permutations of '{}' are:".format(string))
get_permutations(list(string), 0, n) |
8264db493d518586e15cb77bebcb1b4929b92a60 | GiangHo/CodeFight | /14_alternating_sums.py | 213 | 3.71875 | 4 | def alternatingSums(a):
team_1 = 0
team_2 = 0
for i in range(len(a)):
if i%2 ==0:
team_1 = team_1 + a[i]
else:
team_2 = team_2 +a[i]
return [team_1, team_2]
|
4a4782022e2cbe606e5874298e8a232c79d9b311 | sligocki/wikitree | /graph_min_cycle.py | 1,977 | 3.578125 | 4 | """
Find minimal cycles through a given node in graph.
"""
import argparse
import random
import networkx as nx
import graph_tools
import utils
def min_cycle(graph, start_node):
# Map node -> path
paths = {start_node: []}
todos = []
# Start us off with neighbors of start_node (the path directions).
for dir in graph.adj[start_node]:
paths[dir] = [dir]
todos.append(dir)
dirs_seen = set(todos)
while todos and len(dirs_seen) > 1:
new_todos = []
dirs_seen = set()
for node in todos:
path = paths[node]
for neigh in graph.adj[node]:
if neigh in paths:
# Found a cycle.
path_neigh = paths[neigh]
if path_neigh and path[0] != path_neigh[0]:
# The cycle goes through start_node.
return [start_node] + path + list(reversed(path_neigh))
else: # neigh not yet visited
paths[neigh] = path + [neigh]
new_todos.append(neigh)
dirs_seen.add(path[0])
todos = new_todos
# No cycle
return None
def main():
parser = argparse.ArgumentParser()
parser.add_argument("graph")
parser.add_argument("nodes", nargs="*")
args = parser.parse_args()
utils.log("Loading graph")
graph = graph_tools.load_graph(args.graph)
utils.log(f"Initial graph: # Nodes: {graph.number_of_nodes():_} # Edges: {graph.number_of_edges():_}")
if args.nodes:
for node in args.nodes:
utils.log("Searching for cycle through", node)
cycle = min_cycle(graph, node)
utils.log("Min cycle", node, len(cycle), cycle)
else:
nodes = list(graph.nodes)
random.shuffle(nodes)
max_min_cycle = -1
for i, node in enumerate(nodes):
cycle = min_cycle(graph, node)
if not cycle:
utils.log("No cycle through", node)
elif len(cycle) > max_min_cycle:
utils.log("Min cycle", i, node, len(cycle))
max_min_cycle = len(cycle)
utils.log("Done")
if __name__ == "__main__":
main()
|
eb36bb76c20d62f8a8b0d3ba0d9d34dbc4ce653c | sidaf/scripts | /missing_numbers.py | 1,528 | 3.53125 | 4 | #!/usr/bin/env python2.7
import argparse
import sys
def missing_numbers(num_list, start, end):
original_list = [x for x in range(start, end + 1)]
num_list = set(num_list)
return (list(num_list ^ set(original_list)))
########
# MAIN #
########
if __name__ == '__main__':
desc = 'List missing ports from a list'
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('-s', '--start',
type=int,
action='store',
help='Starting number (default: 0)',
metavar='N',
default=0)
parser.add_argument('-e', '--end',
type=int,
action='store',
help='Last number (default: 65535)',
metavar='N',
default=65535)
parser.add_argument('file',
nargs='?',
type=argparse.FileType('r'),
action='store',
help='file containing a list of ports split by a newline, otherwise read from STDIN',
metavar='FILE',
default=sys.stdin)
args = parser.parse_args()
try:
ports = [int(line.strip()) for line in args.file if len(line.strip())>0 and line[0] is not '#']
except KeyboardInterrupt:
exit()
ports.sort()
print '\n'.join(str(p) for p in missing_numbers(ports, args.start, args.end))
|
06b23549b897c22fe42f321b12adbbd3b831c33c | mahesh4555/python_scripts | /copy_files_from_a_sub_dir_to_same_sub_dir_in_another_main_dir.py | 1,806 | 3.65625 | 4 | # handles the incremental_updates
# move(replace or add) the files present in main1 dir to main2 dir
#main1 and main2 directories have the same directory structure, that is, it contains the same sub-directories
#If any files are present in main1 dir, it will be moved to the main2 dir
def copy_files_from_a_sub_dir_to_same_sub_dir_in_another_main_dir():
for dirpath, dirnames, files in os.walk(mieupro_update_path):
curr_dir = dirpath
print("Files")
for file in files:
print("********************************************")
print(file)
src = curr_dir + "/" + file
dest = curr_dir.replace('mieupro_update', 'mieupro') + '/'
print("src:", src)
print("dest:", dest)
copy_file_from_a_folder_to_another(src, dest)
os.remove(src)
print("********************************************")
#source_filepath =/home/Documents/hello.txt
#destination_filepath =/home/Documents_2/
def copy_file_from_a_folder_to_another(source_filepath, destination_filepath):
print("copy file from folder called")
print("From:", source_filepath)
print("To:", destination_filepath)
# retrieving filename from souce path
dir, file_name = os.path.split(source_filepath)
destination_filepath += file_name
if os.path.isfile(destination_filepath):
print("File exist", file_name)
os.remove(destination_filepath)
print("File deleted", file_name)
try:
print("copying process started")
shutil.copyfile(source_filepath, destination_filepath)
print("copying process completed")
return 1
except Exception as e:
print("Exception occured in copy_file_from_a_folder_to_another")
print(e)
return 0
|
208cc27dabf53e926c3de6ff66e585c51dd11197 | e56485766/280201109 | /lab3/example1.py | 206 | 4.4375 | 4 | # Write a Python code that asks the user for
# a number, calculate the absolute value of
# the number and print it.
number = float(input("Number: "))
if number < 0:
number = number * -1
print(number) |
66b92f6764c866037dcac4a24288eea2ab8898fb | luca-tansini/advanced_programming | /Cyber/ngrams.py | 670 | 3.609375 | 4 | def findngramsinword(word,ngramlen,dictionary):
for i in range(0,1+len(word)-ngramlen):
ngram = word[i:i+ngramlen]
if(dictionary.get(ngram)): dictionary[ngram] += 1
else: dictionary[ngram] = 1
def isword(str):
for w in str:
if(not('A' <= w <= 'Z' or 'a' <= w <= 'z' or '0' <= w <= '9')): return False
return True
def sortdict(d):
return sorted(d.items(), key = lambda tuple: tuple[1])[-1:0:-1]
def findngramsintext(textfile,ngramlen):
d = dict()
for i in open(textfile):
j = i.split(' ')
for i in j:
if(isword(i)): findngramsinword(i.lower(),ngramlen,d)
return sortdict(d)[0:50]
|
a09b650302114c97cbba965cd07bf4422cfada58 | AmritaDeb/Automation_Repo | /PythonBasics/py_programas/Assignment_13_12_18/Fibonacii.py | 164 | 3.515625 | 4 | class Fibonacii:
def fibonacii(self,n):
a, b = 0, 1
for i in range(n):
print(a)
a,b=b,a+b
ob=Fibonacii()
ob.fibonacii(4) |
a074eb1eb1d7751d8ce3f8d601f97157314b4427 | takafumihoriuchi/learning_ReadableCode | /original1.py | 8,569 | 3.765625 | 4 | #a game of reversi (original)
import sys
class Board(object):
board = []
def __init__(self, row, col, blank):
self.row = row
self.col = col
self.blank = blank
def createBoard(self):
for i in range(self.row):
self.board.append([self.blank]*self.col)
def setBoard(self, set_row, set_col, color):
self.board[set_row][set_col] = color
def printBoard(self):
print ""
for i in self.board:
print(" ".join(i))
print ""
def possibleChoice(self, color):
possibility = 0 #number of choices of places where possible to put stone
for i in range(self.row):
for j in range(self.col):
if self.board[i][j]==self.blank:
if self.countUp(i,j,color)>0:
possibility+=1
return possibility
def gameSet(self, player_color, ai_color): #print out results
print("------------------")
cnt_player = 0
cnt_ai = 0
for i in range(self.row):
for j in range(self.col):
if self.board[i][j]==player_color:
cnt_player+=1
elif self.board[i][j]==ai_color:
cnt_ai+=1
print("Player (Black): %d" % cnt_player)
print("AI (White): %d" % cnt_ai)
if cnt_player>cnt_ai:
print("Winner : Player")
elif cnt_player<cnt_ai:
print("Winner : AI")
else:
print("Draw")
print("------------------")
sys.exit()
def countUp(self, row, col, color):
count=0
#down
for i in range(row+1, self.row):
if self.board[i][col]==color:
for ii in range(row+1, i):
count+=1
break
elif self.board[i][col]==self.blank:
break
#right
for i in range(col+1, self.col):
if self.board[row][i]==color:
for ii in range(col+1, i):
count+=1
break
elif self.board[row][i]==self.blank:
break
#up
for i in range(row-1,-1,-1):
if self.board[i][col]==color:
for ii in range(row-1,i,-1):
count+=1
break
elif self.board[i][col]==self.blank:
break
#left
for i in range(col-1,-1,-1):
if self.board[row][i]==color:
for ii in range(col-1,i,-1):
count+=1
break
elif self.board[row][i]==self.blank:
break
#left-upper
limit = min(row, col)
for i in range(1,limit+1):
if self.board[row-i][col-i]==color:
for ii in range(1,i):
count+=1
break
elif self.board[row-1][col-1]==self.blank:
break
#right-lower
limit = min(self.row-row, self.col-col)
for i in range(1,limit):
if self.board[row+i][col+i]==color:
for ii in range(1,i):
count+=1
break
elif self.board[row+i][col+i]==self.blank:
break
#left-lower
limit = min(self.row-row, col+1)
for i in range(1,limit):
if self.board[row+i][col-i]==color:
for ii in range(1,i):
count+=1
break
elif self.board[row+i][col-i]==self.blank:
break
#right-upper
limit = min(row+1, self.col-col)
for i in range(1,limit):
if self.board[row-i][col+i]==color:
for ii in range(1,i):
count+=1
break
elif self.board[row-i][col+i]==self.blank:
break
return count
class Player(object):
def __init__(self, color, my_board):
self.color = color
self.my_board = my_board
def selectPoint(self):
self.row = int(input("row: "))
self.col = int(input("col: "))
self.putStone()
def putStone(self):
if self.row not in range(self.my_board.row) or self.col not in range(self.my_board.col):
print("invalid input (out of range)")
self.selectPoint()
elif self.my_board.board[self.row][self.col]==my_board.blank:
if my_board.countUp(self.row, self.col, self.color)>0:
self.my_board.board[self.row][self.col] = self.color
else:
print("invalid input (unflippable)")
self.selectPoint()
else:
print("invalid input (already taken)")
self.selectPoint()
self.flipStone()
def flipStone(self):
#down
for i in range(self.row+1, my_board.row): #this will not be executed if self.row is out of range
if my_board.board[i][self.col]==self.color:
for ii in range(self.row+1, i):
my_board.board[ii][self.col] = self.color
break
elif my_board.board[i][self.col]==my_board.blank:
break
#right
for i in range(self.col+1, my_board.col):
if my_board.board[self.row][i]==self.color:
for ii in range(self.col+1, i):
my_board.board[self.row][ii] = self.color
break
elif my_board.board[self.row][i]==my_board.blank:
break
#up
for i in range(self.row-1,-1,-1):
if my_board.board[i][self.col]==self.color:
for ii in range(self.row-1,i,-1):
my_board.board[ii][self.col] = self.color
break
elif my_board.board[i][self.col]==my_board.blank:
break
#left
for i in range(self.col-1,-1,-1):
if my_board.board[self.row][i]==self.color:
for ii in range(self.col-1,i,-1):
my_board.board[self.row][ii] = self.color
break
elif my_board.board[self.row][i]==my_board.blank:
break
#left-upper
limit = min(self.row, self.col)
for i in range(1,limit+1):
if my_board.board[self.row-i][self.col-i]==self.color:
for ii in range(1,i):
my_board.board[self.row-ii][self.col-ii] = self.color
break
elif my_board.board[self.row-1][self.col-1]==my_board.blank:
break
#right-lower
limit = min(my_board.row-self.row, my_board.col-self.col)
for i in range(1,limit):
if my_board.board[self.row+i][self.col+i]==self.color:
for ii in range(1,i):
my_board.board[self.row+ii][self.col+ii] = self.color
break
elif my_board.board[self.row+i][self.col+i]==my_board.blank:
break
#left-lower
limit = min(my_board.row-self.row, self.col+1)
for i in range(1,limit):
if my_board.board[self.row+i][self.col-i]==self.color:
for ii in range(1,i):
my_board.board[self.row+ii][self.col-ii] = self.color
break
elif my_board.board[self.row+i][self.col-i]==my_board.blank:
break
#right-upper
limit = min(self.row+1, my_board.col-self.col)
for i in range(1,limit):
if my_board.board[self.row-i][self.col+i]==self.color:
for ii in range(1,i):
my_board.board[self.row-ii][self.col+ii] = self.color
break
elif my_board.board[self.row-i][self.col+i]==my_board.blank:
break
class ArtificialIntelligence(Player):
def aiCalculate(self):
#check the four-corners first
max_count = 0
for i in range(2):
for j in range(2):
if my_board.board[i*(my_board.row-1)][j*(my_board.col-1)]==my_board.blank:
count = my_board.countUp(i*(my_board.row-1),j*(my_board.col-1),self.color)
if count>max_count:
max_count = count
self.row = i*(my_board.row-1)
self.col = j*(my_board.col-1)
if max_count>0:
self.putStone()
else:
#if corner not possible, select point to get highest return in that round (if multiple choice, select point that appears first)
max_count = 0
for i in range(my_board.row):
for j in range(my_board.col):
if my_board.board[i][j]==my_board.blank:
count = my_board.countUp(i,j,self.color)
if count>max_count:
max_count = count
self.row = i
self.col = j
if max_count>0:
self.putStone()
my_board = Board(8,8,"O") #initialize board with "O" to represent open space
my_player = Player("B", my_board) #set my_player.color to "B" to represent black
my_ai = ArtificialIntelligence("W", my_board) #set my_ai.color to "W" to represent white
my_board.createBoard()
my_board.setBoard(4,3,my_player.color)
my_board.setBoard(3,4,my_player.color)
my_board.setBoard(3,3,my_ai.color)
my_board.setBoard(4,4,my_ai.color)
while True:
if my_board.possibleChoice(my_player.color)>0:
my_board.printBoard()
my_player.selectPoint()
else:
if not my_board.possibleChoice(my_ai.color)>0:
my_board.gameSet(my_player.color, my_ai.color)
if my_board.possibleChoice(my_ai.color)>0:
my_board.printBoard()
my_ai.aiCalculate()
else:
if not my_board.possibleChoice(my_player.color)>0:
my_board.gameSet(my_player.color, my_ai.color)
|
878ffea24ca0d8889c77f800551742ab3b515878 | munger100/ProjectEulerPython | /Completed/4.py | 292 | 4 | 4 | largest = 0
for one in range(100, 1000):
for two in range(100, 1000):
num = one * two
if str(num) == str(num)[::-1]:
if num > largest:
largest = num
print("Largest Palindrome Product of two 3 digit numbers is %s." % largest)
# Answer: 906609
|
be49779c1e197373cbf73b3294a06f68d1b01dc1 | saurabh-kumar88/Coding-Practice- | /Codebasics/Python_Advance_topics/multiprocess.py | 1,204 | 3.953125 | 4 | from multiprocessing import Process
import time
import math
#passing data B/w process using global variable.......
result = []
def cal_sqr(sqr):
for n in sqr:
result.append(n*n)
print("\nFrom Inside of function :" +str(result))
def cal_cube(cube):
for m in cube:
result.append(m*m*m)
print("\nFrom Inside of function :"+str(result))
#this is the main program
if __name__ == "__main__":
#common data which will be pass to both process
arr = [1,2,3]
p1 = Process(target = cal_sqr,args = (arr,))
p2 = Process(target = cal_cube,args = (arr,))
t1 = time.time()
p1.start()
p2.start()
p1.join()
p2.join()
print("multiprocessing took", time.time() - t1)
t2 = time.time()
cal_cube(arr)
cal_sqr(arr)
print("without multiprocessing ",time.time() - t2)
"""NOTE:Every process creates its own address-space(virtual memory) in which they
store their resuts,so result will only be access fron inside of process...
result will not flow go back to this global variable...so it will
be accesible from inside of function only.
To share data B/w process we have to use IPC(Inter Process Communication) techniques."""
|
fe4fc9a259a6a06cfc82768f0c1528298f7e3944 | p7on/epictasks1 | /6.3.del_element_list.py | 126 | 3.984375 | 4 | names = ['John', 'Paul', 'George', 'Ringo']
names = [elem for elem in names if elem == 'John' or elem == 'Paul']
print(names)
|
73fb819191c49ef12da49f614a9b440cda98994a | antoninabondarchuk/algorithms_and_data_structures | /linked lists/unique_list.py | 813 | 3.84375 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
result = ''
s = self
while s:
result += str(s.val) + '->'
s = s.next
return result[:-2]
def deleteDuplicates(head: ListNode) -> ListNode:
root = temp = ListNode(0)
while head.next:
if head.val != head.next.val:
temp.next = head
temp = temp.next
head = head.next
temp.next = head
return root.next
if __name__ == '__main__':
a = ListNode(1)
a1 = ListNode(1)
a2 = ListNode(2)
a3 = ListNode(3)
a4 = ListNode(3)
a.next = a1
a1.next = a2
a2.next = a3
a3.next = a4
result1 = deleteDuplicates(a)
print(result1)
|
e49eb2c43f8aff63e8f821cd1f4d25a2f1c79c7b | akrias/projects | /practice/flip.py | 828 | 3.625 | 4 | #!/bin/python
import numpy as np
def flipAndInvertImage(A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
#print len(A)
#print len(A[0])
output = []
for mat in A:
mat = mat[::-1]
#print mat
# numpy solution
'''a = np.array(mat)
a = 1 - a
output.append(list(a))
'''
i = 0
for char in mat:
if(char == 1):
char = 0
mat[i] = char
i += 1
else:
char = 1
mat[i] = char
i += 1
output.append(mat)
return output
A = [[1, 1, 0],
[1, 0, 1],
[0, 0, 0]]
A = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
print flipAndInvertImage(A) |
cfd369359d34757d936a22db8c618dd86f2b5a9c | sling254/madlibs | /madlibs game.py | 1,508 | 3.828125 | 4 |
name = raw_input("enter your name: ")
name2 = raw_input("enter your name: ")
chore = raw_input("Chore you hate to do:")
Adjective = raw_input("Adjective (a word that describes someone): ")
chore2 = raw_input("Another chore you hate to do: ")
party = raw_input("Name a kind of party: ")
noun = raw_input(" Noun (thing, object or animal): ")
number = raw_input("enter a really big number: ")
person = raw_input("enter a type of a person: ")
noun2 = raw_input(" Noun (thing, object or animal): ")
food = raw_input("enter type of food: ")
animal = raw_input("name an animal: ")
material = raw_input("Building material: ")
time = raw_input("time = input: ")
doparty = raw_input("something you do at a party: ")
interjection = raw_input("Interjection (single word expressing emotion): ")
room = raw_input("Room of a castle: ")
animal = raw_input("enter an animal: ")
print (name+"and"+name2+"They were mean to Cinderella and made her..."
+chore+"Cinderella pantomimes the chore while her stepsisters laugh at her."
"Then her stepmother comes on stage."
"NARRATOR (COnt.)"
"When Cinderella was done with that chore, her..."
+ Adjective+"Stepmother made her..."
+chore2+
"Stepmother acts in a way that fits the adjective in #4"
"# and Cinderella pantomimes the new chore. A prince appears on stage."
"NARRATOR (CONT.)"
"One day the Prince announced he was having a..." +party+"PRINCE I'm having a..."
)
|
0f140b5b3e9efab6f23212372a6df2f579f962b7 | D4nB113/Euler_Projects | /Euler3.py | 270 | 3.609375 | 4 | def largest_prime_factor(number):
factor = number
counter = 2
while counter <= factor ** 0.5:
if factor % counter == 0:
factor = factor / counter
counter -= 1
counter += 1
if factor >= 2:
return factor
|
1f416156238c48ff1e88c674f70d69363c28c9a1 | B-R-H/Tic-tac-toe | /player.py | 1,902 | 3.59375 | 4 | import random as r
def random_player(board):
#Random player
not_placed = True
while not_placed:
x=r.randint(0,2)
y=r.randint(0,2)
if board[x][y]==None:
return [x,y]
def check_line(start_cordinate,direction,board):
line_values = []
if direction == "v":
#virtical code
for i in range(3):
line_values.append(board[start_cordinate[0]][i])
elif direction == "h":
#horizontal code
for i in range(3):
line_values.append(board[i][start_cordinate[1]])
elif direction == "d":
#diagnol code
line_values = [board[start_cordinate[0]][0],board[1][1],board[2-start_cordinate[0]][2]]
return line_values
def finishing_a_line(vls,hls,dls,player):
for i in vls:
if i.count(player)==2 and i.count(None) != 0:
return [vls.index(i),i.index(None)]
for i in hls:
if i.count(player)==2 and i.count(None) != 0:
return [i.index(None),hls.index(i)]
for i in dls:
if i.count(player)==2 and i.count(None) != 0:
if i.index(None)==1:
return[1,1]
elif dls.index(i)==0:
return [i.index(None),i.index(None)]
else:
return[2-i.index(None),i.index(None)]
return [None,None]
def compitant_player(board,player):
turn_number = 9-sum((x).count(None) for x in board)
print("Current turn is",turn_number)
if turn_number == 0:
return [0,0]
elif turn_number == 1:
if board[0][0] == None:
return[0,0]
return [1,1]
else:
#Getting all of the values of the lines on the board
vls=[check_line([0,0],"v",board),check_line([1,0],"v",board),check_line([2,0],"v",board)]
hls=[check_line([0,0],"h",board),check_line([0,1],"h",board),check_line([0,2],"h",board)]
dls=[check_line([0,0],"d",board),check_line([2,0],"d",board)]
#wining line
x,y = finishing_a_line(vls,hls,dls,player)
if x!=None:
return[x,y]
#blocking line
x,y = finishing_a_line(vls,hls,dls,(player+1)%2)
if x!=None:
return[x,y]
x,y = random_player(board)
return [x,y] |
cbbd9ea34445ee45c301e2ff90433526e44f8c76 | fanliu1991/LeetCodeProblems | /43_Multiply_Strings.py | 2,308 | 4.3125 | 4 | '''
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
Note:
The length of both num1 and num2 is < 110.
Both num1 and num2 contain only digits 0-9.
Both num1 and num2 do not contain any leading zero, except the number 0 itself.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
Example 1:
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:
Input: num1 = "123", num2 = "456"
Output: "56088"
'''
import sys, optparse, os
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
'''
num2 4 5 6
num1 1 2 3
----------------------
n1=3, n2=6 1 8
n1=3, n2=5 1 5
n1=3, n2=4 1 2
n1=2, n2=6 1 2
n1=2, n2=5 1 0
n1=2, n2=4 8
n1=1, n2=6 6
n1=1, n2=5 5
n1=1, n2=6 4
----------------------
0 5 6 0 8 8
'''
product = [0] * (len(num1) + len(num2))
product_start_position = len(product) - 1
for n1 in reversed(num1):
digit_position = product_start_position
for n2 in reversed(num2):
temp_result = int(n1) * int(n2) + product[digit_position]
product[digit_position] = temp_result % 10
product[digit_position-1] += temp_result / 10
digit_position = digit_position - 1
product_start_position = product_start_position - 1
leading_number_position = 0
for i in range(0, len(product)-1):
if product[i] == 0:
leading_number_position += 1
else:
break
leading_number_product = "".join([str(digit) for digit in product[leading_number_position:]])
return leading_number_product
num1 = "123"
num2 = "456"
solution = Solution()
result = solution.multiply(num1, num2)
print result
'''
Complexity Analysis
Time complexity : O(n^2).
A iteration of num2 is needed for each digit in num1.
Space complexity : O(n).
Extra space len(num1) + len(num2) is used.
'''
|
5d6e3416acd2d5c88595513385d1537173caa66a | shadowkael/some_single_py | /LintCode/search_matrix.py | 497 | 3.90625 | 4 | def searchMatrix(matrix, target):
# write your code here
if not matrix:
return False
if target < matrix[0][0]:
return False
if target > matrix[-1][-1]:
return False
for item in matrix:
if item[-1] >= target:
for num in item:
if num == target:
return True
else:
return False
print(searchMatrix([[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]], 7))
|
54ac12d913965204f925a85f5a1d914e1751edc1 | navneettomar11/learn-py | /hackerrank/NestedList.py | 813 | 3.75 | 4 | from typing import List
def findStudentSecondLowestGrade(students: List):
lowest = 9999999999
secondLowest = 0
nameList = []
for student in students:
score = student[1]
if lowest > score:
secondLowest = lowest
lowest = score
elif lowest != score and secondLowest > score:
secondLowest = score
for student in students:
name = student[0]
score = student[1]
if score == secondLowest:
nameList.append(name)
nameList.sort()
for name in nameList:
print(name)
if __name__ == '__main__':
studentList = []
for _ in range(int(input())):
name = input()
score = float(input())
studentList.append([name, score])
findStudentSecondLowestGrade(studentList)
|
38b09fdc75c81cf254cf28a3edfba630fdfe080a | xxd/algorithm004-04 | /Week 08/id_049/LeetCode_151_049.py | 233 | 3.625 | 4 | class Solution:
def reverseWords(self, s: str) -> str:
s = s.strip()
tmp = []
for i in s.split(" "):
if i != "":
tmp.append(i)
tmp.reverse()
return " ".join(tmp) |
7ccd8f02b4089baa1f82f88d04019fca23926e50 | fbhs-cs/CS1-classcode | /Misc/matrix.py | 4,171 | 3.59375 | 4 | #!/usr/bin/env python3
import random
import curses
import time
#Sleep between frame after refresh so that user can see the frame. Value 0.01 or lower results in flickering because the
# animation is too fast.
SLEEP_BETWEEN_FRAME = .04
#How fast the rain should fall. In config, we change it according to screen.
FALLING_SPEED = 2
#The max number of falling rains. In config, we change it according to screen.
MAX_RAIN_COUNT = 10
#Color gradient for rain
COLOR_STEP = 20
START_COLOR_NUM = 128 #The starting number for color in gradient to avoid changing the first 16 basic colors
NUMBER_OF_COLOR = 40
USE_GRADIENT = False
#Reset the config value according to screen size
def config(stdscr):
curses.curs_set(0)
stdscr.nodelay(True)
init_colors()
global MAX_RAIN_COUNT
MAX_RAIN_COUNT = curses.COLS//3
global FALLING_SPEED
FALLING_SPEED = 1 + curses.LINES//25
def init_colors():
curses.start_color()
global USE_GRADIENT
USE_GRADIENT = curses.can_change_color() # use xterm-256 if this is false
if USE_GRADIENT:
curses.init_color(curses.COLOR_WHITE, 1000, 1000, 1000)
for i in range(NUMBER_OF_COLOR + 1):
green_value = (1000 - COLOR_STEP * NUMBER_OF_COLOR) + COLOR_STEP * i
curses.init_color(START_COLOR_NUM + i, 0, green_value, 0)
curses.init_pair(START_COLOR_NUM + i, START_COLOR_NUM + i, curses.COLOR_BLACK)
else:
curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
def get_matrix_code_chars():
l = [chr(i) for i in range(0x21, 0x7E)]
# half-width katakana. See https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms
l.extend([chr(i) for i in range(0xFF66, 0xFF9D)])
return l
MATRIX_CODE_CHARS = get_matrix_code_chars()
def random_char():
return random.choice(MATRIX_CODE_CHARS)
def random_rain_length():
return random.randint(curses.LINES//2, curses.LINES)
def rain(stdscr, pool):
while True:
x = random.choice(pool)
pool.remove(x)
max_length = random_rain_length()
speed = random.randint(1, FALLING_SPEED)
yield from animate_rain(stdscr, x, max_length, speed)
pool.append(x)
def animate_rain(stdscr, x, max_length, speed=FALLING_SPEED):
head, middle, tail = 0,0,0
while tail < curses.LINES:
middle = head - max_length//2
if (middle < 0):
middle = 0
tail = head - max_length
if (tail < 0):
tail = 0
show_body(stdscr, head, middle, tail, x)
show_head(stdscr, head, x)
head = head + speed
yield
def show_head(stdscr, head, x):
if head < curses.LINES:
stdscr.addstr(head, x, random_char(), curses.color_pair(0) | curses.A_STANDOUT)
def show_body(stdscr, head, middle, tail, x):
if USE_GRADIENT:
for i in range(tail, min(head, curses.LINES)):
stdscr.addstr(i, x, random_char(), get_color(i, head, tail))
else:
for i in range(tail, min(middle, curses.LINES)):
stdscr.addstr(i, x, random_char(), curses.color_pair(1))
for i in range(middle, min(head, curses.LINES)):
stdscr.addstr(i, x, random_char(), curses.color_pair(1) | curses.A_BOLD)
def get_color(i, head, tail):
color_num = NUMBER_OF_COLOR - (head - i) + 1
if color_num < 0:
color_num = 0
return curses.color_pair(START_COLOR_NUM + color_num)
def main(stdscr):
stdscr.addstr(0, 0, "Press any key to start. Press any key (except SPACE) to stop.")
ch = stdscr.getch() #Wait for user to press something before starting
config(stdscr)
rains = []
pool = list(range(curses.COLS - 1))
while True:
add_rain(rains, stdscr, pool)
stdscr.clear()
for r in rains:
next(r)
ch = stdscr.getch()
if ch != curses.ERR and ch != ord(' '): #Use space to proceed animation if nodelay is False
break
time.sleep(SLEEP_BETWEEN_FRAME)
def add_rain(rains, stdscr, pool):
if (len(rains) < MAX_RAIN_COUNT) and (len(pool) > 0):
rains.append(rain(stdscr, pool))
if __name__ == "__main__":
curses.wrapper(main) |
accfeb2823421760f736c87a13bd14ee62100ff9 | pentagram5/Python_study | /์กฐ๊ฑด๋ฌธ ๋ฐ๋ณต๋ฌธ ํ์ฉํ๊ธฐ.py | 13,918 | 3.96875 | 4 | # -*- coding: utf-8 -*-
#############################################################################################
"""if๋ฌธ ํ์ฉํ๊ธฐ"""
a = 200
a = 50
if a<100:
print("100๋ณด๋ค ์๋ค ")
else :
print("100๋ณด๋ค ํฌ๋ค ")
print("==========๊ฒฐ๊ณผ================")
price = int(input("๊ตฌ์
๊ธ์ก์ ์
๋ ฅํ์์ค:"))
if price > 100000:
price = price*0.95
print("์ง๋ถ ๊ธ์ก์ %.1f์์
๋๋ค" % price)
else :
print("5% ํ ์ธ ํํ์ด ์์ต๋๋ค.")
print("์ง๋ถ๊ธ์ก์ %d์
๋๋ค." % price)
x = 3; y =2;
x>y
x<y
x==y
x!=y
money = 2000
if money >= 3000:
print("ํ์๋ฅผ ํ๊ณ ๊ฐ๋ผ")
else:
print("๊ฑธ์ด๊ฐ๋ผ")
print("=================================")
bag = float(input("์ง์ ๋ฌด๊ฒ๋ฅผ ์
๋ ฅํ์ธ์:"))
if bag >20:
print("๋ฌด๊ฑฐ์ด ์ง์ 20,000์์ ๋ด์
์ผ ํฉ๋๋ค")
else:
print("์ง์ ๋ํ ์์๋ฃ๋ ์์ต๋๋ค.")
print("๊ฐ์ฌํฉ๋๋ค")
print("=================================")
tem = float(input("ํ์ฌ ๊ธฐ์จ๋ฅผ ์
๋ ฅํ์ธ์:"))
if tem > 30:
print("๋ฐ๋ฐ์ง๋ฅผ ์
์ผ์ธ์. ")
else:
print("๊ธด๋ฐ์ง๋ฅผ ์
์ผ์ธ์.")
print("๋๊ฐ์ ์ด๋ํ์ญ์ผ.")
inte = int(input("์ ์๋ฅผ ์
๋ ฅํ์ธ์:"))
if (inte % 2) == 0:
print("์ง์ ์
๋๋ค.")
else :
print("ํ์ ์
๋๋ค.")
#if ๋ฌธ์ ์กฐ๊ฑด๋ถ ๋ฃ์ด๋ณด๊ธฐ
#and, or, nor, in, not in etc...
money = 2000
card = input("์นด๋๊ฐ ์์ต๋๊น? (y/n):")
if money >3000 or card == 'y' or card == 'Y':
print("ํ์๋ฅผ ํ๊ณ ๊ฐ๋ผ")
else:
print("๊ฑธ์ด๊ฐ์ธ์")
x= [1,2,3]
1 in x
5 in x
'j' not in 'python'
pocket= list(input("์ฃผ๋จธ๋์ ์๋๊ฒ๋ค์ ์จ์ฃผ์ธ์ :\n").split(','))
if 'money' in pocket:
print("ํ์๋ฅผ ํ๊ณ ๊ฐ๋ผ")
else:
print("๊ฑธ์ด๊ฐ์ธ์")
pocket2= list(input("์ฃผ๋จธ๋์ ์๋๊ฒ๋ค์ ์จ์ฃผ์ธ์ :\n").split(','))
if 'card' or 'money' in pocket2:
print("๋ฒ์ค๋ฅผ ํ์์ค")
else:
print("๊ฑธ์ด๊ฐ์ธ์")
pocket = ['paper','money','cellphone']
if 'money' in pocket:
pass
else:
print("์นด๋๋ฅผ ๊บผ๋ด๋ผ")
# ์ค์ฒฉ if ๋ฌธ ์ฌ์ฉํด๋ณด๊ธฐ
a = int(input("์ซ์๋ฅผ ์
๋ ฅํด๋ณด์ธ์:"))
if a> 50:
if a <100:
print("50 ๋ณด๋ค ํฌ๊ณ , 100๋ณด๋ค ์๊ตฐ์.")
else:
print("100๋ณด๋ค ํจ์ฌ ํฌ๋ค์!")
else:
print("50๋ณด๋ค๋ ์๋ค์!")
score = int(input("์ ์๋ฅผ ์
๋ ฅํ์ธ์:"))
if score >= 95:
grade = 'A+'
elif score >= 90:
grade = 'A'
elif score >= 85:
grade = 'B+'
elif score >= 80:
grade = 'B'
elif score >= 75:
grade = 'C+'
elif score >= 70:
grade = 'C'
elif score >= 65:
grade = 'D+'
elif score >=60:
grade = 'D'
else:
grade = 'F'
print("ํ์ = %s"% grade)
sco = 57
if sco >= 60:
print("ํฉ๊ฒฉ")
elif sco >= 40:
print("๋ถํฉ๊ฒฉ์ด๋ ๊ณผ๋ฝ์ ์๋")
else:
print("๋ถํฉ๊ฒฉ์ ๊ณผ๋ฝ์")
while 1:
num = int(input("1. ์
๋ ฅํ ์์ ๊ณ์ฐ 2. ๋ ์ ์ฌ์ด์ ํฉ๊ณ:"))
if num == 1:
a = str(input("*****์์์ ์
๋ ฅํ์ธ์ :"))
result = eval(a)
#eval ํจ์๋, ์ฌ์น์ฐ์ฐ์ด ํฌํจ๋ ์์(์คํธ๋งํ)์ ๊ณ์ฐํด์ฃผ๋ ํจ์
print(a,"์ ๊ฒฐ๊ณผ๋ %.1f์
๋๋ค"% result)
break
elif num == 2:
a = int(input("*****์ฒซ๋ฒ์งธ ์๋ฅผ ์
๋ ฅํ์ธ์ : "))
b = int(input("*****๋๋ฒ์งธ ์๋ฅผ ์
๋ ฅํ์ธ์ : "))
print(a,"+",b,"์ %d์
๋๋ค"% (a+b))
break
else:
print("1์ด๋ 2๋ฅผ ์ ํํ์ธ์")
mon = int(input("์์ ์
๋ ฅํ์ธ์:"))
if mon == 2:
print(mon,"์์ ๋ ์๋ 29์ผ")
elif mon in (4,6,9,10):
print(mon,"์์ ๋ ์๋ 30์ผ")
else:
print(mon,"์์ ๋ ์๋ 31์ผ")
#############################################################################################
"""๋ฐ๋ณต๋ฌธwhile"""
num = 4
while num <1000:
num= num+1
print(num)
#์กฐ๊ฑด๋ฌธ์ ์๋ฐํ๋ฉด, while ๋ฌธ์ ๋ด์ฉ์ ๋์ด์ ์คํ๋์ง ์๋๋ค
i = 0
while i<10:
print("%d : ์๋
ํ์ธ์? while ๋ฌธ์ ๊ณต๋ถ์ค์
๋๋ค. ^^7" %i)
i = i+1
sum, i = 0,0
while i<11:
sum +=i
i = i+1
print(sum)
hap,a,b = 0,0,0
while True:
a = int(input("1:"))
b = int(input("2:"))
hap = a+b
print("%d + %d = % d"% (a,b,hap))
while True:
one = input("์ฒซ๋ฒ์งธ ์๋ฅผ ์
๋ ฅํ์ธ์:")
if one == '0':
print("0์ด ์
๋ ฅ๋์์ต๋๋ค. ์ข
๋ฃํฉ๋๋ค.")
break
two = input("๋๋ฒ์งธ ์๋ฅผ ์
๋ ฅํ์ธ์:")
car = input("์ฐ์ฐ์๋ฅผ ์
๋ ฅํ์ธ์:")
if car not in('*','/','%','+','-','**'):
print("์ฐ์ฐ์๋ฅผ ์๋ชป ์
๋ ฅํ์ต๋๋ค.")
break
tot = one+car+two
print("%s %s %s = %.1f" %(one, car, two, eval(tot)))
coffe = 5
while True:
money = int(input("๋์ ๋ฃ์ด ์ฃผ์ธ์:"))
if money == 300:
print("๋์ ๋ฐ์์ผ๋ ์ปคํผ๋ฅผ ์ค๋๋ค")
coffe -= 1
elif money > 300:
print("๊ฑฐ์ค๋ฆ๋ %d๋ฅผ ์ฃผ๊ณ ์ปคํผ๋ฅผ ์ค๋๋ค." %(money -300))
coffe -=1
else:
print("๋ํํ
์ค ์ปคํผ๋ ์์ต๋๋ค.")
print("๋จ์ ์ปคํผ๋ %d์
๋๋ค." % coffe)
if not coffe:
print("์ฌ๊ณ ๊ฐ ์์ต๋๋ค. ")
break;
a = 0
while a <10:
a +=1
if a%2 == 0:
continue
#continue ์๋์ ์ฝ๋๋ฅผ ์คํํ์ง ์๊ณ while ๋ฌธ ์ฒ์์ผ๋ก ๋์๊ฐ๋ค.
print(a)
#############################################################################################
"""๋ฌธ์ ํ๊ธฐ
1. ๋์ด๋ (2020 - ํ์ด๋ ์ฐ๋ +1)๋ก ๊ณ์ฐ
26์ธ ์ดํ 20์ธ ์ด์์ด๋ฉด '๋ํ์', 20์ธ ๋ฏธ๋ง 17์ธ ์ด์์ด๋ฉด '๊ณ ๋ฑํ์'
17์ธ ๋ฏธ๋ง 14์ธ ์ด์์ด๋ฉด '์คํ์', 14์ธ ๋ฏธ๋ง 8์ธ ์ด์์ด๋ฉด '์ด๋ฑํ์'
๊ทธ ์ธ์ ๊ฒฝ์ฐ๋ 'ํ์์ด ์๋๋๋ค.' ์ถ๋ ฅํ์ธ์.
"""
while True:
year = int(input("๋น์ ์ด ํ์ด๋ ๋
๋๋ฅผ ์
๋ ฅํ์ธ์:"))
age = 2020-year+1
if 26>=age>=20:
student = '๋ํ์'
elif 20>age>=17:
student = '๊ณ ๋ฑํ์'
elif 17>age>=14:
student = '์คํ์'
elif 14>age>=8:
student = '์ด๋ฑํ์'
else:
print("๋์ด๋ %d, ํ์์ด ์๋๋๋ค." %age)
continue
print("๋์ด๋ %d, %s์
๋๋ค."%(age, student))
"""
2. while๋ฌธ์ ์ด์ฉํ์ฌ ์๋์ ๊ฐ์ ๊ฒฐ๊ณผ๊ฐ ๋์ค๋๋ก ํ๋ก๊ทธ๋จ์ ์์ฑํด ๋ณด์ธ์.
์- ๊ฒฐ๊ณผ1)
์์๊ฐ์ ์
๋ ฅํ์ธ์ : 2
๋๊ฐ์ ์
๋ ฅํ์ธ์ : 10
์ฆ๊ฐ๊ฐ์ ์
๋ ฅํ์ธ์ : 3
2์์ 10๊น์ง 3์ฉ ์ฆ๊ฐ์ํจ ๊ฐ์ ํฉ๊ณ : 15
"""
start = int(input("์์๊ฐ์ ์
๋ ฅํ์ธ์:"))
end = int(input("๋๊ฐ์ ์
๋ ฅํ์ธ์:"))
plus = int(input("์ฆ๊ฐ๊ฐ์ ์
๋ ฅํ์ธ์:"))
i,tot = 0,0
while (start+i) < (end+1):
tot+=start+i
i+=plus
print("%d๋ถํฐ %d๊น์ง %d์ฉ ์ฆ๊ฐ์ํจ ๊ฐ์ ํฉ์ %d์
๋๋ค."%(start, end, plus, tot))
#############################################################################################
#############################################################################################
"""for ์จ๋ณด๊ธฐ"""
for i in range(0,100,1):
print("์๋
ํ์ธ์? %d๋ฒ์งธ ์ธ์ฌ "%(i+1))
for i in range(3):
print("์๋
ํ์ธ์? %d๋ฒ์งธ ์ธ์ฌ "%(i+1))
#์ด๊ธฐ ๊ฐ์ ์ฃผ์ด์ฃผ์ง ์์ผ๋ฉด ์๋์ผ๋ก 0์ผ๋ก ์กํ๊ณ , ์ฆ๊ฐ๊ฐ์ 1์ด๋ค.
for i in range(3,0,-1):
print("์๋
ํ์ธ์? %d๋ฒ์งธ ์ธ์ฌ "%(i))
#์ฆ๊ฐ๊ฐ์ -๋ก ์ฃผ๋ฉด ๊ฐ์ํ๊ฒ ์ด์ฉํ ์ ์๋ค
for i in range(1,6):
print("ํ์ํฉ๋๋ค! %d๋ฒ์งธ ์ธ์ฌ "%(i))
for i in range(1,10,2):
print("ํ์ํฉ๋๋ค! %d๋ฒ์งธ ์ธ์ฌ "%(i))
name = ['์ฒ ์', '์ํฌ', '๊ธธ๋', '์ ์ ']
for i in range(0,len(name)):
print("ํ์ํฉ๋๋ค! %s "%(name[i]))
for i in ['์ฒ ์', '์ํฌ', '๊ธธ๋', '์ ์ ']:
print("ํ์ํฉ๋๋ค! %s "%i)
#๋ฆฌ์คํธ์ ์ฐ๊ณํด์ ์ฌ์ฉํด๋ณด๊ธฐ
for i in range(10, 1, -1):
print(i)
for i in range(20, 3, -4):
print(i)
#############################################################################################
for i in range(1,10,3):
for j in range(1,10):
for k in range(0,3):
print("%d * %d = %2d "%((i+k),j, (i+k)*j), end = ' ')
print("\n")
print("\n")
#end = ' '๋ฅผ ์จ์ค์ผ๋ก์จ, for๋ฌธ์ด ๋ฐ๋ณต๋ ๋ ์ถ๋ ฅ์ด ๋ค์์ผ๋ก ๋์ด๊ฐ์ง ์๋๋กํด์ค๋ค.
#############################################################################################
"""while๊ณผ for์ ์ด์ฉํด ๊ตฌ๊ตฌ๋จ ํ๋ก๊ทธ๋จ ์ฝ๋ฉํ๊ธฐ"""
while True:
num =int(input("๊ตฌ๊ตฌ๋จ ๋ช๋จ์ ๊ณ์ฐํ ๊น์?(1~9)"))
if num == 99:
print("ํ๋ก๊ทธ๋จ์ ์ข
๋ฃํฉ๋๋ค")
break
elif num not in range(1,10,1):
print("1๊ณผ 9 ์ฌ์ด์ ์๋ฅผ ์
๋ ฅํ์ธ์")
continue
print("๊ตฌ๊ตฌ๋จ %d๋จ์ ๊ณ์ฐํฉ๋๋ค."%(num))
for i in range(1,10):
print("%d x %d = %d"%(num, i , num*i))
#############################################################################################
"""for๋ฌธ์ ์ด์ฉํด ํฉ๊ณ ๊ตฌํ๊ธฐ"""
hap = 0
for i in range(1,11,1):
hap+=i
print("1๋ถํฐ 10๊น์ง์ ํฉ๊ณ = %d"%hap)
#############################################################################################
tot = 0
for i in range(501,1001, 2):
tot +=i
print("501๋ถํฐ 1001๊น์ง ํ์์ ํฉ๊ณ = %d"%tot)
#############################################################################################
tot = 0
for i in range(0,100, 7):
tot +=i
print("0๊ณผ 100์ฌ์ด์ 7์ ๋ฐฐ์์ ํฉ = %d"%tot)
#############################################################################################
tot = 0
num = int(input("์ซ์๋ฅผ ์
๋ ฅํ์ธ์:"))
for i in range(0,num):
tot +=i
print("1๋ถํฐ %d๊น์ง์ ํฉ๊ณ = %d"%(num,tot))
#############################################################################################
start = int(input("์์๊ฐ์ ์
๋ ฅํ์ธ์:"))
end = int(input("๋๊ฐ์ ์
๋ ฅํ์ธ์:"))
plus = int(input("์ฆ๊ฐ๊ฐ์ ์
๋ ฅํ์ธ์:"))
tot = 0
for i in range(start, end+1, plus):
tot+=i
print("%d๋ถํฐ %d๊น์ง์ %d๋งํผ ์ฆ๊ฐ๊ธฐํจ ๊ฐ์ ํฉ๊ณ = %d"%(start,end,plus,tot))
#############################################################################################
num =int(input("๊ตฌ๊ตฌ๋จ ๋ช๋จ์ ๊ณ์ฐํ ๊น์?(1~9)"))
print("๊ตฌ๊ตฌ๋จ %d๋จ์ ๊ณ์ฐํฉ๋๋ค."%(num))
for i in range(9,0,-1):
print("%d x %d = %d"%(num, i , num*i))
#############################################################################################
"""์ค์ฒฉfor๋ฌธ ์ฌ์ฉํ๊ธฐ"""
for i in range(0,3):
for k in range(0,2):
print("ํ์ด์ฌ์ ์ผ๋ฏผ์
๋๋ค. ^^ i = %d, k = %d"%(i,k))
for i in range(1,10):
print("### %d๋จ ###"%i)
for j in range(1,10):
print("%d X %d = %2d "
%(i,j, i*j))
print("\n")
#############################################################################################
"""for ๋ฌธ์์ break์ฌ์ฉํ๊ธฐ"""
for i in range(1,100):
print("for ๋ฌธ์ %d๋ฒ ์คํํ์ต๋๋ค. " %i)
break
hap = 0
for i in range(1,1001,2):
hap +=i
if hap >=1000:
break
print("1๊ณผ 1000์ฌ์ด์ ์์ค, ํ์๋ค์ ํฉ๊ณ๊ฐ 1000์๋์ด๊ฐ๋ ์ซ์= %d, ํฉ๊ณ = %d"%(i,hap))
#############################################################################################
"""for ๋ฌธ์์ continue ์ฌ์ฉํ๊ธฐ """
hap ,i = 0,0
for i in range(1,101):
if i%3 ==0:
continue
hap +=i
print("3์๋ฐฐ์๋ฅผ ์ ์ธํ 1~100๊น์ง ํฉ๊ณ = %d"%hap)
#############################################################################################
"""๋ฆฌ์คํธ์ for๋ฌธ ํ์ฉ"""
aa=[]
for i in range(0,4):
aa.append(0)
hap = 0
for i in range(0,4):
aa[i] = int(input("%d๋ฒ์งธ ์ซ์:"%(i+1)))
hap +=aa[i]
print("๋ฆฌ์คํธ = %s, ํฉ๊ณ = %d"%(aa,hap))
test_list = ['one','two','three']
for i in test_list:
print(i)
#๋ฆฌ์คํธ ๋ด์ ๋ฐ์ดํฐ๋ฅผ range ๊ฐ๋
์ผ๋ก ์ฌ์ฉ๊ฐ๋ฅ
a= [(1,2),(3,4),(5,6)]
for (i,j) in a:
print(i,j, i+j)
#ํํํํ์ ๋ฐ์ดํฐ๋ ์ถ๋ ฅ๊ฐ๋ฅํ๋ค.
marks =[90,20,50,80,77]
number =0
for score in marks:
number = number+1
if score<60: continue
print("%d๋ฒ ํ์์ %d์ ์ผ๋ก, ํฉ๊ฒฉ์
๋๋ค."%(number,score))
numlist = []
for num in range(1,6):
numlist.append(num)
print(numlist)
#์ปดํ๋ฆฌ ํธ์
์ผ๋ก ์ค์ผ์ ์๋ค.->๋ฆฌ์คํธ ๋ด๋ถ์ for๋ฌธ ์ฌ์ฉ
#๋ฆฌ์คํธ ๋ด๋ถ์ for๋ฌธ์ ๋ฃ์ด์ฃผ๊ณ , ๋ณ์๋ฅผ range์์ ์ ํด์ค ๋ฒ์๋งํผ ์ง์ด๋ฃ๋๋ค.
numlist_com = [num for num in range(1,6)]
print(numlist_com)
numlist_com = [num*num for num in range(1,6)]
print(numlist_com)
#range๋ฒ์ ๋ด์์, 3์ ๋ฐฐ์์ธ number๋ง ๋ฆฌ์คํธ์ ๋ฃ์ด์ค๋
numlist_com = [num for num in range(1,22) if num %3 ==0]
print(numlist_com)
# ๋ค๋ฅธ ๋ฆฌ์คํธ์ value๋ฅผ ๊ฐ์ ธ์ฌ ์๋ ์๋ค.
numlist_com2 = [num*2 for num in numlist_com if num%2 == 0]
print(numlist_com2)
#์ด์ค for๋ฌธ ์ปดํ๋ฆฌ ํธ์
๊ตฌํ
nine = [(str(x)+'x'+str(y)+'='+str(x*y))for x in range(2,10) for y in range(1,10)]
nine
#์์ฃผ ํ์ฉ๋๋ ๊ฒ์ด๊ธฐ ๋๋ฌธ์, ์ ํ์ฉ ํ๋ค.
"""๋ฌธ์ ํ์ด๋ณด๊ธฐ!"""
for i in range(0,10):
for j in range(2,10):
if i == 0:
print(" # %d๋จ #"%j,end = ' ')
else:
print("%d X%2d= %2d"%(j,i,i*j), end = ' ')
print('\n')
for i in range(10,0, -1):
for j in range(9,1,-1):
if i == 10:
print(" # %d๋จ #"%j,end = ' ')
else:
print("%d X%2d= %2d"%(j,i,i*j), end = ' ')
print('\n')
love ='i like you'
for i in range(len(love)-1,-1,-1):
print(love[i], end ='')
tot = 1
for i in range(1,11):
tot*=i
print("10!์ %d์
๋๋ค!"%tot) |
2562a5e6bb63c7e94a0488fda432697bba45638a | sunrain0707/python_exercise_100 | /ex44.py | 339 | 3.828125 | 4 | #44.ไธคไธช 3 ่ก 3 ๅ็็ฉ้ต๏ผๅฎ็ฐๅ
ถๅฏนๅบไฝ็ฝฎ็ๆฐๆฎ็ธๅ ๏ผๅนถ่ฟๅไธไธชๆฐ็ฉ้ต๏ผ
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
sum = [[0,0,0],
[0,0,0],
[0,0,0]]
for i in range(0,3):
for j in range(0,3):
sum[i][j]=(X[i][j]+Y[i][j])
print(sum) |
47d5e896d05111a48b4f4fcd441e7b5d98992bcc | shantanu609/Competitive-Coding-10 | /PeekingIterator.py | 1,108 | 4.03125 | 4 | # Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Your code here along with comments explaining your approach
class PeekingIterator:
temp = None
def __init__(self, iterator):
"""
Initialize your data structure here.
:type iterator: Iterator
"""
self.itr = iterator
if self.itr.hasNext():
self.temp = self.itr.next()
# Time = O(1) | Space = O(1)
def peek(self):
"""
Returns the next element in the iteration without advancing the iterator.
:rtype: int
"""
return self.temp
# Time = O(1) | Space = O(1)
def next(self):
"""
:rtype: int
"""
prev = self.temp
if self.itr.hasNext():
self.temp = self.itr.next()
else:
self.temp = None
return prev
# Time = O(1) | Space = O(1)
def hasNext(self):
"""
:rtype: bool
"""
if self.temp is not None :
return True
else:
return False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.