I have attached a python 2.7 script to answer question number 2 from the following link: http://labs.spotify.com/puzzles/
My attempt to solve is currently being met with a "wrong answer" reply, yet my code successfully works for the sample inputs on the site. I have tried modifying it to return and even print a list of the top m songs, instead of printing them out individually, but that did not work either. Any help or ideas would be great. Thanks in advance
import sys
def main():
line1 = sys.stdin.readline().split()
total_songs = int(line1[0])-1
num_songs_return = int(line1[1])
data = sys.stdin.read().split()
while(total_songs >= 0):
data[2*total_songs]= float(data[2*total_songs]) * (total_songs+1)
total_songs-=1
answers = [(data[a], data[a+1]) for a in range(0,len(data),2)]
answers.sort(reverse=True)
for n in range(num_songs_return):
print answers[n][1]
main()
Related
The Problem:
I am supposed to create a word file with 250x5 placeholders.
The background is akin to a database export into a word document.
So I created the first placeholder
Name_1
Adress_1
City_1
occupation_1
zipcode_1
and copied the block x250.
Now I need the number to be different for each block; so the second block of 250 would read
Name_2
Adress_2
...etc.
I thought to myself, surely this is faster to automate than to individually type 1000+ numbers.
But here I am, stuck, because my Python expertise is very limited.
What I have so far:
from docx import Document
import os
document = Document("Mapping.docx")
paragraph = document.paragraphs[10]
print(len(document.paragraphs))
print(document.paragraphs[1].text)
def replaceNumbers(ReplaceNumber):
number = 0
for i in range(len(document.paragraphs)):
if number == 5:
replaceNumbers(ReplaceNumber + 1)
break
else:
y = document.paragraphs[i].text
if "1" in y:
document.paragraphs[i].text = document.paragraphs[i].text.replace("1", str(ReplaceNumber))
number = number + 1
return
if __name__ == '__main__':
replaceNumbers(2)
document.save("edited.docx")
now I am guessing there is a problem in my usage of the "while" loop, as the program gets stuck. but manually debugging seems impossible with so many imported libraries.
I hope someone can help me here
I'm not sure what's going on with this problem.
I place the exact same code in a jupyter notebook and everything runs fine. But when I place the code in Hackerrank it does not return any output.
Does anyone spot the error here?
Sample:
6 4
give me one grand today night
give one grand today
#!/bin/python3
import math
import os
import random
import re
import sys
from collections import Counter
# Complete the checkMagazine function below.
def checkMagazine(magazine, note):
ds = Counter(magazine)
for m in note:
ds[m] = ds[m] - 1
if ds[m] < 0 or ds[m] is None: return 'No'
return 'Yes'
if __name__ == '__main__':
mn = input().split()
m = int(mn[0])
n = int(mn[1])
magazine = input().rstrip().split()
note = input().rstrip().split()
checkMagazine(magazine, note)
This code returns but doesn't print the output to stdout that the HR code runner is looking for. Try print(checkMagazine(magazine, note)).
In general, HR is a bit fussy about IO. Data will be read through stdin and will be printed to stdout, often in bizarre formats like "Yes" or "Impossible!" for a function that would normally return a boolean.
firstly, I would like to state that the question I am about to ask is not related to any homework or competiton.
Now, I recently started out with codeforces. I am using Python 2.7.10 to code. The link to the question is this - http://codeforces.com/problemset/problem/71/A
n = input('Enter the test cases :')
b=[]
while n>0:
a = raw_input('Enter the string :')
b.append(a)
n=n-1
t = 0
while t<len(b):
if len(b[t]) > 10:
length = len(b[t])-2
length = str(length)
c = b[t]
print c[0] + length + c[len(c)-1]
else:
print b[t]
t=t+1
The problem I am experiencing is that it says runtime error on test case 1.
My answer comes out fine as mentioned is their test cases. I suppose my syntax is wrong!
I hope you guys can help me out.
Thanks in advance! :)
When taking input you are printing some extra lines like 'Enter the test cases :'. In codeforces your output has to exactly match with the desired output. Printing anything extra will give a verdict of wrong answer or run time error.
I'm having some trouble here. For my CS assignment, I have to have python take data from a file on my pc and run the data through my program.
So, this code works fine on http://repl.it/languages/Python, but not in python. I'm assuming because my line of code has some Python 2.0 lines of code? I can't seem to fix it. Can you guys help? And, another small question except this one. I have to input some code in my program to take data from a file and run it through my program as I stated above. I have this.
import math
def mean(values):
average = sum(values)*1.0/len(values)
return average
def deviation(values):
length = len(values)
m = mean(values)
total_sum = 0
for i in range(length):
total_sum += (values[i]-m)**2
root = total_sum*1.0/length
return math.sqrt(root)
def median(values):
if len(values)%2 != 0:
return sorted(values)[len(values)/2]
else:
midavg = (sorted(values)[len(values)/2] + sorted(values)[len(values)/2-1])/2.0
return midavg
def main():
x = [15, 17, 40, 16, 9]
print mean(x)
print deviation(x)
print median(x)
main()
How do I specifically have the program take data from the file and run it through my program? The data is just a bunch of numbers, by the way. It's been giving me trouble for some hours now. Thanks if you can help out.
This is what I know about the opening/closing file stuff so far
f = open("filename.txt")
data = f.readlines()
f.close()
Apparently you are using python2.x:
I'm assuming because my line of code has some Python 2.0 lines of code?
So yes, you do have a problem: In python3.x, print became a function.
Thus, your prints need to be changed:
print mean(x)
print deviation(x)
print median(x)
Becomes
print(mean(x))
print(deviation(x))
print(median(x))
Also, your part about opening and closing files is unclear.
I´m experiencing problems with my code.
I can´t get it to append to the list not_found as well as it loops twice for some reason.
Can anyone point me in the right direction? The match works for my_track, but it doesn't when it doesn't match.
# coding: utf-8
#!/usr/bin/env python
import spotimeta
import sys
import time
my_tracks = raw_input("Please enter a sentence: ").title().split()
playlist = []
real_playlist = []
not_found = []
def check_track(track_name, my_track, track_href):
if track_name == my_track:
playlist.append(track_href)
return 1
# make sure the user does not input a single word as input
if (len(my_tracks) > 1):
path = my_tracks[1]
else:
sys.exit("Invalid input, please enter a sentence.")
# let's search
for my_track in my_tracks:
match = 0
print "Searching for '%s'\n" % (my_track),
data = spotimeta.search_track(my_track)
for result in data['result']:
if not match == 1:
try:
match = check_track(result["name"],my_track,result["href"])
except Exception, e:
error = "not available"
else:
if data['total_results'] > 0:
not_found.append(my_track)
You should try debugging it. One of the simplest ways of debugging is add the lines:
import pdb
pdb.set_trace()
Then when you run the script it will stop at the set_trace line in the debugger.
Check out http://docs.python.org/library/pdb.html for more information.
From my understanding you're trying to do something like:
for my_track in my_tracks:
print "Searching for '%s'\n" % (my_track),
data = spotimeta.search_track(my_track)
for result in data['result']:
if result['name'] == my_track:
playlist.append(result['href'])
elif data['total_results'] > 0:
not_found.append(my_track)
Will this more or less work for you?
Please help me to understand.
Right off the bat, I'm noticing two things.
First, you're checking data['total_results'] a bit late; if the total results value is greater than zero (wait, what?), then you want to add it to the list immediately and move on without parsing the data. I would, after the call from spotimeta.search_track(), check to see if this is the data you don't want (then subsequently add it into the list).
Second, I'm confused about the intention of your for loop. If you're going through it to only find one item, then you can use the in statement (my_track in result).