Stack Exchange Network

Stack Exchange network consists of 175 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Visit Stack Exchange

New answers tagged

0

Here are my comments ignoreWhiteSpaces(): instead of loop on individual chars, can be replaced with regex to find first char not in list. Deleting from the StringBuilder is unnecessary. Matcher has find(int start) now, once you adopt point 2, then you don't need StringBuilder at all. you can read the input into one line, using Files.readAllBytes() (...


2

this is a performance-critical function any replacements will need to keep this requirement in mind restrict fusc_word(ulong u, ulong* a, ulong* b) uses a, b and certainly the algorithm does not work if those pointers point to overlapping data. A complier can not make that assumption though and so must emit code as if a and b potentially point to the same ...


4

Do less writing You can half the code by using the fact \$x^{-n} = \frac{1}{x^n}\$ if n > 0: while n > 0: ... else: while n < 0: ... would become if n < 0: # x**(-n) == 1 / x**n return 1 / old_code(x, -n) return old_code(x, n) (with old code being the code you have from the while loop down) Likewise \$(-x)^n = x^n\$ ...


3

One obvious thing to do is to take advantage of some math. If you want to calculate 2¹⁶, you don't need to calculate it with 2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2. You could instead calculate it as (2⁸)²=(2⁴)²=((2²)²)². With your approach, you will calculate the value of 2⁸ twice. Here is a simplified version that shows the idea. You might want to change it to a ...


1

Style PEP 8 is the official style guide for Python. Unless you have a good reason to deviate, you should use lower_case_with_underscores for variable names and method names. Terminating statements with semicolons is a faux pas in Python. Also, indentation should be four spaces, which is a particularly important convention to follow in Python since ...


1

There is no need for packages. This is easily and efficiently done with basic syntax. # Create data.table dtk <- data.table( var=c(NA,NA,1,NA,NA,2,3,NA,NA,NA,NA,4,5,NA,NA,NA,NA,NA,6,7,NA,NA), group=c("A","A","A","A","A","A","A","A","A","B","B","B","B","B","B","B","B","B","B","B","B","B")) # Backward fill dtk[,order:= (1:.N)]; setorder(dtk,-order); dtk[...


2

