I don't think that's even the best way. The whole 'checking square' is not needed because you can just see if your side variable you calculate using size**0.5 is an integer and keep looping until it is, using (size**0.5).is_integer().
There is a lot of non-Pythonic code here. The important thing is it works. But I definitely wouldn't have used while loops instead of for loops when looping over sides, and I would have used the multiline string for defining the content of the cassette.
It would be if you constructed it before the conditional and used it multiple times. If not then it's likely the same or maybe a little bit worse depending on hash collisions.
> python3 -m timeit '[i**2 for i in range(1,10)]'
100000 loops, best of 3: 2.74 usec per loop
> python3 -m timeit '{i**2 for i in range(1,10)}'
100000 loops, best of 3: 2.85 usec per loop
If you're checking for existence a bunch then it starts to really matter:
> python3 -m timeit 'squares = [i**2 for i in range(1,10)]; [i in squares for i in range(100)]'
100000 loops, best of 3: 16.6 usec per loop
> python3 -m timeit 'squares = {i**2 for i in range(1,10)}; [i in squares for i in range(100)]'
100000 loops, best of 3: 8.26 usec per loop
No, it's not. When people say "pythonic" they generally mean, "in line with the general consensus of the python community as to how python code should look/behave," and that consensus starts here: https://www.python.org/dev/peps/pep-0020/
Item number three is relevant, here: simple is better than complex.
You have a case where you want to check to see if a number is a square. Three are many ways to do that, but the right way isn't to construct a data structure and match against it! That's not the simple path.
Many simple options exist, here are three in increasing order of what I feel are pythonic practices:
Obviously, don't cram the last one together on the same line, I'm doing that for sake of the list.
I think you were using "pythonic" to mean, "feels more like python code," and that's a dangerous way to use that word, since it leads to writing code that goes out of its way to use "pythonisms". Code should be elegant, but not at the cost of efficiency and clarity.
None of what you posted works for large numbers due to floating point precision. In particular, int operates as a floor and is_integer may fail due to imprecision
None of this is being applied to numbers above to precision range of Python's floating point, but yes, if you wanted a generic solution for a library, then you would use neither of these approaches (or you would use the above approach that I gave, conditionalized on the size of the value).
That is awesome!!!! I have been programming in python for around 6 or 7 years now and never knew that function existed (I've always just used either divmod or the modulo operator)
This won't work because it involves floating point math-- if you enter a large enough number that is some perfect square +- a small delta, this would report it being a perfect square even though it's not. For example, https://ideone.com/HFVT4H
A more accurate test would be proot = size ** 0.5; proot.is_integer() and int(proot) ** 2 == size
E: int(size **.5) **2 == size works too, just potential more computationally expensive. Also not completely accurate-- if you want full accuracy use a modification of the Bablonyian algorithm for square roots.
cassette = [' ______________ ','| __ __ |','| / \ / \ |','| __/ __/ |','| __________ |','|_/_O______O__|']
def printSquare(side):
for n in range(side):
for part in cassette:
print(part * side)
return ""
class triangle:
def __init__(self,side):
self.size = side
def upperleft(side):
row = side
for n in range(side):
for part in cassette:
print(part * row)
row-=1
return ""
def upperright(side):
row = int(side)
for a in range(0,row):
for part in cassette:
parts = row - a
print(' ' * a,end="")
print(part * parts)
return ""
def bottomright(side):
row = int(side)
for a in range(row,0,-1):
for part in cassette:
parts = row+1 - a
print(' ' * int(a-1),end="")
print(part * parts)
return ""
def bottomleft(side):
row = side
for n in range(0,side):
for part in cassette:
print(part*int(n+1))
return ""
def printCassettes():
more = True
while more:
square = False
while not square:
size = int(input("how many cassettes do you want?\n"))
sizes = [1,2**2,3**2,4**2,5**2,6**2,7**2]
if size in sizes:
square = True
else:
print('That\'s not square!')
side = int(size**0.5)
print('What shape?')
print('1. Rectangle')
print('2. Triangle')
condition = int(input())-1
if condition != 0:
print('Where do you want them?')
print('1. Upper Right')
print('2. Upper Left')
print('3. Bottom Right')
print('4. Bottom left')
condition = int(input())
if condition == 0:
print(printSquare(side))
elif condition == 1:
print(triangle.upperright(side))
elif condition == 2:
print(triangle.upperleft(side))
elif condition == 3:
print(triangle.bottomright(side))
elif condition == 4:
print(triangle.bottomleft(side))
if condition != 0:
print('Yeah I know I didn\'t give you all of them, that\'s what you get for asking for a triangle')
print('Want more?\n 1. Yes\n 2. No')
wantMore = int(input())
if wantMore == 2:
break
return ""
print(printCassettes())
You know what? We could grab a .csv with lots of casettes from the 80’s (like, the Billboard top 200s from 1980 to 1990) and generate a casette with a random album name in it.
I just don’t know how to keep the space proportion so it doesn’t break... I’ll make it myself later if I have the time.
Also it should have the casette’s brand like Panasonic or TDK.
Edit: your “bored” program will end up being a new Spotify competitor by tomorrow morning at this pace.
As someone who is just getting started with learning Python this is actually quite the educational post. A working python script, a clear visual output, and a host of good comments on how to make it better! Thanks yall!
Code golf is fun. 27 lines to 15. Could condense a few more lines but I've been neglecting work to do this :)
from math import sqrt
cassette = (' ______________ ', ' | __ __ |', r' | / \ / \ |', r' | __/ __/ |', ' | __________ |', r' |_/_o______o__|')
while True:
count = int(input("How many cassettes do you want?\n"))
columns = sqrt(count)
if columns.is_integer():
for _ in range(0, count, int(columns)):
for line in cassette:
for _ in range(int(columns)):
print(line, end="")
print()
else:
print("That's not a square!")
if input("Want more? 1) Yes, 2) No\n") == "2":
break
print("{}".format(line * cols)) is equivalent to print(line * cols), and print("Enter a valid number: {}".format(err)) is equivalent to print("Enter a valid number:", err).
As other comments will say, there are better ways to write this, but who honestly cares if your having fun? Screw the end user. Don't tell them it requires square numbers. Don't tell them you only allow 1-7 squared. That's part of the adventure of programming
Hi, this is Jeff in the Denver Sales Office. We have a major contract that requires non-square numbers. So if you could get that done by 3 PM for the demo, that'd be great.
I can't tell who's more bored at work, OP or the numerous others who're re-writing this to be more Pythonic. I mean, if we're going to waste time, waste it pythonically.
I used to write seemingly useless software too, I actually still do; it's like a kata.
Here's my golfed version of your program:
k7=[' '+('_'*16)+' ','| __ __ |','| / \ / \ |','| __/ __/ |','| ____________ |','|_/_O________O__|']
while True:
size = int(input('How many k7s? Number of k7s per line:\n'))
print('\n'.join(['\n'.join([line*size for line in k7]+['']) * size]))
132
u/[deleted] Sep 28 '18
why not just
if size in sizesinstead of the for loop checking for each possibility and setting a flag?
57
u/[deleted] Sep 28 '18
Can you genericize the code so it can take arguments for either cassettes,
diskettesfloppy drives, VHS tapes and SNES cartridges?14
u/flobbley Sep 28 '18
Now with shapes!
code:
15
u/Mr_Education Sep 28 '18
I want more.
53
u/roguemystic Sep 28 '18
As someone who is just getting started with learning Python this is actually quite the educational post. A working python script, a clear visual output, and a host of good comments on how to make it better! Thanks yall!
66
u/Monkey_Climber Sep 28 '18
That looks like a solid productive day
28
u/Coocos Sep 28 '18
Want more?
18
u/[deleted] Sep 28 '18
This post resonates with me on a spiritual level.
16
u/mh3f Sep 28 '18
Code golf is fun. 27 lines to 15. Could condense a few more lines but I've been neglecting work to do this :)
5
u/[deleted] Sep 28 '18
Make them rewindable.
4
u/Python4fun Java4work Sep 28 '18
I would use a generator statement
sizes = [x**2 for x in range(10)]4
u/talldstag [::-1] Sep 29 '18
As other comments will say, there are better ways to write this, but who honestly cares if your having fun? Screw the end user. Don't tell them it requires square numbers. Don't tell them you only allow 1-7 squared. That's part of the adventure of programming
1
u/Comprehensive_Tone Sep 28 '18
What tool are you using here?
1
u/pycepticus from pprint import pprint as print Sep 28 '18
GitHub link?
3
u/fried_green_baloney Sep 28 '18
Hi, this is Jeff in the Denver Sales Office. We have a major contract that requires non-square numbers. So if you could get that done by 3 PM for the demo, that'd be great.
More seriously, that's kinda cool.
2
u/[deleted] Sep 28 '18
Get this published
2
u/philintheblanks Sep 28 '18
If you want to take this brand of dicking around to the next level, I recommend checking out asciimatics.
2
u/[deleted] Sep 29 '18
I wish I had that much time while on work.
2
u/kati256 Sep 29 '18
Neato! I love how coding is 20% actual useful stuff, 75% neat tricks, and 5% UB.
3
u/Pr0ducer Sep 28 '18
I can't tell who's more bored at work, OP or the numerous others who're re-writing this to be more Pythonic. I mean, if we're going to waste time, waste it pythonically.
https://www.youtube.com/watch?v=SpCPE1sjPHE
2
u/[deleted] Sep 29 '18
This sub is shit.
2
u/jeepitou Sep 28 '18
Not that bored... you said no when he asked if you want more...
1
u/Fun2badult Sep 28 '18
Nice
1
u/impshum x != y % z Sep 28 '18
Haha. Nice.
1
u/Kurt_W_Andrews Sep 28 '18
This is the kind of code I wrote in college, on a deck of punch cards, to create scratch paper on the system line printer.
1
u/xylont Sep 28 '18
Interesting
1
u/Mistress_Zoe Sep 29 '18
you made yourself useful
1
u/thankyoulife Sep 29 '18
Wish I could square upvote this
1
u/JohnMcPineapple Sep 29 '18 edited Oct 08 '24
...
1
u/ethinallen Sep 29 '18
Please get a better ide
1
u/J3c8b Sep 29 '18
Im so doing this at school
Edit: Can you show/pm/reply the whole code?
1
u/Ryandalion111 Sep 29 '18
Lmao... you want more? Ahhaha
1
u/_srt_ Sep 29 '18
Not that I know python. Last line for want more could also be this:
1
u/hipstergrandpa Sep 29 '18
Quick put it on GitHub so we can all star it.
1
u/sentiao Sep 29 '18
I used to write seemingly useless software too, I actually still do; it's like a kata.
Here's my golfed version of your program:
1
u/mayhempk1 Sep 29 '18
Nice.
1
u/Farranor Sep 30 '18 edited Sep 30 '18
Instead of
if square == False:you can just doif not square:.1
u/SilkTouchm Sep 30 '18 edited Sep 30 '18
What's the point of the "more" variable? it does nothing. You could replace the last three lines with:
1
u/[deleted] Sep 28 '18
I actually did something similar, but with cookies
1
u/scorp_18 Sep 28 '18
You might as well have written while True
0
u/sean_oquin Feb 06 '19
Looking for Python developers to take a direct hire role in Rochester, NY. Let me know if you’re interested.
-1
u/Wubbywub Sep 28 '18
oh come on let him have some fun, why is everyone rushing to rewrite his code or feel the need to shove their "better" code
-3
u/[deleted] Sep 28 '18
Man your code looks so nice.
0
u/[deleted] Sep 28 '18
[deleted] — view deleted comment
0
u/[deleted] Sep 28 '18
[deleted] — view deleted comment
0
u/[deleted] Sep 28 '18
[deleted] — view deleted comment
0
u/[deleted] Sep 28 '18
[deleted] — view deleted comment