instruction
stringlengths
71
95.1k
I'm currently working through the google FooBar challenge, and I'm on the third level, in which I have to find the distance between the top left and bottom right points on a grid. The grid is filled by ones and zeros, with zeros representing crossable spaces and ones representing non-crossable spaces (a typical grid wo...
Question might be more appropriate in StackOverflow, however I'd also like a review. I'd like to make my code inline as I feel like this could be possible, I'm just not sure how. int highestWeightOfParcel = 0; if (collo.WeightGrammes.HasValue) { if (collo.WeightGrammes > highestWeightOfParcel) { highes...
I have three modules here models.py, functionals.py, and adjustment.py. These three may be used to perform analysis of Twitter data through tweepy objects. The Tweets class is a simple one which takes 'tweet' objects and take it as a 'list', which is necessary (not yet implemented as necessary) as an argument of Author...
I used a glyphicon as a link to delete a comment: <a class="delCommentLink" href="{% url 'article:comment_delete' comment.id %}"> <span id="{{ comment.id }}" class="glyphicon glyphicon-trash" aria-hidden="true">delete</span> </a> I send the request using Ajax. retrieve the comment_url get the grand-grand-parent e...
I built a class to help me handle image data to use in machine learning. I thought that there would be a pre-existing package that did what I wanted but I couldn't find it so I wrote this. I am not intentionally trying to re-invent the wheel so if there's something that already does this please let me know (although I ...
The task is to fetch some JSON data from an API with a GET request. If the location is not available for any reason, read a cache file. Otherwise write the cache file for future use. The following function works but it is clumsy due to: The nested try/except, which is difficult to read It's difficult to figure out wha...
A challenge from Code Fights; a function that takes a number no less than 10 and that will always have an even number of digits and determines if the sum of the first half of the digits equals the sum of the second half of digits. The function returns a Boolean. Maximum execution time is 4000 milliseconds. Here is the ...
This is a follow up to a previously asked Finding the closest pair of points divide-and-conquer question . The original code changed significantly based on answers from @AJNeufeld therefore I created a new question per codereview guidelines for additional help. After incorporating suggestions from answers to the origi...
I have some zip files somewhere in the order of 2GB+ containing only html files. Each zip contains about 170,000 html files each. My code reads the file without extracting them, Passes the resultant html string into a custom HTMLParser object, And then writes a summary of all the zip files into a CSV (for that parti...
This is a follow up of Non generic Skip List implementation in C++ Version 2 If you don't know what a Skip list is: https://en.wikipedia.org/wiki/Skip_list I tried to incorporate as much improvements as possible from the code review of the last skip list. Also the following changes were made: Templates: I turned the ...
I'm not sure what I'm doing wrong yet, but while I continue to figure it out, I'd love to get some input from others w/ experience. The goal is to cipher the plaintext using a key provided at the command line. I can't wrap my head around why my ciphertext comes out the same as my plaintext. I seem to have figured out c...
I am trying to improve the run time of a program I wrote in R. Generally, what I am doing is feeding a function a data frame of values and generating a prediction off of operations on specific columns. The function is a custom function that is being used with sapply (code below). What I'm doing is much too large to pro...
I need to send email notifications for expired licenses: One Day Before/After Expiration Two Days Before/After Expiration Three Days Before/After Expiration One Week Before/After Expiration Two Weeks Before/After Expiration One Month Before/After Expiration Two Months Before/After Expiration Three Months Before/After ...
The application uses NCalc to execute diverse calculations. The 'natural' way to write powers using a computer is using the ^ symbol. However, NCalc already uses it as bitwise or. I use the following function to parse calculations and convert it to the Pow(a,b) format. Private Function _replacePower(Str As String) ...
UPD: Haskell version, please check it too. gameKey(long id) is authentication function of an MMO game server. When someone wants to play with friends, he sends request to server, server calls gameKey() and returns it as JSON to player via API. When a friend establishes connection, he sends the game id and his key, serv...
I've written a Vigenere decypher and I would like to have some opinions before I try to refactor it into more OOP style with classes and such. #include <bits/stdc++.h> #define Rep(i,a,n) for(int i = a; i < n; i++) #define rep(i,n) Rep(i,0,n) using namespace std; int main(){ string key, line, code = "", dict = "ABCD...
I have just started learning C# and decided to do some problems from Project Euler. I wrote a code to find 10 001st prime and I thought it would be cool optimize it to make it as fast as possible. How could I improve this to make it even faster? using System; using System.Collections.Generic; using System.Linq; using S...
I've implemented the sieve of Eratosthenes in Python 3 as follows: def sieve_of_eratosthenes(n): is_prime = [True] * (n+1) is_prime[0] = False is_prime[1] = False p = 0 while True: for i, prime in enumerate(is_prime): if prime and i > p: p = i ...
I've designed a basic Tetris game, and implemented it in Java language. I'll use it for demonstrating software engineering, designing. I'll re-implement it in many different programming languages, in different platforms. Thus, good concept is very important. Goals: Follow general OOP principles. Readablity, reasonable...
I am a beginner in Python and I am yet to move on from the basics to things like OOP.I wrote all of this code (Python 3) in an hour or so for a simple countdown timer.Although some parts of it are seemingly excessive,is the core of the code pythonic enough or are there better ways of structuring it?I would also like to...
Here are two simple classes - Digit class maintains digit behaviour - primarily flipping animations, and Clock class handles everything that is related to time data. I'm going to use this code for job application, please tell me if there are any improvements that could be done and what do you think of it. Here is the l...
Task: For creating this challenge on Codewars I need a very performant function that calculates Von Neumann Neighborhood in a N-dimensional array. This function will be called about 2000 times The basic recursive approach: calculate the index span influenced by the distance if the index is in the range of the matrix ...
Given the following artificially generated data: t_steps = 30 data = np.array([ np.arange(t_steps) * .05, np.arange(t_steps) * .1, np.arange(t_steps) * .2, np.arange(t_steps) * .3 ]) I find the time-step the each line of data has passed a threshold. If it does not pass the given threshold, I assign a...
Problem Two folders having files with nameEfile that store lines starting with hex codes. Print those hex codes that overlap in both folders. Solution import os import sys import re def process_cache(cache): event_code_set = set() for file_name, multi_line_content in cache.items(): if file_name.endswi...
still new to java and i am trying to improve my understanding and use of OOP concepts.here i am supposed to print the name of a randomly selected card from a deck of 52 cards. Program: /* * RandomCard.java * ------------------- * Displays the name of a card randomly chosen from a complete deck of 52 * playing card...
Given a string, reverse only the vowels present in it and print the resulting string. Input: First line of the input file contains an integer T denoting the number of test cases. Then T test cases follow. Each test case has a single line containing a string. Output: Corresponding to each test case, outpu...
I come from the R language and I gradually switch to Python (Numpy and Pandas). I coded this python code for fun to solve a Sudoku grid. Could you tell me if my code is pythonic enough? For example, did I use the numpy functions correctly. How to make the code more readable? import numpy as np from functools import red...
I'm reading and processing a fairly large csv using Pandas and Python 3.7. Header names in the CSV have periods in them ('full stops', Britons say). That's a problem when you want to address data cells by column name. test.csv: "name","birth.place","not.important" "John","","" "Paul","Liverpool","blue" # -*- coding: ...
The following program converts a string to a double, and checks for errors. It uses the strtod() function to do the conversion, and follows the example given for the strtol() function from the man page to do the error checking. As an example, the program is executed as follows: $ ./a.out 123.45 I would really appreci...
I have a binary file input.hgt from the Shuttle Radar Topography Mission. It contains a 3601✕3601 matrix, stored as 2-Byte big-endian integer numbers. My code converts it to a readable text file output.csv. How can I make it better? Here is my code: #include <iostream> #include <fstream> using namespace std; const i...
This code was reworked and posted here:Text based game “Hunt the Wumpus” Version 2 The following game was a excercise in the PPP book by Stroustrup: Implement a version of the game "Hunt the Wumpus". Hunt the Wumpus" (or just "Wump") is a simple (non-graphically) computer game originally invented by Gregory Yob. ...
I wanted to write a code that each time I will press some button in my menu, a numpy image array will somehow be created, and this image will show up in a new window. So the following code is the same purpose, but with the same numpy image array for all new windows (for simplifying). Which means, for a given numpy imag...
EDIT: I have posted a follow-up to this question. I have implemented counting sort in C. This program takes its input as integers from command line arguments, sorts the integers with counting sort, then outputs the sorted array. This is my first attempt at implementing this and I would really like to see what I could d...
I'm working on a d3 project that has multiple sub-plots with updating data. I have a working example below, but I think I might be over complicating the update() pattern. I didn't include an exit() because the data is consistent (there's always the same amount of divisions, teams and values). d3 experts: does this look...
I am preparing for multithreading interview questions and I don't have much experience with multithreading. I referred some online article to come up with a solution. Is this solution appropriate? public class ThreadSafeArrayList<E> { private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); pri...
In this code, I focused more on code readability rather than algorithmic complexity. I didn't really care about the code in the main function because it was just used to test the code. Some of the classes have a D prefix to differentiate them from the regular Nodes. A few problems in particular I would like comments o...
This is a revised follow-up to this question. I have implemented most of the suggestions in the accepted answer. I am interested to see what I could improve in my code and what I could do to make it better. I have implemented counting sort in C. This program takes its input as integers from command line arguments, sor...
Challenge Using the C++ language, have the function MaximalSquare(strArr) take the strArr parameter being passed which will be a 2D matrix of 0 and 1's, and determine the area of the largest square submatrix that contains all 1's. A square submatrix is one of equal width and height, and your program should return the ...
I wanted to implement Dijkstra's Algorithm in an Excel VBA Add-In and built it to be used as follows: Define a list of paths with distances between points. This list needs to contain 3 headings that are used as flags to pick up where the list is. The 3 headings are !dijk:dat:from, !dijk:dat:to and !dijk:dat:dist Speci...
TCP/IP server which controls up to 500 clients. There's a list of added computers and the server gets this list, selects computers which are not already connected and ping them using host name. using System; using System.Collections.Generic; using System.Linq; using System.Net.NetworkInformation; using System.Threading...
I need to process rabbitmq messages with golang with worker style, is this correct way to process rabbitmq messages with golang? package main import ( "log" "github.com/streadway/amqp" ) func main() { conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/") if err != nil { panic(err) }...
I have implemented a little snake game with Javascript and Html. This is my first game with Javascript. I use a Linkedlist to represent the snake. Both code snippets are in snake.js file. It would be really nice if someone could give me feedback. LinkedList: function Point(x, y) { this.x=x; this.y=y; this.toString ...
I was wondering if there is a better, more elegant way to write the following JavaScript code block: var searchString = 'ma'; var names = ['Mark Kennel', 'Hellen Smith', 'Jane Mary Annet', 'Peter']; var filteredNames = names.filter(name => { var words = name.toLowerCase().split(' '); for(var i = 0; i < words.lengt...
I have a use case in which I need to check whether a given value is explicitly True or False: def stringify(value): """Returns the string representation of the value.""" if value is None: return '-' if value is True: return '✓' if value is False: return '✗' return str(val...
public static void main(String[] args) { int minKmh = 10; int maxKmh = 20; int step = 5; String allSpeeds = ""; while (minKmh <= maxKmh) { allSpeeds += minKmh + ","; minKmh += step; } String[] allSpeedsAsArray = removeLastChar(allSpeeds).split(","); // result: 10,15,20 } p...
Hello I wrote the following code. It allows me to use objects as keys in a map. I have a constraint though: In addElement function both arguments must be pointers // Example program #include <iostream> #include <string.h> #include <map> typedef struct { std::string name; } Test; class Tester { /*I want th...
C++ code version (description copied from it) gameKeys id is authentication function of an MMO game server. When someone wants to play with friends, he sends request to server, server calls generateId, then gameKeys id and returns it as JSON using encodeJSON to player via API. When a friend establishes connection, he s...
I have a function: def palindrome(n): assert(n < 10) res = [['0']] for x in range(1, n + 1): str_x = str(x) l = len(res) res.insert(0, [str_x] * l) res.append([str_x] * l) for line in res: line.insert(0, str_x) line.append(str_x) return '\n...
I've recently made a program which generates a (pseudo) random binary digit (1,0) which is tied to a specific subject to learn for every day of the week. The program generates the digits the first time it's used, stores them in a file for later use and after that every Monday it generates them again. Currently I'm usin...
As practice, I have written a prime number sieve in Standard ML. It works in a pretty straightforward way: The list of known primes starts with just 2. Starting with 3, check whether each odd integer is relatively prime to all numbers in the list of known primes (i.e. is not divisible by them) If it's relatively pri...
As I'm learning to program in C, I'm making my way through K&R. The goal of the exercise is to add a option to the program so that the sorting does not depend on upper or lower-case letters. What are your opinions on my use of function pointers in this exercise? Do you see any obvious beginner traps in the code? #...
I've not used this site before, I would like to get opinions on the code I've completed for my first 'program' in Python. I would like to understand how 'good' it is and where it can be improved, anything that says "you're clearly a beginner and haven't learned xxx" would be helpful. Background to project: My payslips ...
For practice JavaScript I created simple To-do app. This app can add TODOs and track the number of total TODOs as well as the number of unchecked TODOs. For this I written 4 functions: for add newTodo - newTodo(), where I add new todo to todos array for render list of todo - drawTodoList(), where I also add event lis...
Given the following instructions I have created a function that achieves the requirements. I feel my function is a bit too complex, though it does what it's supposed to. The difficult part for myself was avoiding the equality operators. The only way I could think to solve this is with a bit of math and a comparison ope...
I have managed to write this piece of code but as I am using it on big data sets it ends up being quite slow. I am pretty sure it would be possible to optimize it but I am very knew to coding and I don't really know where to start.. I think getting rid of the for loop would be one way but honestly I'm lost. A little bi...
I am a beginner and have created this bash script that helps me with creating bash scripts. The script shows no issues on shellcheck.net The code can be found here. https://github.com/plutesci/Iwanttobash/blob/master/Icode.bash I would like some feedback from more experienced users. Any suggestions or thoughts about ...
I have a huge array that I want to group by by category and subcategory. A Book is contained in a shelf. A Shelf is contained in a Library. The output is a list of Library. I cannot change my Book class, but I am free to organize the Shelf and the Library class.How can I improve the grouping? Current running time is O(...
This is the main.py script that does most of the work of Adding movies (Movie objects) as well as modifying and removing: from flask import Flask, render_template, request, flash, url_for, redirect import sqlite3 from datetime import date from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from...
I am trying to generate predictions using the function below in combination with sapply. My actual datasets are very large, I am attempting to make 1.5 million predictions with this function and it is currently taking about 10 seconds per prediction which is... prohibitive to say the least. mean_rating <- function(df){...
I've just found out there is sendfile(). In the man page of sendfile(), it says: sendfile() is more efficient than the combination of read(2) and write(2). So, I wrote a function to copy a file using sendfile(). Is really my code more efficient than the combination of read(2) and write(2)? /* leftsize is initialized ...
Challenge Using the C++ language, have the function PentagonalNumber(num) read num which will be a positive integer and determine how many dots exist in a pentagonal shape around a center dot on the Nth iteration. For example, in the image below you can see that on the first iteration there is only a single dot, on th...
I decided to try and recreate Microsoft's REG.exe query functionality."Reg.exe" is Microsoft's Console Registry Tool. I used Microsoft's documentation of "reg query" to recreate it's functionality within C++. I thought that it would be a great way to test myself and help to get a better grasp of Microsoft API's as wel...
For the purpose of defining a lot of Maximum Likelihood estimators, I think I need a metaclass. At the moment I have to copy/paste a lot of code for every new class definition and just substitute the corresponding scipy.stats functions. from scipy.stats import fisk, t from statsmodels.base.model import GenericLikelihoo...
I have been working through the euler project and I have created the following code for Problem 14, which asks which starting number, under 1 million, produces the longest Collatz Sequence chain. It takes a good minute to process. Can I make it faster? class Collatz: def __init__(self): self.c = 1 de...
I have 3 tables on my database: BusinessObject and CustomEvent, and EventType. BusinessObject having a lot of columns, CustomEvent having the following: Id EventTypeId DateEvent CommentEvent UserId BusinessObjectId I want to get all the BusinessObject having two CustomEvent with EventTypeId in (10, 11) such has the di...
I wrote the following simple 1 producer - 1 consumer problem, in attempt to learn some C++11 threading / generics. #include <iostream> #include <mutex> #include <condition_variable> #include <deque> #include <thread> struct data { int x, y; std::string s; data() : s("test") { x = std::rand() % 10...
I managed to make a many to many relationship work correctly using mysql, doctrine 2 and symfony 3.4. When a new element A that contains 0 to m element Bs is inserted, the B elements that already have the same content are reused, instead of creating new ones. This is not the default doctrine 2 behaviour in a ManyToMan...
Windows only. So I am writing code to decompile a Windows compiled html help file (*.chm) and then tidy the files found within. Whilst, I have blogged some simple Python examples I now want to write Python code closer to production standards so I'd like a code review thanks. I will bring forth a series of classes ...
This is a follow-up of: Text based game "Hunt the Wumpus" A follow up of this review was posted here: Text based game “Hunt the Wumpus” Version 3 I tried to incorporate the suggestions made in the first question into the code. However I still feel that there is maybe space for improvement. I completely changed how the ...
I've written some simple helper functions that read data types from a vector of bytes (binary files) and having a tough time deciding which route to go. Method 1 : reinterpret_cast int32_t read_32s(const std::vector<uint8_t> &buf, const unsigned offset, const bool bswap = false) { // Check for out o...
Introduction I am working on a semi large project with a few hundred files. In this project there is a series of lesson.yml files I want to check is formatted correctly. And, yes, every file I want is called exactly that. Just to clarify my code works, and does exactly what I want. However, I expect there either exist...
I am a golang novice... I am trying to write an application that takes in many requests - up to a sustained 10000 HTTP posts/sec and post the payload to two back-ends in parallel (5 second timeout). A canned message is returned to the client, it doesn't matter whether the backed end returns a response or errors out, t...
std::variant and boost::variant do not require the types involved to be unique, but lose some functionality when types repeat. I'm trying to create a simple type that has a fixed number of cases (std::variant and boost::variant are variadic) and has an elimination form that approximates the look and feel of match/case....
This is my first ever project I've coded in Python so I'm sorry if it's a little novice. I'm just looking for beginner feedback on what I could improve next time. There is one issue with this calculator: let's say I add 1 and 2, I expect to get 3, instead it returns 3.0, but I'm guessing that's because I'm casting to a...
on leetcode.com, there is a question with the following description: Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below. link to the question here. Here is my implementation: class Solution { public: std::vector<std::...
I'm new to Python and decided to work on a personal project and make a program that web scrapes and downloads manga. It works as expected, however, I am sure that there is a better way to structure my code. I'd appreciate some guidance on how to better write this project. You can check it out on my GitHub here. import ...
I have two lists of Person objects. I need to compare the lists to determine if items in list1 exist in list2 and vice versa. This is not a straight equals() scenario as the objects are not the same, but may have identical field values. It is those values that I need to compare. Currently, I am using Java 8's Streams A...
I want to take the capitalization of one string and apply it to another. For example: take Apple and orange and turn that into Orange. This is the solution I implemented. Is there a more efficient way of doing this? public static String applyCapitalization(String to, String from) { int[] capArray = toCapitalization...
NICK binary thresholding essentially boils down to a convolution where the kernel at each pixel calculates the sum and squared sum (for the standard deviation). These values are then used in the threshold function to determine whether the grayscale value should be black or white. A kernel size of 19x19 is pretty common...
I have written a class to quantize values to arbitrary bit depths within a specified amplitude. It is meant to process one value at a time, and has two ways of quantizing values. I wrote the class so that i could create objects of it as a property for another class, so that the quantization process can easily be includ...
I wrote code to extract the contour of a hole, based mostly on the Moore-Neighbor Tracing algorithm. Only a. instead of finding a shape, I'm finding a "hole"; and, b. I'm looking for the (outer) boundary of the hole, i.e. the actual pixels that are not part of the hole but that are hole boundary. public class MooreTr...
I'm totally new to python and coding in general and I tried for my first project to recreate Conway's game of life. After days of trial and error, I came up with this code: import numpy as np import copy import png import PIL as PIL def a(a) : if a == "gen" : size=int(input("size ? ")) rat...
You are given two binary search trees, the goal is produce a sorted array of elements containing elements from both the trees. I wanted to know if there is a simpler approach, and if the use of boost variant is justified in the code. The code uses a stack to iterate over the binary search tree. The stack maintains the...
I'm preparing for an interview doing the preparation questions on Hacker Rank and I want to become better at this. Is it possible to get some feedback on this? How can I improve my code? How did you solve this question? function getCount(array){ let counts = {} for(let word of array){ let count = coun...
I like to collect images for my desktop background, the problem is sometimes the image names don't represent what the image is. I decided to write a script that reads a text file that contains the source of the images to be renamed, and the base name. The script renames the images using the base name and increment coun...
I have a following exercise from ANSI C book: Exercise 6.1. Our version of getword does not properly handle underscores, string constants, comments, or preprocessor control lines. Write a better version. Here's my improved version of getword function and code that test if it works: #include <ctype.h> #include <st...
I stumbled upon this problem on cses.fi (a problem set for the Finnish Olympiad in Informatics. This problem is in finnish so I'll translate it). I'll describe the problem, present the code and think what went wrong. The problem You are given a blueprint of a house. The size of the blueprint is \$n * m\$ and each squa...
Any tips to reduce lines, improve speed, or any cool thing, are welcome. I have been using this for years and I just realized, why not improve ...? Sub AtualizarRelatorioGeral() Application.Calculation = xlCalculationManual Application.ScreenUpdating = False Application.EnableEvents = False Application....
I'm a Java beginner currently practising MVC pattern and came up with this. Could you please check if this is a proper implementation of MVC and if there are any best practices that I have broken? public class Appka { public static void main(String[] args) { Model model = new Model(); Cont...
Please give me some pointers on how I can improve this project with Python 2.7. import json import urllib urls = ["https://data.calgary.ca/resource/kqmd-3dsq.json","https://data.calgary.ca/resource/4wni-k3sg.json"] print " \nThis is Json Data Parser Program. \nThis program will print the Unique Voting Station Name from...
After implementing SAT (separating axis theorem) and not being happy with it only working on stationary shapes, this in theory allowing for fast objects to glitch through others, I came up with this approach to detect collisions between moving objects. Algorithm explained The idea is quite simple: I figured that, if t...
I have written this function (in C++) to apply an arithmetic operation on two numbers and print the result. void printResults(double a, double b, char c) { double r; if (c=='+') { r = a + b; } else if (c == '-') { r = a - b; } else if (c == '*') { r = a * b; ...
I am working with 2 databases. One for admins ('backoffice') and one for users. Account managers: Use the 'backoffice' database to manage customer accounts. Customers: Whenever a users connects and inserts his username password and company name, the code must connect to the backoffice database, validate his data, ge...
This is my first program in Python that I have coded and I am relatively happy with how it turned out. I would like to know how I could make my code shorter and more efficient. def one_round(player): #Distinguish player 1 from player 2 if player == "p1": p = "Player 1" elif player == "p2": ...
I'm very new to Python, and I've made a small program/script that will allow me to stream specific files at a given time. My idea is that I have a .csv file for each day, with one row for each movie/tv show i want to watch and a cron job that checks every 30 minutes (at :00 and :30). If the job finds any row that matc...
I wrote a little script to automate upgrading Firefox to a new version under Debian, since I don't want to install it from unstable and the snap version has rendering issues. Any comments are welcome, is there anything I have missed or any potential problems? #!/bin/bash # firefox_upgrade - program to upgrade firefox ...
Here is my very first event dispatcher. I would like to get both, style and code review, as well as some ideas to improve this implementation (new features etc.) I tried to write code in C++17 style as much as possible. IEventDispatcher.h #pragma once #include <map> #include <functional> template<typename EventType> ...
Note this was the wrong version of the code. The updated version is here: Efficiently counting rooms from a floorplan (version 2) My apologies! Update Final version 3 with test harness here: Multithreaded testing for counting rooms from a floor plan solution I was inspired by Calculating the number of rooms in a 2D ...
This is version 2 of Efficiently counting rooms from a floorplan. I had accidentally pasted in the wrong version of the code. Update Final version (version 3) of the code with updated test harness is here: Multithreaded testing for counting rooms from a floor plan solution I was inspired by Calculating the number of ...
I have got some code that calculates the angle between all of the points in an array. It works, but it is quite slow. This is because it has complexity O(n^2). It has to loop through the array and apply the angle function to every combination of points. import math import random def angle(pos1,pos2): dx=pos2[0]-pos...