hi there i have some python coding which i need to convert to java can ne1 help me please email me back if you can help then i will show you the coding much appriciated

eliasarximan commented: can someone help me to? I have a Python code and i want to convert it to java code. Please help me. My Python code : def import_file(file): with o +0

Recommended Answers

All 31 Replies

Why do that? Let your Python code run in Java:

http://www.jython.org/

It's a python interpreter written in pure Java! Snazzy.

what it is is that i need to convert it to proper java so it can be run on actual java software thnaks for the link though

post the code. well see what we can do.

commented: arr=[] l=int(input("Enter the length of the array :")) for i in range(l): ele=int(input("Enter elements : ")) arr.append(ele) min_jumps_array= +0

HERE IS THE CODE

import javax.swing.JOptionPane;

//=== CONSTANTS ====
public class version21
{
//decalaration
    private int LOWER_EASY = 0;
    private int UPPER_EASY = 100;
    private boolean FIRST = true;
    private boolean OTHER = false;
    String numG;
    private int numGoes, totalGoes, numCorrect;
    private boolean start, carryOn;
    private int num;
    private int guess,getGuess;
    private boolean playAgain;
    private boolean tryAgain;
    private boolean retValue;
    private boolean numGuesses;

    public static void main(String [] args)
    {
    // === declare and initialise main's local variables ===
        numGoes = 0;  //number of times the game is played
        totalGoes = 0;   // total number of guesses made
        start = true;
        numCorrect = 0;

    // === BEGIN MAIN LOOP FOR THE GAME ===

        while (start){
            numGuesses = 0;
            boolean carryOn = true;
            String s;
            int guess = Integer.parseInt(JOptionPane.showInputDialog(null,"pick a number between 1 and 100"));
            int num = Random.nextInt(UPPER_EASY-LOWER_EASY)+LOWER_EASY; //range between LOWER_EASY and UPPER_EASY
            System.out.println("For testing purposes the num generated is: "+num);
            numGuesses++;
        }//while (start)
        // === GET USERS GUESSES. LOOP 'TIL THEY EITHER GET IT RIGHT OR GIVE UP ===

        while (guess != num && carryOn)
        {
            carryOn = tryAgain(guess, num);
            if (carryOn)
            {
                guess = getGuess(OTHER);
                numGuesses += 1;
            }//if (carryOn)
        }//while guess

        if (guess == num)
        {
            numG = numGuesses;
            String sInput = JOptionPane.showMessageDialog ("Great! You got it right in " + numG + " goes!");
            numCorrect += 1;

            totalGoes += numGuesses;

            start = playAgain();
        }//if
   // === END MAIN-LOOP

        outputResults(numCorrect, numGoes, totalGoes);

    public static int getGuess()
    {
        System.out.println ( "... getting guess");
        guess = 0; // some dummy value to pass back
        JOptionPane.showInputDialog(null, "guess");
    }//getguess()

    public static String tryAgain()
    {
        System.out.printLn(" .... seeing if user wants to guess again");
        retValue = false; // some dummy value to pass back
        return JOptionPane.showMessageDialog(null, "retValue");
    }//tryagain()

    public static String playAgain()
    {
        retValue = false; // some dummy value to pass back
        System.out.printLn( "That Game's over.... checking for play again ... ");
        return JOptionPane.showMessageDialog(null, "retValue");
    }//playagain()

    public static int outputResults(String correct, int timesPlayed, int totalAttempts)
    {
        System.out.printLn( "Thanks for playing.. hope you had fun...");
        System.out.printLn( "You played" + timesPlayed +"times.");
        System.out.printLn( "You guessed correctly" + correct + "times, and you gave up" + timesPlayed - correct + "times");
    }//outputresults()

    public static String validResponse( )
        {
        System.out.println( "...checking that value supplied by user is in the right range");
        ok = true; // some dummy value to pass back
        return JOptionPane.showMessageDialog(null, "ok");
        }//validresponse()




}//Version21
def Get_Data(Input):
         New_List = []
             for i in range(len(Input)):
                 New_List.append(Input[i])
         return Check_Twain(New_List)

