5 ms·
char_lengths_in_px = {"a": 9, "b": 7, "c": 8, ... } px_per_line = 768 current_length = reduce(lambda x,y: y+char_lengths_in_px[x], my_text, 0) space_left
by frisco 16y ago
char_lengths_in_px = {"a": 9, "b": 7, "c": 8, ... }
px_per_line = 768
current_length = reduce(lambda x,y: y+char_lengths_in_px[x], my_text, 0)
space_left = (px_per_line*num_lines)-current_length
FTFY
- mkramlich 16y agoI first thought that was a solution written in pseudo-code. Then I realized, "Hey, that's Python!"
- pak 16y agoI wish it were this simple, but you forgot about word-wrapping. Also, what to do in the event that space_left is negative, but the user hasn't reached 150 words. (Also, it's layout for print, so better to think in terms of pts or picas.)
- frisco 16y agoThis will give you an upper-bound, which is the worst case. You're right that you'll end up not giving the students as much as they "should" have, but its still infinitely better than just truncating it without warning.
- pak 16y agoYou mean lower-bound. current_length should be greater than what you calculate given any my_text with >1 char words. So you will wind up giving the students more than you can fit, not less than they should have. That's just as bad as truncating without warning.