blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
7cf7a34d09d0a5889a577850391ebf14d486d535
ImwaterP/learn-Python
/Python note/元组.py
323
4.1875
4
""" 元组: 特点:元组内元素无法修改,以圆括号括起来 """ location = (1,2,3) print(location) location[0] = 10 print(location) #重新创建新元组,覆盖旧元组即可 location = (10, 2, 3) print(location) #遍历元组内所有元素 for i in location: print(i)
53389f820b15d0207c45673b07b85c5dd6296c55
Atomator/Q-Learning-Snake
/snakeGame.py
6,310
3.75
4
import math import random import pygame class snakeOb(object): # Sets inital perameters def __init__(self, color, pos, snakeSize, width): self.color = color self.width = width self.snakeSize = snakeSize self.dirnx = 0 self.dirny = 0 self.cube = cube() s...
4662f17d0912611f4d02a13f23c75bd062fb079c
maycamss14/pythonExercicios
/exercicio3.py
155
3.6875
4
temperaturacelsius = float(input('Digite a temperatura em celsius: ')) passo1= temperaturacelsius/5 passo2= passo1*9 passo3= passo2+32 print (passo3)
646d6816429c5dac188fd8693ffb4406aa57e752
aamartinez25/effective-system
/cpu.py
1,482
4.1875
4
# #Author: Adrian Martinez #Description: takes a few inputs on CPU specs and organizes them accordingly # # cpu_ghz = float(input('Enter CPU gigahertz:\n')) #input for CPU specs cpu_core = int(input('Enter CPU core count:\n')) cpu_hyper = input('Enter CPU hyperthreading (True or False):\n') print() if cpu_...
9a576e7335c48f855798d6c1e42d8be4da138fd5
niksanand1717/TCS-434
/03 feb/solution_2.py
499
4.15625
4
num1 = eval(input("Enter the first number: ")) num2 = eval(input("Enter the second number: ")) count1, count2 = 0, 0 print("\n\nNumbers divisible by both 3 and 5") for num in range(num1, num2+1): if num%3 == 0 and num%5 == 0: print(num) count1+= 1 print("Total numbers of numbers:",count1) print(...
d92f391fb53b5308ce1e4625f3ed756d1a5c0f82
niksanand1717/TCS-434
/17 feb/word_counter.py
179
3.859375
4
counts = dict() line = input("Enter a string: ") # print("Line Entered: ", line) for word in line:#.lower(): counts[word] = counts.get(word, 0) + 1 print('Counts', counts)
360b2dba16714f2e2fee62d85537d49faefab8c1
niksanand1717/TCS-434
/28 april/fourth.py
292
4.34375
4
"""Input a string and return all the words starting with vowels""" import re pattern = '^[aeiou]' str1 = input("enter string: ") print("Following are the words in entered string starting with vowel: ", end=' ') [print(word, end=' ') for word in str1.split(" ") if re.match(pattern, word)]
e3c9452a5563afe71101af97ced7f3834d042b83
niksanand1717/TCS-434
/28 april/first.py
276
4.5
4
"""Print all the words from a string having length of 3""" import re pattern = '(...)$' input_data = input("input string: ") print("Following are the words which have length 3: ") for words in input_data.split(" "): if re.match(pattern, words): print(words, end=" ")
31f30e06a236c526003bb38be8e86a82d6d49d70
niksanand1717/TCS-434
/30 april/fourth.py
426
4.0625
4
"""Create a python file and count number of this, that, is present in that file""" file = "file.txt" fh = open(file, 'r') That = 0 This = 0 Is = 0 for line in fh: for word in line.split(): if word.lower() == 'this': This += 1 if word.lower() == 'that': That += 1 if word.lower() == 'is': ...
22889ffb49d5a099d6cfbb1983c1baee576e4728
cbraz/AoC2019
/password.py
1,781
4.09375
4
#!/usr/bin/env python3 input_init = 367479 input_end = 893698 # Rule 3 - at least two adjacent numbers are the same def rule3(password): previous_char = None for char in password: if char == previous_char: return True previous_char = char return False # Rule 3 (day 2) - has ...
54c0a19b7a129b029706eab9707bee9557ba08ad
WongMatthew/MidnightRidersBasicTextGame
/Midnight Riders Text game.py
5,971
3.921875
4
# Name: Midnight Riders # Author: Matt Wong # Date: Feb 20, 2019 # Inspired by a text only game import time import math import random # Welcome print(f"""-------Welcome To Midnight Rider!------- We've stolen a car. We need to get to the home base. The car is special. It has some sort of mystical powe...
6688eabf3691270c3ed0cfa26dc7c7c25b6c3434
lchristiani44/Introduction-to-Computer-Science
/Week 6 - Python/lecture6/mario.py
151
3.6875
4
import cs50 for i in range(4): print("?", end="") # the second arg is optional ("\n" being the default option for Python) print() print("?" * 4)
904d4c5fdb828290fa29b57bac2c728cecc1d899
farmani60/coding_practice
/others/two_sum.py
2,951
3.71875
4
# Given an array of integers, return indices of the two numbers # such that they add up to a specific target. # You may assume that each input would have exactly one solution, # and you may not use the same element twice. # Example: # Given nums = [2, 7, 11, 15], target = 9, # Because nums[0] + nums[1] = 2 + 7 = 9, # r...
5819081685ea8fb0d3e8fad1cc9f83e124d05ea0
farmani60/coding_practice
/topic10_bigO/O_1.py
1,136
3.828125
4
""" O(1) describes algorithms that take the same amount of time to compute regardless of the input size. For instance, if a function takes the identical time to process ten elements as well as 1 million items, then we say that it has a constant growth rate or O(1). Let’s see some cases. Examples of constant runtime a...
63a9642ac4dec73be63e31928e325dcad20a880f
farmani60/coding_practice
/topic2_lists/InsertNodeAtTail.py
694
3.9375
4
class Node: def __init__(self, data): self.data = data self.nextnode = None def insertNodeAtEnd(headnode, data): NewNode = Node(data) if headnode.nextnode is None: headnode.nextnode = NewNode return headnode laste = headnode while laste.nextnode: laste = last...
7704e1bf7dd9fe2c34959f00ad118c39a7d4ec32
farmani60/coding_practice
/topic4_hashmaps/try.py
944
3.703125
4
def isPrime(number): if all([number % i != 0 for i in range(2, number)]): return True else: return False def getDigits(number): digits = [] while number != 0: digits.append(number % 10) number = number // 10 return digits[::-1] def colourful(number): digits = g...
988e6c74f312fb266703497df9ad016e3cde9c21
farmani60/coding_practice
/topic7_graphs/BFS.py
879
3.78125
4
""" Breadth First Search Algorithm: Breadth-first search (BFS) is an algorithm for traversing or searching tree or graph data structures. It starts at the tree root (or some arbitrary node of a graph, sometimes referred to as a 'search key', and explores all of the neighbor nodes at the present depth prior to moving o...
04680654bc17937b0d8f2939891f622784a66a56
farmani60/coding_practice
/topic5_sorting/InsertionSortPart1.py
340
4.15625
4
# Description: # https://www.hackerrank.com/challenges/insertionsort1/problem?h_r=internal-search def insertionSort1(arr): for i in range(len(arr)): if arr[i] > arr[-1]: temp = arr[i] arr[i] = arr[-1] arr[-1] = temp input_list = [2, 4, 6, 8, 3] insertionSort1(input_list...
75c5efae3cd6515a6964e4236775e57cf61994ba
farmani60/coding_practice
/topic6_trees/SwapNodes.py
4,006
3.875
4
""" Description: https://www.hackerrank.com/challenges/swap-nodes/problem?h_r=internal-search <<<<<<< HEAD A binary tree is a tree which is characterized by any one of the following properties: * It can be an empty (null). * It contains a root node and two subtrees, left subtree and right subtree. These subtrees ar...
d448f3cebeff50b9eb66a2d1749d703c7a4f635e
farmani60/coding_practice
/topic10_bigO/log_n.py
1,147
4.15625
4
""" Logarithmic time complexities usually apply to algorithms that divide problems in half every time. If we implement (Algorithm A) going through all the elements in an array, it will take a running time of O(n). We can try using the fact that the collection is already sorted. Later, we can divide in half as we look ...
75cdb3a8b212efcc7fefce3ae68702162e8d4ab8
nomatterhowyoutry/GeekPython
/HT_6/HomeTask6_2.py
2,226
3.6875
4
# Напишіть програму в стилі ООП, що задовольняє наступним умовам: # у програмі повинні бути два класи та два об'єкта, що належать різним класам; # один об'єкт за допомогою методу свого класу повинен так чи інакше змінювати дані іншого об'єкта class Class1(object): """docstring for Class1""" def __init__(sel...
688a5985d9687cdd48588d31cf1c6b7f7eaf66d2
nomatterhowyoutry/GeekPython
/HT_1/Task4.py
311
3.84375
4
# 4. Write a script to concatenate N strings. import random, string def randomString(length): letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range(length)) N = int(input()) tuple = (randomString(random.randint(0,20)) for i in range(0, N)) S = ''.join(tuple) print(S)
0f8fe20a3d49ce95591f9d9c46dd57d17e007866
nomatterhowyoutry/GeekPython
/HT_1/Task6.py
263
4.28125
4
# 6. Write a script to check whether a specified value is contained in a group of values. # Test Data : # 3 -> [1, 5, 8, 3] : True # -1 -> (1, 5, 8, 3) : False list = [1, 5, 8, 3] tuple = tuple(list) print(3 in list) print(-1 in tuple)
2d7a436200b726a0c7dcddfa547b49b48a318569
snowmancode/soft3
/thereturn2.py
300
3.609375
4
first_name = "Kevin" print(first_name) cartoon_name = "Coyote" print(cartoon_name) if cartoon_name == "Coyote": print("Too funny") if cartoon_name == "Road Runner": print("Really!?!") else: print("Interesting") score = 0 while score < 5: print("Good..Good..Good...Keep firing")
96819f1bdd9469451af6089d77a9c6a979709856
vanTrant/py4e
/ex3_try_exec/script.py
361
4.1875
4
# hours = input('Enter Hours: ') # rate = input('Enter Rate: ') try: hours = float(input('Enter Hours: ')) rate = float(input('Enter Rate: ')) except: print('Please enter a valid number') quit() if hours > 40: overtime_pay = (hours - 40) * (rate * 1.5) pay = 40 * rate + overtime_pay else: ...
daef5783f6c2770a24bc3996bfe73b4596fda477
koushi06/Python-Learing
/factorial.py
99
3.734375
4
def fact(x): f=1 for i in range(1,x+1): f=f*i return f x=5 f = fact(x) print(f)
a2a045b5c71ac664f881912ae17e3e9e099777aa
niuyaning/PythonProctice
/06/18/test11.py
158
3.90625
4
list = ['a','b','c'] list1 = [] for i in list: print(i) list1.append(i) print(list1) for i in list1: print("所有三明治已制作完成")
33e6ff71411f89c06e8f61faaa2d17693f468a34
niuyaning/PythonProctice
/06/18/test8.py
209
4.09375
4
# 在列表之间移动元素 list = ['apple','banana','orange','pear'] list1 = [] while list: res = list.pop() print({res.title()}) list1.append(res) for i in list1: print(i.title())
e50e451700d776a531728c19bacd17cd61ef0269
niuyaning/PythonProctice
/06/15/opration_list4.py
76
3.59375
4
list = ['pizza1','pizza2','pizza3'] print(list) list1 = list[:] print(list1)
636b8d27e85d033cf8c969d73ec24e0e1de98404
niuyaning/PythonProctice
/06/17/diciionary8.py
263
3.78125
4
favorite_fruit = { 'michael':'苹果', 'summer':'香蕉', 'andrew':'橙子' } for key,value in favorite_fruit.items(): print(f"{key.title()} 最喜欢吃的水果是 {value.title()}") for result in favorite_fruit: print(result.title())
5c7aea4161144a139c4707f538f9abaed5e50fec
niuyaning/PythonProctice
/06/18/test2.py
275
3.78125
4
# mes = int(input("请问有多少人用餐?")) # if mes > 8: # print("已没有空桌") # else: # print("请稍等") res = int(input("请输入一个数字:")) if res % 10 == 0: print("该数是10的整数倍") else: print("该数不是10的整数倍")
1d0e8665d2f572c3392009c5a86356b4555f2d60
niuyaning/PythonProctice
/06/19/test9.py
183
3.65625
4
#传递列表 def greet_users(names): for name in names: msg = f"Hello,{name.title()}" print(msg) usernames = ['summer','michael','andrew'] greet_users(usernames)
5ef5955c4b7c1b014b7f476b10f04a4552a2d5c8
rdmunden/challenges
/set_1/11.py
1,097
3.90625
4
""" Find the largest circle that does not contain any duplicate tags """ from math import hypot def solution(S, X, Y): radii = list(map(hypot, X, Y)) tags = list(zip(radii, S)) tags.sort() print (tags) found_tags = [] found_circles = [] for i in tags: if i[1] in found_tags: ...
0ffe1bce7705a553801e31ebb398ed9febd0f2fe
vandana002/Pos
/fcfs.py
426
3.5625
4
def fcfs(arr,head): previous=head num=0 print("Seek sequence is") for i in range(len(arr)): if(arr[i]>previous): num+=arr[i]-previous else: num+=previous-arr[i] print(arr[i]) previous=arr[i] return num arr=list(map(int,input().split()...
6bd36125c0426b205c6da63124af98d8c5e49fbd
OskarAa/klases_biblioteka
/biblioteka.py
1,719
3.96875
4
Klases nosaukums class Robots: """Klase reprezentē robotu ar specifisku vārdu.""" # Klases konstruktors. Ar šo metodi tiek inicializēts objekts. def __init__(self, vards): """Datu inicializācija.""" # Īpašības definēšana self.vards = vards print("(Inicializējam {})".format(self.vards)) # Metode, kas izvada tekstu def i...
b55418c33f961f83b0d79668e7eed31260190ea8
janFrancoo/TensorFlow-Tutorials
/tf_ex_7_knn.py
1,701
3.53125
4
import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data # Import data data = input_data.read_data_sets('/MNIST_data', one_hot=True) # Split data to train and test x_train, y_train = data.train.next_batch(5000) x_test, y_test = data.test.nex...
728512cea28c1ad73185958e02e6da3ea78e2e12
Tinkotsu/lemin
/Lem-in/visualize/parser.py
1,471
3.5
4
from room import * def add_room(room, lem): name = room[0] x = int(room[1]) * 10 + 640 y = int(room[2]) * 20 + 360 lem.rooms[name] = Room(x, y) def add_start(room, lem): name = room[0] add_room(room, lem) lem.start = lem.rooms[name] def add_end(room, lem): name = room[0] add_room(...
d5b0514e7c3e53f7f1bf6ec53717c79f81325591
yevgenybulochnik/lp3thw
/ex03/drill1.py
859
4.375
4
# Simple print statement that prints a string print("I will count my chickens:") # Prints a string then divides 30 by 6 then adds 25 print("Hens", 25 + 30 / 6) # Prints a string then gives you the remainder of 75/3 or 3 and subtracts from 100 print("Roosters", 100 - 25 * 3 % 4) print("Now I will count the eggs:") # ...
8905a8a1c3bd892fef8604ff4e1c8741c730654a
PaulSweeney89/squareroot
/sqrt_test.py
830
4.3125
4
# defining a fuction to calculate the square root of a positive real number # using Newton's method (ALTERNATIVE) while True: A = float(input("Please input positive value ")) if A > 0: break else: ...
af5740d78c30230901171f299561a05e5664ebda
SauravKanchan/workshop
/classes.py
532
3.796875
4
class Person(): def __init__(self,first_name, last_name): print("Hel lo",first_name, last_name) self.first_name = first_name self.last_name = last_name def say_hi(self): print("Hi",self.first_name) def set_name(self,fn,ln): self.first_name = fn self.last_nam...
2cd335681d15f490a48ac2cd85d605822354996f
asaf0813/hustar_python
/4일차과제/ex4.py
674
3.5625
4
def average(x, y): return (x * 0.4 + y * 0.6) def grade_avg(x): if x >= 90: return 'A' elif x >= 80: return 'B' elif x >= 70: return 'C' elif x >= 60: return 'D' else: return 'F' fr = open("score.txt", "r") fw = open("report.txt", "w") d = {} avg = 0 ...
a657aa0370e4af40f199d85a6d2ba1513b270bed
widelec9/codewars
/kata/python/6kyu/replace_with_alphabet_position.py
345
3.921875
4
import re def replace(match): char = match.group(0) if char.islower(): return str(ord(char) - ord('a') + 1) + ' ' elif char.isupper(): return str(ord(char) - ord('A') + 1) + ' ' else: return '' def alphabet_position(text): return re.compile("[a-z\d\s\.\'-]", re.IGNORECASE...
4b33c4b3fee0e230ad67fd0e7a7f0b5d37fe6439
widelec9/codewars
/kata/python/6kyu/nut_farm.py
434
3.53125
4
def shake_tree(tree): nuts = [1 if c == 'o' else 0 for c in tree.pop(0)] while len(tree) > 0: for i, c in enumerate(tree[0]): if nuts[i] > 0 and c in ['\\', '/', '_']: if c == '\\' and i < len(nuts) - 1: nuts[i+1] += nuts[i] elif c == '/' a...
97e83ea230fc1da1042cbc6e6c47d1b921b1e507
widelec9/codewars
/kata/python/6kyu/tribonacci_sequence.py
133
3.734375
4
def tribonacci(signature, n): tr = signature while len(tr) < n: tr.append(tr[-3] + tr[-2] + tr[-1]) return tr[:n]
2b4b74bafe511dff48b0d78e2babb42c9fa53ecb
widelec9/codewars
/kata/python/5kyu/resistor_color_codes_part2.py
343
3.578125
4
def encode_resistor_colors(r): code = ['black', 'brown', 'red', 'orange', 'yellow', 'green', 'blue', 'violet', 'gray', 'white'] r = float(r[:-6]) * 1e6 if 'M' in r else float(r[:-6]) * 1e3 if 'k' in r else float(r[:-5]) return '{} {} {} {}'.format(code[int(str(r)[0])], code[int(str(r)[1])], code[str(r)[2:-2...
027057d1206747093955628b56bd3a0ae894b4d0
widelec9/codewars
/kata/python/5kyu/80s_kids_rock_em_sock_em_robots.py
596
3.734375
4
def fight(robot_1, robot_2, tactics): robots = [robot_1, robot_2] if robot_1['speed'] >= robot_2['speed'] else [robot_2, robot_1] turn = 0 while robot_1['health'] > 0 and robot_2['health'] > 0 and (robot_1['tactics'] or robot_2['tactics']): if robots[turn]['tactics']: robots[turn ^ 1]['h...
5269ccd2224888ce1fd43698da15cbbb9b2f2496
widelec9/codewars
/kata/python/5kyu/simple_fraction_to_mixed_number_converter.py
644
3.625
4
def gcd(a, b): if not b: return a return gcd(b, a % b) def mixed_fraction(s): num, den = int(s.split('/')[0]), int(s.split('/')[1]) if not den: raise ZeroDivisionError if not num: return '0' num_sign, den_sign = [-1, 1][num > 0], [-1, 1][den > 0] num, den = abs(num)...
d0a9278c67f74a01f00036044c1ff32ef3bc082b
widelec9/codewars
/kata/python/6kyu/numbers_expanded_form.py
271
3.59375
4
def expanded_form(num): num_arr = [] div = 10 while num > 0: rem = num % div num_arr += [int(rem)] num -= int(div * (rem/div)) div *= 10 return ''.join([str(n) + ' + ' for n in sorted(num_arr, reverse=True) if n != 0])[:-3]
289eb4b8175ae2b8b0d8524d2555ef26e4f62b71
esterified/Python-OOP
/excercise-4/main.py
2,488
3.640625
4
class Time: def __init__(self,h,m,s): self._h = h self._m = m self._s = h #Read-only field accessors @property def hours(self): return self._h @property def minutes(self): return self._m @property def seconds(self): return self._s ...
0ad794722abfb826b414f7d7eeb51f6b59293c5f
ljsauer/DS-From-Scratch
/Notes/Chapter 4.py
1,188
4.375
4
"""Linear Algebra: the branch of math that deals with vector spaces """ # # Vectors - objects that can be added together to form new vectors, # and that can be multiplied by scalars; points in some # finite-dimensional space from typing import List Vector = List[float] height_weight_age = [70, ...
742df2bb8c6083e635da7bf4f09f85ddbec6bcae
xiaoqibao-growing/Algorithm
/Algorithm/String/longest_substring_without_repeating_characters.py
950
4.0625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2017-10-20 15:34:18 # @Author : xuejun (xuemyjun@gmail.com) """ Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answer is "b", w...
9d1d0a1cef60d029dc37f7d86f60d17830a197b2
xiaoqibao-growing/Algorithm
/Algorithm/count_and_say.py
2,093
3.9375
4
# coding=utf-8 """ 问题描述:The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 111221, ... 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n, generate the nth sequence. ...
087d450d77a4d2b8165a9a522528d8c1afc6e8e2
xiaoqibao-growing/Algorithm
/Algorithm/Arrays/Max_Consecutive_Ones.py
1,152
3.875
4
# coding=utf-8 ''' 问题描述:Given a binary array, find the maximum number of consecutive 1s in this array. Example 1: Input: [1,1,0,1,1,1] Output: 3 Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. Note: The input array will only contain 0 and 1...
65330ec4e470e6412beba1d80bcc907850fcabdb
erfanz/Applied-Artificial-Intelligence
/Classification/LogisticRegressionClassifier.py
3,311
3.875
4
from Classifier import * import numpy as np import math from operator import add class LogisticRegressionClassifier(Classifier): def learn(self, X, y): """ Performs an iterative gradient ascent on the weight values. Args: X: A list of feature arrays where each feature ...
6b997548a37e7a761a789a4b44df67cfa69651d8
blainekuhn/Python
/Reverse_text.py
255
4.15625
4
def reverse(text): word = [text] new_word = "" count = len(text) - 1 for letter in text: word.insert(0, letter) for a in range(len(word) - 1): new_word = new_word + word[a] return new_word print reverse("This is my text to reverse")
5c132cb68d833cf2dc372ccc838cdb667ed60d34
choidoyeong/BOJ_Algorithm
/10820.py
417
3.75
4
from sys import stdin strings = stdin.readlines() for string in strings: big = 0 small = 0 num = 0 space = 0 for n in string: if n == '\n': continue elif n == ' ': space += 1 elif n.isdigit(): num += 1 elif n == n.lower(): ...
06369ace24819c25fc59d3d2d4da3520168795a0
salimfadhley/toytable
/src/toytable_tests/test_column.py
1,363
3.796875
4
import array import unittest from toytable.columns import Column, ArrayColumn class TestColumn(unittest.TestCase): def test_column(self): """A column can be constructed with no data.""" c = Column('foo') self.assertEqual(list(c), []) def test_column_data(self): """A column ca...
3d0f5b49b7da2acc8a2ba864170d794aba5b726d
yjshiki/leetcode
/code/python/divide.py
1,181
3.5
4
class Solution: def divide(self, dividend: int, divisor: int) -> int: if dividend > 0 and divisor < 0: flag = -1 divisor = -divisor elif dividend < 0 and divisor < 0: flag = 1 dividend = -dividend divisor = -divisor elif div...
0c58c833070f70135c6375d7635c86ec3ad8942b
yjshiki/leetcode
/code/python/simplifyPath.py
552
3.71875
4
class Solution: def simplifyPath(self, path: str) -> str: if(len(path) == 0): return "" lst = path.split("/") res = [] for i in range(len(lst)): if(lst[i] == ".." and res != []): res.pop(-1) else: if('.' != lst[i]) ...
494d979b41757904cbcc0e9f10a6adfb0d5132f2
Gopi3998/UPPERCASE-AND-LOWERCASE
/Uppercase and Lowercase...py
527
4.34375
4
#!/usr/bin/env python # coding: utf-8 # In[1]: print('Starting the program for count the upper and lower case'.center(80,'*')) sample = input('enter string: ') uppercase = 0 lowercase = 0 for ch in sample: if str .isupper(ch): uppercase+=1 elif str.islower(ch): lowercase+=1 print('No of upper...
550c0ef610a75045566532e91687569f3e7d6e49
aashay01/pythonprogramminglb01
/aashaybhoyar01.py
287
3.703125
4
#aashay-bhoyar #gr no.-11810789 #roll no-04(M div.) #factorial of a no. num=int(input()) total=1 if num<0: print("invalid") elif num==0: print("factorial is 1") else: while num>0: total=num*total num=num-1 print("factorial is total",total)
6e9034990271d7ed4549663f9d537dd7ac8f6a86
Veletronic/Farmville
/Sheep_class.py
1,217
4.125
4
from Animal import * class Sheep(Animal): #Cow inherits from Animal """A sheep""" #Constructor def __init__(self): #Call the parent class constructor with default value #Growth rate =1; food requirement = 3; water requirement = 3 super().__init__(1,3,3) self._type...
aba62e446f468bd67757e96536aeeeb91846f53d
aLinSir/Leetcode
/easy/204.计数质数.py
404
3.9375
4
#!/usr/bin/python  # -*- coding: utf-8 -*- def countPrimes(n: int) -> int: if n < 2: return 0 isPrime = [1] * n isPrime[:2] = [0, 0] for i in range(2, int(n ** 0.5) + 1): if isPrime[i]: tmp = isPrime[i*i: n: i] isPrime[i * i: n: i] = [0] * len(tm...
b8af8b4d9eacea979b1216116f0f0127418bbe1c
aLinSir/Leetcode
/easy/581.最短无序连续子数组.py
543
3.9375
4
#!/usr/bin/python  # -*- coding: utf-8 -*- from typing import List def findUnsortedSubarray(nums: List[int]) -> int: sn = sorted(nums, reverse=False) left, right = 0, 0 con_l, con_r = False, False for i in range(len(nums)): if nums[i] != sn[i] and not con_l: left = i ...
2d189cb3c4d0a4853ce2a8281029863d6d954fb5
aLinSir/Leetcode
/easy/434.字符串中的单词数.py
184
4.0625
4
#!/usr/bin/python  # -*- coding: utf-8 -*- def countSegments(s: str) -> int: return len(s.split()) x = "Hello, my name is John" y = countSegments(x) print(y)
14025dd27c8f83cf0fed8b4cfea0c76badea0319
sarahovey/AnalysisOfAlgos
/hw1/mergesort.py
1,995
4.15625
4
#Sort #Merge Sort def merge_sort(numbers): #Divide the list into halves recursively if len(numbers) > 1: #get midpoint of list mid = len(numbers)/2 left = numbers[:mid] right = numbers[mid:] merge_sort(left) merge_sort(right) #index varia...
945f1a6fcb14d16dcbc3ec2dce5680db066110c1
StormComingMove/Coding
/Tarakesh/star0.py
305
3.515625
4
''' n = 4 (input) * ** *** **** ''' x = int(input()) for line in range(1, x+1): # line -> traverse from 1 to x for star in range(0, line): # star ->traverse from 0 to line-1, because line needs line no. of stars print("*", end ='') print() # after each line we need eol(end of line)
6631696a4d7a0d0b746a9e8029ae7b8c96fc4cec
MaxFritzhand/i101
/w6lab1.py
2,608
3.890625
4
#Tasks: # # 1.) Turn your compliment generator into a random sentece generator # a.) Change your starting sentence (to your choice). In addition to have a place # for an adjective to be inserted, make a place for a noun. # b.) Create a list of nouns. # c.) Add another if sta...
3b2412be99e06d8e6602823083f048e56e6f2424
iaraota/PasswordGenerator
/password_generator.py
2,245
3.625
4
import string import random import argparse import sys def password_generator(length=20, lowercase=True, uppercase=True, numbers=True, symbols=True, punctuation=False): """Strong Password Generator. Parameters ---------- length : int, optional Password length. Default is 20. lowercase : b...
2ad2891489db9ee7ddfd36acf02fbf71eac598bf
codeaudit/tutorial
/exercises/exercise01.py
1,863
4.125
4
# The goal of this exercise is to show how to run simple tasks in parallel. # # EXERCISE: This script is too slow, and the computation is embarrassingly # parallel. Use Ray to execute the functions in parallel to speed it up. # # NOTE: This exercise should work even if you have only one core on your # machine because t...
f3ea978bdffa35807b1289428428cc665b34aa71
serhansezgin/PythonStudies
/oop2_yb2advancedenemytrials2.py
2,816
3.5
4
import random class Oyun: def __init__(self,isim="Bas Komutan",can=100,mermi=100): self.isim=isim self.can=can self.mermi=mermi def atak(self): print(self.isim + " Ataturk konusuyor: Ordular ilk hedefiniz Akdeniz ileri!!!") harcanan_mermi=random.randrange(...
eb0fbbe83d7a46e6935b706ebf1e7720cd5f8d7c
prateekmaj21/Python-Programs
/3. Numpy Linear Algebra/1. Basics.py
559
3.890625
4
# Numpy Linear Algebra 1 import numpy as np A = np.array([[7, 1, 1, 8], [4, -2, 5, -5], [2, 8, 4, -4], [3, 6,-1, 7] ]) print(" Array A= ") print(A) # Rank of the matrix print("Rank of matrix A:", np.linalg.matrix_rank(A)) # Shape of matrix print("Shape o...
a7c345eec7c0eb26aee351a324fc524d3ff149a1
nodirt/edu
/algo/ordering/order_statistic.py
2,418
3.625
4
"""Find i-th smallest element in the array Complexity: Time: O(n^2). Average: O(n) Space: O(n). Average: O(log(n)) Description: Wikipedia: http://en.wikipedia.org/wiki/Order_statistic Cormen [1]: section 9.2, page 216 History: Author: Hoare (1961) Hoare is author of quicksort """ import rando...
2d03cf3383718e1d476fcf95eca005899a1271f5
nodirt/edu
/algo/ordering/heapsort.py
1,487
4.03125
4
import test def heapsort(nums): """Heapsort Properties: Unstable Time: O(n * log(n)) Space: O(1) Description: Wikipedia: http://en.wikipedia.org/wiki/Heapsort Cormen [1]: section 6.4, page 159 Sedgewick [2]: section 2.4, page 323 History: Autho...
9ae34fa88403e302c6c8f714ab7128077975cfa8
nodirt/edu
/algo/ordering/insertion_sort.py
746
3.953125
4
import test def insertion_sort(nums): """Insertion sort. Suitable for small arrays or nearly sorted arrays. Properties: Stable Time: O(n^2) Space: O(1) Adaptive: O(n) time when nearly sorted Very low overhead Description: Wikipedia: http://en.wikipedia.org/...
f7665071ade5a70b81e1eb2f646ccb17c2122115
Abhishek-kr7/Basic-Python-Programming
/11_Lambda_Map_Reduce_Filter_in_python.py
7,441
4.40625
4
#============================================# # Lambda/Map/Filter/Reduce # #============================================# #============================================# # Lambda # #============================================# #Lambda Functions are also known as a...
cf3480dca530bcedcb764f2cb0655914d004a409
Abhishek-kr7/Basic-Python-Programming
/09_Functions_in_python.py
1,759
4.375
4
def hello(): """This function will print the Hello Message when called""" print('Hey there! Hello') # hello() def hello_user(user): '''This function will take a parameter or name and will print hello with the parameter/name''' print("Hello",user, "How are you") hello_user('abhi') print(help(hell...
87a4132cd049edf1d4cc2bf5009b9041d06f12b5
limetree-indigo/allForAlgolithmWithPython
/Part3 탐색과 정렬/11 퀵 정렬/연습문제/ex11-1.py
539
3.765625
4
# 거품 정렬 # 입력: 리스트 a # 출력: 없음(입력으로 주어진 a가 정렬됨) def bubble_sort(a): n = len(a) while True: changed = False # 자료를 앞뒤로 바꾸었는지 여부 # 자료를 훑어보면서 뒤집힌 자료가 있으면 바꾸고 바뀌었다고 표시 for i in range(n-1): if a[i] > a[i+1]: a[i], a[i+1] = a[i+1], a[i] changed = T...
07184f85abcf2764d8b494b82b806f6f4c33b70f
limetree-indigo/allForAlgolithmWithPython
/Part1 알고리즘 기초/01 1부터 n까지의 합 구하기/연습문제/ex1-1.py
429
3.703125
4
# 1부터 n까지 연속한 숫자의 제곱의 합을 구하는 프로그램을 for 반목문으로 만들 어보세요. # 예를 들어 n = 10이라면 1^2 + 2^2 + 3^2 + --- + 10^2 = 385를 계산하는 프로그램입니다. # 계산 복잡도 => 2n번 실행되지만 복잡도는 O(n) def sum_sq(n): result = 0 for i in range(1, n+1): result += i*i return result print(sum_sq(10)) print(sum_sq(100))
86418b3d6255ee8d9b3ef03d690f4305b2df7288
hz37/JWG
/magnitude2.py
884
3.859375
4
#!/usr/local/bin/python3 # Bereken verschil in helderheid tussen twee objecten op basis van magnitude. # Hens Zimmerman, 01-05-2016. import math import sys def controleer_versie(): """Controleer of we wel met de juiste python werken""" if not sys.version_info >= (3,0): print("Je hebt minstens python ...
0c1d298aa46756a750e193d3b40549a9826f79f1
kekkaishi1/algorithm
/algorithm.py
23,311
3.625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- __Author__ = 'Lin Xin' """ 一些算法题记录 """ from data_structure import Stack, BinHeap, Chain, BinaryTree class Algorithm: # 1、硬币找零问题 @staticmethod def change_num(coin_value_list, change, known_results): """ 使用备忘录方法递归实现 :param coin_value_l...
ed8cd6824f4fc623a78916aa9b554016d5aeda3a
Lintik/CodeFights-Arcade
/Intro/Dark Wilderness/longestDigitsPrefix/code.py3
201
3.734375
4
def longestDigitsPrefix(inputString): temp = "" if len(inputString) == 0: return "" for c in inputString: if(c > '9' or c < '0'): break else: temp += c return temp
d5cfa91bee6c9787aca2c204434cfd8f0f794190
Tearrockster/Prepro---Python
/Sublime pt/0002.py
201
3.671875
4
"""Percentage""" def main(): """Main function""" mny = int(input()) allmny = int(input()) name = input() percen = (mny * 100)/allmny print("%s %.2f%%" %(name, percen)) main()
71667f633e9a6969d4b41ca2caf089ebf3bd0eec
Tearrockster/Prepro---Python
/Sublime pt/00056.py
186
3.890625
4
"""Substring""" def main(): """Main function""" text = input() find = input() if find in text: print("COOL") if find not in text: print("SAD") main()
3d09558dee06b794a5f70295d3f7b046cc81c250
Tearrockster/Prepro---Python
/Sublime pt/00053.py
666
3.6875
4
"""Four Dots""" from math import (sqrt) def main(): """Main function""" xa1 = int(input()) ya1 = int(input()) xb1 = int(input()) yb1 = int(input()) xc1 = int(input()) yc1 = int(input()) xd1 = int(input()) yd1 = int(input()) space1 = (function(xb1, xa1, yb1, ya1)) space2 = (f...
2249d9bd941a805f19c32b1cf6031ab31a3848a7
Tearrockster/Prepro---Python
/Sublime pt/000035.py
306
3.984375
4
"""Past Tense""" def main(): """Main function""" sentence = input().lower() change1 = sentence.replace('is', 'was') change2 = sentence.replace('are', 'were') if "is" in sentence and sentence.find('is'): print(change1) if "are" in sentence: print(change2) main()
7212475b8ccc0b89ece01691bb3d230bf770f8ec
Tearrockster/Prepro---Python
/Sublime pt/00004.py
291
3.828125
4
"""Alphabet Sequence""" def main(): """Main function""" alphabet = input() for i in range(ord('A'), ord('Z') + 1): if chr(i) > alphabet: break print(chr(i), end='') if chr(i) <= alphabet: break print(chr(i), end='') main()
cb2d7047375402e1b176ca591c557de774691205
Tearrockster/Prepro---Python
/Sublime pt/00063.py
505
3.78125
4
"""Match Winner""" def main(): """Main function""" function(1) function(2) function(3) function(4) function(5) function(6) def function(num): """My function""" nameteam1 = input() score1 = int(input()) nameteam2 = input() score2 = int(input()) if score1 > score2: ...
089f110e7eac6bfc949044077b9a4de652975c5d
Tearrockster/Prepro---Python
/Sublime pt/00007.py
520
3.890625
4
"""Pancake""" def main(): """Main function""" amount = int(input()) extra = int(input()) demand = int(input()) pack = amount + extra #Pack size pay, get = 0, 0 while demand >= pack: #Recieve one pack of pancake get += pack pay += amount*20 demand -= pack ...
5fc1530a3fb637127abf517484c0e96f3940fdd4
Axl11475581/Projects-Folder
/Python Exercises/Python Basics/Practical Exercise.py
2,256
4.53125
5
# 7 Exercise to practice the previous topics viewed 1 price_product_1 = input("What is the price of the product 1?: \n ") quantity_product_1 = input("How many of the product 1 will you buy?: \n ") price_product_2 = input("What is the price of the product 2?: \n ") quantity_product_2 = input("How many of the product 2 ...
b8f090d72c4065c18bfd430e24ce11254b369fee
boluocat/core-python-programming
/Fiboacci.py
1,147
4.4375
4
'''递归 recursion ''' def Fibonacci_recursion(n): if n == 0: return 0 elif n ==1: return 1 else: return Fibonacci_recursion(n-1)+Fibonacci_recursion(n-2) '''迭代 iteration 前一个数字+当前数值=下一个数值 ''' def Fibonacci_interation(n): if n ==0 : return 0 elif n == 1...
77af61601a9c9efcbc31a47bb3fbcf0238b6b0be
boluocat/core-python-programming
/随机数去重排序.py
1,251
3.71875
4
''' 明明想在学校中请一些同学一起做一项问卷调查,为了实验的客观性,他先用计算机生成了N个1到1000之间的随机整数(N≤1000),对于其中重复的数字,只保留一个,把其余相同的数去掉,不同的数对应着不同的学生的学号。然后再把这些数从小到大排序,按照排好的顺序去找同学做调查。请你协助明明完成“去重”与“排序”的工作(同一个测试用例里可能会有多组数据,希望大家能正确处理)。 注:测试用例保证输入参数的正确性,答题者无需验证。测试用例不止一组。 当没有新的输入时,说明输入结束。 ''' while True: #有新的输入则继续 try: inputs,num_id=int(input()),set() #...
4a62df0e8925e264bc4650e061c4ea43108170a1
boluocat/core-python-programming
/名次排名.py
3,207
3.671875
4
''' 有M个裁判(3<M<10),N个选手(3<N<10)。每个裁判依次给选手打分(最高为10分)。当比赛结束后,按照选手的总分进行名次排序,选前三名输出(如果选手总分一样的情况下,比较所得分值,例如A选手2个9分,B选手3个9分,则B名次高于A)。 输入: 1、第一行为裁判数、选手数,用英文逗号分隔 2、第二行至第j行为第j+1个裁判打出的分数,从左至右依次为第一位选手至第n位选手的分数 输出: 1、当M或N小于3时,输出-1; 2、当裁判所给分数>10时,输出-1; 3、输出前面前三的选手序号 #输入 4,5 10,6,9,7,6 9,10,6,7,5 8,10,6,5,10 9,10,8,4,9 #输出 2,1,5 '''...
84b0fc0d704a0d55157835bd75b32466b8a4ada0
boluocat/core-python-programming
/BiTree.py
3,226
3.890625
4
class Nodes: #结点生成,先初始化 def __init__(self, item): self.item = item self.lchild = None self.rchild = None class BiTree: #初始化root为None def __init__(self,node=None): self.root = node def addnode(self,item): #如果根节点为None,则将第一个接收到的值赋给根结点 ...
9206ec6515c1a0309d65035ac6286fb3553da76c
ppiatkowski/pocztowki
/pocztowki.py
4,767
3.546875
4
#!/usr/bin/python3 import sys import argparse import logging from PIL import Image # Given: # 1. Print paper size # 2. Passepartout size # 3. Picture to be printed # This tool will create an image with added white border of the right size so that input image will fit into the passepartout # Aspect ratio of the ima...
c54301c325a2299292f1766e5d192cfdc2404311
Darksidesfear/ctf-writeups-1
/2017/picoctf/cryptography/SoRandom-75/sorandom.py
1,620
3.71875
4
import random,string lower = string.ascii_lowercase upper = string.ascii_uppercase digits = string.digits ciphered = "BNZQ:449xg472190mwx6869b8pt10rwo92624" flag = "" encflag = "" def cipher(str): encflag = "" random.seed("random") for c in flag: if c.islower(): #rotate ...
770dfec0ac2a38cd1d55cd33087dde8caf87db28
ikamesh/Algorithms
/inputs.py
1,314
4.375
4
import random """This is file for generating input list for algorithms""" #input method1 -- filling list with try-except def infinite_num_list(): print(""" Press enter after each input. Press 'x' to when done...! """) num_list = [] while True: num = input("Enter num to fill the list : "...
7a17875ff135f6d0541a5d54eb7f4a9ccf33fa38
JiteshJitz/Bike_Share_Project
/bikeshare.py
9,469
4.125
4
import time import pandas as pd import numpy as np import itertools as it import operator def m_c(k): """ Takes argument to check most common element Returns: (srt) most common element in series """ sl=sorted((x,i) for i,x in enumerate(k)) gro=it.groupby(sl,key = operator.itemgetter(0)) ...
40f3256d80ed140adba46d690f33be58d1c42445
uit-inf-1400-2021/uit-inf-1400-2021.github.io
/lectures/oop-02-03-oo-concepts/code/tomato.py
333
3.984375
4
#!/usr/bin/env python3 class Tomato: def __init__(self, desc="Tomato"): self.desc = desc def __repr__(self): return self.desc def __add__(self, other): print("Smashing {} and {}".format(self.desc, other)) return Tomato("Ketchup") t1 = Tomato() t2 = Tomato('Tomato B') pr...
7504bbb277af091a8b5b4bd1230ea416f169a5b3
uit-inf-1400-2021/uit-inf-1400-2021.github.io
/lectures/oop-02-03-oo-concepts/code/extending.py
1,281
4.375
4
#!/usr/bin/env python3 """ Based on code from the OOP book. """ class ContactList(list): def search(self, name): '''Return all contacts that contain the search value in their name.''' matching_contacts = [] for contact in self: if name in contact.name: m...