New answers tagged

4

Welcome to Code Review! I'm always glad to see someone who reads the classics. You made some interesting observations about the program. The statement Use more "self-explaining" variable names is absolutely correct: the variable name nb could definitely be improved. I would like to point out that self-documenting might be better than self-explaining. If ...


-4

here is how I did it in golang func is_prime(num int) int { // get the floor root of num floorRoot := (int(math.Floor(math.Sqrt(float64(num))))) //fmt.Println for i := 2; i < floorRoot; i++ { // if mode of num and i is 0 it is not prim if num%i == 0 { //return 0 fmt.Println("not prim") ...


0

Not sure how using roots help you, but here is my solution to the porblem (a pyramid, n-th row has length of n): EDIT: I assumed that if the number won't be a perfect pyramid (like 24) then print until the number. If you want to print the biggest pyramid possible it simplifies the code a bit. public static String pyr(int n) { //n is the target num ...


1

Here was my updated v0.02 written as a generator. (Can combine with either Reinderien's datetime.timedelta aproach or dfhwze's modulo code) import re #tracklist = """... as defined above ...""" tracklist = iter(t for t in tracklist.split('\n') if t) pat = re.compile(r'(?P<no>[0-9]+)\. (?P<name>.*) (?P<mm>[0-9]+):(?P<ss>[0-9]+)') ...


3

This part is not that compact in terms of code lines, which you seek to decrease: tss += lss tmm += lmm if tss >= 60: tmm += 1 tss -= 60 One solution is to keep track of t (total seconds) instead of tss and tmm. t = 0 result = [] for t in tracklist: m = pat.match(t) lmm, lss = int(m['mm']), int(m['ss']) result.append((int(m['no']),...


5

Implicit tuples (tmm,tss) = (0,0) This shouldn't need any parens. Generator couldn't easily see how to rewrite it from a for-loop to a generator It actually is quite easy. Make your code into a function, delete result, and replace result.append with yield. Time spans are there better idioms for the (mm,ss) modulo-60 counters? Yes! Custom ...


2

Portability To be clear, strtoi() and strtou() that OP's code relies on is not in the standard C library. OP's code is limited to the requisites. strtol() may be more complex, yet it is portable throughout all compliant C implementations. Bug - failure to clear errno When strtod() succeeds, it does not change errno, so the tests on errno are testing the ...


10

If your code is checked by an automated process, you will probably fail all test cases because your code prints a #, which was not asked for. You should better remove it. Just print "Case %d" instead of "Case #%d".


15

Following @Martin R's comment, I'll make my comment above a solution: printf already supports what you're trying to achieve with your if-then-else jungle: #include <stdio.h> int main() { int T; scanf("%d", &T); for (int i = 1; i <= T; i++) { int N; scanf("%d", &N); int hours = N / 60; int ...


2

You're doing things quite the hard way. You don't need to call sqrt, or determine perfect squares at all. Simply track y, and as soon as the row's x == y, make a newline, increment y and set x = 0. The following examples show different results from what you've described: import java.io.StringWriter; import java.lang.Math; class Pyramid { interface ...


1

The built-in print function (in Python 3+) has a sep (separator) argument. Performance is not as good as with str.join, but I just thought I'd mention it. In combination with * argument unpacking: print(*flavours, sep=', ', end='.\n')


3

The main advantage of strtol and family is that they compute (for free!) the point where the conversion ended. It is a very valuable information, because usually after extracting the number you want to continue parsing. Your wrappers throw it away. DRY. The switches (which compute result) for integral types is identical. Factor it out into a function.


3

Using f-strings, which are pretty fast: flavors = ['chocolate', 'vanilla', 'caramel', 'strawberry', 'coffee'] print(f'{", ".join(flavors)}.')


71

TL;DR: Despite this being the currently accepted & highest voted answer, these methods from this answer and variations (1, 2) of it: print(", ".join(flavours) + ".") # Peilonrayz print(", ".join(flavours), end=".\n") # Maarten Fabré print(f'{", ".join(flavors)}.') # Andy are all faster than the solution originally proposed in this ...


42

The best solution is to use str.join(), using ', ' as the joining string. def display(flavours): print(', '.join(flavours) + '.') Outputting: >>> display(['chocolate', 'vanilla', 'caramel', 'strawberry', 'coffee']) chocolate, vanilla, caramel, strawberry, coffee. Comparing this to the two adaptions of my approach, and against AJNeufeld in ...


10

There is indeed a better way. flavours = ('chocolate', 'vanilla', 'caramel', 'strawberry', 'coffee') for i, flavour in enumerate(flavours): if i == len(flavours) - 1: end = '.' else: end = ', ' print(flavour, end=end) Even better: print(', '.join(flavours) + '.') The most expensive part of your solution is the call to index. That ...


1

I wouldn't use strings at all. I would write to a stream. If wished, I would convert the stream to a string. (defun d20 () (+ 1 (random 19))) initlist can be written more compact: (defun initlist (specs) (sort (loop for (a b) in specs collect (list a (+ b (d20)))) #'> :key #'second)) Now we pass a stream to htmlinitlist and write the ...


Top 50 recent answers are included