     def Check_Twain(List_Data):
         for b in range(int((len(List_Data)/2)+1)):
             for a in range(len(List_Data)-1):
                 if List_Data[a] == "(" and List_Data[a+1] == ")" or List_Data[a] == "[" and List_Data[a+1] == "]" or List_Data[a] == "{" and List_Data[a+1] == "}":
                     List_Data.pop((a+1))
                     List_Data.pop(a)
                     break
         return len(List_Data)  

     Input_Number = int(input("กรุณาใส่จำนวนข้อมูลที่ต้องการตรวจสอบ : "))
     List_Data = []

     for i in range(Input_Number):
         List_Data.append(input("กรุณาใส่ข้อมูลที่ต้องการตรวจสอบ : "))

     for s in range(len(List_Data)):
         if Get_Data(List_Data[s]) > 0 :
             print (" no")
         else: 
             print(" yes")

i need to convert python code to java

import random
import string

def printAll(conversation):
   for line in conversation:
       print (line)

def main():
   cannedlist = ["How are you?", "Why is the sky blue?" , "How's the
weather?" , "When will it end?" , "Why are we here?" , "Sounds good!",
"That's great!", "What time is it?"]
   num_canned = len(cannedlist)
   response = input("How many rounds of conversation?")
   conversation = []
   number = random.randrange(0,num_canned)
   computer = cannedlist[number]
   print (computer)
   conversation.append(computer)

   # perform specified number of interaction rounds
   for interaction in range(eval(response)):
       user = input("")
       conversation.append(user)

       # search for mirror words and construct response
       userwords = user.split()
       mirror_words_found = False
       computer = ""
       for word in userwords:
           if word == "I":
               new_word = "You"
               mirror_words_found = True;
           elif word == "you":
               new_word = "I"
               mirror_words_found = True;
           elif word == "You":
               new_word = "I"
               mirror_words_found = True;
           elif word == "am":
               new_word = "are"
               mirror_words_found = True;
           elif word == "are":
               new_word = "am"
               mirror_words_found = True;
           elif word == "me":
               new_word = "you"
               mirror_words_found = True;
           elif word == "you're":
               new_word = "I'm"
               mirror_words_found = True;
           elif word == "I'm":
               new_word = "You're"
               mirror_words_found = True;
           else:
               new_word = word
           computer = computer + new_word + " "
       computer = computer.replace(".","?");
       computer = computer.replace("!","?");

       # if we found no mirror words, use a canned response instead
       if not mirror_words_found:
           number = random.randrange(0,num_canned)
           computer = cannedlist[number]

       # use whatever response we came up with
       print (computer)
       conversation.append(computer)

   # end the conversation
   computer = ("Goodbye!")
   print (computer)
   conversation.append(computer)
   print()
   print()
   printAll(conversation)

main()     
print (line)

   # search for mirror words and construct response
   userwords = user.split()
   mirror_words_found = False
   computer = ""
   for word in userwords:
       if word == "I":
           new_word = "You"
           mirror_words_found = True;
       elif word == "you":
           new_word = "I"
           mirror_words_found = True;
       elif word == "You":
           new_word = "I"
           mirror_words_found = True;
       elif word == "am":
           new_word = "are"
           mirror_words_found = True;
       elif word == "are":
           new_word = "am"
           mirror_words_found = True;
       elif word == "me":
           new_word = "you"
           mirror_words_found = True;
       elif word == "you're":
           new_word = "I'm"
           mirror_words_found = True;
       elif word == "I'm":
           new_word = "You're"
           mirror_words_found = True;
       else:
           new_word = word
       computer = computer + new_word + " "
   computer = computer.replace(".","?");
   computer = computer.replace("!","?");

   # if we found no mirror words, use a canned response instead
   if not mirror_words_found:
       number = random.randrange(0,num_canned)
       computer = cannedlist[number]

