i have a problem i want to submit it on online judge it want me to print the result in co-ordinates x,y like
print (2,3)
(2, 3) # i want to remove this space between the , and 3 to be accepted
# i want it like that
(2,3)
i make it with c++ but i want python i challenge my friends that python make any thing please help me
the whole code of proplem i work on it
Bx,By,Dx,Dy=map(int, raw_input().split())
if Bx>Dx:
Ax=Dx
Ay=By
Cx=Bx
Cy=Dy
print (Ax,Ay),(Bx,By),(Cx,Cy),(Dx,Dy) #i want this line to remove the comma between them to print like that (Ax,Ay) not that (Ax, Ay) and so on the line
else:
Ax=Bx
Ay=Dy
Cx=Dx
Cy=By
print (Ax,Ay),(Dx,Dy),(Cx,Cy),(Bx,By) # this too
you can use format:
>>> print "({},{})".format(2,3)
(2,3)
your code should be like this:
print "({},{})({},{}),({},{}),({},{})".format(Ax,Ay,Bx,By,Cx,Cy,Dx,Dy)
To do this in the general case, manipulate the string representation. I've kept this a little too simple, as the last item demonstrates:
def print_stripped(item):
item_str = item.__repr__()
print item_str.replace(', ', ',')
tuple1 = (2, 3)
tuple2 = (2, ('a', 3), "hello")
tuple3 = (2, "this, will, lose some spaces", False)
print_stripped(tuple1)
print_stripped(tuple2)
print_stripped(tuple3)
My space removal is a little too simple; here's the output
(2,3)
(2,('a',3),'hello')
(2,'this,will,lose some spaces',False)
"Strip" the tuple whitespace with listcomprehension;
tuple_ = (2, 3)
tuple_ = [i[0] for i in tuple]
in function
def strip_tuple(tuple_):
return [i[0] for i in tuple_]
Related
Okay so I'm new to Python, trying to move away from Java.
Basically I want to switch the index of a string from 0 to 1, the now switched 1 to 4, the old 4th to 5th and so on.
For an example
string_msg = ['HBTUET']
needs to print out ['BUTTHE']
How do I do this?
What I've tried so far
string_msg = 'HBTUET'
lst = list(string_msg)
lst[::2], lst[1::2] = lst[1::2], lst[::2]
''.join(lst)
print(lst)
You can use a list of tuples to express the index swapping but you have to be careful with the order of these swap operations:
def strSwap(msg,swaps):
chars = list(msg)
for i,j in swaps: chars[i],chars[j] = chars[j],chars[i]
return "".join(chars)
output:
msg = 'HBTUET'
swaps = [(0,1),(1,3),(3,5),(4,5)]
strSwap(msg,swaps) # 'BUTTHE'
msg = 'WRFLVEOO'
swaps = [(0,7),(1,2),(1,4),(2,3),(2,5)]
strSwap(msg,swaps) # 'OVERFLOW'
msg = 'ESLHTYGOHOE'
swaps = [(0, 1), (0, 8), (2, 5), (4, 7), (6, 9), (6, 10)]
print(strSwap(msg,swaps)) # 'HEYHOLETSGO'
Strings are an immutable data type, so you can't rearrange the characters in a string. However, you can use the list() function to convert the string to a list, rearrange the items, then use the str.join() method to convert the list back to a string.
I'm not exactly sure what the pattern is supposed to be in switching the characters, so I just switched the specific cases which you mentioned.
string = "HBTUET"
list_string = list(string)
list_string[0], list_string[1] = list_string[1], list_string[0]
list_string[1], list_string[4] = list_string[4], list_string[1]
list_string[4], list_string[5] = list_string[5], list_string[4]
new_string = "".join(list_string)
Obviously you would have to rearrange the index assignment statements to match the exact procedure desired, but this is a basic layout.
If you have pre-set positions to switch, then it would be easy to use a for loop to switch all the specified items.
string = "HBTUET"
list_string = list(string)
positions = [(0, 1), (1, 4), (4, 5)]
for tup in positions:
list_string[tup[0]], list_string[tup[1]] = list_string[tup[1]], list_string[tup[0]]
mew_string = "".join(list_string)
Alternatively, if there is a specific pattern for switching the characters, e.g. transpose one position right:
string = "HBTUET"
list_string = list(string)
for i in range(len(list_string)-1):
list_string[i], list_string[i+1] = list_string[i+1], list_string[i]
new_string = ''.join(list_string)
How would I get this to print an ordered list so if I entered kiwi, dog, cat, it would print
cat
kiwi
dog
Here is the code I have:
input_string = input("Enter a list element separated by comma:")
lisp = input_string. split(',')
for i in lisp:
if 'cat' == i:
print ('cat')
elif 'kiwi' == i:
print ('kiwi')
else:
print (i)
Here is what it produces:
kiwi
dog
cat
[Updated the code]
I know how to use the sort method to alphabetize, but I need the list to be in a certain order with the random words (ex.dog) just added at the bottom. I am not a coder, and am not a student, I am trying to just learn. So I appreciate all help, all approaches, and your patience.
just do :
input_string = input("Enter a list element separated by comma")
lisp = input_string. split(',')
print(sorted(lisp))
input:
[c,b,a]
output:
[a,b,c]
the "sorted" method sorts elements. you can specify the sort method if you wish.
e.g:
sorted(iterable[, key][, reverse])
It sounds like you want to print your list in order except that "cat" and "kiwi" should be moved to the front. This would have worked:
lisp = ['kiwi', 'cat', 'dog']
if 'cat' in lisp:
print('cat')
if 'kiwi' in lisp:
print('kiwi')
for i in lisp:
if i not in ('cat', 'kiwi'):
print(i)
Output:
cat
kiwi
dog
In response to the comment from my first answer. set up a key and then use sorted. more here : https://www.programiz.com/python-programming/methods/built-in/sorted
check example 3. it defines a custom sort function and passes that in to the key flag:
# take second element for sort
def takeSecond(elem):
return elem[1]
# random list
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
# sort list with key
sortedList = sorted(random, key=takeSecond)
This snipit of code prints the values in the list sorted by the third character. This is an example of using a lambda function to do your bidding. Remember that a sort is a potentially destructive function. If you want to preserve the original list, you should enclose it in a copy-list function.
(loop for an ele in (sort '("cat" "kiwi" "dog")
#'(lambda (x y) (char-lessp (elt x 2) (elt y 2))))
do (print ele))
When I use "\n" in my print function it gives me a syntax error in the following code
from itertools import combinations
a=[comb for comb in combinations(range(1,96+1),7) if sum(comb) == 42]
print (a "\n")
Is there any way to add new line in each combination?
The print function already adds a newline for you, so if you just want to print followed by a newline, do (parens mandatory since this is Python 3):
print(a)
If the goal is to print the elements of a each separated by newlines, you can either loop explicitly:
for x in a:
print(x)
or abuse star unpacking to do it as a single statement, using sep to split outputs to different lines:
print(*a, sep="\n")
If you want a blank line between outputs, not just a line break, add end="\n\n" to the first two, or change sep to sep="\n\n" for the final option.
Two possibilities:
print "%s\n" %a
print a, "\n"
This will work for you:
I used 1,2...6 in my example and 2 length tuples with a combination sum of 7.
from itertools import combinations
a=["{0}\n".format(comb) for comb in combinations(range(1,7),2) if sum(comb) == 7]
print(a)
for thing in a:
print(thing)
Output
['(1, 6)\n', '(2, 5)\n', '(3, 4)\n']
(1, 6)
(2, 5)
(3, 4)
for me in the past something like print("\n",a) works.
I am trying to take a text file and take all the words longer then three letters and print them in a column. I then want to match them with the line numbers that they appear on, in a second column. e.g.
Chicken 8,7
Beef 9,4,1
....
The problem is I don't want to have duplicates. Right now I have the word kings which appears in a line twice, and I only want it to print once. I am thoroughly stumped and am in need of the assistance of a wise individual.
My Code:
storyFile=open('StoryTime.txt', 'r')
def indexMaker(inputFile):
''
# Will scan in each word at a time and either place in index as a key or
# add to value.
index = {}
lineImOn = 0
for line in inputFile:
individualWord = line[:-1].split(' ')
lineImOn+=1
placeInList=0
for word in individualWord:
index.get(individualWord[placeInList])
if( len(word) > 3): #Makes sure all words are longer then 3 letters
if(not individualWord[placeInList] in index):
index[individualWord[placeInList]] = [lineImOn]
elif(not index.get(individualWord[placeInList]) == str(lineImOn)):
type(index.get(individualWord[placeInList]))
index[individualWord[placeInList]].append(lineImOn)
placeInList+=1
return(index)
print(indexMaker(storyFile))
Also if anyone knows anything about making columns you would be a huge help and my new best friend.
I would do this using a dictionary of sets to keep track of the line numbers. Actually to simplify things a bit I'd use acollections.defaultdictwith values that were of typeset. As mentioned in another answer, it's probably best to parse of the words using a regular expression via theremodule.
from collections import defaultdict
import re
# Only process words at least a minimum number of letters long.
MIN_WORD_LEN = 3
WORD_RE = re.compile('[a-zA-Z]{%s,}' % MIN_WORD_LEN)
def make_index(input_file):
index = defaultdict(set)
for line_num, line in enumerate(input_file, start=1):
for word in re.findall(WORD_RE, line.lower()):
index[word].add(line_num) # Make sure line number is in word's set.
# Convert result into a regular dictionary of simple sequence values.
return {word:tuple(line_nums) for word, line_nums in index.iteritems()}
Alternative not usingremodule:
from collections import defaultdict
import string
# Only process words at least a minimum number of letters long.
MIN_WORD_LEN = 3
def find_words(line, min_word_len=MIN_WORD_LEN):
# Remove punctuation and all whitespace characters other than spaces.
line = line.translate(None, string.punctuation + '\t\r\n')
return (word for word in line.split(' ') if len(word) >= min_word_len)
def make_index(input_file):
index = defaultdict(set)
for line_num, line in enumerate(input_file, start=1):
for word in find_words(line.lower()):
index[word].add(line_num) # Ensure line number is in word's set.
# Convert result into a regular dictionary of simple sequence values.
return {word:tuple(line_nums) for word, line_nums in index.iteritems()}
Either way, themake_index()function could be used and the results output in two columns like this:
with open('StoryTime.txt', 'rt') as story_file:
index = make_index(story_file)
longest_word = max((len(word) for word in index))
for word, line_nums in sorted(index.iteritems()):
print '{:<{}} {}'.format(word, longest_word, line_nums)
As a test case I used the following passage (notice the word "die" is in the last line twice):
Now the serpent was more subtle than any beast of the field which
the LORD God had made. And he said unto the woman, Yea, hath God said,
Ye shall not eat of every tree of the garden? And the woman said
unto the serpent, We may eat of the fruit of the trees of the garden:
But of the fruit of the tree which is in the midst of the garden,
God hath said, Ye shall not eat of it, neither shall ye touch it, lest
ye die, or we all die.
And get the following results:
all (7,)
and (2, 3)
any (1,)
beast (1,)
but (5,)
die (7,)
eat (3, 4, 6)
every (3,)
field (1,)
fruit (4, 5)
garden (3, 4, 5)
god (2, 6)
had (2,)
hath (2, 6)
lest (6,)
lord (2,)
made (2,)
may (4,)
midst (5,)
more (1,)
neither (6,)
not (3, 6)
now (1,)
said (2, 3, 6)
serpent (1, 4)
shall (3, 6)
subtle (1,)
than (1,)
the (1, 2, 3, 4, 5)
touch (6,)
tree (3, 5)
trees (4,)
unto (2, 4)
was (1,)
which (1, 5)
woman (2, 3)
yea (2,)
First of all I would use regex to find words. To remove line repeats simply make set() from a list (or use set). "Pretty format" is possible with str.format() from 2.6+ (other solutions tabulate, clint, ..., column -t)
import re
data = {}
word_re = re.compile('[a-zA-Z]{4,}')
with open('/tmp/txt', 'r') as f:
current_line = 1
for line in f:
words = re.findall(word_re, line)
for word in words:
if word in data.keys():
data[word].append(current_line)
else:
data[word] = [current_line]
current_line += 1
for word, lines in data.iteritems():
print("{: >20} {: >20}".format(word, ", ".join([str(l) for l in set(lines)])))
I've written a function in python that returns a list, for example
[(1,1),(2,2),(3,3)]
But i want the output as a string so i can replace the comma with another char so the output would be
'1#1' '2#2' '3#3'
Any easy way around this?:)
Thanks for any tips in advance
This looks like a list of tuples, where each tuple has two elements.
' '.join(['%d#%d' % (t[0],t[1]) for t in l])
Which can of course be simplified to:
' '.join(['%d#%d' % t for t in l])
Or even:
' '.join(map(lambda t: '%d#%d' % t, l))
Where l is your original list. This generates 'number#number' pairs for each tuple in the list. These pairs are then joined with spaces (' ').
The join syntax looked a little weird to me when I first started woking with Python, but the documentation was a huge help.
You could convert the tuples to strings by using the % operator with a list comprehension or generator expression, e.g.
ll = [(1,1), (2,2), (3,3)]
['%d#%d' % aa for aa in ll]
This would return a list of strings like:
['1#1', '2#2', '3#3']
You can concatenate the resulting list of strings together for output. This article describes half a dozen different approaches with benchmarks and analysis of their relative merits.
' '.join([str(a)+"#"+str(b) for (a,b) in [(1,1),(2,2),(3,3)]])
or for arbitrary tuples in the list,
' '.join(['#'.join([str(v) for v in k]) for k in [(1,1),(2,2),(3,3)]])
In [1]: ' '.join('%d#%d' % (el[0], el[1]) for el in [(1,1),(2,2),(3,3)])
Out[1]: '1#1 2#2 3#3'
[ str(e[0]) + ',' + str(e[1]) for e in [(1,1), (2,2), (3,3)] ]
This is if you want them in a collection of string, I didn't understand it if you want a single output string or a collection.
[str(item).replace(',','#') for item in [(1,1),(2,2),(3,3)]]
You only need join and str in a generator comprehension.
>>> ['#'.join(str(i) for i in t) for t in l]
['1#1', '2#2', '3#3']
>>> ' '.join('#'.join(str(i) for i in t) for t in l)
'1#1 2#2 3#3'
you could use the repr function and then just replace bits of the string:
>>> original = [(1,1),(2,2),(3,3)]
>>> intermediate = repr(original)
>>> print intermediate
[(1, 1), (2, 2), (3, 3)]
>>> final = intermediate.replace('), (', ' ').replace('[(','').replace(')]','').replace(', ','#')
>>> print final
1#1 2#2 3#3
but this will only work if you know for certain that none of tuples have the following character sequences which need to be preserved in the final result: ), (, [(, )], ,