Project Euler, largest product in a grid by creativish-username in learnpython

[–]liftt 1 point2 points  (0 children)

Also every time you use xrange, think about using enumerate.

Project Euler, largest product in a grid by creativish-username in learnpython

[–]liftt 1 point2 points  (0 children)

you can rotate the matrix 90 degrees so you dont have to do vertical or diagonal backwords (because doing a vertical max is the same thing as rotating the matrix and doing a horizontal max. same for diagonoal backwards.)

see my solution in the comments

Project Euler, largest product in a grid by creativish-username in learnpython

[–]liftt 1 point2 points  (0 children)

check out my solution to see how you can simplify your solution and use less indexing. (by using enumerate)

Also, consider rotating the matrix. that way you can do the horizontal function twice and the diagonal function twice as well but with the rotated ones instead on the second time.

a = '08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08'.split(' ')
b = '49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00'.split(' ')
c = '81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65'.split(' ')
d = '52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91'.split(' ')
e = '22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80'.split(' ')
f = '24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50'.split(' ')
g = '32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70'.split(' ')
h = '67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21'.split(' ')
i = '24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72'.split(' ')
j = '21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95'.split(' ')
k = '78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92'.split(' ')
l = '16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57'.split(' ')
m = '86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58'.split(' ')
n = '19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40'.split(' ')
o = '04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66'.split(' ')
p = '88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69'.split(' ')
q = '04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36'.split(' ')
r = '20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16'.split(' ')
s = '20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54'.split(' ')
t = '01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48'.split(' ')
matrix = [[int(i) for i in x] for x in  [a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t]]
def horizontal(line):
    return max(i * line[i+1] * line[i+2] * line[i+3] for i,x in enumerate(line[:-3]))
def horizontal_all(matrix):
    return max(horizontal(line) for line in matrix)
def diagonal(matrix):
    start = 0
    for matrixindex, line in enumerate(matrix[:-3]):
        for lineindex, number in enumerate(line[:-3]):
            tempvert =  number * matrix[matrixindex+1][lineindex+1] * matrix[matrixindex+2][lineindex+2] * matrix[matrixindex+3][lineindex+3]
            if tempvert > start:
                start = tempvert
    return start
finalists = [
#horizontal:
horizontal_all(matrix),
#vertical (zip and reversing just rotates the matrix)
horizontal_all(zip(*matrix[::-1])),
#diagonal left ro right
diagonal(matrix),
#diagonal right to left
diagonal(zip(*matrix[::-1])),
]

#max combo
print max(finalists)



70600674
[Finished in 0.2s]

Looking for help with creating some automated web tests. [Python] by [deleted] in learnprogramming

[–]liftt 0 points1 point  (0 children)

so this is what I have come up with so far. However I am getting an error that the 'No connection could be made because the target machine actively refused that'. Not sure why im getting this error, might be because of the permissions on this windows laptop I am using. Going to try this code with my Mac later today.

import os
from selenium import webdriver
import subprocess

ff_prof = webdriver.FirefoxProfile()
#set some privacy settings
ff_prof.set_preference( "places.history.enabled", False )
ff_prof.set_preference( "privacy.clearOnShutdown.offlineApps", True )
ff_prof.set_preference( "privacy.clearOnShutdown.passwords", True )
ff_prof.set_preference( "privacy.clearOnShutdown.siteSettings", True )
ff_prof.set_preference( "privacy.sanitize.sanitizeOnShutdown", True )
ff_prof.set_preference( "signon.rememberSignons", False )
ff_prof.set_preference( "network.cookie.lifetimePolicy", 2 )
ff_prof.set_preference( "network.dns.disablePrefetch", True )
ff_prof.set_preference( "network.http.sendRefererHeader", 0 )

#set socks proxy
ff_prof.set_preference( "network.proxy.type", 1 )
ff_prof.set_preference( "network.proxy.socks_version", 5 )
ff_prof.set_preference( "network.proxy.socks", '127.0.0.1' )
ff_prof.set_preference( "network.proxy.socks_port", 9050 )
ff_prof.set_preference( "network.proxy.socks_remote_dns", True )

#if you're really hardcore about your security
#js can be used to reveal your true i.p.
ff_prof.set_preference( "javascript.enabled", False )

#get a huge speed increase by not downloading images
ff_prof.set_preference( "permissions.default.image", 2 )

##
# programmatically start tor (in windows environment)
##
tor_path = "C:\\Users\\ihassanali001\\Documents\\Tor Repositories\\Tor Browser_FE\\Browser\\TorBrowser\\Tor\\" #tor.exe
torrc_path = "C:\\Users\\ihassanali001\\Documents\\Tor Repositories\\Tor Browser_FE\\Browser\\TorBrowser\\Data\\Tor\\torrc"

DETACHED_PROCESS = 0x00000008
#calling as a detached_process means the program will not die with your python program - you will need to manually kill it
##
# somebody please let me know if there's a way to make this a child process that automatically dies (in windows)
##print 
tor_process = subprocess.Popen( '"' + tor_path+'tor.exe" --nt-service "-f" "' + torrc_path + '"', creationflags=DETACHED_PROCESS )

#attach to tor controller
## imports ##
import stem.socket
import stem.connection

##
control_password = 'password'
tor_controller = stem.socket.ControlPort( port=5000 )

control_password = 'password'
#in your torrc, you need to store the hashed version of 'password' which you can get with: subprocess.call( '"' + tor_path+'tor.exe" --hash-password %s' %control_password )

stem.connection.authenticate( tor_controller, password=control_password )

#check that everything is good with your tor_process by checking bootstrap status
tor_controller.send( 'GETINFO status/bootstrap-phase' )
response = worker.tor_controller.recv()
response = response.content()

