我正在尝试修改一段文字以应用以下翻译:
import UIKit
import MapKit
import CoreLocation
import DJISDK
import Foundation
class FlyToPointsViewController: DJIBaseViewController, DJIFlightControllerDelegate, DJIMissionManagerDelegate {
@IBOutlet weak var mapView: MKMapView!
var mission: DJIWaypointMission? = nil
var flightController: DJIFlightController?=nil
var missionCoordinates=[CLLocationCoordinate2D]()
var allSteps = [DJIWaypoint]()
var missionManager: DJIMissionManager?=nil
var currentState: DJIFlightControllerCurrentState?=nil
override func viewDidAppear(animated: Bool) {
let alertController = UIAlertController(title: "Hello Team", message:
"There are quite a few easter eggs hidden away in here. Hopefully you find them and have a good laugh. Sorry I couldn't make it to test, the mountains are calling. But I put alot of time into this so hopefully it works as expected. I didn't add a return to home functionality to make this a bit spicy for ya so make sure your last point is near you other wise you're gonna do a bit of walking... Cheers ", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
//initialize our aircraft
mapView.delegate=self
let aircraft: DJIAircraft? = self.fetchAircraft()
if aircraft != nil {
//makes the view controller watch for particular functions like the flight controller one below
aircraft!.delegate = self
aircraft!.flightController?.delegate = self
}
else{
print("aircraft not found")
}
self.missionManager=DJIMissionManager.sharedInstance()
self.missionManager?.delegate=self
//initialize core location to put mapp on our location
let manager = CLLocationManager()
if CLLocationManager.authorizationStatus() == .NotDetermined {
manager.requestAlwaysAuthorization()
}
//start uploading location into manager object so we can use .location method
if CLLocationManager.locationServicesEnabled() {
manager.startUpdatingLocation()
}
//let location = manager.location!.coordinate; //get ipads current location and turn it into a coordinated
let location = CLLocationCoordinate2DMake(40.0150, -105.2705)
let region = MKCoordinateRegionMakeWithDistance(location, 7000, 7000) //create a square region using center point and size of square
mapView.region = region //tells the mapview to center itself around this region
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillDisappear(animated: Bool) {
let aircraft: DJIAircraft? = self.fetchAircraft()
if aircraft != nil {
if aircraft!.flightController?.delegate === self {
aircraft!.flightController!.delegate = nil
}
}
}
@IBAction func revealRegionDetailsWithLongPressOnMap(sender: UILongPressGestureRecognizer) {
if sender.state != UIGestureRecognizerState.Began { return }
let touchLocation = sender.locationInView(mapView)
let locationCoordinate = mapView.convertPoint(touchLocation, toCoordinateFromView: mapView)
self.missionCoordinates.append(locationCoordinate)
print("Tapped at lat: \(locationCoordinate.latitude) long: \(locationCoordinate.longitude)")
let annotation = CustomMissionPressLocation(location: locationCoordinate)
mapView.addAnnotation(annotation)
}
//Mark: - Functions Called from Button Presses
@IBAction func clearCoordinates(sender: AnyObject) {
self.missionCoordinates=[]
mapView.removeAnnotations(mapView.annotations)
}
@IBAction func startMission(sender: AnyObject) {
if (!self.missionCoordinates.isEmpty){
print("start Mission Attempted")
self.mission = DJIWaypointMission()
self.mission!.autoFlightSpeed=10
self.mission!.maxFlightSpeed=15
self.mission!.exitMissionOnRCSignalLost=true
let waypoint = DJIWaypoint(coordinate: (self.currentState?.aircraftLocation)!)
waypoint.altitude=15
waypoint.speed=10
waypoint.heading=0
waypoint.actionRepeatTimes = 1
waypoint.actionTimeoutInSeconds = 60
waypoint.cornerRadiusInMeters = 5
waypoint.turnMode = DJIWaypointTurnMode.Clockwise
self.mission!.addWaypoint(waypoint)
for locations in self.missionCoordinates{
let waypoint = DJIWaypoint(coordinate: locations)
waypoint.altitude=15
waypoint.speed=10
waypoint.heading=0
waypoint.actionRepeatTimes = 1
waypoint.actionTimeoutInSeconds = 60
waypoint.cornerRadiusInMeters = 5
waypoint.turnMode = DJIWaypointTurnMode.Clockwise
self.mission!.addWaypoint(waypoint)
}
let waypointStep = DJIWaypointStep(waypointMission: self.mission!)
self.startWayPointMission()
}
else{
let alertController = UIAlertController(title: "Mission Error", message:
"you haven't added any waypoints ya dingus", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
}
//avoids a bunch of knuckleheads from sending the drone to china
func missionIsntTooFar()-> Bool{
let startLoc=self.currentState?.aircraftLocation
let locations = self.missionCoordinates
//let startLoc=locations[0]
for locs in locations{
let distance = MKMetersBetweenMapPoints(MKMapPointForCoordinate(startLoc!), MKMapPointForCoordinate(locs))
if distance > 4000{
return false
}
}
return true
}
func startWayPointMission() {
if self.missionIsntTooFar(){
self.missionManager?.prepareMission(self.mission!, withProgress: nil, withCompletion: {[weak self]
(error: NSError?) -> Void in
if error == nil {
print("uploaded")
print(String(self?.missionManager?.isMissionReadyToExecute))
self?.missionManager?.startMissionExecutionWithCompletion({[weak self]
(error: NSError?)->Void in
if error == nil{
print("mission started")
}
else{
print("error: \(error!)")
}
})
}
else {
self?.showAlertResult("mission upload failed \(error!)")
}
})
}
else{
mapView.removeAnnotations(mapView.annotations)
let alertController = UIAlertController(title: "Mission is too far", message:
"you're trying to fly the drone too far ya knucklehead", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
}
//Mark: - Flight Controller Delegate Methods
func flightController(fc: DJIFlightController, didUpdateSystemState state: DJIFlightControllerCurrentState) {
self.flightController=fc
self.currentState=state
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension FlyToPointsViewController: MKMapViewDelegate{
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
let annotationView = DroneAnnotationView(annotation: annotation, reuseIdentifier: "Attraction")
annotationView.canShowCallout = false //we're going to customize the callout
return annotationView
}
}
也就是说,每个before: abcdefghijqlmnopqrstuvwxyz
after: zyxwvutsrqponmlkjihgfedcba
变为a
;每个z
变为b
;每个y
变为c
;等等。
我的剧本:
x
不幸的是它不起作用。例如,如果我写:
我是菜鸟
回报应该是:
rznmlly
因为myInput = input("Entrer une chaine de caracteres:\n\n")
myInputSansEspace = myInput.replace(" ", "")
myInputAsciiInverse = myInputSansEspace.replace("a","z").replace("b","y").replace("c","x").replace("d","w").replace("e","v").replace("f","u").replace("g","t").replace("h","s").replace("i","r").replace("j","q").replace("k","p").replace("l","o").replace("m","n").replace("n","m").replace("o","l").replace("p","k").replace("q","j").replace("r","i").replace("s","h").replace("t","g").replace("u","f").replace("v","e").replace("w","d").replace("x","c").replace("y","b").replace("z","a")
print(myInputAsciiInverse)
被i
取代; r
a
; z
m
;等
我得到的结果是:
boonmai
答案 0 :(得分:9)
你的方法有副作用,所以不能做你想做的事 第一次更换:
'a...z'.replace('a', 'z') == 'z...z'
现在考虑最后一次替换:
'z...z'.replace('z', 'a') == 'a...a'
因此仅以字母表的一半结束。
您只需将所有replace
替换为reverse
或切片:
'abc..xyz'.reverse() == 'zyx..cba'
'abc..xyz'[::-1] == 'zyx..cba'
如果您尝试翻译作为密码的方式,那么您可以使用str.maketrans
和str.translate
,例如:
>>> alphabet = 'abcdefghijklmnopqrstuvxyz'
>>> trans = str.maketrans(alphabet, alphabet[::-1], ' ')
>>> noob = 'I am noob'
>>> noob.lower().translate(trans)
'rznmlly'
注意:alphabet
相当于string.ascii_lowercase
以上几乎相当于:
>>> import string
>>> trans_table = dict(zip(string.ascii_lowercase, string.ascii_lowercase[::-1]))
>>> ''.join(trans_table.get(c, c) for c in noob.lower() if c not in ' ')
'rznmlly'
答案 1 :(得分:1)
以下是完成替换的功能方法:
s = "I am noob"
import string
letters = string.ascii_lowercase
# construct a dictionary mapping from a letter to its dual opposite starting from the end
# of the alphabet table
rep_dict = dict(zip(letters, letters[::-1]))
# use the dictionary to replace the letters
''.join(map(rep_dict.get, s.replace(" ", "").lower()))
# 'rznmlly'
您的代码存在的问题是您正在执行replace('a', 'z')....replace('z', 'a')
,因此所有以前替换的字符都会被替换回来。
答案 2 :(得分:1)
您可以使用python的切片来反转字符串:
>>> my_string = "abcdefghijqlmnopqrstuvwxyz"
>>> my_reversed_string = my_string[::-1]
>>> my_reversed_string
'zyxwvutsrqponmlqjihgfedcba'
编辑:好的所以问题是如何使用反转字母表翻译字符串。有了这样的问题,我想到的第一个就是建立一个字典来进行翻译:
>>> alphabet = "abcdefghijklmnopqrstuvwxyz"
>>> reversed_alphabet = alphabet[::-1] # zyxwvutsrqponmlkjihgfedcba
>>> my_dict = dict(zip(alphabet, reversed_alphabet))
>>> my_str = "i am noob"
>>> translated_str = ''.join(my_dict[c] for c in my_str.replace(' ', ''))
>>> translated_sentence
'rznmlly'
答案 3 :(得分:1)
Python有一个名为.reverse()
的字符串函数,可以通过
var = "abcdefghijklmnopqrstuvwxyz"
var = var.reverse()
print var
> zyxwvutsrqponmlkjihgfedbca
答案 4 :(得分:0)
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 22 11:46:50 2020
@author: Tumbu John
An encryption program "REVERSE ALPHABET"
"""
包含值的字典(每个字母将转换为新格式)
code = {"a":"z", "b":"y", "c":"x" ,"d":"w" ,"e":"v", "f":"u", "g":"t", "h":"s", "i":"r","j":"q","k":"p","l":"o", "m":"n", "n":"m", "o":"l", "p":"k", "q":"j", "r":"i", "s":"h", "t":"g", "u":"f", "v":"e", "w":"d","x":"c", "y":"b", "z":"a"," ":" "}
plainText = input("Enter text to be encrypted: ")
plainText = plainText.lower() #Converts the input to lowecase letters for better management and error free program since python is case sensitive
encryptedText = ""
For循环检查输入的每个字符,将其转换为各自的值(加密文本)
for c in plainText:
添加此块是为了使非字母保留在消息中,以防止输入错误不在字典中
if c in "abcdefghijklmnopqrstuvwxyz ":#checks if each character of plainText exist in 26 letters of alphabet
encryptedText += code[c]
else: #if a character doesn't exist in the dictionary, do nothing to it
encryptedText+=c
打印加密的文本
print("This is the encrypted text: ",encryptedText)
输出
>>> enter text to be encrypted: abcdefghijklmnopqrstuvwxyz
>>> this is the encrypted text: zyxwvutsrqponmlkjihgfedbca
查看该程序的图片:
答案 5 :(得分:0)
# p[10:36] -> alphabet(lowercase)
# p[35:9:-1] -> reverse alphabet
# p[:10]+p[36:62]+p[62:] -> Remove uppercase, numbers and special characters
import string
p = string.printable
k = [(x,y) for x in p[10:36] for y in p[35:9:-1]][0::27]
def solution(x):
r = []
for i in x:
for k1,k2 in k:
if i in p[:10]+p[36:62]+p[62:]:
pass
elif i == k1:
r.append(k2)
print(''.join(r))
solution("yeah! i can't believe lance lost his job at the colony!!")
输出:
"bvzs! r xzm'g yvorvev ozmxv olhg srh qly zg gsv xlolmb!!"
答案 6 :(得分:0)
以下代码通过忽略大写和其他字符来反转小写字符:
def solution(x):
i=0
m=""
while(i<len(x)):
if(ord(x[i])<97 or ord(x[i])>122):
m=m+(m.join(x[i]))
else:
if(ord(x[i])<123):
m=m+(m.join(chr(((ord(x[i])+(2*(109-ord(x[i]))+1))))))
i=i+1
print(m)
如果您使用 solution("@Tsrh rh vmxibkg!vw g-.vcg")
运行此代码,那么您将获得:
@This is encrypt!ed t-.ext