-
Greetings!! Here's a series of Cold Golf problems and solutions in Python as a part of 21 days of Code | Code Golf by Skillenza
https://skillenza.com/challenge/21days-of-code
DAY - I
A Little Complex
Given n complex numbers each x + yi, where x is the real part and y is the imaginary part, find their product.Input Format
The first line of input consists of an integer t denoting the number of test cases. t test cases follow. The first line of each test case consists of an integer n denoting the number of complex numbers. Following n lines of the test case consists of two integers x and y separated by a space denoting x + yi.Output Format
For each test case, output the product of the complex numbers. Each product is in the form p and q space separated denoting p + qi.Sample Input
430 12 34 521 00 149 -30 10-10 54 -43-2 -60 0-4 -2Sample Output
-22 -70 1-6000 00 0Explanation
(2 + 3i)(4 + 5i) = 2*4 + 2*5i + 3i*4 + 3i*5i = 8 + 10i + 12i - 15 = -7 + 22iNote
i^2 = -1 (where ^ denotes raised to the power).Complex number multiplication is both commutative and associative.For any two complex numbers z1 and z2, z1z2 = z2z1For any three complex numbers z1, z2 and z3, we have (z1z2)z3 = z1(z2z3)Constraints
1 <= t <= 100002 <= n <= 10-10 <= a,b <= 10Environment and Scoring
Read from STDIN and write to STDOUT.This is a Code Golf contest where smaller source awards higher score. Score is calculated by the following formula(1 - s/10000) *100where s is the number of bytes in your source.For e.g. if a correct source uses 1000 bytes, a score of (1 - 1000/10000) *100 i.e. 90 will be awarded. The source size limit in bytes is 10000.Please check the sample programs below which print the sum of two numbers received as inputCODE:
- z=input
- b=int
- for _ in[0]*b(z()):
- p=1+0j
- for i in[0]*b(z()):p*=complex(*map(b,z().split()))
- print(b(p.real),b(p.imag))
RESULT
Exit Code0PassedtrueMemory5572kbTime0.16sTotal (out of 1)0.98791View comments
- z=input
-
For the need of a simple tabular Grid in your Angular JS application, one of the most basic and simple to use package is angular-ui-grid. The implementation is easy in many of the use cases, but when it comes to extend the limits of the ui-grid, life becomes tough.
One of the tricky task is to set the Grid height as dynamic, in other words to make the grid more flexible to number of rows and the grid size would depend on it.
Lets begin with the
Prerequisites:
- Angular JS: v1.4.2
- ui-grid-stable: v3.0.1
- Dataset: https://rawgit.com/angular-ui/ui-grid.info/gh-pages/data/100.json
the Dataset contains 100 rows
In case you are new to ui-grid refer to the official doc: angular-ui-grid
Refer to the complete code in this plnkr: http://plnkr.co/edit/i5zAuUKz2RdJpuq5YKud
The Next Step-
Setting up all the things:
- Create 3 file:
- app.js - Contains your Angular JS code.
- index.html - Contains the UI HTML5 code.
- main.css - Our styling stuff goes here.
- Required imports in index.html are:
- JS Scripts
- src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.js"
- src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular-touch.js"
- src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular-animate.js"
- src="http://ui-grid.info/release/ui-grid-stable.js"
- CSS Styling
- href="http://ui-grid.info/release/ui-grid-stable.css"
Lets jump to the code:
Our base controller is in app.jsvar app = angular.module('app', ['ngAnimate', 'ui.grid']); app.controller('MainCtrl', ['$scope', '$http', function ($scope, $http) { $scope.maxRowToShow = 1000; $scope.gridOptions = { enableColumnMenus: false, enableHiding: false, enableSorting: false }; $scope.gridOptions.columnDefs= [ { field: 'name' }, { field: 'gender' }, { field: 'company', enableSorting: false } ]; $scope.getTableHeight = getTableHeight; $http.get('https://rawgit.com/angular-ui/ui-grid.info/gh-pages/data/100.json') .success(function(data) { $scope.gridOptions.data = data; setMinRowsToShow(); }); function setMinRowsToShow(){ //This function is to set the rowContainer with minimum row limit to be stored //in the visibleRowCache. //It handles and rogue cache or missed rows due to dynamically generated Table Height. $scope.gridOptions.minRowsToShow = Math.min($scope.gridOptions.data.length, $scope.maxRowToShow); $scope.gridOptions.virtualizationThreshold = $scope.gridOptions.minRowsToShow ; } function getTableHeight() { let rowHeight = 37; // row height let headerHeight = 48; // header height return { height: ($scope.gridOptions.data.length * rowHeight + headerHeight) + "px" }; } }]);
Dive in the Code:
- maxRowToShow: This defines the upper limit of rows to be rendered
- Initial Grid config:
- enableColumnMenus: false,
- enableHiding: false,
- enableSorting: false
- Fetch and store data in scope.gridOptions.data
- getTableHeight: Now here is where the magic happens-
- we give the rowHeight and headerHeight as defined in our css or as per your requirement
- Calculation of height attribute using the below formula:-
(Number of data rows) * rowHeight + headerHeight [in px]
- columnDefs: Contains the meta data for your grid column, like name, specific formatting etc.
- Lastly, the one which is bit confusion is setMinRowsToShow, which we will cover once i have shown you the output
The initial output looks like this without dynamic height:Now with the Dynamic Height:UI Grid with dynamic height, but we can see a large white gap between the last row and footer As you can see in the above image there is a large white gap between the last row and footer, this is because of below reason:- grid.renderContainers.body.visibleRowCache does not refresh the renderedRows arry when splicing in more data. That means when the number of rows are more in conjunction with the grid height, the module is unable to refresh renderedRows and we see only 4 rows
Here are the counts: - renderedRows: 4
- visibleRowCache: 100
- visibleColumnCache: 3
- viewportAdjuster: 1
- The above issue of only 4 rows in renderedRows array is due to the fact that ui-grid does not completely support dynamic height feature.
- But there is this parameter which comes to our rescue - virtualisationThreshold
- Lets fix the above issue gracefully:
$scope.gridOptions.minRowsToShow = Math.min($scope.gridOptions.data.length, $scope.maxRowToShow); $scope.gridOptions.virtualizationThreshold = $scope.gridOptions.minRowsToShow ;
In Above code we will set gridOptions.virtualizationThreshold to the number of data rows or the max rows as configured, this was the ui-grid rendering mechanism knows that how many rows it need to check for to refresh renderedRows.
After the above changes our issue is resolved and we see the output like below:
Hope you find this article useful, let me know the feedback or any queries below as comments.0Add a comment
-
Hey guys, Hope you all are doing great.
Algorithm To Convert Post-fix Expression into Infix expression:-
- Scan the Post-fix String from Left to Right.
- If the character is an Operand, then Push it on to the deque.
- If the character is an Operator, then Pop left Operator 1 and Operand 2 and concatenate them using Infix notation where the Operator is in between the Two Operands.
- The resultant expression is then pushed on the deque.
- Repeat the above steps till the Post-fix string is not scanned completely.
- Use parentheses properly to ensure correct order for evaluating the final expression.
Code Implementation:-
# -*- coding: utf-8 -*- """ Created on Wed Dec 22 22:58:14 2018 @author: Kurtesy """ from collections import deque OPERATORS = '+-/*' def postfix_to_infix(my_queue): if len(my_queue) == 1: return my_queue variable_1 = my_queue.popleft() """Handles left to right operation""" if variable_1 in OPERATORS: operand2 = my_queue.pop() operand1 = my_queue.pop() my_queue.append(('(%s)' % ''.join([operand1, variable_1, operand2]))) return postfix_to_infix(my_queue) """Handles previous expression and next operand""" variable_2 = my_queue.popleft() if variable_2 in OPERATORS: operand1 = my_queue.pop() my_queue.append(('(%s)' % ''.join([operand1, variable_2, variable_1]))) return postfix_to_infix(my_queue) """Process complete expression""" operation = my_queue.popleft() my_queue.append(('(%s)' % ''.join([variable_1, operation, variable_2]))) return postfix_to_infix(my_queue) def func(x): return eval() while 1: expression = input() """Input till # is enforced""" if '#' in expression: break queue = deque(expression) postfix = postfix_to_infix(queue) print(postfix.pop())
Please let me know your feedback, on how i can improve and make it better. Till then!! Cheers!!0Add a comment
-
Hey guys, Hope you all are doing great.
As the first part of this series of Python package and installation we will cover pip vs Condapip vs Conda
- Python packages only. Compiles everything from source. Installs binary, wheel, the ones which pypi supply
- Blessed by the core Python community (i.e., Python 3.4+ includes code that automatically boostraps pip).
condaPython agnostic. The main focus of existing packages are for Python, and indeed conda itself is written in Python, but you can also have conda packages for C libraries, or R packages, or really anything.Installs binaries. There is a tool called conda build that builds packages from source, but conda install itself installs things from already built conda packages.External. Conda is the package manager of Anaconda, the Python distribution provided by Continuum Analytics, but it can be used outside of Anaconda too. You can use it with an existing Python installation by pip installing it (though this is not recommended unless you have a good reason to use an existing installation).In both cases:- Written in Python
- Open source (conda is BSD and pip is MIT)
The Difference...
pip Conda pip uses the official PyPI package index Conda uses the anaconda repo pip does not install the binaries and focus more on package installation. Conda allows you to install precompiled binaries that will work on your system, such as C Compiled binaries, etc. pip focusses just on package management and leaves environment management to other tools Conda also functions as an environment manager PyPI packages are actively updated Conda's repos generally lag behind PyPI
To Summarize...
pip is for Python only
Conda is only for Anaconda + other scientific packages like R dependencies etc. NOT everyone needs Anaconda that already comes with Python. Anaconda is mostly for those who do Machine learning/deep learning etc. Casual Python dev won't run Anaconda on his laptop.
Please let me know your feedback, on how i can improve and make it better. Till then!! Cheers!!0Add a comment
-
Hey guys,
Hope you all are doing great. I love Code Golfing, what it brings out in you is the hidden concepts of a programming language and especially the push to implement same thing in numerous ways.
Code Golfing and Python - Yeah that's my Poison!
Below are few tips and tricks which will give you an edge over other programmer to write the shortest code:
1. The foo if condition else bar condition can be shortened to
True if condition else False ------- [False,True][condition]
2. Convert long range rifle to pistol: range to an small format
for i in range(n) ------ for i in [1]*n
3. String input in Python2 vs String input in Python3:string = raw_input() vs string = input()4. For Python2 convert datatype to string:
str(variable) ------ `variable`
5.Remove unnecessary spaces(' '):
'Goku' if dragon_balls == 9 else 3PO ----- 'Goku'if dragon_balls==9else3PO
Please let me know your feedback, on how i can improve and make it better. Till then!! Cheers!!0Add a comment
-
Hey guys, Hope you all are doing great.
I have always found Regular expressions or REGEX quite amazing. You can solve your string related problem in just some simple magic of patterns.
Our brain works very well to identify the pattern in our day to day life. As these are visual clues, we tend to catch and analyse them better. In fact, their you make negligible mistake to tackle the scenario.
Say you have a pattern with concentric cirles:
This can be generalized in mathematical way, as in geometry is:
x + y + 2gx + 2fy + c' = 0
This same thing applies to string patterns or character arrays.
For Python we have a Regex module called re
Below are few function which you will find useful is many applications
Syntax Definition Examples re.search(regex,str) return match object if found, else None pika = re.search(r"\w+@\w+\.com", "from pikachu@pokemon.com address") if pika : print "yes" print pika.group() # → pika@pika.com else: print "no"
re.match(regex,str) similar to re.search(), but match starts at beginning of string.
goku = re.match('ha','kamehameha') # succeed if goku == None: print "no match" else: print "yes match"
re.split(regex,str) return a list.
print re.split(r' +', 'Clark Kent is Superman')' # output: ['Clark', 'Kent', 'is', 'Superman'] print re.split(r'( +)(@+)', 'what @@do @@you @@think') # output: ['what', ' ', '@@', 'do', ' ', '@@', 'you', ' ', '@@', 'think'] print re.split(r' ', 'a b c d e', maxsplit = 2) # output: ['a', 'b', 'c d e']
re.findall(regex,str) return a list of non-overlapping (repeated) matches.
print re.findall(r'( +)(@+)', 'what @@@do @@you @think') # output: [(' ', '@@@'), (' ', '@@'), (' ', '@')]
re.finditer(…) similar to re.findall(), but returns a iterator.
for matched in re.finditer(r'(\w+)', 'where are the avengers'): print matched.group() # prints each word in a line
re.sub(regex,replacement,str) does replacement. Returns the new string.
def ff(pika): if pika.group(0) == "bulba": return "vena" elif pika.group(0) == "mender": return "izard" else: return pika.group(0) print re.sub(r"[aeiou]+", ff, "bulbasaur") # venasaur print re.sub(r"[aeiou]+", ff, "charmender") # charizard print re.sub(r"[aeiou]+", ff, "geek") # geek
re.subn(…) similar to re.sub(), but returns a tuple. 1st element is the new string, 2nd is number of replacement.
re.subn('\w+', 'Try', 'Cry Cry, Cry and Cry Again!', count=3) # ('Try Try, Try and Try Again!', 3)
re.escape(str) add backslash to string for feeding it to regex as pattern. Return the new string.
re.escape('Lets meet spider man?') # output: Lets\\ meet\\ spider\\ man\\?
To form a regular expression, it needs a bit or creativity and foresightedness of the outcome.For sure you need to know the regex symbols and rules to do that, and all should be dancing in your mind to create an efficient and effective pattern. To help you out, below is the Python Regex Jump-starter:
Python Regex Jump-starter:Regular Expression Basics . Any character except newline a The character a ab The string ab a|b a or b a* 0 or more a's \ Escapes a special character Regular Expression Quantifiers * 0 or more + 1 or more ? 0 or 1 {2} Exactly 2 {2, 5} Between 2 and 5 {2,} 2 or more (,5} Up to 5 Default is greedy. Append ? for reluctant. Regular Expression Groups (...) Capturing group (?P...) Capturing group named Y (?:...) Non-capturing group \Y Match the Y'th captured group (?P=Y) Match the named group Y (?#...) Comment Regular Expression Character Classes [ab-d] One character of: a, b, c, d [^ab-d] One character except: a, b, c, d [\b] Backspace character \d One digit \D One non-digit \s One whitespace \S One non-whitespace \w One word character \W One non-word character Regular Expression Assertions ^ Start of string \A Start of string, ignores m flag $ End of string \Z End of string, ignores m flag \b Word boundary \B Non-word boundary (?=...) Positive lookahead (?!...) Negative lookahead (?<=...) Positive lookbehind (?<!...) Negative lookbehind (?()|) Conditional Regular Expression Flags i Ignore case m ^ and $ match start and end of line s . matches newline as well x Allow spaces and comments L Locale character classes u Unicode character classes (?iLmsux) Set flags within regex Regular Expression Special Characters \n Newline \r Carriage return \t Tab \YYY Octal character YYY \xYY Hexadecimal character YY Regular Expression Replacement \g<0></0> Insert entire match \g Insert match Y (name or number) \Y Insert group numbered Y Please let me know your feedback, on how i can improve and make it better. Till then!! Cheers!!1View comments
-
Hey guys, Hope you all are doing great. I am back with Some Python Programming tips for
CODE GOLF Challenges.
Here are the Second part of code golfing Tips in Python
I prefer Python or Python3 myself for code golfing
So we will discuss dome tips as generics for code golf programming in Python:
7. Use `n` to convert an integer to a string instead of using str(n).
Ex: >>data=187987987 >>`data` '187987987'
8.For integer n, you can write
n+1 as -~n
n-1 as ~-n
Ex: >> (n-1)/10+(n-1)%10 Can be written as >> ~-n/10+~-n%10
9. Build a string instead of joining
To concatenate strings or characters, it can be shorter to repeatedly append to the empty string than to join.
Ex: 23 chars s="" for x in l:s+=f(x) 25 chars s="".join(f(x)for x in l)
10. If you want to know the type of a variable x
Ex: x*0 is 0 # -> integer x*0==0 # -> float (if the previous check fails) x*0=="" # -> string x*0==[] # -> array
11. map can take multiple iterable arguments and apply the function in parallel.
Instead of a=[1,4,2,6,4] b=[2,3,1,8,2] map(lambda x,y:...,zip(a,b)) you can write map(lambda x,y:...,a,b)
12. To find out if both a and b are true, use * instead of and:
>>if a and b: #7 chars >>if a*b: #3 chars
Stay tuned for more Tips and Tricks in the next Post!!
Till Then Cheers!!
0Add a comment
-
Hey guys, Hope you all are doing great. I am back with Some Python Programming tips for
CODE GOLF Challenges.
So, What is CODE GOLF??
As per Wikipedia, it is a type of recreational computer programming competition in which participants strive to achieve the shortest possible source code (not to be confused with binary Sizecoding) that implements a certain algorithm.
In simple terms, your goal is to write a code is shortest way, using minimum number of characters to implement a logic in correct way.
You can use any language Java, C++, Python, Perl, Ruby, JavaScript, and anything to write it. But scripting language have a upper-hand over descriptive language as you can write programs in concise way in scripting language like Ruby, Python, etc, while it takes an extra character each time to write the code in Java, C#, etc.
So Preferred code golf languages are GolfScript, Flogscript, Perl, Python, Erlang, Ruby, Haskell, Bash, PHP, Clojure, K, Javascript, Vim and the list go on....
I prefer Python or Python3 myself for code golfing
So we will discuss dome tips as generics for code golf programming in Python:
1. Make the assignments shorter.
Use a=b=c=0 instead of a,b,c=0,0,0. Use a,b,c='123' instead of a,b,c='1','2','3'.
2. Tweak the if-else condition.
b=2*a if a<0 else 3*a # proper python b=a<0 and 2*a or 3*a # codegolf1 b=a*(3,2)[a<0] # codegolf2
3. Combine multiple conditionals. Instead of "1<x and x<2".
Use 1<x<2
4. Using a built-in function repeatedly, it might be more space-efficient to give it a
new name, if using different arguments.
r=range
for x in r(10): for y in r(100):print x,y
5. Read only two lines from standard in (without the carriage return) and store then in an array of strings.
r=raw_input a=r(),r()
6. Simulating C's ternary operator (p?a:b)
r=[b,a][p]
Stay tuned for more Tips and Tricks in the next Post!!
Till Then Cheers!!
12View comments
-
Hey guys, Hope you all are doing great. I am back with with a byte of python performance.
I have been playing on codingame.com a lot now a days during my weekends.
Its cool site for the player aka coders who want to try there hands into gaming domain. You have plenty to select from
So stay tuned for the coming new gen puzzles and coding tips to increase your efficiency and performance!!
Hope you find this post useful and interesting. Please let me know your feedback, on how i can improve and make it better. Till then!! Cheers!!0Add a comment
Add a comment