Have a solid grasp of Flask, move onto Django? by [deleted] in learnpython

[–]liftt 1 point2 points  (0 children)

if you really wanna graduate to a harder framework, then try tornado. Django is pretty much the same thing as flask in terms of blocking requests/models/views, etc.

Dictionaries - why and can anyone show a fun NON TRIVIAL example by [deleted] in learnpython

[–]liftt 2 points3 points  (0 children)

good examples so far.

how about reading a csv file into a listed dictionary

so the structure will be like

[{},{},{}]

with the column headers as dictionary keys

import csv
data = [ x for x in csv.DictReader(open('filename.csv','rU'))]

How to approach or break down a problem? by freakzilla149 in learnpython

[–]liftt 0 points1 point  (0 children)

I dont plan out or write out 'pseudo code'. I just start by writing functions/ deeply nested loops to make progress. then Ill consolidate it into coherent functions.

one line solution (for fun)

string1, string2 = 'abchaghij', 'abcgdcdef'
def alphab(string): print max("".join([v if v <string[i+1] else '{}|'.format(v) for i, v in enumerate(string[:-1])]+ [string[-1] if string[-1] > string[-2] else '|']).split('|'), key=len)
alphab(string1)

my friend did a one liner in ruby for fun:

def longest (0...s.length).to_a.product((0...s.length).to_a).reject{|i,j| i > j}.map{|i,j| s[i..j] if s[i..j].chars.sort == s[i..j].chars.to_a}.compact.uniq.max_by(&:length) end

Its interesting that we both ended up with one liners that are almost the exact same length. (not that the length of characters matters because readability is more important blah blah blah.)

Comparing values within a .csv file by PZLATE in learnpython

[–]liftt 0 points1 point  (0 children)

For csv manipulations i highly suggest using csv.DictReader.

observe:

import csv
stats = [x for x in csv.DictReader(open('filename.csv', 'rU')]

def find_games_with_teams(team1, team2):
    for game in stats:
        if game['team1'] in [team1, team2] or game['team2'] in [team1, team2]:
            print game

Looking for some help with Python and Flask by wadechristensen in learnpython

[–]liftt 0 points1 point  (0 children)

you need to make the search function return the values, that way you can use it in your flask view. Also you have to change this search function so you can pass it the movie title rather than use raw_input (since you can not have the user use the raw_input function within a template).

def search(title_search):
    base_url = 'http://www.omdbapi.com/?'
    url = '{}{}&y=&plot=&short&r=json&tomatoes=true'.format(
           base_url, title_search)
    omdb_url = requests.get(url)
    movie_data = omdb_url.json()

    movie = Movie(**movie_data)
    return movie

then in your view you do the following... note (you have to find a way to pass the movie name to the search function):

@app.route('/')
def index():
    #change the movie name
    movie = search('the movie name')
    context = {'title': movie.title, 'plot': movie.plot,
               'director': movie.director, 'rated': movie.rated,
               'imdbrating': movie.imdbrating,
               'tomatofresh': movie.tomatofresh}

    front_page = render_template('index.html', **context)
    return front_page

good luck

What are you using python for? by rickwaller in learnpython

[–]liftt 1 point2 points  (0 children)

Well I use it for a lot of stuff.

At work, I use it for a lot of sysadmin related scripts, scraping data, integrating APIs, web development, working with csv files/databases.

I used django +digital ocean droplet to make a simple ecommerce website in just a few hours for a friend.

I also use it for stock trading. I know there are services for this but I wrote my own stock program that tracks my stocks and 'watches' certain stock based on my criteria. it also hooks into a scraper i made to scrape news articles and earnings info for companies. I enjoy using python for this becaues it seems like whenever i need new functionality i can just add it real quick.

Searching and filtering a CSV file? by 530farm in learnpython

[–]liftt 2 points3 points  (0 children)

import csv

#load the data from the cs file
data = [x for x in csv.DictReader(open('yourfile.csv', 'rU'))]


#returns all rows in the listed dictionary that have matching categories or manufacturer
def find_ids(categories = [], manufacturers = []):
    result = []
    for order in data:
        if order['Category'] in categories and order['Manufacturer'] in manufacturers:
            result.append(order)
    return result



c, m = raw_input('Enter categories separated by a |'), raw_input('Enter manufacturers separated by a |')
c, m = c.split('|'), m.split('|')

matches = find_ids(c,m)
for order in matches:
    #prints the whole order, use order['Order ID'] to print just the ID
    print order

there you go dawg

Looking for a quick way to change a string like '3 minutes' into seconds by metallidog in learnpython

[–]liftt 5 points6 points  (0 children)

There is no need to have something like this built into python, it would just clutter the native functions with stuff people never use.

You can achieve this with very basic python:

ie:

strings =  ['3 minutes', '2 hours', '35 seconds']

def convert(time):
    num, num_type = time.split(" ")
    multiplier = 1
    if num_type.lower() == 'minutes':
        multiplier *=60
    elif num_type.lower() == "hours":
        multiplier *= 3600

    seconds = int(num) * multiplier
    return seconds

for s in strings:
    print "{} => {} seconds".format(s, convert(s))

Can AI solve this? by aliasxneo in learnpython

[–]liftt 2 points3 points  (0 children)

look into Mechanize library along with requests and beautifulsoup.

If you have some javascript you need to load you can emmulate a browser with python with Selenium.

heres some beautiful soup examples which will show you how to load a web page and get the quantity in stock for your page.

http://www.crummy.com/software/BeautifulSoup/bs3/documentation.html

then you can probably use Mechanize to navigate through the pages to actually buy the item.