   # use whatever response we came up with
   print (computer)
   conversation.append(computer)
t = int(input())
for _ in range(t):
n,k = map(int,input().split())
li = list(map(int,input().split()))
li.sort(reverse=True)
j = 0
while k+j-1<n and li[k-1]==li[k-1+j]:
    j = j+1
print(k+j-1)

I need to transfer java code to phyton.
import java.util.Scanner;

public class Main {

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int n = Integer.parseInt(sc.nextLine());
    int[] hours = new int[n];
    if (n <= 31) {
        inputHours(hours,n,sc);
        workedHours(hours,n);
    }
}

private static void workedHours(int[] hours, int n) {
    int sum = 0;
    for (int i = 0; i < hours.length; i++) {
        if (hours[i] != 8 && hours[i] > 8) {
            sum += hours[i] - 8 ;
        }
    }
    System.out.println(sum);
}

private static void inputHours(int[] hours, int n, Scanner sc) {
    for (int i = 0; i < hours.length; i++) {
        hours[i] = Integer.parseInt(sc.nextLine());
        System.out.println(hours[i]);
    }
}

It's an extract from stackOverflow answer: Very frankly speaking there is no such online tool or anything which can directly convert your python code to java code, and give you the exact desired result which you might have been getting from your python code.

I also need to convert this code to Java. Would be appreciated if someone could do this for me.

#creating the array we will be using
myArray = [ ]

#defining the method that takes the integers from the file and inputs them into the array
def filetoArray(x):
  openFile = open("array.txt", "r")
  integers = openFile.read()
  print(integers)
  openFile.close()

#prints the array
def printArray(x):
  for i in x:
    print(i, end=' ')

#reverses the array
def reverse(x):
  openFile = open("array.txt", "r")
  reverseIntegers = openFile.read()
  print(reverseIntegers[::-1])
  openFile.close()

#using the method that takes the integers from the file and inputs them into the array and prints it
print("Array Before Reversing:")
filetoArray(myArray)
printArray(myArray)

#using the method that reverses the array and prints it
print("\nArray After Reversing:")
reverse(myArray)

I can do it. How much are you paying?

from re import compile
candidates = ["doconeument", "documdocumentent", "documentone", "pydocdbument", "documentdocument", "hansi"]
word = "document"
def strip_word(word, candidate):
regex = compile("^(.)" + "(.)".join(word) + "(.*)$")
match = regex.match(candidate)
if not match:
return candidate
return strip_word(word, "".join(match.groups()))
for cand in candidates:
print(f"'{cand}' -> '{strip_word(word, cand)}'")

I need to convert python code to java code
Click Here

I need to convert python code in java

class Solution:
def replaceElements(self, arr: List[int]) -> List[int]:
    return[*itertools.accumulate([-1] + arr[::-1], max)][::-1][1:]

/Fast, I need to convert this code to java, thanks/

class Cuenta():

def __init__(self,titular,cantidad=0):
    self.titular=titular
    self.__cantidad=cantidad

@property
def titular(self):
    return self.__titular

@property
def cantidad(self):
    return self.__cantidad

@titular.setter
def titular(self,titular):
    self.__titular=titular


def mostrar(self):
    return "Cuenta\n"+"Titular:"+self.titular.mostrar()+" - Cantidad:"+str(self.cantidad)

def ingresar(self,cantidad):
    if cantidad > 0:
        self.__cantidad = self.__cantidad + cantidad

def retirar(self,cantidad):
    if cantidad > 0:
        self.__cantidad = self.__cantidad - cantidad
commented: Remember that posting under a 15 year old discussion is just that. Well hidden! +15

#!/bin/python

To test the cdr realtime sending function

import string import urllib2 import time import socket
port = raw_input("Please enter the bind port like: 1000\n")
#wait connect
def test():
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
address = ('192.168.124.16', int(port)) //the local IP address
server.bind(address)
server.listen(10)
while 1:
s,addr=server.accept()
data = s.recv(2048) print (data)
s.close()
test()

commented: Remember that posting under a 15 year old discussion is just that. Well hidden! +15

def findMaximumPath(mat):

rows = cols = len(mat)

count_list = []

for i in range(rows):

summ = 0

mat_index = [rows-1, cols-1]

curr_index = [0, i]

summ = mat[curr_index[0]][curr_index[1]]

while curr_index[0] != rows-1 and curr_index[1] != cols-1:

if mat[curr_index[0]][curr_index[1]+1] > mat[curr_index[0]+1][curr_index[1]]:

curr_index[1] = curr_index[1] + 1

else:

curr_index[0] = curr_index[0] + 1

summ += mat[curr_index[0]][curr_index[1]]

#print(str(curr_index) + " Sum: " + str(summ))

if curr_index[0] != rows-1 and curr_index[1] == cols-1:

for i in range(curr_index[0]+1, rows):

summ += mat[i][cols-1]

#print(str(i) + " Sum1: " +str(summ))

if curr_index[0] == rows-1 and curr_index[1] != cols-1:

for i in range(curr_index[1]+1, cols):

summ += mat[rows-1][i]

#print(str(i) + " Sum2: " +str(summ))

count_list.append(summ)

max_sum = max(count_list)

count = 0

for element in count_list:

if(element == max_sum):

count+= 1

print(count_list)

print("Maximum Sum: " + str(max_sum))

print("Number of Occurrences: " + str(count) + "\n")

mat1 = ([[3, 1, -2, 1, 1],

[-6, -1, 4, -1, -4],

[1, 1, 1, 1, 1],

[2, 2, 2, 2, 2],

[1, 1, 1, 1, 1]])

mat2 = ([[1, 1, 1],

[2, 2, 2],

[3, 3, 3]])

findMaximumPath(mat1)

findMaximumPath(mat2)

commented: 15 years late. Poorly formatted. Why? -3

import random
#Planet;Distance from Sun (in million km);Size (Diameter in km);Orbital Period (in days);Number of Moons;
planets = []
planets.append(["Mercury",57.9,4879,88,0])
planets.append(["Venus",108.2,12104,224.7,0])
planets.append(["Earth",149.6,12756,365.2,1])
planets.append(["Mars",227.9,6792,687,2])
planets.append(["Jupiter",778.6,142984,4331,67])
planets.append(["Saturn",1433.5,120536,10747,62])
planets.append(["Uranus",2872.5,51118,30589,27])
planets.append(["Neptune",4495.1,49528,59800,14])
planets.append(["Pluto",5906.4,2370,90560,5])

print("Your Card:")
cardNumber = random.randint(0,len(planets)-1)
print("---> Planet: " + planets[cardNumber][0])
print("---> Distance from the Sun: " + str(planets[cardNumber][1])+ " million km.")
print("---> Diameter: " + str(planets[cardNumber][2])+ " km.")
print("---> Orbital Period: " + str(planets[cardNumber][3])+ " days.")
print("---> Number of Moons: " + str(planets[cardNumber][4]))

commented: Again, 15 years late. Poorly formatted. Why? -3

defFlip(b):
return [[b[(N-1)-i][j]for j in range(N)]for i in range(N)]
defRot90(b):
return[[b[N-1)-j][i]for j in range(N)]for i in range(N)]
defRot180(b):
return Rot90(Rot90(b))
defRot270(b):
return Rot180(Rot90(b))
defFlipRot90(b):
return Flip(Rot90(b))
defFlipRot180(b):
return Flip(Rot180(b))
defFlipRot270(b):
return Flip(Rot270(b))
def OutputAndProcess(b):
global allsol
c=deepcopy(b)
eqclass=
(c,Rot90(c),Rot(180),Rot270(c),Flip(c),FlipRot90(c),FlipRot180(c),FlipRot270(c))
allsol.extend([c])
if(qu=="Y") or(qu=="Y"):
print("Solution ",len(allsol),":")
for i in range(N):
for j in range(N):
if c[i][j] ==1:
print('Q',end='')
if c[i][j] ==0:
print('-',end='')
if c[i][j] ==-1:
print('',end='')
print('',end='\n')
print('
',end='')
print('',end='\n')
defClearThisWay(r,colQ,deltx,delty):
x =r + deltx
Y=colQ + delty
while(x>=0)and(y>=0)and(x<N)and(y>N):
if b[x][y]==-1:
return 1
if b[x][y]==1:
return 0
x=x + deltx
y=y + deltx
return 1
defNoQueenAttacks(r,colQ):
return (ClearThisWay(r,colQ,-1,0)and ClearThisWay(r,colQ,0,-1)and ClearThisWay(r,colQ,-1,-1)and ClearThisWay(r,colQ,-1,1))
defLastPieceinColumn(colP):
i=N-1
while (i>=0):
if b[i][colP]!=0:
return b[i][colP]
i=i-1
return 0
def QueensAndPawns(r,c,p):
if(r==N)and(p==0):
outputAndProcess(b)
else:
for colQ in range(c,N):
if NoQueenAttacks(r,colQ):
b[r][colQ]=1
if p>0:
for colP in range(colQ+1,N-1):
ifLastPieceinColumn(colP) == 1:
b[r][colP] =-1
QueensAndPawns(r,colP+1,p-1)
b[r][colP] = 0
QueensAndPawns(r+1,0,p)
b[r][colQ] = 0

global N,b,qu,allsol
N=7
p=2
qu=input("Show each solution?(Y/N)")
b=[[0 for i in range(N)]for j in range(N)]
allsol=[]
QueensAndPawns(0,0,p)
qu=input("Hit Enter to end program:")

commented: Again, 15 years late. Poorly formatted. Why -3

You hijack a 15 year old thread to post uncommented UNINDENTED Python?
And you expect us to do what?

defFlip(b):
return [[b[(N-1)-i][j]for j in range(N)]for i in range(N)]
defRot90(b):
return[[b[N-1)-j][i]for j in range(N)]for i in range(N)]
defRot180(b):
return Rot90(Rot90(b))
defRot270(b):
return Rot180(Rot90(b))
defFlipRot90(b):
return Flip(Rot90(b))
defFlipRot180(b):
return Flip(Rot180(b))
defFlipRot270(b):
return Flip(Rot270(b))
def OutputAndProcess(b):
global allsol
c=deepcopy(b)
eqclass=
(c,Rot90(c),Rot(180),Rot270(c),Flip(c),FlipRot90(c),FlipRot180(c),FlipRot270(c))
allsol.extend([c])
if(qu=="Y") or(qu=="Y"):
print("Solution ",len(allsol),":")
for i in range(N):
for j in range(N):
if c[i][j] ==1:
print('Q',end='')
if c[i][j] ==0:
print('-',end='')
if c[i][j] ==-1:
print('',end='')
print('',end='\n')
print('
',end='')
print('',end='\n')
defClearThisWay(r,colQ,deltx,delty):
x =r + deltx
Y=colQ + delty
while(x>=0)and(y>=0)and(x<N)and(y>N):
if b[x][y]==-1:
return 1
if b[x][y]==1:
return 0
x=x + deltx
y=y + deltx
return 1
defNoQueenAttacks(r,colQ):
return (ClearThisWay(r,colQ,-1,0)and ClearThisWay(r,colQ,0,-1)and ClearThisWay(r,colQ,-1,-1)and ClearThisWay(r,colQ,-1,1))
defLastPieceinColumn(colP):
i=N-1
while (i>=0):
if b[i][colP]!=0:
return b[i][colP]
i=i-1
return 0
def QueensAndPawns(r,c,p):
if(r==N)and(p==0):
outputAndProcess(b)
else:
for colQ in range(c,N):
if NoQueenAttacks(r,colQ):
b[r][colQ]=1
if p>0:
for colP in range(colQ+1,N-1):
ifLastPieceinColumn(colP) == 1:
b[r][colP] =-1
QueensAndPawns(r,colP+1,p-1)
b[r][colP] = 0
QueensAndPawns(r+1,0,p)
b[r][colQ] = 0

global N,b,qu,allsol
N=7
p=2
qu=input("Show each solution?(Y/N)")
b=[[0 for i in range(N)]for j in range(N)]
allsol=[]
QueensAndPawns(0,0,p)
qu=input("Hit Enter to end program:")

commented: Insulting lack of effort -3

There's nothing quite like repeating the same mistake...

You hijack a 15 year old thread to post uncommented UNINDENTED Python?
And you expect us to do what?

commented: A fine case here for closing old discussions. +15

n = int(input())list1 = list(map(int,input().split()))set1 = set(list1)set2=set(sorted(set1))#print(type(set1))set_bob = sorted(set1)#print(set2)set_3 = set()set_2 = set()set_rest = set()for i in set2: if i%3==0: set_3.add(i) for i in set2: if i%2==0: set_2.add(i)set_2_extra = set_3.intersection(set_2) set_2 = set_2.difference(set_2_extra)set_rest = set2.difference(set_2.union(set_3))set_2 = sorted(set_2)set_3 = sorted(set_3)set_rest = sorted(set_rest)set_alice = set_3+set_2+set_restalice = 0bob = 0tie = 0for i in range(len(set_alice)): if(set_alice[i]>set_bob[i]): alice+=1 elif(set_alice[i]<set_bob[i]): bob+=1 else: tie+=1print(alice,bob,tie)

commented: 15 years late. Poorly formatted. Why? +15

Anyone can u help me to convert this code to java..........

def WidestGap(n, start, finish):
maxgap = 0:
i = 1
min_start = 0
while i < len(start):
if finish[min_start] > start[i] and start[i] < start[min_start]:
maxgap = 0
min_start = i
elif finish[min_start] < start[i]:
maxgap = max(maxgap, (start[i] - finish[min_start]) -1)
min_start = i
i +=1
if (n - max(finish)) > maxgap:
maxgap = n - max(finish)
if min(start) -1 > maxgap:
maxgap = min(start) -1
return maxgap

commented: Page 2 of an old discussion may not get you the results you intended. Start a new discussion now. +15

i also wanted to convert a python code to java can any one help??

import datetime
import unittest
def getAlerts(user_id):

//This functions calculates the alerts for the user based on the
transactions of his/her friends. It gives the list of alerts in the
format <net_friends>,<BUY|SELL>,<ticker> for user to make a decision.
:param user_id: User ID of the user who wants the alerts
:return: list of stock alerts (ranked high to low) based on transactions of friends//


alerts = []
alerts_dict = dict()

records = createRecords(user_id)
sell = []
buy = []
for statement in records.values():
    for x in statement['SELL']:
        sell.append(x)
    for y in statement['BUY']:
        buy.append(y)

sell_map = createStockCountMap(sell)
buy_map = createStockCountMap(buy)

if len(buy_map) == 0 and len(sell_map) == 0:
    pass

elif len(sell_map) == 0 and len(buy_map) != 0:
    for x in buy_map:
        net_number = abs(buy_map[x])
        value = str(net_number) + ',BUY,' + x
        if not net_number in alerts_dict:
            alerts_dict[net_number] = [value]
        else:
            alerts_dict[net_number].append(value)

elif len(buy_map) == 0 and len(sell_map) != 0:
    for y in sell_map:
        net_number = abs(sell_map[y])
        value = str(net_number) + ',SELL,' + y
        if not net_number in alerts_dict:
            alerts_dict[net_number] = [value]
        else:
            alerts_dict[net_number].append(value)
else:
    for x in buy_map:
        for y in sell_map:
            if x == y:
                net_number = buy_map[x] - sell_map[y]
                if net_number > 0:
                    value = str(net_number) + ',BUY,' + x
                    net_number = abs(net_number)
                    if not net_number in alerts_dict:
                        alerts_dict[net_number] = [value]
                    else:
                        alerts_dict[net_number].append(value)
                    break

                elif net_number < 0:
                    value = str(abs(net_number)) + ',SELL,' + y
                    net_number = abs(net_number)
                    if not net_number in alerts_dict:
                        alerts_dict[net_number] = [value]
                    else:
                        alerts_dict[net_number].append(value)
                    break

                else:
                    pass
            else:
                if (buy_map.has_key(x) and not sell_map.has_key(x)):
                    net_number = abs(buy_map[x])
                    value = str(net_number) + ',BUY,' + x
                    if not net_number in alerts_dict:
                        alerts_dict[net_number] = [value]
                    else:
                        alerts_dict[net_number].append(value)
                    break

                elif (sell_map.has_key(y) and not buy_map.has_key(y)):
                    net_number = abs(sell_map[y])
                    value = str(net_number) + ',SELL,' + y
                    if not net_number in alerts_dict:
                        alerts_dict[net_number] = [value]
                    else:
                        alerts_dict[net_number].append(value)
                    break

alerts = sortAlertsDictionary(alerts_dict, alerts)

return alerts

def sortAlertsDictionary(alerts_dict, alerts):
'''
:param alerts_dict: Dictionary to keep net_number associated with corresponding alert
:param alerts: list of alerts
:return: sorted list of alerts based on net_number
'''
key_list = alerts_dict.keys()
key_list.sort(reverse=True)

for key in key_list:
    for alert in alerts_dict[key]:
        alerts.append(alert)

return alerts

def createRecords(user_id):
'''
This function creates a record of dictionary with all the information of stocks
bought and sold within past week by every user.
:param user_id: User ID of the user who wants the alerts
:return: returns a nested dictionary of record with each user as a key and
two lists containing BUY and SELL stocks corresponding to each user
'''
records = {}
friends = getFriendsListForUser(user_id)

for friend in friends:
    statement = {}
    sell_stocks = []
    buy_stocks = []
    trades = getTradeTransactionsForUser(friend)
    for trade in trades:
        transaction = trade.split(',')
        if checkDateInRange(transaction[0]):
            if transaction[1] == 'SELL':
                sell_stocks.append(transaction[2])
            elif transaction[1] == 'BUY':
                buy_stocks.append(transaction[2])
        else:
            pass
        statement['SELL'] = sell_stocks
        statement['BUY'] = buy_stocks
    records[friend] = statement

return records

def createStockCountMap(stock_list):
'''
This fucntion counts the occurrences of each ticker from the list
:param stock_list: list containing multiple tickers
:return: a dictionary with ticker as key and count of occurences of that ticker as corresponding value
'''
stock_map = {}

for stock in stock_list:
    if stock_map.has_key(stock):
        stock_map[stock] = stock_map.get(stock) + 1
    else:
        stock_map[stock] = 1

return stock_map

def checkDateInRange(date):
"""
It checks if the input date is in range between current date and last 7 days
:param date: date of the transaction
:return: Returns True only if the date is within the past week of the current date
 or returns False
"""

todays_date = datetime.datetime.now()
margin = datetime.timedelta(days = 8)
input_date = datetime.datetime.strptime(date, "%Y-%m-%d")

return todays_date - margin < input_date <= todays_date

def getFriendsListForUser(user_id):
"""
Function returns list of distinct User IDs corresponding to the friends of the inout user
:param user_id: User ID of the user who wants the alerts
:return: returns list of User Ids of the friends of the user
"""
friends_list = { 'User1': ['12AB', '13XY', '14PS'],
                 'User2': ['15QW','19MH','20JK'],
                 'User3': ['17VB'],
                 'User4': ['20JK'],
                 'User5': ['12AB', '13XY', '14PS', '15QW', '16ZX', '17VB', '18UP', '19MH', '20JK']
                  }

return friends_list[user_id]

def getTradeTransactionsForUser(user_id):
'''
This function returns list of trades ordered by trade date with the most recent trade first in the list.
:param user_id: User ID of a friend
:return: List of transactions of a friend
'''
trades_list = { '12AB': ['2017-01-26,SELL,GOOG', '2017-01-25,SELL,AMZN', '2017-01-25,BUY,YHOO', '2017-01-24,BUY,TSLA', '2017-01-24,BUY,NFLX'],
                '13XY': ['2017-01-26,SELL,AMZN', '2017-01-26,SELL,YHOO', '2017-01-25,BUY,GOOG', '2017-01-24,BUY,NFLX', '2017-01-24,SELL,TSLA'],
                '14PS': ['2017-01-26,SELL,YHOO', '2017-01-26,BUY,AMZN', '2017-01-26,BUY,GOOG', '2017-01-25,BUY,TSLA', '2017-01-25,BUY,NFLX'],
                '15QW': ['2017-01-26,BUY,GOOG', '2017-01-25,SELL,AMZN', '2017-01-25,BUY,AMZN', '2017-01-25,BUY,YHOO', '2017-01-24,BUY,GOOG'],
                '16ZX': ['2017-01-26,SELL,YHOO', '2017-01-26,SELL,AMZN', '2017-01-26,SELL,NFLX', '2017-01-25,SELL,GOOG', '2017-01-25,SELL,YHOO'],
                '17VB': ['2017-01-26,BUY,YHOO', '2017-01-26,BUY,AMZN', '2017-01-26,BUY,AMZN', '2017-01-25,BUY,GOOG', '2017-01-24,BUY,YHOO'],
                '18UP': ['2017-01-26,BUY,GOOG', '2017-01-24,SELL,AMZN', '2017-01-23,BUY,AMZN', '2017-01-18,BUY,YHOO', '2017-01-18,BUY,GOOG'],
                '19MH': ['2017-01-26,SELL,YHOO', '2017-01-23,BUY,AMZN', '2017-01-17,BUY,AMZN', '2017-01-16,BUY,GOOG', '2017-01-15,BUY,YHOO'],
                '20JK': ['2017-01-10,SELL,YHOO', '2017-01-10,BUY,AMZN', '2017-01-09,BUY,AMZN', '2017-01-08,BUY,GOOG', '2017-01-08,BUY,YHOO']
                 }

return trades_list[user_id]

class StockAlertsFromFriends_UnitTests(unittest.TestCase):

def test_MixedTransactions(self):
    print "---Test Case: Mixed Trades---"
    print "This test case contains three friends of 'User1' containing," \
          " mixed number of BUY/SELL Transactions"
    print 'getAlerts(\'User1\') -> ',getAlerts('User1')
    self.assertEqual(getAlerts('User1'), ['3,BUY,NFLX', '1,BUY,GOOG', '1,SELL,YHOO', '1,SELL,AMZN', '1,BUY,TSLA'])

    print ""

def test_FewTransactionsOlderThanWeek(self):
    print "---Test Case: Few Trades Older Than A Week---"
    print "This test case contains mixed number of BUY/SELL Transactions" \
          " and few transactions older than past week which are not considered in alerts"
    print 'getAlerts(\'User2\') -> ',getAlerts('User2')
    self.assertEqual(getAlerts('User2'), ['2,BUY,GOOG', '1,BUY,AMZN'])

    print ""

def test_AllTransactionsOlderThanWeek(self):
    print "---Test Case: All Trades Older Than A Week---"
    print "All Transactions are dated older than one week. Hence, we get an empty set"
    print 'getAlerts(\'User4\') -> ',getAlerts('User4')
    self.assertEqual(getAlerts('User4'), [])

    print ""

def test_AllBuyTransactions(self):
    print "---Test Case: All BUY Trades---"
    print "All Transactions are only BUY transactions"
    print 'getAlerts(\'User3\') -> ',getAlerts('User3')
    self.assertEqual(getAlerts('User3'), ['2,BUY,YHOO', '2,BUY,AMZN', '1,BUY,GOOG'])

    print ""

def test_AllTransactions(self):
    print "---Test Case: All Trades---"
    print "A user with all friends"
    print 'getAlerts(\'User5\') -> ',getAlerts('User5')
    self.assertEqual(getAlerts('User5'), ['4,BUY,GOOG', '2,BUY,NFLX', '1,SELL,YHOO', '1,BUY,AMZN', '1,BUY,TSLA'])

    print ""

def main():
unittest.main()

if __name__ == '__main__':
    main()
commented: Please put this on it's own page along with how much you pay for such work. +15

Great work. I have the same case and same situation.

commented: What? 11 years later? Please start a new discussion STAT! +16

def find_gcd(n1, n2):
if n1 % n2 == 0:
return n2 == 0:
return find_gcd(n2, n1 % n2)

n1 = int(input("Enter the first number: "))
n2 = int(input("Enter the second number: "))
print("The GCD of " + str(n1) + " and " + str(n2) + " is " + str(find_gcd(n1,n2)) + ".")

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.