Once again I'm asking for you advice. I'm trying to print a complex string block, it should look like this:
32 1 9999 523
+ 8 - 3801 + 9999 - 49
---- ------ ------ -----
40 -3800 19998 474
I wrote the function arrange_printer() for the characters arrangement in the correct format that could be reutilized for printing the list. This is how my code looks by now:
import operator
import sys
def arithmetic_arranger(problems, boolean: bool):
arranged_problems = []
if len(problems) <= 5:
for num in range(len(problems)):
arranged_problems += arrange_printer(problems[num], boolean)
else:
sys.exit("Error: Too many problems")
return print(*arranged_problems, end=' ')
def arrange_printer(oper: str, boolean: bool):
oper = oper.split()
ops = {"+": operator.add, "-": operator.sub}
a = int(oper[0])
b = int(oper[2])
if len(oper[0]) > len(oper[2]):
size = len(oper[0])
elif len(oper[0]) < len(oper[2]):
size = len(oper[2])
else:
size = len(oper[0])
line = '------'
ope = ' %*i\n%s %*i\n%s' % (size,a,oper[1],size,b,'------'[0:size+2])
try:
res = ops[oper[1]](a,b)
except:
sys.exit("Error: Operator must be '+' or '-'.")
if boolean == True:
ope = '%s\n%*i' % (ope,size+2, res)
return ope
arithmetic_arranger(['20 + 300', '1563 - 465 '], True)
#arrange_printer(' 20 + 334 ', True)
Sadly, I'm getting this format:
2 0
+ 3 0 0
- - - - -
3 2 0 1 5 6 3
- 4 6 5
- - - - - -
1 0 9 8
If you try printing the return of arrange_printer() as in the last commented line the format is the desired.
Any suggestion for improving my code or adopt good coding practices are well received, I'm starting to get a feel for programming in Python.
Thank you by your help!
The first problem I see is that you use += to add an item to the arranged_problems list. Strings are iterable. somelist += someiterable iterates over the someiterable, and appends each element to somelist. To append, use somelist.append()
Now once you fix this, it still won't work like you expect it to, because print() works by printing what you give it at the location of the cursor. Once you're on a new line, you can't go back to a previous line, because your cursor is already on the new line. Anything you print after that will go to the new line at the location of the cursor, so you need to arrange multiple problems such that their first lines all print first, then their second lines, and so on. Just fixing append(), you'd get this output:
20
+ 300
-----
320 1563
- 465
------
1098
You get a string with \n denoting the start of the new line from each call to arrange_printer(). You can split this output into lines, and then process each row separately.
For example:
def arithmetic_arranger(problems, boolean:bool):
arranged_problems = []
if len(problems) > 5:
print("Too many problems")
return
for problem in problems:
# Arrange and split into individual lines
lines = arrange_printer(problem, boolean).split('\n')
# Append the list of lines to our main list
arranged_problems.append(lines)
# Now, arranged_problems contains one list for each problem.
# Each list contains individual lines we want to print
# Use zip() to iterate over all the lists inside arranged_problems simultaneously
for problems_lines in zip(*arranged_problems):
# problems_lines is e.g.
# (' 20', ' 1563')
# ('+ 300', '- 465') etc
# Unpack this tuple and print it, separated by spaces.
print(*problems_lines, sep=" ")
Which gives the output:
20 1563
+ 300 - 465
----- ------
320 1098
If you expect each problem to have a different number of lines, then you can use the itertools.zip_longest() function instead of zip()
To collect all my other comments in one place:
return print(...) is pretty useless. print() doesn't return anything. return print(...) will always cause your function to return None.
Instead of iterating over range(len(problems)) and accessing problems[num], just do for problem in problems and then use problem instead of problems[num]
Debugging is an important skill, and the sooner into your programming career you learn it, the better off you will be.
Stepping through your program with a debugger allows you to see how each statement affects your program and is an invaluable debugging tool
I have a code with asking for errors on interfaces from my network switches. The output that I'm getting varies sometimes.
the output that i get from the switches in this format : (number changes from time to time)
output
so i want to print from the output that i get only line with end with number that grater then 0 like the line with start BAG16
my code is going like that :
import re
kobi = '''
BAGG11 13917779236 10133016 16491979 64
BAGG15 30841323485 22747672 19201545 0
BAGG16 811970 0 811970 0
'''
err = re.findall (r'[BAGG]',kobi)
print(err)
I think this can be done without regex.
Try this:
kobi = '''
BAGG11 13917779236 10133016 16491979 64
BAGG15 30841323485 22747672 19201545 0
BAGG16 811970 0 811970 0
'''
lst = kobi.split()
lines = [lst[i:i+5] for i in range(0, len(lst), 5)]
for line in lines:
if int(line[-1]) > 0:
print(' '.join(line))
Output:
BAGG11 13917779236 10133016 16491979 64
I've made some assumptions about your input:
it's always five rows
last row is a numerical value
You might use a pattern to match BAGG and digits at the start and match a digit starting with 1-9 at the end.
^BAGG\d+[^\S\r\n].*[^\S\r\n][1-9]\d*$
Regex demo
If there should be 3 columns following, a bit more precise match could be using a quantifier {3} to match the number of "columns" in the middle.
^BAGG\d+(?:[^\S\r\n]+\d+){3}[^\S\r\n]+[1-9]\d*$
Explanation
^ Start of line
BAGG\d+ Match BAGG and 1+ digits
(?: Non capture group
[^\S\r\n]+\d+ Match 1+ whitespace chars without a newline followed by 1+ digits
){3} Close non capture group and repeat 3 times
[^\S\r\n]+ Match 1+ whitespace chars without newlines
[1-9]\d* Match a digit 1-9 followed by optional digits
$ End of line
Regex demo | Python demo
For example
import re
kobi = '''
BAGG11 13917779236 10133016 16491979 64
BAGG15 30841323485 22747672 19201545 0
BAGG16 811970 0 811970 0
'''
err = re.findall (r'^BAGG\d+(?:[^\S\r\n]+\d+){3}[^\S\r\n]+[1-9]\d*$', kobi, re.MULTILINE)
print(err)
Output
['BAGG11 13917779236 10133016 16491979 64']
I have a text file:
10
List of ARFCNs = 987 988 989 991 992 993 995 999 1000 1004 1008 1009 1010 1011 1012 1018 1019 1020 1023
I want a code such that it returns the number of values in the list i.e. 19 in this case.
Furthermore, I need to use this number of entries such that if the answer is either 0 or more than 1, the output prints a textline. But if the numbe ris exactly 1, then another statement is printed.
I know its a very basic question but I cant find any specific solution.
I tried using len, but im not sure as to what should be the delimiter. Putting space as a delimiter gives a faulty answer. I want an exception to the code where entries after the = sign are counted and then processed in an if/else loop probably.
Here is the full code:
with open('problem.txt','r') as myfile:
file_str = myfile.read()
my_list = [] ##initializing a list
for word in string.split('=')[1].split(' '): ##using split function to split, the list.this splits the value in index specified and return the value.
## storing the updated list
my_list.append(word)
for var in my_list:
if var == '':
my_list.remove(var)
if len(my_list) == 0 :
print(f'the number of entries are zero')
else:
print(f'the number of entries are {len(my_list)}')
This will help you:
numbers = data.split("=")[1].split(" ")
for value in numbers:
if value == "":
numbers.remove(value)
count = len(numbers)
Here data the the whole string tha you are reading from text file.
This will return the number counts and you can use it further.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
The challenge
The shortest code by character count that will output the numeric equivalent of an Excel column string.
For example, the A column is 1, B is 2, so on and so forth. Once you hit Z, the next column becomes AA, then AB and so on.
Test cases:
A: 1
B: 2
AD: 30
ABC: 731
WTF: 16074
ROFL: 326676
Code count includes input/output (i.e full program).
Excel, 9 chars :)
Use the right tool for the job:
=COLUMN()
Perl, 36 34 33 31 30 17 15 11 characters
$_=()=A..$_
Usage:
$ echo -n WTF | perl -ple '$_=()=A..$_'
16074
Reduced to 17 by using echo -n to avoid a chop call.
Reduced to 15 by using say instead of print.
Reduced to 11 by using -p instead of say.
Explanation:
A is evaluated in string context and A..$_ builds a list starting at "A" and string-incrementing up to the input string. Perl interprets the ++ operator (and thus ..) on strings in an alphabetic context, so for example $_="AZ";$_++;print outputs BA.
=()= (aka "goatse" operator) forces an expression to be evaluated in list context, and returns the number of elements returned by that expression i.e., $scalar = () = <expr> corresponds to #list = <expr>; $scalar = #list.
J, 17 12 10 characters
26#.64-~av
Example:
26#.64-~av 'WTF'
16074
Explanation:
J parses from right to left.
av returns a list of the ascii indexes of each of the characters in its argument, so for example av'ABC' returns 65 66 67.
Then we subtract 64 from each element of that list with the verb 64-~.
Then we convert the list to base 26 using the #. verb.
Brainf*ck, 81 characters (no whitespace)
,[>>>[->>+++++[-<+++++>]<+<]>[-<+>]<<++++++++[<++++++++>-]<[<->-]<[>>>+<<<-],]>>>
Explanation
,[ // get character input into p[0], enter loop if it isn't null (0)
>>>[->>+++++[-<+++++>]<+<] // take what's in p[3] and multiply by 26, storing it in p[4]
>[-<+>] // copy p[4] back to p[3]
<<++++++++[<++++++++>-]< // store 64 in p[1]
[<->-]< // subtract p[1], which is 64, from the input char to get it's alphabetical index
[>>>+<<<-] // add p[0] to p[3]
,] // get another character and repeat
>>> // move to p[3], where our final result is stored
So you'll notice I didn't actually convert the numerical value to an ascii string for printing. That would likely ruin the fun. But I did the favor of moving the pointer to the cell with the result, so at least it's useful to the machine.
Hey, what do you know, I beat C#!
Ruby 1.8.7, 53 50 46 44 24 17 characters
p ('A'..$_).count
Usage:
$ echo -n ROFL | ruby -n a.rb
326676
$ echo -n WTF | ruby -n a.rb
16074
$ echo -n A | ruby -n a.rb
1
APL
13 characters
Put the value in x:
x←'WTF'
then compute it with:
26⊥(⎕aV⍳x)-65
The only reason J beat me is because of the parentheses. I'm thinking there should be some way to rearrange it to avoid the need for them, but it's been a long day. Ideas?
(Heh, you perl programmers with your 30+ character solutions are so cute!)
Excel (not cheating), 25 chars
Supports up to XFD:
=COLUMN(INDIRECT(A1&"1"))
Installation:
Put the formula in cell A2.
Usage:
Enter the column string in cell A1.
Read the result at cell A2.
54 chars, plus a lot of instructions
Supports ROFL also:
(A2) =MAX(B:B)
(B2) =IFERROR(26*B1+CODE(MID(A$1,ROW()-1,1))-64,0)
Installation:
Clear the whole spreadsheet.
Put the formula (A2) in cell A2.
Put the formula (B2) in cell B2.
Fill formula (B2) to as far down as possible.
Usage:
Enter the column string in cell A1.
Read the result at cell A2.
C# 156 146 118 Chars
using System.Linq;class P{static void Main(string[]a){System.Console.Write(
a[0].Aggregate(0,(t,c)=>(t+c-64)*26)/26);}}
Ungolfed:
using System.Linq;
class P
{
static void Main(string[] a)
{
System.Console.Write(a[0]
.Aggregate(0, (t, c) => (t + c - 64) * 26) / 26);
}
}
Golfscript - 16 chars
[0]\+{31&\26*+}*
$ echo -n WTF | ./golfscript.rb excel.gs
16074
$ echo -n ROFL | ./golfscript.rb excel.gs
326676
Haskell, 50 51 56 chars
main=interact$show.foldl(\x->(26*x-64+).fromEnum)0
Usage:
~:166$ echo -n "ROFL" | ./a.out
326676
~:167$ echo -n "WTF" | ./a.out
16074
Python, 64 49 characters
s=0
for c in raw_input():s=26*s+ord(c)-64
print s
You can also replace raw_input() with input() to reduce the character count by 4, but that then requires the input to contain quotation marks around it.
And here's a subroutine that clocks in at 47 characters:
f=lambda x:len(x)and 26*f(x[:-1])+ord(x[-1])-64
k4 (kdb+), 11 characters
26/:1+.Q.A?
Explanation:
k4 parses left of right
.Q.A is defined within k4 - it is the vector "ABC...XYZ"
? is the find operator - the index of the first match for items in the y arg within the x arg
+1 to offset the index
26/: to convert to base 26
One caveat - this will only work where listed types are passed in:
26/:1+.Q.A? "AD"
30
26/:1+.Q.A? "WTF"
16074
but:
26/:1+.Q.A? ,"A"
1
Powershell, 42 chars
[char[]]$args[($s=0)]|%{$s=$s*26+$_-64};$s
JavaScript 1.8: 66 characters
function a(p)Array.reduce(p,function(t,d)t*26+d.charCodeAt()-64,0)
Javascript 1.8: 72 characters
function a(p)(t=0,p.replace(/./g,function(d)t=t*26+d.charCodeAt()-64),t)
JavaScript 1.6: 83 characters
function a(p){t=0;p.split("").map(function(d){t=t*26+d.charCodeAt(0)-64});return t}
JavaScript: 95 characters
function a(p){r=0;t=1;l=p.length;for(i=0;i<l;i++){r+=(p.charCodeAt(l-1-i)-64)*t;t*=26}return r}
JavaScript: 105 characters
function a(p,i){i=i||0;l=p.length;return p?(p.charCodeAt(l-1)-64)*Math.pow(26,i)+a(p.slice(0,l-1),i+1):0}
Usage:
a("A") // 1
a("B") // 2
a("AD") // 30
a("ABC") // 731
a("WTF") // 16074
a("ROFL") // 326676
Scala, 30 chars
print((0/:args(0))(_*26+_-64))"
Example:
C:\>scala -e "print((0/:args(0))(_*26+_-64))" AD
30
C89, 58 characters
s;main(c){while(c=getchar()+1)s=26*s+c-65;printf("%d",s);}
The input (stdin) must contain only A-Z, no other characters (including newlines) are allowed.
Explanation of Concepts - Excelcification
Nice. I wrote my own version of this with a little more explanation a long time ago at
http://aboutdev.wordpress.com/2009/12/19/excelcification-brain-teaser-code/. Although it's not quite an optimized version!
FYI. The base 26 arithmetic is called hexavigesimal and Excel's maximum column is XFD which converts to 16383 (using 0 as the first cell) which is coincidentally exactly 2^14 cells.
Can anyone guess as to why it is 2^14??
Common Lisp, 103 128 characters
(defun x(s)(reduce(lambda(x y)(+(* 26 x)y))(map 'vector(lambda(b)(-(char-code b)(char-code #\A)-1))s)))
C#, 117 111 chars
No contest compared to the likes of Perl, Ruby and APL but an improvement on the other C#/Java answers given so far.
This uses Horner's rule.
class C{static void Main(string[]a){int t=0;foreach(var c in a[0]){t=(t+c-64)*26;}System.Console.Write(t/26);}}
Perl, 34 characters
map$\=26*$\-64+ord,pop=~/./g;print
Thanks to mobrule for several suggestions.
C#, 148 chars
using System;class P{static void Main(string[]a){var r=0d;int j=0,i=a[0].
Length;while(i-->0)r+=(a[0][i]-64)*Math.Pow(26,j++);Console.WriteLine(r);}}
Ungolfed:
using System;
class P
{
static void Main(string[] a)
{
var r = 0d;
int j = 0, i = a[0].Length;
while (i-- > 0)
r += (a[0][i] - 64) * Math.Pow(26, j++);
Console.WriteLine(r);
}
}
Python - 63 chars
>>> f=lambda z: reduce(lambda x,y: 26*x+y, [ord(c)-64 for c in z])
>>> f('ROFL')
326676
Clojure:
user> (reduce #(+ (* 26 %1) %2) (map #(- (int %) 64) "AD"))
30
user> (reduce #(+ (* 26 %1) %2) (map #(- (int %) 64) "ROFL"))
326676
51 characters, plus the number of characters in the input string.
C:
int r=0;
while(*c)r=r*26+*c++-64;
String is stored in 'c', value is in 'r'.
Ruby 1.9, 21 characters
p'A'.upto(gets).count
Tests:
$ echo -n A| ruby x.rb
1
$ echo -n WTF| ruby x.rb
16074
$ echo -n ROFL| ruby x.rb
326676
Common Lisp, 86 characters.
(defun z(s)(let((a 0))(map nil(lambda(v)(setf a(+(* 26 a)(digit-char-p v 36)-9)))s)a))
Java: 112 124 characters
class C{public static void main(String[]a){int r=0;for(int b:a[0].getBytes())r=26*r+b-64;System.out.print(r);}}
Common Lisp, 81 characters
(defun y(s)(reduce(lambda(x y)(+(* 26 x)(-(char-code y)64)))s :initial-value 0))
Funny that as a new user I can post my own answer but not comment on someone else's. Oh well, apologies if I'm doing this wrong!
MATLAB: 24 characters
polyval(input('')-64,26)
Usage:
>> polyval(input('')-64,26)
(after pressing enter) 'WTF'
ans =
16074
Note: You can get it down to 16 characters if you pre-store the string in x, but I kind of thought it was cheating:
>> x = 'WTF'
x =
WTF
>> polyval(x-64,26)
ans =
16074
PHP - 73 Chars
$n=$argv[1];$s=$i=0;while($i<strlen($n))$s=$s*26+ord($n[$i++])-64;echo$s;
Usage:
php -r '$n=$argv[1];$s=$i=0;while($i<strlen($n))$s=$s*26+ord($n[$i++])-64;echo$s;' AA
> 27