lichenran1234

PythonInputOutput

Apr 15th, 2021 (edited)
266
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.78 KB | None | 0 0
  1. # Get time in milli secs
  2. import time
  3. cur_time_milli_sec = int(time.time() * 1000)
  4.  
  5. # Read file
  6. with open("1.txt") as f:
  7.   for line in f.xreadlines():
  8.     print line.rstrip('\r\n')
  9.  
  10. # Write file ('a' for append, 'w' for write)
  11. with open("2.txt", 'a') as f:
  12.   f.write("123\n")
  13.  
  14. # Read from stdin (the input stream has to end with EOF)
  15. import sys
  16. for line in sys.stdin.xreadlines():
  17.   print line.rstrip('\r\n')
  18.  
  19. # Read from stdin (prompt the user for input)
  20. name = raw_input("type your name: ")
  21. print name, len(name)
  22.  
  23. # bash redirect file to stdin: python 1.py 0<1.txt
  24. # bash redirect stdout to file: python 1.py 0<1.txt 1>3.txt
  25.  
  26. # random numbers
  27. from random import seed
  28. from random import random
  29. from random import randint
  30.  
  31. seed(1)
  32.  
  33. # random float number between 0-1
  34. rand_float = random()
  35. print rand_float
  36.  
  37. # random int number between [0, 1] (inclusive)
  38. rand_int = randint(0, 1)
  39. print rand_int
  40.  
  41. # iterator (note that xrange is not a iterator)
  42. a = iter(range(5))
  43. print next(a, None) # get the next with a default value so we can check if there is not more values
  44. print next(a, None)
  45.  
  46. # Find the first index in an array where array[index] >= target
  47. a = [1,2,3,3,3,4,5,6,6,6]
  48.  
  49. def findIndex(array, target):
  50.     if not array:
  51.         return 0
  52.    
  53.     if array[0] >= target:
  54.         return 0
  55.        
  56.     if array[-1] < target:
  57.         return len(array)
  58.    
  59.     left = 0
  60.     right = len(array) - 1
  61.     while left < right:
  62.         mid = (left + right) / 2
  63.         if array[mid] >= target:
  64.             if (mid - 1) >= 0 and array[mid-1] < target:
  65.                 return mid
  66.             right = mid - 1
  67.         elif array[mid] < target:
  68.             left = mid + 1
  69.     return left
  70.  
  71. for i in range(8):
  72.     print "find " + str(i) + " = " + str(findIndex(a, i))
Add Comment
Please, Sign In to add comment