General Guidelines Please put any technical restrictions in the initial post. Like, for instance, framework 3.5 :-( Declare variables as var rather than their type for readability. Split big methods into smaller ones for readability and testibility. Performance Your biggest bottleneck is the sequential loop of 7000 users. You could use the TPL to maximize ...


2

This problem lends itself to a recursive solution. You want a recursive algorithm that returns 0 if the length of the input array nums is 1 otherwise creates a new input array for a jump of size from 1 to nums[0], calculates the jumps for the new input array, adds 1, and returns the minimum In Python this would be: def jump(nums): if len(nums)<=1: ...


2

I performed some timings of the solutions presented by @AustinHastings in his answer on my machine at work (Linux 64bit, Intel Core i7-2600, 16GB RAM, Anaconda Python 3, ). The timing function was slightly modified to use repetitions get more accurate results as well as to easier get the timings for visual display. def time_func(f, shape=1000, n_reps=10): ...


2

I tried some alternative approaches, and got this result: Time for orig: 0.15900921821594238 Time for concat: 0.18401050567626953 Time for block: 0.16700983047485352 Time for stack_ravel: 0.1760098934173584 Time for stack_flatten: 0.32501864433288574 It's worth pointing out that I'm on a 32-bit machine with not enough RAM to hang with you. So I used ...


1

Here's how I would find the longest strings in a list of strings: import itertools def longest_string(strings): if not strings: return [] strings_by_length = itertools.groupby(strings, len) maximum_length = max(strings_by_length.keys()) return strings_by_length[maximum_length]


1

Only the second solution meets the memory requirement of using constant extra space. The first solution has other issues as well, for example some unnecessary optimization attempts such as removing negative values, which is likely to do more harm than good, because removing items from the middle of a list is usually a costly operation. The second solution ...


2

Improving the first solution I like the first solution better, because I find it easier to understand how it works, and it's shorter. It can be a bit simpler. The condition if i <= curr_far: is unnecessary and can be safely dropped. Instead of iterating over a range of indexes, I nice trick is to use enumerate, like this: for index, value in enumerate(...


0

The best solution here is a modified counting sort. If we store the first integer not yet found, we can move an element of value i to the ith spot of the array until we find a duplicate or something bigger than the array size, at which point we throw that away and go to the next index. At the end of this process, we will have an array where the first i ...


1

As an alternative, I will suggest a solution that instead of iterating through all of the grid's nodes in search of a component that was not visited in the main loop, it avoids visiting a visited node in this loop via a modified BFS. The gist of this algorithm is to perform an explorative BFS, which triggers a DFS (like your algorithm) to measure the size ...


1

You open with SELECT DISTINCT . Is this really necessary? This is a performance killer. Perhaps duplicates can only occur between certain tables. If that were the case, put the distinct as deep as you can in query, even if this means adding additional nested queries.


1

To optimize this query, I would only perform the date checks once, regardless of how Oracle optimizes internally. , COUNT(case when cq.entry_date > TO_DATE('09-Jun-2017', 'dd-mm-yyyy') then 1 END) AS cq_count , SUM(case when cq.entry_date > TO_DATE('09-Jun-2017', 'dd-mm-yyyy') then (cq.unit_price * cq.qty_quoted) END) AS cq_total , SUM(case ...


1

Without specific explain plan details, consider these broad stroke recommendations. Currently, I do not see how UNION fits into your needs as you are essentially joining two conditional aggregation queries. And due to re-use of calculated columns, you require sub-select derived tables. Of course as always, analyze each SELECT queries' explain plan and add ...


0

EDIT: While accepted by the site, this solution doesn't meet the memory requirement. This looks like an opportunity to use a set. By keeping the numbers in a set instead of a list, you can look up successive values of n directly, no element-by-element searching required. So, make a set, put n at 1, then see how far you can increase n before it's no longer ...


7

Since Acccumulation's answer was considered too confusing, here's the same using a real Python ternary operator. print('Equal' if len(s1) == len(s2) else 'Larger is ' + max(s1, s2, key=len)) I don't see the point in using .format for this kind of simple concatenation.


1

I think the menu is effective but a bit awkward. Reading the string directly might be a nice bit of user friendliness. The code below only multiplies two numbers, but I think it could probably go to many more. Hopefully this code will show you about regex and such. Findall is quite useful. import re while True: my_operation = input("Enter a ...


0

You can immediately assume that the first one is larger and then reassign it to the second one if that one is larger, like this: larger = input("Enter first string: ") string2 = input("Enter second string: ") if (len(string2) > len(larger)): larger = string2 print(larger)


1

As I told in another answers, your code is very C/C++ styled, it is not Pythonic. Try to avoid manual iteration with indices as much as possible. Python has an enormous standard library that contains many useful modules. I already recommended you an itertools module. It contains pair of dozens generic functions to work with iterators. One of them - ...


1

Since you say in a comment that you may need to find the divisors of a number \$n\$ up to \$10^{60}\$, trial division is not practical, even if performed only up to \$\sqrt n\$ . The only option is to find the prime factorisation and then reconstruct the divisors from the prime factorisation. There are quite a few algorithms to find the prime factorisation. ...


1

While memoization can result in impressive performance improvements, it's not really appropriate for this task, when a trivial loop would do what you want def fib(n): res = [0, 1] if n < 2: return res[0:n] for i in range(2, n): res.append(res[i - 1] + res[i - 2]) return res But the answers all depend on the problem ...


5

It would save a lot of time to start from the other end, by making the sums first. Notice that a digit combination like (1, 2, 3) is shared by six numbers: 123, 132, 213, 231, 312, 321. They all have the same digit cube sum 1^3 + 2^3 + 3^3 = 36. Your code will iterate over those numbers and recalculate the same sum 6 times. Instead, you could use the digit ...


8

As you are effectively reading the whole file test_in into memory in lots of small independent chunks, consider a different approach: Read the whole file as one big chunk, or preferably simply map it. Put std::string_views into that array in the vector, instead of strings. Most std::strings employ SSO, meaning there are two possible states (external string,...


26

Limit execution to main module It is customary for code that starts executing a series of commands to be surrounded in a special if-block: if __name__ == '__main__': ... This prevents the code from being executed when it is imported into another module. It's probably a good idea to put most of your code into a method or two Particularly once you've ...


5

Building off of WeRelic and user201327 answers, if you really want to optimize for short code, you can do: print(('Larger string is:{}'.format(max(string1,string2, key=len)),'Both strings are equal.')[len(string1)==len(string2)]) However, a more readable version would be if len(string1)==len(string2): print('Both strings are equal.') else: ...


35

Here's how I would get the longer string: max(string_1, string_2, key=len) # Returns the longer string The key keyword argument is a pattern you'll see frequently in python. It accepts a function as an argument (in our case len). If you wanted to find the longest of multiple strings, you could do that too: max('a', 'bc', 'def', 'ghi', 'jklm', key=len) #...


4

I'm going to focus on the performance aspect, as I believe other parts already have good answers. While the program may be simple and performant, it is still fun to go in and micro-optimize a little. In general I would recommend against it. Here is your code put into a function to make it clear what changes in the future. I've made the function return the ...


2

So I would like to know whether I could make this program shorter and more efficient. Others have addressed style, but I will address algorithm. The memoized recursion is a decent solution: import functools @functools.lru_cache(maxsize=None) def fib(n): if n <= 1: return n else: return fib(n-1) + fib(n-2). This memoization ...


-4

Using Python2 this worked. def minion_game(s): Stuart, Kevin = 0,0 length = len(s) for idx,sub in enumerate(s): if sub in 'AEIOU': Kevin += length - idx else: Stuart += length - idx print(['Draw','Kevin {}'.format(Kevin),'Stuart {}'.format(Stuart)][0 if Kevin == Stuart else 1 if Kevin>Stuart else 2]) if __name__ == '...


4

JavaScript The loop that generates people - an expensive bridge to cross ”...DOM access is actually pretty costly - I think of it like if I have a bridge - like two pieces of land with a toll bridge, and the JavaScript engine is on one side, and the DOM is on the other, and every time I want to access the DOM from the JavaScript engine, I have to pay ...


2

Long live the Ternary: def print_longer(s,s2): # return (s,s2)[len(s)<len(s2)] if you don't want to print within the function. print( ( s, s2 )[ len(s) < len(s2) ] ) Explanation: if-else statements are clean, but they're verbose. A ternary operation would reduce this to a one-liner. The format is as follows: (result_if_false,result_if_true)[...


12

Names Using sum as a variable name is not adviced as it hides the sum builtin. I'd suggest sum_pow as an alternative. Also, temp does not convey much information. I'd use remaining even though I am not fully convinced. Extracting digits from a number You've used divisions and modulo to compute the different digits for a number. You can use divmod which ...


9

Python has a good standard module for work with decimal numbers: decimal. Your code (still C/C++-style) can be replaced with this code: import decimal # A separate function to check if the number is an Armstrong number def is_armstrong(number): # Get tuple of number digits num_digits = decimal.Decimal(number).as_tuple().digits # Return the ...


6

One issue I see is with casting the user's input to int: num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) You can prompt the user the input only integers, but there is currently nothing stopping them from inputting a string. When an attempt to cast the string as an int is made, it will fail inelegantly. I suggest either ...


7

You have several functions. What if you will have 100 functions? 1000? Will you copy-paste all your code dozens of times? Always keep in mind the DRY rule: "Don't repeat yourself". In your case you can store all functions and its info in some kind of structure, like dict. You run your program, it calculates something once and quits. Why not letting the user ...


1

Don't Re-Invent the Wheel Unless Absolutely Necessary The C programming language already contains the function strcpy(destination, source). You have access to this function and many more string functions when you include string.h in your program. There is also the char* strncpy(char* dst, const char* src, size_t size); function that limits the number of ...


34

Python strings supports Python built-in len function. You don't need to iterate through them manually, as for lists/dicts/sets etc (it is not Pythonic): def compare_strings_len(s1, s2): if len(s1) > len(s2): print('String 1 is longer: ', s1) elif len(s1) < len(s2): print('String 2 is longer: ', s2) else: print('...


3

All answers provided are great and offer suggestions with a complexity in O(sqrt(n)) instead of the original O(n) by using the trick to stop at sqrt(n). On big inputs, we can go for an even faster solution by using the decomposition in prime numbers: the decomposition in prime numbers can be computed in a time proportional to the square root of the biggest ...


3

Looking over your code, this is what I have for you: Your function can be turned into a one-liner You should use if __name__ == '__main__' to ensure you're not running this program externally. Refactored Code: def recur_factorial(x): return 1 if x == 1 else (x * recur_factorial(x - 1)) def main(): num = int(input("Enter number: ")) print("The ...


4

A few people mentioned that your implementation is inefficient. To emphasise just how inefficient it is, try calculating recur_fibonacci(35), and then recur_fibonacci(40): On my computer, the former takes about a second, while the latter takes almost a minute. recur_fibonacci(41) will take more than twice as long. However, contrary to what some people ...


3

You should always handle edge cases. For instance, if one were to provide an empty list (or None) to your find_max_subarray() function, alist[start] would throw an IndexError.


5

Building on @Snakes and Coffee's answer a bit: The purpose of the program is to print out the sequence fib(0) to fib(n) - in which case, I would argue that a recursive solution is not the most appropriate. Currently, when the code goes to calculate fib(5), it starts by calculating the value fib(4) - it actually did this already when it printed out fib(4) ...


5

Just to have a more readable (than the answer by @Justin) and complete (than the answer by @Sedsarq) version of the algorithm presented in the other answers, here is a version that keeps the factors in a set and uses the fact that factors always come in pairs: from math import sqrt def get_factors(n): """Returns a sorted list of all unique factors of `...


3

If your question is whether the recursive function could be made shorter, then the following is a way to rephrase your function in a more compact form: def recur_fibonacci(n): return n if n <= 1 else recur_fibonacci(n-1) + recur_fibonacci(n-2) This is assuming you must have a recursive solution. As others have already pointed out, the solution could ...


2

To me, this seems like the most efficient way of finding all the factors of a number in Python. from functools import reduce n = int(input("Enter number: ")) def factors(n): return sorted(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))) print(factors(n)) This will return all of the factors, very ...


3

Divisors come in pairs. Since 2*50 = 100, both 2 and 50 are divisors to 100. You don't need to search for both of these, because once you've found that 100 is divisible by 2, you can do 100 / 2 to find 50, which is the other divisor. So for every divisor you find, use division to find its "partner" at the same time. That way you don't need to look further ...


Top 50 recent answers are included