Python递归函数缺少结果

时间:2015-08-19 18:52:32

标签: python recursion

来自Python recursively appending list function 尝试以递归方式获取与文件结构关联的权限列表。

我有这个功能:

def get_child_perms(self, folder, request, perm_list):
        # Folder contains other folders
        if folder.get_children():
            # For every sub-folder
            return [self.get_child_perms(subfolder, request, perm_list) for subfolder in folder.get_children()]
        return folder.has_read_permission(request)

返回除包含其他文件夹的文件夹以外的所有结果。

folder <- Missing (allowed)
    subfolder <- Missing (restricted)
        subsubfolder <- Get this (restricted)
            files

来自功能的输出将是 [真,假,假]

另一种情况是,A =允许,R =受限

folder  A
    subfolder   A
        subsubfolder    R
            files
        files
    subfolder   R
        files
    subfolder   A
        subsubfolder    A
            files
        files
    subfolder   A
        files
    files

输出将是 [真,TRUE,FALSE,FALSE,TRUE,TRUE,TRUE]

2 个答案:

答案 0 :(得分:3)

基本问题是,您只返回Where-Object,当文件夹没有任何子项时,当它有子项时,您不会在返回结果中包含using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace MergeResx { class Program { static void Main(string[] args) { var folder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory),"resx"); var x = MergeResxFiles(new [] { Path.Combine(folder,args[0]), Path.Combine(folder, args[1])}); File.WriteAllText(Path.Combine(folder, "merged.xml"), x.ToString()); Console.WriteLine("--done--"); Console.ReadLine(); } static XDocument MergeResxFiles(string[] files) { var allResources = from f in files let doc = XDocument.Load(f) from e in doc.Root.Elements("data") select Resource.Parse(e, f); var elements = new List<XElement>(); var enumerable = allResources.GroupBy(r => r.Name).OrderBy(x=>x.Key).ToList(); foreach (var g in enumerable) { elements.AddRange(MergeResources(g.Key, g)); } Console.WriteLine("Terms: " + enumerable.Count()); var output = new XDocument(new XElement("root", elements)); return output; } private static IEnumerable<XElement> MergeResources(string name, IEnumerable<Resource> resources) { var grouped = resources.GroupBy(r => r.Value).ToList(); if (grouped.Count == 1) { yield return grouped[0].First().Xml; } else { Console.WriteLine($"Duplicate entries for {name}"); foreach (var g in grouped) { var comments = g.Select(r => new XComment($"Source: {r.FileName}")); yield return new XElement( "data", comments, new XAttribute("name", name), new XElement("value", g.Key)); } } } class Resource { public string Name { get; } public string Value { get; } public string Comment { get; } public string FileName { get; } public XElement Xml { get; } public Resource(string name, string value, string fileName,string comment, XElement xml) { Name = name; Value = value; Comment = comment; FileName = fileName; Xml = xml; } public static Resource Parse(XElement element, string fileName) { string name = element.Attribute("name").Value; string value = element.Element("value").Value; string comment = element.Element("comment")?.Value; return new Resource(name, value, fileName, comment, element); } } } ,这很可能是导致你发出问题。你需要做 -

folder permission

这应该导致(未经测试) -

folder.has_read_permission(request)

答案 1 :(得分:0)

为什么不 os.walk

  

当topdown为True时,调用者可以就地修改dirnames列表   (可能使用del或slice赋值),而walk()只会递归   进入名称保留在dirnames中的子目录;这可以   用来修剪搜索,强加一个特定的访问顺序,甚至   通知walk()有关调用者创建或重命名的目录   在它再次恢复步行()之前。自上而下修改dirnames   假是无效的,因为在自下而上模式下的目录   dirnames是在生成dirpath本身之前生成的。

例如,您可以构建仅生成非受限目录的生成器(惰性列表)

import System.IO
import System.Environment
import Control.Monad
import Data.Bits
import Data.Word
import Data.Maybe
import Data.List hiding (maximumBy)
import Data.Char
import Data.Ord
import Data.Foldable hiding (sum)


hexChars = "0123456789ABCDEF"

hexToBytes :: String -> Maybe [Word8]
{- Converts a hex string into a byte array -}

hexToBytes hexes = hexToBytes' (map toUpper hexes)
hexToBytes' (char1 : char2 : xs) = do
    tail <- hexToBytes' xs
    byte1 <- char1 `elemIndex` hexChars
    byte2 <- char2 `elemIndex` hexChars
    return ((fromIntegral(byte1*16 + byte2) :: Word8) : tail)
hexToBytes' [_] = Nothing
hexToBytes' [] = Just []

maxBy :: Ord b => Foldable f => (a -> b) -> f a -> a
maxBy = maximumBy . comparing

bytesToString :: Integral i => Monad m => m i -> m Char
bytesToString = liftM (chr . fromIntegral)  

isLowercase x = (x >= 'a') && (x <= 'z')

asciiCheck :: Word8 -> Int
asciiCheck x = if (isLowercase . chr . fromIntegral) x then 1 else 0

score = (sum . map asciiCheck)

readLines :: Handle -> IO [String]
readLines handle = do
    eof <- hIsEOF handle
    if eof then
        return []
    else liftM2 (:) (hGetLine handle) (readLines handle)

decode key = map (xor key)

keys = [minBound ..] :: [Word8]

massDecode inputs =
    maxBy score (liftM2 decode keys inputs)

main = do
    hSetEncoding stdout latin1
    args <- getArgs
    handle <- case args of
        [] -> return stdin
        (x:xs) -> openFile x ReadMode
    lines <- readLines handle
    putStrLn $ bytesToString $ massDecode $ catMaybes $ map hexToBytes lines